branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. import {describe, it} from 'mocha'; import {Operation} from 'google-gax'; describe('VideoIntelligenceServiceSmokeTest', () => { it('successfully makes a call to the service', done => { const videoIntelligence = require('../src'); const client = new videoIntelligence.v1p1beta1.VideoIntelligenceServiceClient( { // optional auth parameters. } ); const inputUri = 'gs://cloud-samples-data/video/cat.mp4'; const featuresElement = 'LABEL_DETECTION'; const features = [featuresElement]; const request = { inputUri, features, }; // Handle the operation using the promise pattern. client .annotateVideo(request) .then((responses: Operation[]) => { const operation = responses[0]; const initialApiResponse = responses[1]; console.log(operation); console.log(initialApiResponse); // Operation#promise starts polling for the completion of the LRO. return operation.promise(); }) .then((responses: Operation[]) => { // The final result of the operation. const result = responses[0]; // The metadata value of the completed operation. const metadata = responses[1]; // The response of the api call returning the complete operation. const finalApiResponse = responses[2]; console.log(result); console.log(metadata); console.log(finalApiResponse); }) .then(done) .catch(done); }); it('successfully makes a call to the service', done => { const videoIntelligence = require('../src'); const client = new videoIntelligence.v1p1beta1.VideoIntelligenceServiceClient( { // optional auth parameters. } ); const inputUri = 'gs://cloud-samples-data/video/cat.mp4'; const featuresElement = 'LABEL_DETECTION'; const features = [featuresElement]; const request = { inputUri, features, }; // Handle the operation using the event emitter pattern. client .annotateVideo(request) .then((responses: Operation[]) => { const operation = responses[0]; // Adding a listener for the "complete" event starts polling for the // completion of the operation. operation.on('complete', (result: string) => { console.log(result); }); // Adding a listener for the "progress" event causes the callback to be // called on any change in metadata when the operation is polled. operation.on('progress', (metadata: string) => { console.log(metadata); }); // Adding a listener for the "error" event handles any errors found during polling. operation.on('error', () => { // throw(err); }); }) .then(done) .catch(done); }); }); <file_sep>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** import * as protosTypes from '../protos/protos'; import * as assert from 'assert'; import { describe, it } from 'mocha'; const streamingvideointelligenceserviceModule = require('../src'); import {PassThrough} from 'stream'; const FAKE_STATUS_CODE = 1; class FakeError{ name: string; message: string; code: number; constructor(n: number){ this.name = 'fakeName'; this.message = 'fake message'; this.code = n; } } const error = new FakeError(FAKE_STATUS_CODE); export interface Callback { (err: FakeError|null, response?: {} | null): void; } export class Operation{ constructor(){}; promise() {}; } function mockBidiStreamingGrpcMethod(expectedRequest: {}, response: {} | null, error: FakeError | null) { return () => { const mockStream = new PassThrough({ objectMode: true, transform: (chunk: {}, enc: {}, callback: Callback) => { assert.deepStrictEqual(chunk, expectedRequest); if (error) { callback(error); } else { callback(null, response); } } }); return mockStream; } } describe('v1p3beta1.StreamingVideoIntelligenceServiceClient', () => { it('has servicePath', () => { const servicePath = streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient.servicePath; assert(servicePath); }); it('has apiEndpoint', () => { const apiEndpoint = streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient.apiEndpoint; assert(apiEndpoint); }); it('has port', () => { const port = streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient.port; assert(port); assert(typeof port === 'number'); }); it('should create a client with no option', () => { const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient(); assert(client); }); it('should create a client with gRPC fallback', () => { const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient({ fallback: true, }); assert(client); }); it('has initialize method and supports deferred initialization', async () => { const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient({ credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.streamingVideoIntelligenceServiceStub, undefined); await client.initialize(); assert(client.streamingVideoIntelligenceServiceStub); }); it('has close method', () => { const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient({ credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.close(); }); describe('streamingAnnotateVideo', () => { it('invokes streamingAnnotateVideo without error', done => { const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); // Initialize client before mocking client.initialize(); // Mock request const request: protosTypes.google.cloud.videointelligence.v1p3beta1.IStreamingAnnotateVideoRequest = {}; // Mock response const expectedResponse = {}; // Mock gRPC layer client._innerApiCalls.streamingAnnotateVideo = mockBidiStreamingGrpcMethod(request, expectedResponse, null); const stream = client.streamingAnnotateVideo().on('data', (response: {}) =>{ assert.deepStrictEqual(response, expectedResponse); done(); }).on('error', (err: FakeError) => { done(err); }); stream.write(request); }); it('invokes streamingAnnotateVideo with error', done => { const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); // Initialize client before mocking client.initialize(); // Mock request const request: protosTypes.google.cloud.videointelligence.v1p3beta1.IStreamingAnnotateVideoRequest = {}; // Mock response const expectedResponse = {}; // Mock gRPC layer client._innerApiCalls.streamingAnnotateVideo = mockBidiStreamingGrpcMethod(request, null, error); const stream = client.streamingAnnotateVideo().on('data', () =>{ assert.fail(); }).on('error', (err: FakeError) => { assert(err instanceof FakeError); assert.strictEqual(err.code, FAKE_STATUS_CODE); done(); }); stream.write(request); }); }); });
797cc8c1e370191981080bc68b1667e843ebfae2
[ "TypeScript" ]
2
TypeScript
SurferJeffAtGoogle/nodejs-video-intelligence
34bc168cfd66ab8e9512c751f23dc3c9de413cfe
21cd9566afbcd894e13ca50d4ce4702bac06ba05
refs/heads/master
<file_sep><?php namespace app\social; class Youtube { } <file_sep><?php namespace app\social; class Twitter { } <file_sep><?php namespace models; use app\Core; class Exemple { protected $core; function __construct() { $this->core = Core::getInstance(); } //__ Get all posts public function getAllData() { global $pdo; $data = array(); $selectStatement = $pdo->select() ->from('atome'); if ($stmt = $selectStatement->execute()) { $data = $stmt->fetchAll(); } else { $data = 0; } return $data; } //__ Get all posts public function getData($slug) { global $pdo; $data = array(); $selectStatement = $pdo->select() ->from('atome') ->where('slug', '=', $slug); if ($stmt = $selectStatement->execute()) { $data = $stmt->fetchAll(); } else { $data = 0; } return $data; } } <file_sep># dev-php <file_sep><?php //__ requirement obligatoire require 'vendor/autoload.php'; //__ USE use app\Helpers; //__ gestion des erreurs ini_set('display_errors','on'); error_reporting(E_ALL); //__connection à la base de données $dsn = 'mysql:host=localhost;dbname=base;charset=utf8'; $usr = 'root'; $pwd = '<PASSWORD>'; //__ initialisation des variables $app = new Slim\App(array( 'log.writer' => new \Slim\Logger\DateTimeFileWriter() )); $pdo = new \Slim\PDO\Database($dsn, $usr, $pwd); $helper = new Helpers(); // Fetch DI Container $container = $app->getContainer(); // Register Twig View helper $container['view'] = function ($c) { $view = new \Slim\Views\Twig('views'); /* $view = new \Slim\Views\Twig('views', [ 'cache' => 'cache' ]); */ // Instantiate and add Slim specific extension $view->addExtension(new Slim\Views\TwigExtension( $c['router'], $c['request']->getUri() )); return $view; }; //__ Algorithme $helper->slash(); //__ routing : Automatically load router files $routers = glob('routers/*.router.php'); foreach ($routers as $router) { require $router; } $app->run(); <file_sep><?php namespace routers; use models\Exemple; $app->get('/', function ($request, $response) { $response->write("Hello, Everybody !"); return $response; }); $app->get('/hello/{name}', function ($request, $response, $args) { return $this->view->render($response, 'profile.html', [ 'name' => $args['name'] ]); })->setName('profile'); $app->get('/atomes', function ($request, $response, $args) { $ex = new Exemple(); $data = $ex->getAllData(); return $this->view->render($response, 'atomes.html', [ 'atoms' => $data ]); }); $app->get('/atome/{name}', function ($request, $response, $args) { $ex = new Exemple(); $data = $ex->getData($args['name']); echo json_encode($data); });
61df3fd9743a8726991db50bdcb06a889677d2ec
[ "Markdown", "PHP" ]
6
PHP
Guillaume-RICHARD/dev-php
3a93f9bac867fc8c41c62524cdb6737dbba2c501
644e14da6bbdde71ab3f60ba09643d5773f5abaa
refs/heads/master
<file_sep>package t4ka.com.lifecyclestudy.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import t4ka.com.lifecyclestudy.R; import t4ka.com.lifecyclestudy.commons.DBDatas; /** * Created by taka-dhu on 2015/12/08. */ public class DataAdapter extends ArrayAdapter<DBDatas> { private LayoutInflater inflater; public DataAdapter(Context context, int textViewResourceId, List<DBDatas> objects){ super(context,textViewResourceId,objects); inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position,View convertView, ViewGroup parent){ //get position's data // DBDatas item = getItem(position); //if you want to show newest one in the top position, use this logic DBDatas item = getItem(getCount() - 1 - position); //make a single instance of convertView if(convertView == null){ convertView = inflater.inflate(R.layout.db_list_items,null); } //Set each data of DBDatas for each view TextView idtv = (TextView)convertView.findViewById(R.id.id_tv); idtv.setText(item.getId()); TextView nametv = (TextView)convertView.findViewById(R.id.name_tv); nametv.setText(item.getName()); TextView commenttv = (TextView)convertView.findViewById(R.id.comment_tv); commenttv.setText(item.getComment()); return convertView; } }
866a6b1efd034e3c0e629229a28d8ad5471fa6a7
[ "Java" ]
1
Java
D3vel0pper/Lifecyclestudy
2693a1543ede788f505303e80c65564647f920a4
06f3f184253a8bfd24ca812e67768e6de5178f1f
refs/heads/master
<repo_name>Diegod96/Cryptography<file_sep>/IndexOfCoincidence/tester.py import math # Uses Counter to get the frequency of letters in provided text def frequencyAnalysis(input_text): frequency = {} for keys in input_text: frequency[keys] = frequency.get(keys, 0) + 1 return frequency # Affine Cipher encrypt def affineCipherEncrypt(input_text, a, b): alphabet = 'abcdefghijklmnopqrstuvwxyz' output = '' # If a is not a co-prime of a then raise error if math.gcd(a, 26) != 1: raise ValueError("a and 26 are not co-primes. Try again.") # If input text contains white spaces, raise an error if ' ' in input_text: raise ValueError("Please enter a text with no spaces") for i in range(len(input_text)): current_letter = input_text[i] index = alphabet.find(current_letter) c = a * index + b % 26 cIdx = c % 26 i = alphabet[cIdx] output += i return output def IndexOfCoincidence(input_text, freq): string_length = len(input_text) x = 0 for value in freq.values(): x += ((value / string_length) ** 2) return x if __name__ == '__main__': string = "<NAME> was a successful ruler because his actions created long lasting effects on cultures that continue to the present day. One example of his legacy was the creation of a Hellenistic society. Hellenism was the combination of Greek, Persian, and Egyptian cultures. During this remarkable time period, people were encouraged to pursue a formal education and produce many different kinds of art. New forms of math, science, and design made a great impact on society." string = string.replace(" ", "") string = string.replace(".", "") string = string.replace(",", "") string = string.lower() print("Make sure a is a co-prime of 26!!!") a = int(input("Enter a: ")) b = int(input("Enter b: ")) cipher_text = affineCipherEncrypt(string, a, b) print(f"Your cipher text: {cipher_text}") print(f"Your plain text: {string}") dict = frequencyAnalysis(cipher_text) dicts = frequencyAnalysis(string) print(f"Frequency of letters in cipher text {dict}") print(f"Frequency of letters in plain text {dicts}") IOCCipher = IndexOfCoincidence(cipher_text, dict) IOCPlain = IndexOfCoincidence(string, dicts) print(f"Index of coincidence for cipher text {IOCCipher}") print(f"Index of coincidence for plain text {IOCPlain}") <file_sep>/Crypto-HW3/tester.py import operator import math def freqAnalysis(data): result = {} for keys in data: result[keys] = result.get(keys, 0) + 1 result = sorted(result.items(), key=operator.itemgetter(1), reverse=True) return result # Shift Cipher decrypt def shiftCipherDecrypt(input_cipher_text, input_shift): alphabet = 'abcdefghijklmnopqrstuvwxyz' output = '' # Iterate over the characters in the cipher text # find location of character in comparision to its location in the aplhabet # Mod 26 the difference of the location and shift # Append new letter to output for i in range(len(input_cipher_text)): current_letter = input_cipher_text[i] index = alphabet.find(current_letter) index = (index - input_shift) % 26 output = output + alphabet[index] return output def LRT(input_text): alphabet_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] alpha_length = len(alphabet_list) input_text_length = len(input_text) alphabet_frequency_table = [.082, .015, .028, .043, .127, .022, .020, .061, .070, .002, .008, .040, .024, .067, .075, .019, .001, .060, .063, .091, .028, .010, .023, .001, .020, .001] list_of_zeros = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(alpha_length): for j in range(input_text_length): if alphabet_list[i] == input_text[j]: list_of_zeros[i] += 1.0 lrt = 0.0 pNoise = 1.0 / 26.0 length_of_zero_list = len(list_of_zeros) for x in range(length_of_zero_list): frequency = (list_of_zeros[x] / input_text_length) lrt += (frequency * math.log(alphabet_frequency_table[x] / pNoise)) return round(lrt, 4) if __name__ == '__main__': cipher_text = "<KEY>" freq = freqAnalysis(cipher_text) print(freq) # Iterating over different shifts and testing them in the LRT Test # if LRT Test returns a positive number then print out the plain text and the shift i = 0 while i < 26: plain_text = shiftCipherDecrypt(cipher_text, i) lrt = LRT(plain_text) if lrt >= 0.0: print(plain_text) print(lrt) print(f"Shift is {i}") i += 1 <file_sep>/IndexOfCoincidence/README.md # IndexOfCoincidence <file_sep>/Crypto-HW1/CryptoHw1.py from collections import Counter import math from itertools import starmap, cycle # Uses Counter to get the frequency of letters in provided text def frequencyAnalysis(input_text): frequency = Counter(input_text) return frequency # Shift Cipher encrypt def shiftCipherEncrypt(input_text, input_shift): alphabet = 'abcdefghijklmnopqrstuvwxyz' output = '' input_shift = int(input_shift) # Iterate over the characters in the input text # find location of character in comparision to its location in the aplhabet # Mod 26 the sum of the location and shift # Append new letter to output for i in range(len(input_text)): current_letter = input_text[i] current_location_of_letter = alphabet.find(current_letter) new_location_letter = (current_location_of_letter + input_shift) % 26 output += alphabet[new_location_letter] return output # Shift Cipher decrypt def shiftCipherDecrypt(input_cipher_text, input_shift): alphabet = 'abcdefghijklmnopqrstuvwxyz' output = '' # Iterate over the characters in the cipher text # find location of character in comparision to its location in the aplhabet # Mod 26 the difference of the location and shift # Append new letter to output for i in range(len(input_cipher_text)): current_letter = input_cipher_text[i] index = alphabet.find(current_letter) index = (index - input_shift) % 26 output = output + alphabet[index] return output # Affine Cipher encrypt def affineCipherEncrypt(input_text, a, b): alphabet = 'abcdefghijklmnopqrstuvwxyz' output = '' # If a is not a co-prime of a then raise error if math.gcd(a, 26) != 1: raise ValueError("a and 26 are not co-primes. Try again.") # If input text contains white spaces, raise an error if ' ' in input_text: raise ValueError("Please enter a text with no spaces") # Iterate over input text # Get location of letter in comparision to its location in the alphabet # x is the product of a and the index plus b mod 26 # x index is x mod 26 # Append i to the output text for i in range(len(input_text)): current_letter = input_text[i] index = alphabet.find(current_letter) x = a * index + b % 26 x_index = x % 26 i = alphabet[x_index] output += i return output # Gets inverse of a based of 26 def getInverse(a): result = 1 for i in range(1, 26): if (a * i) % 26 == 1: result = i return result # Affine Cipher decrypt def affineCipherDecrypt(input_cipher_text, a, b): alphabet = 'abcdefghijklmnopqrstuvwxyz' output = '' # If a is not a co-prime of 26 then raise error if math.gcd(a, 26) != 1: raise ValueError("a and 26 are not co-primes. Try again.") # Iterate over cipher text # Get location of letter in comparision to its location in the alphabet # Get the inverse of a # set plain text input to a * (character index-b) mod 26 # Check is the plain text iindex is less than 0 # append character found to plaintext # appends plain text to output for character in input_cipher_text: character_index = alphabet.index(character) inverse_of_a = getInverse(a) plain_text_index = inverse_of_a * (character_index - b) % 26 if plain_text_index < 0: plain_text_index += 26 plain_text = alphabet[plain_text_index] output += plain_text return output # Viginere Encryption def viginereEncrpyt(input_text, input_key): # Converts input_text to all uppercase letters input_text = filter(str.isalpha, input_text.upper()) # Encrypts charachter-by-charachter # ord() returns an integer representing the unicode code point of the character # chr() function takes integer argument and return the string representing a character at that code point def encrypt(character, key): return chr(((ord(key) + ord(character) - 2 * ord('A')) % 26) + ord('A')) # Zips the characters back together to make the cipher text return ''.join(starmap(encrypt, zip(input_text, cycle(input_key)))) # Viginere Decryption def viginereDecrypt(cipher_text, key): # Decrypts character-by-charcter def decrypt(character, key): return chr(((ord(character) - ord(key) - 2 * ord('A')) % 26) + ord('A')) # Zips plain text characters back into plain text message as all Uppercase and no spaces return ''.join(starmap(decrypt, zip(cipher_text, cycle(key)))) if __name__ == '__main__': # Implementation of Frequency Analysis user_input = input("Please enter text you would like to get analysed: ") freq_result = frequencyAnalysis(user_input) print(f"Frequency of letters in text provided: {freq_result}") # Implementation of Shift Cipher encrypt user_input = input("Please enter text you would like to encrypt with shift cipher: ") shift = input("Please enter shift you would like to use: ") cipher_text = shiftCipherEncrypt(user_input, shift) print(f"Encrypted cipher text: {cipher_text}") # Implmentation of Shift Cipher decrypt using freq_analysis function from Question 1 cipher_text = "xultpaajcxitltlxaarpjhtiwtgxktghidhipxciwtvgtpilpitghlxiwiwtxgqadd" freq_result = frequencyAnalysis(cipher_text) print(f"Text provided: {cipher_text}") print(f"Frequency of letters in text provided: {freq_result}") # Most frequent letter in the cipher text was 't', postion from 'e' -> 't' is 15 # Determined key for this cipher text was 15 shift = int(input("Please enter key: ")) plain_text = shiftCipherDecrypt(cipher_text, shift) print(f"Plain text message: {plain_text}") # Implementation of Affine cipher encrypt and decrypt user_input = input("Please enter text you would like to get encrypted: ") print("Make sure a is a co-prime of 26!!!") a = int(input("Enter a: ")) b = int(input("Enter b: ")) cipher_text = affineCipherEncrypt(user_input, a, b) print(f"Your cipher text: {cipher_text}") plain_text = affineCipherDecrypt(cipher_text, a , b) print(f"Your plain text: {plain_text}") # Implementation of Viginere encrypt and decrypt # Uses two keys plain_text = "Hellenism was the combination of Greek, Persian, and Egyptian cultures. During this remarkable time period, people were encouraged to pursue a formal education and produce many different kinds of art. New forms of math, science, and design made a great impact on society" input_key_1 = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?" cipher_text = viginereEncrpyt(plain_text, input_key_1) print(f"Cipher text using key #1: {cipher_text}") plain_text = viginereDecrypt(cipher_text, input_key_1) print(f"Plain text: {plain_text}") input_key_2 = "Out of the three operating systems, linux is by far my favorite." cipher_text = viginereEncrpyt(plain_text, input_key_2) print(f"Cipher text using key #1: {cipher_text}") plain_text = viginereDecrypt(cipher_text, input_key_2) print(f"Plain text: {plain_text}")
adffede88312a6ffc8c5cc6447f32cc26aa94cb2
[ "Markdown", "Python" ]
4
Python
Diegod96/Cryptography
06297ecc5ba3871f5df54542d4fc5f335d4a066a
ff79776282fc4e770aee23f2bb9cf243fe906d4d
refs/heads/master
<repo_name>openmrs/openmrs-module-spa<file_sep>/omod/src/test/java/org/openmrs/module/spa/servlet/SpaServletTest.java /* * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.spa.servlet; import org.junit.Before; import org.junit.Test; import org.openmrs.test.BaseModuleContextSensitiveTest; import org.springframework.core.io.Resource; import org.springframework.test.context.ContextConfiguration; import javax.servlet.http.HttpServletRequest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @ContextConfiguration(locations = {"classpath:applicationContext-service.xml", "classpath:webModuleApplicationContext.xml"}, inheritLocations = false) public class SpaServletTest extends BaseModuleContextSensitiveTest { //Just a placeholder url for testing, we don't make an actual request private static final String DEFAULT_REMOTE_URL = "https://dev3.openmrs.org/openmrs/spa/@openmrs/esm-app-shell/latest/"; private static final String PREFIX_REMOTE_URL = "url:" + DEFAULT_REMOTE_URL; private static final String INDEX_HTML = "index.html"; private SpaServlet servlet; @Before public void setup() { servlet = new SpaServlet(); } @Test public void shouldReturnDefaultResourcePath() { String path = ""; String resultPath = servlet.constructRemoteUrl(path); assertNotNull(resultPath); assertEquals(resultPath, PREFIX_REMOTE_URL + "index.html"); } @Test public void shouldExtractValidResourcePath() { String path = "manifest-build.html"; String resultPath = servlet.constructRemoteUrl(path); assertNotNull(resultPath); assertTrue(resultPath.startsWith("url:")); assertEquals(resultPath, PREFIX_REMOTE_URL + path); } @Test public void shouldReturnValidResource() { SpaServlet spaServlet = mock(SpaServlet.class); Resource resourceMock = mock(Resource.class); HttpServletRequest requestMock = mock(HttpServletRequest.class); when(requestMock.getPathInfo()).thenReturn(INDEX_HTML); when(resourceMock.exists()).thenReturn(true); when(spaServlet.getResource(requestMock)).thenReturn(resourceMock); Resource resource = spaServlet.getResource(requestMock); assertNotNull(resource); assertTrue(resource.exists()); } @Test public void shouldReturnDefaultIndexHtmlForInvalidResource() { HttpServletRequest request = mock(HttpServletRequest.class); SpaServlet spaServlet = mock(SpaServlet.class); Resource resourceMock = mock(Resource.class); when(request.getPathInfo()).thenReturn(INDEX_HTML); when(resourceMock.exists()).thenReturn(true); when(resourceMock.getFilename()).thenReturn(INDEX_HTML); when(spaServlet.getResource(request)).thenReturn(resourceMock); Resource resource = spaServlet.getResource(request); assertNotNull(resource); assertTrue(resource.exists()); assertEquals(resource.getFilename(), INDEX_HTML); } @Test public void shouldReturnResourceLoaderBean() { assertNotNull(servlet.getResourceLoaderBean()); } } <file_sep>/omod/src/main/java/org/openmrs/module/spa/SpaActivator.java /* * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.spa; import lombok.extern.slf4j.Slf4j; import org.openmrs.module.BaseModuleActivator; import org.openmrs.module.ModuleException; import org.openmrs.module.spa.utils.SpaModuleUtils; import java.io.File; @Slf4j public class SpaActivator extends BaseModuleActivator { @Override public void started() { createFrontendDirectory(); log.info("SPA module started"); } @Override public void stopped() { log.info("SPA module stopped"); } /** * Creates a directory to hold static files for the frontend if none exists. * The default directory name is stored in a global property and can be edited. * By default, the directory is created in the OpenMRS app directory * If the default value is edited, and a full path provided, the directory is created as per user specification * */ public void createFrontendDirectory() { File folder = SpaModuleUtils.getSpaStaticFilesDir(); // now create the modules folder if it doesn't exist if (!folder.exists()) { log.warn("Frontend directory " + folder.getAbsolutePath() + " doesn't exist. Creating it now."); folder.mkdirs(); } if (!folder.isDirectory()) { throw new ModuleException("SPA frontend repository is not a directory at: " + folder.getAbsolutePath()); } } }<file_sep>/omod/src/main/java/org/openmrs/module/spa/servlet/SpaServlet.java /* * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * <p> * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.spa.servlet; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.openmrs.api.context.Context; import org.openmrs.module.spa.component.ResourceLoaderComponent; import org.openmrs.module.spa.utils.SpaModuleUtils; import org.openmrs.util.OpenmrsUtil; import org.springframework.core.io.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; @Slf4j public class SpaServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String BASE_URL = "/spa/spaServlet"; /** * Used for caching purposes * * @see HttpServlet#getLastModified(HttpServletRequest) */ @SneakyThrows @Override protected long getLastModified(HttpServletRequest servletRequest) { if (SpaModuleUtils.isRemoteAssetsEnabled()){ Resource resource = getResource(servletRequest); return resource.lastModified(); } else { File file = getFile(servletRequest); if (file == null) { return super.getLastModified(servletRequest); } return file.lastModified(); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (SpaModuleUtils.isRemoteAssetsEnabled()) { handleRemoteAssets(request, response); } else { handleLocalAssets(request, response); } } protected void handleLocalAssets(HttpServletRequest request, HttpServletResponse response) throws IOException { File file = getFile(request); if (file == null || !file.exists()) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } response.setDateHeader("Last-Modified", file.lastModified()); addCacheControlHeader(request, response); response.setContentLength((int) file.length()); String mimeType = getServletContext().getMimeType(file.getName()); response.setContentType(mimeType); try (InputStream is = new FileInputStream(file)) { OpenmrsUtil.copyFile(is, response.getOutputStream()); } } /** * Handles fetching of resources from remotes or those fronted assets which doesn't * resides in the filesystem * * @param request {@link HttpServletRequest} * @param response {@link HttpServletResponse} * @throws IOException {@link IOException} F */ protected void handleRemoteAssets(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Resource resource = getResource(request); if (!resource.exists()) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } response.setDateHeader("Last-Modified", resource.lastModified()); addCacheControlHeader(request, response); response.setContentLength((int) resource.contentLength()); String mimeType = getServletContext().getMimeType(resource.getFilename()); response.setContentType(mimeType); InputStream is = resource.getInputStream(); try { OpenmrsUtil.copyFile(is, response.getOutputStream()); } finally { OpenmrsUtil.closeStream(is); } } /** * Turns the given request/path into a File object * * @param request the current http request * @return the file being requested or null if not found */ protected Resource getResource(HttpServletRequest request) { String path = request.getPathInfo(); /* * we want to extract everything after /spa/spaServlet from the path info. * This should cater for sub-directories */ return getResourceLoaderBean().getResource(constructRemoteUrl(path)); } protected String constructRemoteUrl(String path) { String resourceName = path.substring(path.indexOf('/', BASE_URL.length() - 1) + 1); // Remove the trailing slash if (resourceName.length() > 0 && resourceName.charAt(resourceName.length() - 1) == '/') { resourceName = resourceName.substring(0, resourceName.length() - 1); } String frontedAssetsDirectoryPath = SpaModuleUtils.getRemoteAssetsUrl(); log.info("Serving assets from {}", frontedAssetsDirectoryPath); if (resourceName.endsWith("index.htm") || !resourceName.contains(".")) { resourceName = "index.html"; } String extractedResourcePath = frontedAssetsDirectoryPath + resourceName; if (extractedResourcePath.contains("http") && !extractedResourcePath.contains("url:")) { extractedResourcePath = "url:" + extractedResourcePath; } log.info("Frontend asset {}", extractedResourcePath); return extractedResourcePath; } protected ResourceLoaderComponent getResourceLoaderBean() { return Context.getRegisteredComponent("spaResourceLoader", ResourceLoaderComponent.class); } protected File getFile(HttpServletRequest request) { // all url will have a base of /spa/spaResources/ String path = request.getPathInfo(); // we want to extract everything after /spa/spaResources/ from the path info. This should cater for sub-directories String extractedFile = path.substring(path.indexOf('/', BASE_URL.length() - 1) + 1); File folder = SpaModuleUtils.getSpaStaticFilesDir(); //Resolve default index.html if (extractedFile.endsWith("index.htm") || !extractedFile.contains(".")) { extractedFile = "index.html"; } File file = folder.toPath().resolve(extractedFile).toFile(); if (!file.exists()) { log.warn("File with path '{}' doesn't exist", file.toString()); return null; } return file; } private void addCacheControlHeader(HttpServletRequest request, HttpServletResponse response) { String path = request.getPathInfo(); if (path.endsWith("importmap.json") || path.endsWith("import-map.json")) { response.setHeader("Cache-Control", "public, must-revalidate, max-age=0;"); } } } <file_sep>/README.md # OpenMRS Module SPA ![Build Status](https://github.com/openmrs/openmrs-module-spa/workflows/Build%20with%20Maven/badge.svg) This module provides backend functionality to serve frontend assests. See "Configurations" below for more details. ## Pre-requisties - Maven - Java >= 8 ## Build To build this module, first clone the repository. Then navigate into `openmrs-module-spa` and run the build command: ```sh cd openmrs-module-spa && mvn clean install ``` ## Configurations | Property | Description | Default Value | | ----------- | ----------- | ------------ | | `spa.local.directory` | The directory containing the Frontend 3.0 application's `index.html`. Can be an absolute path, or relative to the application data directory. Only used if `spa.remote.enabled` is false. | frontend | | `spa.remote.enabled` | If enabled, serves from `spa.remote.url` instead of `spa.local.directory` | false | | `spa.remote.url` | The URL of the Frontend 3.0 application files. Only used if `spa.remote.enabled` is true. | https://spa-modules.nyc3.digitaloceanspaces.com/@openmrs/esm-app-shell/latest/ | <file_sep>/deploy.sh #!/bin/bash export SSHPASS=$<PASSWORD> sshpass -e scp -o stricthostkeychecking=no omod/target/*.omod $USER@$HOST:./travis_deployments/$TRAVIS_BRANCH sshpass -e ssh -o stricthostkeychecking=no $USER@$HOST <<EOF cd /opt/openmrs-ref-app/modules ls | grep -P "spa-[0-9]\.[0-9](\.[0-9])?(-SNAPSHOT)?\.omod" | xargs -d"\n" rm mv ~/travis_deployments/$TRAVIS_BRANCH/*.omod ./ cd ../ && docker-compose restart echo "Module SPA Successfully Deployed" EOF
94516500ab5e80ffc15a26ab33a458f97291b6cf
[ "Markdown", "Java", "Shell" ]
5
Java
openmrs/openmrs-module-spa
589f30b837f87d5cae885eb4ee1c06ed3e2af5e5
860eeb249c2c616c95948be84497770b5943cb03
refs/heads/master
<repo_name>lkhan961221/elasticsearchstudy<file_sep>/src/main/java/com/haan/elasticsearchstudy/config/ESConfig.java package com.haan.elasticsearchstudy.config; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.transport.client.PreBuiltTransportClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.net.InetAddress; import java.net.UnknownHostException; @Configuration public class ESConfig { @Value("${spring.data.elasticsearch.cluster-name}") private String clustername; @Value("${spring.data.elasticsearch.cluster-nodes}") private String[] clusternodes; private static final String HOST_PORT_SPLIT_SYMBOL = ":"; private static final Logger LOGGER = LoggerFactory.getLogger(ESConfig.class); @Bean public Settings MySettings(){ Settings settings = Settings.builder() .put("cluster.name",clustername) .build(); return settings; } public TransportClient MyTransportClient(Settings settings) throws UnknownHostException { TransportClient client = new PreBuiltTransportClient(settings); for (String clusternode:clusternodes) { String[] split = clusternode.split(HOST_PORT_SPLIT_SYMBOL); String host = split[0]; String port = split[1]; LOGGER.info(host+":"+port); TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(host), Integer.parseInt(port)); client.addTransportAddress(transportAddress); } return client; } } <file_sep>/src/test/java/com/haan/elasticsearchstudy/ElasticsearchstudyApplicationTests.java package com.haan.elasticsearchstudy; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.haan.elasticsearchstudy.entity.User; import org.elasticsearch.action.delete.DeleteRequestBuilder; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.rest.RestStatus; 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 java.util.HashMap; import java.util.Map; @RunWith(SpringRunner.class) @SpringBootTest public class ElasticsearchstudyApplicationTests { @Autowired private TransportClient client; @Test public void addDoc1() { String json = "{" + "\"user\":\"kimchy\"," + "\"age\":\"22\"," + "\"message\":\"trying out Elasticsearch\"" + "}"; IndexResponse indexResponse = client.prepareIndex("index_test", "type_index") .setSource(json, XContentType.JSON) .get(); } @Test public void addDoc2() { Map<String,Object> map =new HashMap<>(); map.put("user","libai"); map.put("age",23); map.put("message","hello map"); IndexResponse indexResponse = client.prepareIndex("index_test", "type_index") .setSource(map, XContentType.JSON) .get(); } @Test public void addDoc3() throws JsonProcessingException { User user =new User("zhangliang",21,"hello javabean"); ObjectMapper mapper =new ObjectMapper(); String s = mapper.writeValueAsString(user); IndexResponse indexResponse = client.prepareIndex("index_test", "type_index") .setSource(s,XContentType.JSON) .get(); } @Test public void deletDoc(){ DeleteResponse deleteResponse = client.prepareDelete("index_test", "type_index", "OTUINW0BGY9H9s-fp1lZ") .get(); } }
4ea52c56105e7e1df1a7d0b12aa8a6cfd6f90804
[ "Java" ]
2
Java
lkhan961221/elasticsearchstudy
beac38870413952528799b05f6c7120736697a45
cbcb7522e53bd6f30b95fe0e269530989b2babde
refs/heads/master
<file_sep>= クラスの構造と初歩のパターン == はじめに このプロジェクトは、ごく簡易なカードゲームを題材として、Javaのクラス作成パターンを意識する練習を狙ったハンズオン用のプロジェクトです。 Javaでプログラミングの基本文法や、`ArrayList` などの標準ライブラリの使い方を学んだレベルの学習者の利用を想定しています。 このプロジェクトで取り上げる(取り上げたい)内容は以下の通りです。 - クラス、フィールド、メソッド、コンストラクタ - リスト - 列挙型 - イミュータブルとミュータブル - クラスを跨ぐ処理の切り分け - 色々なものをクラスで表す - [line-through]#同値性と同一性#(カードゲームに盛り込む良いサンプル を考え中...🤔) 本来、クラス作成(設計)のパターンには、各種のデザインパターンや、ドメイン駆動設計におけるドメインモデルパターンなど、実践的な体系が確立されています。 + このハンズオンはより初心者向けに、前述のパターンなどに手をかける前の手習いとして「積極的にクラスを作る」練習をする部分を狙っています。 なお、コードはあくまで一例で、実際には様々なクラス分けのパターン・考え方があると思います。このプログラムが100%正解ということではないので、ぜひ色々な観点でクラス分けを考えるきっかけになればと思います。 == お題 image::./お題.jpg[scaledwidth="100%",align="center"] == 解説資料 * https://speakerdeck.com/gishi_yama/javado18-20200829[Java Doでしょう#18 〈オンライン〉Javaを始めた&これから使う人向けモブプログラミング会] == 備考 JavaDocはAsciiDoc構文を使っているので、IntelliJ IDEAに、 https://plugins.jetbrains.com/plugin/7391-asciidoc[AsciiDocプラグイン] を入れるとよい。 プラグインのインストール後、設定項目の `Languages & Frameworks` > `AsciiDoc` で、 `Enabled Asciidoclet Support` をONにする。<file_sep>package org.example.rule; import org.example.model.Mark; import org.example.model.Player; import java.util.Objects; /** * == ゲームの勝敗を表現するクラス(イミュータブル) * * . スペードはジョーカーに無条件に勝つ * . カードに与えられた強さが大きい方が勝つ */ public class WinLoseRule { private final Mark p1Mark; private final Mark p2Mark; public WinLoseRule(Player p1, Player p2) { this.p1Mark = Objects.requireNonNull(p1.getCardMark()); this.p2Mark = Objects.requireNonNull(p2.getCardMark()); System.out.println(String.format("Player1 : %s, Player2 : %s", p1Mark, p2Mark)); } // 左が勝つ public boolean isPlayer1Win() { return isBeatenJokerBySpade() || isHigherStrengthWins(); } // スペードはジョーカーに無条件に勝つ boolean isBeatenJokerBySpade() { if (p1Mark == Mark.SPADE) { // もし左がSPADEなら、右がJOKERの時だけ勝てる。 return p2Mark == Mark.JOKER; } return false; } // カードに与えられた強さが大きい方が勝つ boolean isHigherStrengthWins() { return p2Mark.getStrength() < p1Mark.getStrength(); } } <file_sep>package org.example.model; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class YamaTest { @Test public void カードの山に全種類のカードが入っている() { var sut = new Yama(); var actualSize = sut.getMaisu(); var actualCards = sut.copyCards(); assertAll(() -> assertEquals(5, actualSize), () -> assertTrue(actualCards.contains(new Card(Mark.CLOVER))), () -> assertTrue(actualCards.contains(new Card(Mark.HART))), () -> assertTrue(actualCards.contains(new Card(Mark.DIA))), () -> assertTrue(actualCards.contains(new Card(Mark.SPADE))), () -> assertTrue(actualCards.contains(new Card(Mark.JOKER))) ); } } <file_sep>package org.example.rule; import org.example.model.Card; import org.example.model.Mark; import org.example.model.Player; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class WinLoseRuleTest { @Test public void 左がダイア右がスペードで左が勝つ() { Player p1 = new Player(new Card(Mark.DIA)); Player p2 = new Player(new Card(Mark.SPADE)); var sut = new WinLoseRule(p1, p2); assertTrue(sut.isPlayer1Win()); } @Test public void 右がダイア左がスペードで左が負ける() { Player p1 = new Player(new Card(Mark.SPADE)); Player p2 = new Player(new Card(Mark.DIA)); var sut = new WinLoseRule(p1, p2); assertFalse(sut.isPlayer1Win()); } @Test public void 左がスペード右がジョーカーで左が勝つ() { Player p1 = new Player(new Card(Mark.SPADE)); Player p2 = new Player(new Card(Mark.JOKER)); var sut = new WinLoseRule(p1, p2); assertTrue(sut.isPlayer1Win()); } } <file_sep>package org.example.model; /** * == カードのマークの種類を表現する列挙型クラス * * マークの名前に対し、強さ数値をフィールドで表す。 * * インスタンス化されてからフィールドが変化しない(イミュータブル)。 */ public enum Mark { SPADE(1), HART(2), DIA(3), CLOVER(4), JOKER(5); private final int strength; private Mark(int strength) { this.strength = strength; } public int getStrength() { return strength; } } <file_sep>package org.example.rule; import org.example.model.Yama; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class DrawRuleTest { private Yama yama; @BeforeEach public void 山を準備() { yama = new Yama(); } @Test public void 入力値が数値に変換できない時にfalse() { var sut = new DrawRule(yama, "Test"); assertFalse(sut.isOK()); } @Test public void 入力値が山の枚数より大きい時にfalse() { var sut = new DrawRule(yama, "6"); assertFalse(sut.isOK()); } @Test public void 入力値が山の枚数より小さいときにTrue() { var sut = new DrawRule(yama, "2"); assertTrue(sut.isOK()); } @Test public void 入力値が負の時にfalse() { var sut = new DrawRule(yama, "-1"); assertFalse(sut.isOK()); } }
4ec4c4fc718b3547d01d685e540d3f59287103db
[ "Java", "AsciiDoc" ]
6
AsciiDoc
gishi-yama/CardGame
e5c3fcd287eb0689c6c4607eb56a2afe966a8f91
f8308af89d11aa7153262a748455260187a69d2e
refs/heads/master
<repo_name>wahidAmini/addressMVC<file_sep>/view/detail_user_view.php <h2>Bienvenu sur votre porfile monsieur <?=$user['prenom']?></h2> <table class="table"> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Expediteur</th> <th>Description</th> <th>Adress</th> <th>Postal Code</th> <th>City</th> <th>Edit</th> </tr> </thead> <tbody> <tr> <td><?=$user["user_id"]?></td> <td><?=$user["prenom"]?></td> <!-- <td><?=$user["nom"]?></td> <td><?=$user["sexe"]?></td> <td><?=$user["date_naissance"]?></td> <td><?=$user["email"]?></td> <td><?=$user["telephone"]?></td> <td><?=$user["identifiant_id"]?></td> <td><?=$user["pays"]?></td> <td><?=$user["password"]?></td> --> <td><?=$user["expediteur"]?></td> <td><?=$user["description"]?></td> <td><?=$user["address"]?></td> <td><?=$user["code_postal"]?></td> <td><?=$user["city"]?></td> <td><a href="update_user.php?id=<?=$user['user_id']?>"> <i class="far fa-edit"></i></a></td> </tr> </tbody> </table><file_sep>/processAddUserForm.php <?php ini_set('display_errors', 1); ini_set('log_errors', 1); ini_set('error_log', dirname(__file__) . '/log_error_php.txt'); // print_r($_POST); //1. include model in order to be abble to access model function include("model/model.php"); //2. get data from the POST Request in order to get the value typed by the visitor if(!empty($_POST['fname']) && !empty($_POST['lname'])){ $first_name = filter_var($_POST['fname'], FILTER_SANITIZE_STRING); $last_name = filter_var($_POST['lname'], FILTER_SANITIZE_STRING); $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL); $telephone = filter_var($_POST['telephone'], FILTER_VALIDATE_INT); $birth_date = filter_var($_POST['dob'], FILTER_SANITIZE_STRING); $date = change_date($birth_date); $password = filter_var($_POST['password'], FILTER_SANITIZE_STRING); $gender = filter_var($_POST['gender']); $country = filter_var($_POST['country']); add_user($last_name,$first_name,$email,$telephone,$date,$gender,$country,$password); echo"a record has been successfuly registered "; } else{ header("location:list_users.php"); } //3. filter those entries (/!\ never trust the user ) ==> filter_var. //4. call the function add_user( in the model :) //5. reward the visitor with a message if everythign is ok by calling the good view (view/success.php) ?><file_sep>/update_user.php <?php //active_error(); // MySQL == un serveur de baseSSSSSSSS de données ini_set('display_errors', 1); // Enregistrer les erreurs dans un fichier de log ini_set('log_errors', 1); // Nom du fichier qui enregistre les logs (attention aux droits à l'écriture) ini_set('error_log', dirname(__file__) . '/log_error_php.txt'); include("template/header.php"); include("model/model.php"); if(isset($_GET['id']) && !empty($_GET['id'])){ $id = filter_var($_GET['id'], FILTER_VALIDATE_INT); /* $last_name = filter_var(GET['nom'], FILTER_SANITIZE_STRING); $first_name = filter_var(GET['prenom'], FILTER_SANITIZE_STRING); $email = filter_var(GET['email'], FILTER_SANITIZE_EMAIL); $telephone = filter_var(GET['telephone'], FILTER_SANITIZE_NUMBER_INT); $date = filter_var(GET['date_naissance'], FILTER_SANITIZE_STRING); $gender = filter_var(GET['sexe'], FILTER_SANITIZE_STRING); $country = filter_var(GET['pays'], FILTER_SANITIZE_STRING); $password = filter_var(GET['password'], FILTER_SANITIZE_STRING); */ $user = getUserById($id); } else { header("location: list_users.php"); } include("view/update_user_view.php"); include("template/footer.php"); ?><file_sep>/login_controler.php <?php // MySQL == un serveur de baseSSSSSSSS de données ini_set('display_errors', 1); // Enregistrer les erreurs dans un fichier de log ini_set('log_errors', 1); // Nom du fichier qui enregistre les logs (attention aux droits à l'écriture) ini_set('error_log', dirname(__file__) . '/log_error_php.txt'); include("template/header.php"); // Recieving uername ana password from users if(isset("username")){ $username = $_POST["username"]; $userPassword = $_POST["password"]; // connection to database $user = "student"; $dbpassword = "<PASSWORD>"; $dbh = new PDO('mysql:host=localhost;dbname=Myaddress',$user,$dbpassword); if($username=="Wahid" && $userPassword=="<PASSWORD>"){ header("location:profile.php"); } else{ echo " username or password inccorrect"; } } else{ echo " please first Login"; } header("location:profile.php"); } else{ echo "Incorrect username or password !"; } } include("template/footer.php"); ?><file_sep>/view/list_users_view.php <table class="table table-hover"> <thead> <tr> <th>ID</th> <th>Last Name</th> <th>Name</th> <th>Telephone</th> <th>Email Adress</th> <th>Detail</th> <th>Delete</th> <th>Edit</th> </tr> </thead> <tbody> <?php foreach($users as $user) {?> <tr> <td><?=$user['user_id']?></td> <td><?=$user['nom']?></td> <td><?=$user['prenom']?></td> <td><?=$user['telephone']?></td> <td><?=$user['email']?></td> <td><a href="detail_user.php?id=<?=$user['user_id']?>">voir le detail..</a></td> <td><a href="delete_user.php?id=<?=$user['user_id']?>" onClick="return confirm('Are you sure to delete this recrod?');"><i class="fas fa-trash"></i></a></td> <td><a href="update_user.php?id=<?=$user['user_id']?>"><i class="far fa-edit"></i></a></td> </tr> <?php } ?> </tbody> </table> <a href="add_user.php">ajouter un Utilisateur </a> <file_sep>/delete_user.php <?php // MySQL == un serveur de baseSSSSSSSS de données ini_set('display_errors', 1); // Enregistrer les erreurs dans un fichier de log ini_set('log_errors', 1); // Nom du fichier qui enregistre les logs (attention aux droits à l'écriture) ini_set('error_log', dirname(__file__) . '/log_error_php.txt'); include("model/model.php"); if(isset($_GET['id']) && !empty($_GET['id'])){ $id = filter_var($_GET['id'], FILTER_VALIDATE_INT); $user = deleteUserById($id); } else { header("location: list_users.php"); } ?><file_sep>/add_user.php <?php ini_set('display_errors', 1); ini_set('log_errors', 1); ini_set('error_log', dirname(__file__) . '/log_error_php.txt'); include("template/header.php"); include("model/model.php"); include("view/add_user_view.php"); include("template/footer.php"); ?><file_sep>/view/update_user_view.php <form action = "process_update_user.php" method = "POST"> <table class="user_table" align=center> <tbody> <tr> <td><label>Prénom : </label></td> <td><input type="text" name="fname" value="<?=$user['prenom'];?>"></td> </tr> <tr> <td><label>Nom: </label></td> <td><input type="text" name="lname" value="<?=$user['nom'];?>"></td> </tr> <tr> <td><label>Email_Adress: </label></td> <td><input type="text" name="email" value="<?=$user['email'];?>"></td> </tr> <tr> <td><label>Telephone: </label></td> <td><input type="text" name="telephone" value="<?=$user['telephone'];?>"></td> </tr> <tr> <td><label>Date de naissance: </label></td> <td><input type="date" name="dob" value="<?=$user['date_naissance'];?>"></td> </tr> <tr> <td><label>Sexe: </label> </td> <td> <input type="text" name="gender" value="<?=$user['sexe'];?>"> </td> </tr> <tr> <td><label>Pays: </label> </td> <td><input type="text" name="country" value="<?=$user['pays'];?>"></td> </tr> <tr> <td><label>Mot de Passe: </label> </td> <td><input type="password" name="password" value="<?=$user['password'];?>"></td> </tr> <tr> <td> </td> <td><input type="submit" value="Mise ajour"></td> </tr> </tbody> </table> </form><file_sep>/list_users.php <?php ini_set('display_errors', 1); ini_set('log_errors', 1); ini_set('error_log', dirname(__file__) . '/log_error_php.txt'); include("template/header.php"); //1. make the connection with model : like db connection include("model/model.php"); // 2 analyze the user querry if needed analyze NTU //3 request the data necessary model $users = getAllUsers(); // request for the best view , or the best template like display the data from db include("view/list_users_view.php"); include("template/footer.php"); ?> <file_sep>/detail_user.php <?php ini_set('display_errors', 1); ini_set('log_errors', 1); ini_set('error_log', dirname(__file__) . '/log_error_php.txt'); include("template/header.php"); // prendre conaissance de model include("model/model.php"); // analyze the url filter NTU if(isset($_GET['id']) && !empty($_GET['id'])){ $id = filter_var($_GET['id'], FILTER_VALIDATE_INT); $user = getUserDeteilById($id); } else { header("location: list_users.php"); } include("view/detail_user_view.php"); include("template/footer.php"); ?><file_sep>/process_update_user.php <?php //active_error(); ini_set('display_errors', 1); ini_set('log_errors', 1); include("model/model.php"); if(isset($_POST['id']) && !empty($_POST['id'])){ //... vérifier si tout est bon $id = filter_var($_POST['id'], FILTER_VALIDATE_INT); $last_name = filter_var($_POST['nom'], FILTER_SANITIZE_STRING); $first_name = filter_var($_POST['prenom'], FILTER_SANITIZE_STRING); $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); $telephone = filter_var($_POST['telephone'], FILTER_SANITIZE_NUMBER_INT); $date = filter_var($_POST['date_naissance'], FILTER_SANITIZE_STRING); $gender = filter_var($_POST['sexe'], FILTER_SANITIZE_STRING); $country = filter_var($_POST['pays'], FILTER_SANITIZE_STRING); $password = filter_var($_POST['password'], FILTER_SANITIZE_STRING); updateUserById($id,$last_name,$first_name,$email,$telephone ,$date ,$gender,$country,$password); echo "a record has been succesfully updated "; } else { echo "Could not update an error has been accoured !"; header("location: list_users.php"); } include("template/header.php"); include("view/update_user_view.php"); include("template/footer.php"); ?><file_sep>/view/detail_address_view.php <div class="row"> <div class="col-md-8"> <h1><?=$address['nom'] ?> </h1> <h3><?=$address['full_name'] ?> </h3> <?=$address['detail'] ?> </div> <div class="col-md-4"> <p> <?=$address['address'] ?><br/> <?=$address['code_postal'] ?> <br/> <?=$address['city'] ?> <br/> <?=$address['telephone'] ?> </p> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d5568.438288309018!2d4.8342390658865995!3d45.74675244335552!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47f4ea47c9eebb5b%3A0x37d26059298c7310!2s40+Rue+Bancel%2C+69007+Lyon!5e0!3m2!1sen!2sfr!4v1544696509993" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe> </div> </div><file_sep>/view/list_address_view.php <table class="table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Telephone</th> <th>Address</th> <th>Code Postal</th> <th>City</th> <th>Detail</th> </tr> </thead> <tbody> <?php foreach($addresses as $address){ ?> <tr> <td><?=$address['id'] ?></td> <td><?=$address['nom'] ?></td> <td><?=$address['telephone'] ?></td> <td><?=$address['address'] ?></td> <td><?=$address['code_postal'] ?></td> <td><?=$address['city'] ?></td> <td><a href="address_detail.php?add_id=<?=$address['id']?>">voir le detail..</a></td> </tr> <?php } ?> </tbody> </table> <file_sep>/address_detail.php <?php ini_set('display_errors', 1); ini_set('log_errors', 1); ini_set('error_log', dirname(__file__) . '/log_error_php.txt'); include("template/header.php"); // prendre conaissance de model include("model/model.php"); // analyze the url filter NTU if(isset($_GET['add_id']) && !empty($_GET['add_id'])){ $id = filter_var($_GET['add_id'], FILTER_VALIDATE_INT); $address = get_address_by_id($id); } else { header("location: list_users.php"); } include("view/detail_address_view.php"); include("template/footer.php"); ?><file_sep>/model/model.php <?php function activeError(){ // MySQL == un serveur de baseSSSSSSSS de données ini_set('display_errors', 1); // Enregistrer les erreurs dans un fichier de log ini_set('log_errors', 1); // Nom du fichier qui enregistre les logs (attention aux droits à l'écriture) ini_set('error_log', dirname(__file__) . '/log_error_php.txt'); return activeError(); } function connectDB(){ $servername = "mysql:host=localhost;dbname=Myaddress"; $username = "student"; $password = "<PASSWORD>"; $pdo = new PDO($servername,$username,$password); $pdo->query("SET NAMES 'UTF8'"); return $pdo; } // function that dispalys all users to web browser function getAllUsers(){ // connection to DB $pdo = connectDB(); // preparation request en text $sql_data = "select * from Users"; // prepare the request $statement = $pdo->prepare($sql_data); $statement->execute(); $results=$statement->fetchAll(); $pdo=null; return $results; } // A function that displays un specific user to borwser function getUserDeteilById($id){ $pdo = connectDB(); // preparation request from sql in text $sql = "SELECT user_id, prenom, expediteur, description, address, code_postal, city FROM Users INNER jOIN Courriers ON Courriers.id_user = Users.user_id INNER JOIN Address ON Address.id = Users.address_id WHERE user_id=:id;"; // transform in right $statement = $pdo->prepare($sql); // bindValue $statement->bindValue(':id',$id, PDO::PARAM_INT); // execution $statement->execute(); // fecth all $user = $statement->fetch(); $pdo = null; return $user; } // a function that delets a specific user by it's ID function deleteUserById($id){ $pdo = connectDB(); $sql = "DELETE FROM Users WHERE user_id=:id;"; $statement = $pdo->prepare($sql); $statement->bindValue(':id',$id, PDO::PARAM_INT); //you need to use : bindvalue ;) $statement->execute(); $pdo=null; } function addUser($last_name,$first_name,$email,$telephone,$date,$gender,$country,$password){ //1 connected to db $pdo = connectDB(); //2. build sql query as text $sql = "INSERT INTO Users (nom, prenom, email, telephone, date_naissance, sexe, pays, password) VALUES (:nom, :prenom, :email, :telephone, :date_naissance, :sexe, :pays, :password);"; //3./ prepare query //4./ bindValue //5. execute $statement = $pdo->prepare($sql); $statement->bindValue(':id', $id); $statement->bindValue(':nom',$last_name); $statement->bindValue(':prenom',$first_name); $statement->bindValue(':email',$email); $statement->bindValue(':telephone',$telephone); $statement->bindValue(':date_naissance',$date); $statement->bindValue(':sexe',$gender); $statement->bindValue(':pays',$country); $statement->bindValue(':password',$password); $statement->execute(); } function change_date($birth_date){ $date = new DateTime($birth_date); //$date->format('Y-m-d'); return $date->format('Y-m-d'); } // for updating a user record function getUserById($id){ $pdo = connectDB(); $sql = "SELECT * FROM Users WHERE user_id=:id;"; $statement = $pdo->prepare($sql); $statement->bindValue(':id',$id, PDO::PARAM_INT); $statement->execute(); $user = $statement->fetch(); return $user; } function updateUserById($id,$name,$lName,$email,$telephone,$dateOfBirth,$gender,$country,$password){ $pdo = connectDB(); $sql = "UPDATE Users SET user_id='".$id."',prenom='".$name."',nom='".$lName."',email='".$email."', telephone='".$telephone."',date_naissance='".$dateOfBirth."',sexe='".$gender."', pays='".$country."',password='".$<PASSWORD>."'; WHERE user_id=:id;"; $statement = $pdo->prepare($sql); $statement->bindValue(':id',$id, PDO::PARAM_INT); $statement->bindValue(':prenom',$name); $statement->bindValue(':nom',$lName); $statement->bindValue(':email',$email); $statement->bindValue(':telephone',$telephone); $statement->bindValue(':date_naissance',$dateOfBirth); $statement->bindValue(':sexe',$gender); $statement->bindValue(':pays',$country); $statement->bindValue(':password',$password); // $statement->bindValue(':name',$name); $statement->execute(); $user = $statement->fetch(); return $user; } function get_all_address(){ $pdo = connectDB(); $sql = "SELECT * FROM Address;"; $statement = $pdo->prepare($sql); $statement->execute(); $results = $statement->fetchAll(); return $results; } function get_address_by_id($id){ $pdo = connectDB(); $sql = "SELECT * FROM Address WHERE id = :id;"; $statement = $pdo->prepare($sql); $statement->bindValue(':id',$id, PDO::PARAM_INT); $statement->execute(); $result = $statement->fetch(); return $result; } ?>
04fd9a76e969c0c7d6ef4778a179b81b24a2e3da
[ "PHP" ]
15
PHP
wahidAmini/addressMVC
d2aa48d002655305e391c302cf2f20abdd877825
fb8fc9a1e7ebd721a7d9ad657e9c165a326cd8bd
refs/heads/master
<repo_name>roybass/raa<file_sep>/src/component/arrow-pagination.js import React from 'react'; import Button from '@material-ui/core/Button'; import ChevronLeft from '@material-ui/icons/ChevronLeft'; import ChevronRight from '@material-ui/icons/ChevronRight'; import Toolbar from '@material-ui/core/Toolbar'; const ArrowsPagination = ({ page, perPage, total, setPage }) => { const nbPages = Math.ceil(total / perPage) || 1; return ( nbPages > 1 && <Toolbar> <span style={{margin: 'auto'}}> {page > 1 && <Button key="prev" onClick={() => setPage(page - 1)}> <ChevronLeft /> Prev </Button> } {page !== nbPages && <Button key="next" onClick={() => setPage(page + 1)}> Next <ChevronRight /> </Button> } </span> </Toolbar> ); }; export default ArrowsPagination; <file_sep>/src/generator/edit.js import React from 'react'; import { Edit, SimpleForm, TabbedForm, FormTab } from 'react-admin'; import generateInput from './input'; import breakToTabs from './tabs'; function generateEdit(editDef) { if (!editDef) { return editDef; } const tabs = breakToTabs(editDef.inputs); if (tabs) { return (props) => ( <Edit title={editDef.title} {...props}> <TabbedForm> {tabs.map(tab => ( <FormTab label={tab.label}> {tab.inputs.map((input) => generateInput(input))} </FormTab> ))} </TabbedForm> </Edit> ) } else { return (props) => ( <Edit title={editDef.title} {...props}> <SimpleForm> {editDef.inputs.map((input) => generateInput(input))} </SimpleForm> </Edit> ) } } export default generateEdit; <file_sep>/src/generator/cards.js import React from 'react'; import {List} from 'react-admin'; import generateField from './field'; import generateFilters from './filters'; import generateBulkActionButtons from '../generator/bulk-action-buttons'; import ArrowsPagination from '../component/arrow-pagination'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import {EField} from "../meta/consts"; const cardStyle = { width: 300, minHeight: 300, margin: '0.5em', display: 'inline-block', verticalAlign: 'top', }; const contentStyle = { paddingTop: "5px", paddingBottom: "5px" } const CardGrid = (props) => { const {ids, data, basePath, listDef} = props; const bgField = listDef.fields.find(f => f.type === EField.ImageField); const fieldsToRender = listDef.fields.filter(f => f.type !== EField.ImageField); console.log("Card props ", props); return ( <div style={{margin: '1em'}}> {ids.map(id => <Card key={id} style={{ ...cardStyle, background: bgField ? 'url(' + data[id][bgField.source] + ') no-repeat' : '', backgroundSize: '100% 100%', }}> {fieldsToRender.map((field) => <CardContent style={contentStyle}> {generateField({...field, record: data[id], basePath: basePath}, 'list')} </CardContent> )} </Card> )} </div> ) }; CardGrid.defaultProps = { data: {}, ids: [], }; function generateGrid(listDef, filtersDef) { if (!listDef) { return listDef; } return (props) => ( <List key='list' title={listDef.title} bulkActionButtons={generateBulkActionButtons(listDef)} {...props} filters={generateFilters(filtersDef)} pagination={<ArrowsPagination/>}> <CardGrid listDef={listDef}/> </List> ) } export default generateGrid; <file_sep>/src/component/icon-select.js import React from 'react'; import * as icons from '@material-ui/icons'; import { SelectInput } from 'react-admin'; import generateIcon from '../generator/icon'; const iconNames = Object.keys(icons); const choices = iconNames.map(i => { return { id: i, name: i, key: i }; }); const optionRenderer = choice => (<span>{generateIcon(choice.name)} {choice.name}</span>); const IconSelect = ({ className, ...rest }) => ( <SelectInput translateChoice={false} className={className} {...rest} choices={choices} optionText={optionRenderer} /> ); export default IconSelect; <file_sep>/src/component/url-field-ex.js import React from 'react'; import PropTypes from 'prop-types'; import get from 'lodash/get'; const UrlFieldEx = ({ className, source, transform, record = {}, ...rest }) => ( <a className={className} href={get(record, source)} {...rest} > {transform ? transform(get(record, source)) : get(record, source)} </a> ); UrlFieldEx.propTypes = { addLabel: PropTypes.bool, basePath: PropTypes.string, className: PropTypes.string, cellClassName: PropTypes.string, headerClassName: PropTypes.string, label: PropTypes.string, record: PropTypes.object, sortBy: PropTypes.string, source: PropTypes.string.isRequired, }; UrlFieldEx.defaultProps = { addLabel: true, }; export default UrlFieldEx; <file_sep>/src/api/localdb.js /** * Super-simple LocalStorage DB */ class LocalDB { constructor() { this.db = {}; this.id = 0; this.readFromStorage(); } writeToStorage() { window.localStorage.setItem('raa.db', JSON.stringify(this.db)); window.localStorage.setItem('raa.db.lastId', this.id); } readFromStorage() { this.db = JSON.parse(window.localStorage.getItem('raa.db')) || {}; this.id = JSON.parse(window.localStorage.getItem('raa.db.lastId')) || 0; } getList(resource) { if (!this.db[resource]) { return { data: [], total: 0 }; } const data = Object.values(this.db[resource]); return { data, total: data.length }; } getOne(resource, id) { if (!this.db[resource]) { return { data: null }; } const item = this.db[resource][id]; return { data: item }; } save(resource, obj) { if (!obj.id) { obj.id = this.id++; } if (!this.db[resource]) { this.db[resource] = {}; } this.db[resource][obj.id] = obj; this.writeToStorage(); return { data: obj }; } deleteOne(resource, id) { const data = this.db[resource][id]; delete this.db[resource][id]; this.writeToStorage(); return { data }; } deleteMany(resource, ids) { for (let id of ids) { delete this.db[resource][id]; } this.writeToStorage(); return { data: ids }; } } export default new LocalDB(); <file_sep>/src/component/avatar.js import React from 'react'; import {TextInput} from 'react-admin'; import {Avatar as MuiAvatar} from '@material-ui/core'; import get from 'lodash/get'; export const AvatarField = (props) => { return (<MuiAvatar src={get(props.record, props.source)} {...props}/>); }; export const AvatarInput = (props) => { console.log("Avatar props = ", props); return (<TextInput {...props}/>); }<file_sep>/src/dynamic-resource.js import { EField, EType, EVisibility } from './meta/consts'; import { required } from 'react-admin'; function capitalize(str) { if (!str) { return; } return str.charAt(0).toUpperCase() + str.slice(1); } function convertChoices(choices) { return choices.map(choice => { if (choice.hasOwnProperty('id')) { return choice; } return { id: choice, name: choice }; }); } function entityToModel(entity) { if (entity.actions) { entity.actions.forEach(action => { if (!action.inputs) { action.inputs = []; return; } action.inputs = action.inputs.map(input => convertToInput(input, entity.resourceName)); } ) } const operations = new Set(entity.operations || ['edit', 'create', 'list']); if (entity.editable === false) { const fields = entity.fields .filter(f => f.hidden !== true) .map(f => { f.readOnly = true; return f; }); return { readOnly: true, name: entity.resourceName, icon: entity.icon, listType: entity.listType || 'list', list: !operations.has('list') ? null : { readOnly: true, title: entity.title, actions: entity.actions || [], fields: convertToFields(fields, entity.resourceName, EVisibility.list) .concat([{ type: EField.ShowButton, label: "View" }]) }, show: { title: "View " + entity.title, fields: convertToFields(fields, entity.resourceName, EVisibility.show) }, filters: { fields: convertToFilterInputs(fields, entity.resourceName) } }; } const fields = entity.fields.filter(f => f.hidden !== true); let convertedFields = convertToFields(fields, entity.resourceName, EVisibility.list); if (operations.has('edit')) { convertedFields = convertedFields.concat([{ type: EField.EditButton }]); } return { name: entity.resourceName, icon: entity.icon, listType: entity.listType || 'list', list: !operations.has('list') ? null : { readOnly: false, title: entity.title, fields: convertedFields, actions: entity.actions || [] }, filters: { fields: convertToFilterInputs(fields, entity.resourceName, EVisibility.filter) }, edit: !operations.has('edit') ? null : { title: "Edit " + entity.title, inputs: convertToInputs(entity.fields, entity.resourceName, EVisibility.edit) }, create: !operations.has('create') ? null : { title: "Create New " + entity.title, inputs: convertToInputs(entity.fields, entity.resourceName, EVisibility.create) }, show: { title: "View " + entity.title, fields: convertToFields(fields, entity.resourceName, EVisibility.show) } } } function convertToFields(fieldDataArr, entityName, visibility) { if (!fieldDataArr) { return []; } return fieldDataArr .filter(item => !item.visibility || item.visibility.indexOf(visibility) !== -1) .map(i => convertToField(i, entityName)); } function convertToField(fieldData, entityName) { const rest = Object.assign({}, fieldData); delete rest.name; delete rest.type; if (!rest.label) { rest.label = capitalize(rest.name); } if (rest.display) { rest.display = convertToField(rest.display, entityName + "_" + fieldData.name); } if (rest.fields) { rest.fields = rest.fields.map(i => convertToField(i, entityName + "_" + fieldData.name)); } if (rest.choices) { rest.choices = convertChoices(rest.choices); } if (!rest.readOnly && rest.required === true) { rest.validate = [required()]; } if (!rest.className && entityName !== undefined) { //rest.className = entityName + '_' + fieldData.name; } return { source: fieldData.name, type: EType[fieldData.type.toLowerCase()].field, ...rest }; } function convertToInputs(fieldDataArr, entityName, visibility) { if (!fieldDataArr) { return []; } return fieldDataArr .filter(item => EType[item.type.toLowerCase()].input !== null) .filter(item => visibility === EVisibility.edit || !item.readOnly) .filter(item => !item.visibility || item.visibility.indexOf(visibility) !== -1) .map(i => convertToInput(i, entityName)); } function convertToInput(fieldData, entityName) { if (fieldData.type.toLowerCase() === "referencemany") { return convertToField(fieldData, entityName); } const rest = Object.assign({}, fieldData); delete rest.name; delete rest.type; if (!rest.label) { rest.label = capitalize(rest.name); } if (rest.display) { rest.display = convertToInput(rest.display, entityName + "_" + fieldData.name); } if (rest.fields) { rest.fields = rest.fields.map(i => convertToInput(i, entityName + "_" + fieldData.name)); } if (rest.choices) { rest.choices = convertChoices(rest.choices); } if (!rest.readOnly && rest.required === true) { rest.validate = [required()]; } if (!rest.className && entityName !== undefined) { //rest.className = entityName + '_' + fieldData.name; } return { source: fieldData.name, type: EType[fieldData.type.toLowerCase()].input, ...rest }; } function convertToFilterInputs(fieldDataArr, visibility) { if (!fieldDataArr) { return []; } return fieldDataArr .filter(item => EType[item.type.toLowerCase()].filter !== null) .filter(item => !item.visibility || item.visibility.indexOf(visibility) !== -1) .map(convertToFilterInput); } function convertToFilterInput(fieldData) { const rest = Object.assign({}, fieldData); delete rest.name; delete rest.type; delete rest.readOnly; if (!rest.label) { rest.label = capitalize(rest.name); } if (rest.display) { rest.display = convertToInput(rest.display); } if (rest.choices) { rest.choices = convertChoices(rest.choices); } return { source: fieldData.name, type: EType[fieldData.type.toLowerCase()].filter, ...rest }; } class DynamicResources { constructor() { this.updateListeners = []; this.key = 0; this.assignKeys(this.resources); } getResources(model) { // Place the actions inside entities, for simpler processing if (model.actions) { model.actions.forEach(action => { const entityName = action.resource; const entity = model.data.find(e => e.resourceName === entityName); if (!entity.actions) { entity.actions = []; } entity.actions.push(action); entity.fields.forEach(field => { if (field.type === "action" && field.action === action.id) { field.action = action; field.visibility = field.visibility || ['list']; } }) }) } const resources = model.data.map(entityToModel); this.assignKeys(resources); console.log('resources ', resources); return resources; } assignKeys(obj) { if (!obj) { return; } if (typeof obj !== 'object') { return; } if (!Array.isArray(obj)) { obj.key = this.key++; } const keys = Object.keys(obj); for (let key of keys) { this.assignKeys(obj[key]); } } } export default new DynamicResources(); <file_sep>/src/component/option-renderer.js import React from 'react'; import generateIcon from '../generator/icon'; const style = { verticalAlign: 'middle' }; const optionRenderer = choice => { if (choice.name && choice.icon) { return (<span>{generateIcon(choice.icon, {style})} <span>{choice.name}</span></span>); } if (choice.icon) { return (<span>{generateIcon(choice.icon, {style})}</span>); } const name = choice.name || ""; console.log("name = ", choice); return (<span>{name}</span>); }; export default optionRenderer; <file_sep>/src/dashboard/export-model-action.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Button from '@material-ui/core/Button'; import { showNotification } from 'react-admin'; import fileDownload from 'react-file-download'; import { push } from 'react-router-redux'; import mustache from 'mustache'; import localDB from '../api/localdb'; const template = ` <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"> <meta name="theme-color" content="#000000"> <link rel="shortcut icon" href="http://static-test.outbrain.com/raa/favicon.ico"> <title>{{{title}}}</title> <link href="http://static-test.outbrain.com/raa/static/css/main.css" rel="stylesheet"> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <script> window.raHide = true; window.raTitle = '{{{title}}}' // You can change this title. window.raModelUrl = undefined; // Place a URL here to read the model from. window.raModel = {{{model}}} ; </script> <script type="text/javascript" src="http://static-test.outbrain.com/raa/static/js/main.js"></script> </body> </html> `; class ExportAppButton extends Component { constructor(props) { super(props); this.props = props; } handleClick = () => { this.props.showNotification('Exporting ' + this.props.resource); const view = { model: JSON.stringify(localDB.getList(this.props.resource), null, 2), title: 'Management App' }; fileDownload(mustache.render(template, view), this.props.resource + '.html'); }; render() { return <Button onClick={this.handleClick}>Export App File</Button>; } } ExportAppButton.propTypes = { push: PropTypes.func, record: PropTypes.object, showNotification: PropTypes.func, }; export default connect(null, { showNotification, push, })(ExportAppButton); <file_sep>/src/meta/consts.js export const EField = { TextField: "TextField", ChipField: "ChipField", JsonField: "JsonField", EmailField: "EmailField", ReferenceField: "ReferenceField", EditButton: "EditButton", ShowButton: "ShowButton", BooleanField: "BooleanField", DateField: "DateField", NumberField: "NumberField", IconField: "IconField", SelectField: "SelectField", FunctionField: "FunctionField", UrlField: "UrlField", ImageField: "ImageField", ArrayField: "ArrayField", ActionField: "ActionField", ReferenceMany: "ReferenceMany", AvatarField: "AvatarField" }; export const EInput = { DisabledInput: "DisabledInput", BooleanInput: "BooleanInput", TextInput: "TextInput", NumberInput: "NumberInput", LongTextInput: "LongTextInput", SelectInput: "SelectInput", DateInput: "DateInput", AutocompleteInput: "AutocompleteInput", ImageInput: "ImageInput", IconInput: "IconInput", ReferenceInput: "ReferenceInput", ArrayInput: "ArrayInput", ActionField: "ActionField", ReferenceMany: "ReferenceMany", JsonInput: "JsonInput", AvatarInput: "AvatarInput" }; export const EVisibility = { list: 'list', edit: 'edit', create: 'create', show: 'show', filter: 'filter' }; export const EType = { string: { field: EField.TextField, input: EInput.TextInput, filter: EInput.TextInput }, number: { field: EField.NumberField, input: EInput.NumberInput, filter: EInput.NumberInput }, boolean: { field: EField.BooleanField, input: EInput.BooleanInput, filter: EInput.BooleanInput }, text: { field: EField.TextField, input: EInput.LongTextInput, filter: EInput.LongTextInput }, date: { field: EField.DateField, input: EInput.DateInput, filter: EInput.DateInput }, url: { field: EField.UrlField, input: EInput.TextInput, filter: EInput.TextInput }, chip: { field: EField.ChipField, input: EInput.TextInput, filter: EInput.TextInput }, select: { field: EField.TextField, input: EInput.SelectInput, filter: EInput.SelectInput }, enum: { field: EField.SelectField, input: EInput.SelectInput, filter: EInput.SelectInput }, image: { field: EField.ImageField, input: EInput.ImageInput, filter: null }, icon: { field: EField.IconField, input: EInput.IconInput, filter: EInput.IconInput }, reference: { field: EField.ReferenceField, input: EInput.ReferenceInput, filter: EInput.TextInput }, list: { field: EField.ArrayField, input: EInput.ArrayInput, filter: null }, referencemany: { field: EField.ReferenceMany, input: EInput.ReferenceMany, filter: null }, action: { field: EField.ActionField, input: EInput.ActionField, filter: null }, function: { field: EField.FunctionField, input: EInput.TextInput, filter: EInput.TextInput }, json: { field: EField.JsonField, input: EInput.JsonInput, filter: EInput.TextInput }, avatar: { field: EField.AvatarField, input: EInput.AvatarInput, filter: null } }; <file_sep>/src/generator/input.js import React from 'react'; import { EInput } from '../meta/consts'; import generateField from './field'; import IconSelect from '../component/icon-select'; import optionRenderer from '../component/option-renderer'; import ActionButton from '../component/action-button'; import { JsonInput } from '../component/jsonView' import { AvatarInput } from '../component/avatar' import { ArrayInput, AutocompleteInput, BooleanInput, DateInput, DisabledInput, LongTextInput, NumberInput, ReferenceInput, SelectInput, SimpleFormIterator, TextInput } from 'react-admin'; function generateInput(input) { const params = Object.assign({}, input); delete params.type; delete params.rangeStyles; if (input.readOnly && input.type !== EInput.ReferenceMany) { return (<DisabledInput {...params}/>); } switch (input.type) { case EInput.DisabledInput: return (<DisabledInput {...params}/>); case EInput.BooleanInput: return (<BooleanInput {...params}/>); case EInput.TextInput: return (<TextInput {...params}/>); case EInput.NumberInput: return (<NumberInput {...params}/>); case EInput.JsonInput: return (<JsonInput {...params}/>); case EInput.LongTextInput: return (<LongTextInput {...params}/>); case EInput.SelectInput: return (<SelectInput {...params} optionText={optionRenderer} translateChoice={false}/>); case EInput.DateInput: return (<DateInput {...params}/>); case EInput.AutocompleteInput: return (<AutocompleteInput {...params}/>); case EInput.IconInput: return (<IconSelect {...params}/>); case EInput.ImageInput: return (<LongTextInput {...params}/>); case EInput.ReferenceInput: return ( <ReferenceInput {...params}> {generateInput(params.display)} </ReferenceInput>); case EInput.ArrayInput: return ( <ArrayInput {...params}> <SimpleFormIterator> {input.fields.map(generateInput)} </SimpleFormIterator> </ArrayInput> ); case EInput.ReferenceMany: return generateField(input); case EInput.ActionField: return (<ActionButton {...params}/>); case EInput.AvatarInput: return (<AvatarInput {...params}/>); default: throw new Error("Unknown input type " + input.type); } } export default generateInput; <file_sep>/src/generator/rangestyles.js import React from 'react'; import { withStyles } from '@material-ui/core/styles'; import classnames from 'classnames'; function createStylesFromRanges(ranges) { if (!ranges) { return; } const result = {}; for (let i = 0; i < ranges.length; i++) { result['range_' + i] = ranges[i].style; } return result; } function isInRange(range, value) { if (!range) { return false; } if (range.hasOwnProperty('value')) { const regex = new RegExp(range.value); return regex.test(value); } if (range.hasOwnProperty('values') && range.values.length > 0) { for (let str of range.values) { const regex = new RegExp(str); if (regex.test(value)) { return true; } } return false; } if (range.hasOwnProperty('range') && range.range.length === 2) { const min = range.range[0]; const max = range.range[1]; if (min !== null && value <= min) { return false; } if (max !== null && value > max) { return false; } return true; } return false; } function generateClassSelector(classes, ranges, value) { const selector = {}; for (let i = 0; i < ranges.length; i++) { const classname = "range_" + i; selector[classes[classname]] = isInRange(ranges[i], value); } return selector; } function withRangeStyles(ranges) { if (!ranges) { return (WrappedComponent => WrappedComponent); // When no styles provided, provide an identify function. (No change in the original Component } return ((WrappedComponent) => { const styles = createStylesFromRanges(ranges); const wrapper = withStyles(styles)( ({ classes, ...props }) => ( <WrappedComponent translateChoice={false} className={classnames(generateClassSelector(classes, ranges, props.record[props.source]))} {...props} /> )); wrapper.defaultProps = WrappedComponent.defaultProps; return wrapper; }); } export default withRangeStyles; <file_sep>/src/api/local-dataprovider.js /** * Created by rbass on 8/6/18. * This data provider is supposed to bridge gap between typical server apis without pagination, sorting and filter, * and a client application with all these features. It does so by doing these actions on the client side. */ import { CREATE, DELETE, DELETE_MANY, GET_LIST, GET_MANY, GET_MANY_REFERENCE, GET_ONE, UPDATE, UPDATE_MANY } from 'react-admin'; import localDB from './localdb'; class LocalDataProvider { constructor() { this.updateListeners = []; } onUpdate(f) { if (typeof f === "function") { this.updateListeners.push(f); } } update(resource, value) { for (let func of this.updateListeners) { func(resource, value); } } withUpdate(resource, value) { this.update(resource, value); return value; } processRequest(type, resource, params) { console.log(type, ' ', resource, ' ', params); switch (type) { case GET_LIST: return localDB.getList(resource); case GET_ONE: return localDB.getOne(resource, params.id); case CREATE: return this.withUpdate(resource, localDB.save(resource, params.data)); case UPDATE: return this.withUpdate(resource, localDB.save(resource, params.data)); case UPDATE_MANY: throw new Error('Unsupported Operation ' + type); case DELETE: return this.withUpdate(resource, localDB.deleteOne(resource, params.id)); case DELETE_MANY: return this.withUpdate(resource, localDB.deleteMany(resource, params.ids)); case GET_MANY: const filteredList = localDB.getList(resource).data.filter((item) => params.ids.indexOf(item.id) >= 0); return { data: filteredList }; case GET_MANY_REFERENCE: const refList = localDB.getList(resource).data.filter((item) => item[params.target] === params.id); return { data: refList, total: refList.length }; default: throw new Error(`Unsupported Data Provider request type ${type}`); } } } export default new LocalDataProvider(); <file_sep>/src/generator/create.js import React from 'react'; import { Create, SimpleForm, TabbedForm, FormTab } from 'react-admin'; import generateInput from './input'; import breakToTabs from './tabs'; function generateCreate(createDef) { if (!createDef) { return createDef; } const tabs = breakToTabs(createDef.inputs); if (tabs) { return (props) => ( <Create title={createDef.title} {...props}> <TabbedForm redirect="list"> {tabs.map(tab => ( <FormTab label={tab.label}> {tab.inputs.map((input) => generateInput(input))} </FormTab> ))} </TabbedForm> </Create> ) } else { return (props) => ( <Create title={createDef.title} {...props}> <SimpleForm redirect="list"> {createDef.inputs.map((input) => generateInput(input))} </SimpleForm> </Create> ) } } export default generateCreate; <file_sep>/src/api/example-model.js const DyplomaModel = { authentication: { url: "http://dyploma.outbrain.com:8080/DyPloMa/auth" }, actions: [ { id: "restart", title: "Restart", resource: 'service', icon: "BatteryCharging80", confirm: "Are you should you want to restart {{ids.length}} services?", endpoint: { url: "http://localhost:3000/service/show/ids={{ids}}", method: 'POST', headers: { CUSTOM: 'HELLO' } }, inputs: [ { name: "comment", label: "Comment", required: true, type: "string" } ] } ], data: [ { title: "Service", resourceName: "service", icon: "BatteryCharging60", endpoint: "http://dyploma.outbrain.com:8080/DyPloMa/api/v1/services", customEndpoints: { baseUrl: "http://dyploma.outbrain.com:8080/DyPloMa/api/v1", list: { url: "/services/find/limit/{{limit}}/offset/{{offset}}" }, get: { url: "/services/{{id}}", method: "GET" }, create: { url: "/services/", method: "POST" }, update: { url: "/services/", method: "PUT" }, getBy: { name: { url: "/services/name/like/{{name}}" }, owner: { url: "/services/owner/{{owner}}" } } }, operations: ['edit', 'create', 'list'], fields: [ { name: "id", type: "Number", readOnly: true }, { tab: "Main", name: "name", type: "String", required: true }, { tab: "Main", name: "owner", type: "String", required: true }, { tab: "Main", name: "serviceType", type: "Select", required: true, choices: ["ob1k", "sage", "zemanta"], rangeStyles: [ { style: { color: 'pink' }, values: ['sage', 'zem.*'] }, ] }, { tab: "Advanced", name: "external", type: "Boolean", defaultValue: false, rangeStyles: [ { style: { color: 'LawnGreen' }, value: true } ] }, { tab: "Advanced", name: "antiAffinity", type: "Boolean", defaultValue: false }, { tab: "Advanced", name: "externalPort", label: "External Port", type: "Number", defaultValue: 0 }, { tab: "Advanced", name: "creationTimestamp", type: "Date", readOnly: true }, { name: "restart", type: "action", action: "restart" }, { tab: "Advanced", name: "deployments", label: "Deployments", type: "ReferenceMany", reference: "deployment", readOnly: true, target: "serviceId", display: { name: "name", type: "Chip" } } ] }, { title: "Deployment", resourceName: "deployment", icon: "BatteryCharging20", endpoint: "http://dyploma.outbrain.com:8080/DyPloMa/api/v1/deployments", customEndpoints: { list: { url: "http://dyploma.outbrain.com:8080/DyPloMa/api/v1/deployments/find/limit/{{limit}}/offset/{{offset}}" }, get: { url: "http://dyploma.outbrain.com:8080/DyPloMa/api/v1/deployments/{{id}}", method: "GET" }, create: { url: "http://dyploma.outbrain.com:8080/DyPloMa/api/v1/deployments/", method: "POST" }, update: { url: "http://dyploma.outbrain.com:8080/DyPloMa/api/v1/deployments/", method: "PUT" }, getBy: { serviceId: { url: "http://dyploma.outbrain.com:8080/DyPloMa/api/v1/deployments/service/{{id}}" } } }, editable: false, fields: [ { name: "id", type: "Number", readOnly: true, options: { useGrouping: false } }, { name: "name", type: "String", required: true }, { label: "Environment", name: "environmentId", type: "enum", choices: [ { id: 1, name: 'all' }, { id: 2, name: 'junit' }, { id: 3, name: 'prod' }, { id: 5, name: 'test' }, { id: 6, name: 'sim' }, { id: 8, name: 'simulator' }, { id: 9, name: 'dev' }, { id: 10, name: 'rnd' } ] }, { label: "Cluster", name: "kubeClusterId", type: "enum", choices: [ { id: 2, name: 'nydc1' }, { id: 3, name: 'sadc1c' }, { id: 4, name: 'chidc2c' }, { id: 5, name: 'stg' }, { id: 11, name: 'simulator' }, { id: 12, name: 'test' }, { id: 13, name: 'dev' }, { id: 14, name: 'rnd' } ] }, { name: "artifactId", type: "Reference", reference: "artifact", display: { name: "version", render: (record) => { return record.version + " - " + record.commitMessage }, type: "String" } }, { name: "extraTag", type: "String" }, { name: "external", type: "Boolean", defaultValue: false }, { name: "creationTimestamp", type: "Date", readOnly: true }, { label: "Tags", name: "serviceTags", type: "String", hidden: true }, { name: "serviceId", type: "Reference", reference: "service", display: { name: "name", type: "Select" } } ] }, { title: "Artifact", resourceName: "artifact", endpoint: "http://dyploma.outbrain.com:8080/DyPloMa/api/v1/artifacts", customEndpoints: { list: { url: "http://dyploma.outbrain.com:8080/DyPloMa/api/v1/artifacts/find/limit/{{limit}}/offset/{{offset}}" }, get: { url: "http://dyploma.outbrain.com:8080/DyPloMa/api/v1/artifacts/{{id}}", method: "GET" }, getBy: { serviceId: { url: "http://dyploma.outbrain.com:8080/DyPloMa/api/v1/artifacts/service/{{id}}" } } }, editable: false, fields: [ { name: "id", type: "Number", options: { useGrouping: false } }, { name: "version", type: "String" }, { name: "buildNumber", type: "String", hidden: true }, { name: "kind", type: "String" }, { name: "commitMessage", type: "Text" }, { name: "creationTimestamp", type: "Date" }, { name: "uri", type: "Url" }, { name: "serviceId", type: "Reference", reference: "service", display: { name: "name", type: "String" } } ] } ] }; const BandsModel = { data: [ { title: "Band", resourceName: "band", endpoint: "/band", fields: [ { name: "id", type: "Number", readOnly: true }, { name: "name", type: "String", required: true }, { name: "bio", label: "Biography", type: "Text", placeholder: "Enter band biography here" }, { name: "Icon", type: "icon" }, { name: "comData", type: "json" }, { name: "Avatar", type: "avatar", label: "Avatar" }, { name: "Level", type: "enum", choices: [ { id: 1, name: "Level 1", icon: "LooksOne" }, { id: 2, name: "Level 2", icon: "LooksTwo" }, { id: 3, icon: "Looks3" } ] }, { name: "active", type: "Boolean", defaultValue: true }, { name: "members", type: "List", fields: [ { name: "name", type: "String", required: true }, { name: "part", type: "Select", required: true, choices: ["Vocals", "Drums", "Bass", "Guitar", "Keyboard", "Violin"] } ] }, { label: "Albums", type: "ReferenceMany", reference: "album", target: "band", display: { name: "name", type: "Chip" } } ] }, { title: "Album", resourceName: "album", endpoint: "/album", listType: "cards", fields: [ { name: "id", type: "Number", readOnly: true }, { name: "poster", type: "image" }, { name: "name", type: "String", required: true }, { name: "band", type: "Reference", reference: "band", display: { name: "name", type: "Select", optionText: "name" } }, { name: "publishDate", label: "Publish Date", type: "Date" } ] } ] }; const BumperModel = { "total": 4, "data": [{ "id": 0, "resourceName": "pom", "title": "Pom", "endpoint": "http://dev.bumper.service.nydc1.consul:8080/Bumper/crud", "fields": [{ "name": "id", "label": "Id", "type": "NUMBER", "required": true, "readOnly": true, "hidden": false, "options": { "useGrouping": false } }, { "name": "name", "label": "Name", "type": "STRING", "required": false, "readOnly": false, "hidden": false }, { "name": "type", "label": "Type", "type": "STRING", "required": false, "readOnly": false, "hidden": false }, { "name": "path", "label": "Path", "type": "URL", "required": false, "readOnly": false, "hidden": false, "className": "projectPath" }, { "name": "owner", "label": "Owner", "type": "STRING", "required": false, "readOnly": false, "hidden": false }, { "name": "slug_key", "label": "Slug_key", "type": "STRING", "required": false, "readOnly": false, "hidden": true }, { "name": "project_key", "label": "Project_key", "type": "STRING", "required": false, "readOnly": false, "hidden": true }, { "name": "timestamp", "label": "Timestamp", "type": "DATE", "required": true, "readOnly": false, "hidden": true }, { "name": "dependencys", "label": "Dependencies", "type": "REFERENCEMANY", "required": false, "readOnly": false, "reference": "dependency", "target": "pom", "display": { "name": "name", "type": "Chip", "optionText": "name" }, "hidden": false }], "editable": false }, { "id": 1, "resourceName": "property", "title": "Property", "endpoint": "http://dev.bumper.service.nydc1.consul:8080/Bumper/crud", "fields": [{ "name": "id", "label": "Id", "type": "NUMBER", "required": true, "readOnly": true, "hidden": false, "options": { "useGrouping": false } }, { "name": "name", "label": "Name", "type": "STRING", "required": false, "readOnly": false, "hidden": false }, { "name": "groupId", "label": "GroupId", "type": "STRING", "required": false, "readOnly": false, "hidden": false }, { "name": "owner", "label": "Owner", "type": "STRING", "required": false, "readOnly": false, "hidden": true }, { "name": "timestamp", "label": "Timestamp", "type": "DATE", "required": true, "readOnly": false, "hidden": true }, { "name": "dependencys", "label": "Dependencies", "type": "REFERENCEMANY", "required": false, "readOnly": false, "reference": "dependency", "target": "property", "display": { "name": "name", "type": "Chip", "optionText": "name" }, "hidden": false }], "editable": false }, { "id": 2, "resourceName": "dependency", "title": "Dependency", "endpoint": "http://dev.bumper.service.nydc1.consul:8080/Bumper/crud", "fields": [{ "name": "id", "label": "Id", "type": "NUMBER", "required": true, "readOnly": true, "hidden": false, "options": { "useGrouping": false } }, { "name": "name", "label": "Name", "type": "STRING", "required": false, "readOnly": false, "hidden": false }, { "name": "version", "label": "Version", "type": "STRING", "required": false, "readOnly": false, "hidden": false }, { "name": "property", "label": "Property", "type": "REFERENCE", "required": true, "readOnly": false, "reference": "property", "display": { "name": "name", "type": "Select", "optionText": "name" }, "hidden": false }, { "name": "pom", "label": "Pom", "type": "REFERENCE", "required": true, "readOnly": false, "reference": "pom", "display": { "name": "name", "type": "Select", "optionText": "name" }, "hidden": false }, { "name": "timestamp", "label": "Timestamp", "type": "DATE", "required": true, "readOnly": false, "hidden": false }, { "name": "bumps", "label": "Bumps", "type": "REFERENCEMANY", "required": false, "readOnly": false, "reference": "bump", "target": "dependency", "display": { "name": "id", "type": "Chip", "optionText": "id" }, "hidden": false }, { "name": "requests", "label": "Requests", "type": "REFERENCEMANY", "required": false, "readOnly": false, "reference": "request", "target": "dependency", "display": { "name": "name", "type": "Chip", "optionText": "name" }, "hidden": true }], "editable": false }, { "id": 3, "resourceName": "bump", "title": "Bump", "endpoint": "http://dev.bumper.service.nydc1.consul:8080/Bumper/crud", "fields": [{ "name": "id", "label": "Id", "type": "NUMBER", "required": true, "readOnly": true, "hidden": false, "options": { "useGrouping": false } }, { "name": "property_name", "label": "Property Name", "type": "STRING", "required": false, "readOnly": false, "hidden": false }, { "name": "version", "label": "Version", "type": "STRING", "required": false, "readOnly": false, "hidden": false }, { "name": "dependency", "label": "Dependency", "type": "REFERENCE", "required": true, "readOnly": false, "reference": "dependency", "display": { "name": "name", "type": "Select", "optionText": "name" }, "hidden": false }, { "name": "timestamp", "label": "Timestamp", "type": "DATE", "required": true, "readOnly": false, "hidden": false }, { "name": "requests", "label": "Pull Requests", "type": "LIST", "required": false, "readOnly": false, "reference": "request", "target": "bump", "display": { "name": "name", "type": "Chip", "optionText": "name" }, "hidden": false, "fields": [{ "name": "id", "label": "Id", "type": "NUMBER", "required": true, "readOnly": true, "hidden": false, "options": { "useGrouping": false } }, { "name": "name", "label": "Name", "type": "STRING", "required": false, "readOnly": false, "hidden": false }, { "name": "status", "label": "Status", "type": "STRING", "required": false, "readOnly": false, "hidden": false }, { "name": "pull_request_url", "label": "Pull Request Url", "type": "URL", "required": false, "readOnly": false, "hidden": false, "className": "projectPath" }, { "name": "dependency", "label": "Dependency", "type": "REFERENCE", "required": true, "readOnly": false, "reference": "dependency", "display": { "name": "name", "type": "Select", "optionText": "name" }, "hidden": false }, { "name": "timestamp", "label": "Timestamp", "type": "DATE", "required": true, "readOnly": false, "hidden": false }, { "name": "pull_request_id", "label": "Pull_request_id", "type": "NUMBER", "required": false, "readOnly": false, "hidden": true }] }], "editable": false }], "actions": [{ "resource": "dependency", "actionName": "Bump", "title": "Bump", "icon": "BatteryCharging80", "endpoint": { "url": "http://dev.bumper.service.nydc1.consul:8080/Bumper/crud/dependency/action/Bump?ids={{ids}}", "method": "Post" }, "inputs": [{ "name": "versionToApprove", "label": "VersionToApprove", "type": "TEXT", "required": true }], "editable": true }, { "resource": "property", "actionName": "Bump", "title": "Bump", "icon": "BatteryCharging80", "endpoint": { "url": "http://dev.bumper.service.nydc1.consul:8080/Bumper/crud/property/action/Bump?ids={{ids}}", "method": "Post" }, "inputs": [{ "name": "versionToApprove", "label": "VersionToApprove", "type": "TEXT", "required": true }], "editable": true }], "authentication": { "url": "http://dev.bumper.service.nydc1.consul:8080/Bumper/auth" } }; const TODOs = { data: [ { title: "ToDos", resourceName: "todos", endpoint: "https://jsonplaceholder.typicode.com", fields: [ { name: "id", type: "number", readOnly: true }, { name: "title", type: "string", required: true, }, { name: "completed", type: "boolean", required: true }, { name: "icon", type: "icon" } ] } ] }; const lowercaseWithNoSpace = () => (value) => { const onlyLetters = /^[a-z]+$/.test(value); return onlyLetters ? undefined : 'Lowercase letters only'; }; const MetaModel = { data: [ { title: "Models", resourceName: "model", endpoint: "localstorage", fields: [ { name: "Entities", type: "list", validate: [lowercaseWithNoSpace()], fields: [ { name: "title", type: "string", placeholder: "Display name of the entity", required: true }, { name: "resourceName", type: "string", placeholder: "Entity name (used to refer to this entity)", validate: [lowercaseWithNoSpace()], required: true }, { name: "fields", type: "list", fields: [ { name: "name", type: "string" }, { name: "type", type: "select", choices: ["string", "number", "boolean", "text", "date", "select"] } ] } ] } ] } ] }; const RulesModel = { actions: [ { id: "checkRule", title: "Check now", resource: 'rule', icon: "BatteryCharging80", confirm: "Select source and widget for checking {{ids.length}} rule(s)", endpoint: { url: "http://localhost:3000/check/rules/ids={{ids}}", method: 'POST' }, inputs: [ { name: "sourceId", label: "Source Id", required: true, type: "number" }, { name: "widgetId", label: "Widget Id", required: true, type: "number" } ] }, { id: "checkGroup", title: "Check now", resource: 'group', icon: "BatteryCharging80", confirm: "Select source and widget for checking {{ids.length}} rule(s)", endpoint: { url: "http://localhost:3000/check/group/ids={{ids}}", method: 'POST' }, inputs: [ { name: "sourceId", label: "Source Id", required: true, type: "number" }, { name: "widgetId", label: "Widget Id", required: true, type: "number" } ] } ], data: [ { title: "Rules Group", resourceName: "group", endpoint: "localstorage", fields: [ { name: "id", type: "number", readOnly: true }, { name: "name", type: "string", required: true, }, { name: "rules", label: "Rules", type: "ReferenceMany", reference: "rule", target: "list", display: { name: "name", type: "Chip" } }, { name: "check", label: "check now", type: "action", action: "checkGroup" } ] }, { title: "Rule", resourceName: "rule", endpoint: "localstorage", fields: [ { name: "id", type: "number", readOnly: true }, { name: "parentId", type: "number" }, { name: "name", type: "string", required: true, }, { name: "list", type: "Reference", reference: "group", display: { name: "name", type: "Select", optionText: "name" } }, { tab: "Validations", label: "Combine Operator", name: "combine", type: "select", choices: ["And", "Or"], defaultValue: "And" }, { tab: "Validations", name: "validations", type: "List", fields: [ { name: "settingId", title: "Setting Id", type: "number", required: true }, { name: "operator", type: "select", choices: ["=", ">=", "<=", ">", "<", "is null", "contains", "starts with", "ends with"], required: true }, { name: "value", type: "string" } ] }, { tab: "Actions", label: "Action if true", name: "trueAction", type: "select", choices: ["Alert", "Stop", "Run next rule"] }, { tab: "Actions", label: "Action If false", name: "falseAction", type: "select", choices: ["Alert", "Stop", "Move to next rule"] }, { label: "Check Now", name: "check", type: "action", action: "checkRule" }, ] }, ] }; export { BandsModel, DyplomaModel, BumperModel, TODOs, MetaModel, RulesModel } <file_sep>/src/App.js import React from 'react'; import dynamicResources from './dynamic-resource'; import { Admin, Resource } from 'react-admin'; import generateResource from './generator/resource'; import localdataprovider from './api/local-dataprovider'; import entitydataprovider from './api/entity-dataprovider'; import modelProvider from './api/modelprovider'; import entityOperations from './meta/entity'; import AuthProvider from './api/authProvider'; import { createMuiTheme } from '@material-ui/core/styles'; class App extends React.Component { constructor(props) { super(props); this.hide = window.raHide || false; this.userLocalDB = window.useLocalDB || (window.localStorage.getItem("raa.useLocalDb") === 'true') || false; this.dataprovider = this.userLocalDB ? localdataprovider : entitydataprovider; this.title = window.raTitle || 'React Admin Admin'; this.theme = window.raTheme ? createMuiTheme(window.raTheme) : undefined; this.state = { error: null, isLoaded: false, model: null }; const modelPromise = modelProvider.getModel(); modelPromise.then((model) => { console.log('Resolved model ', model); this.setState({ isLoaded: true, model: model, error: null }); }).catch((err) => { console.log('Error: ', err); this.setState({ isLoaded: false, model: null, error: err.message }) }); } render() { if (this.state.error) { return (<div>Error {JSON.stringify(this.state.error)}</div>); } if (!this.state.isLoaded) { return (<div>Loading...</div>); } return ( <Admin authProvider={AuthProvider.provide()} dataProvider={this.dataprovider.processRequest.bind(this.dataprovider)} title={this.title} theme={this.theme} > {dynamicResources.getResources(this.state.model).map((item) => generateResource(item)) } {this.hide ? (<span/>) : <Resource name='entity' label='Entity' {...entityOperations}/>} </Admin> ) }; } export default App; <file_sep>/src/api/entity-dataprovider.js /** * Created by rbass on 8/6/18. * This data provider is supposed to bridge gap between typical server apis without pagination, sorting and filter, * and a client application with all these features. It does so by doing these actions on the client side. */ import customDataProvider from './customizable-dataprovider'; import localDataProvider from './local-dataprovider'; import modelProvider from './modelprovider'; import { CREATE, DELETE, DELETE_MANY, UPDATE, UPDATE_MANY } from 'react-admin'; class EntityDataProvider { constructor() { this.updateListeners = []; this.entityToDataprovider = {}; this.operationsWithUpdate = [CREATE, UPDATE, UPDATE_MANY, DELETE, DELETE_MANY]; } onUpdate(f) { if (typeof f === "function") { this.updateListeners.push(f); } } update(resource, value) { for (let func of this.updateListeners) { func(resource, value); } } withUpdate(resource, value) { this.update(resource, value); return value; } getProvider(entity) { if (!this.entityToDataprovider[entity.name]) { this.entityToDataprovider[entity.name] = customDataProvider.processRequest; } return this.entityToDataprovider[entity.name]; } processRequest(type, resource, params) { if (resource === 'entity') { return localDataProvider.processRequest(type, resource, params); } return this._getEntity(resource).then(entity => { const dataProvider = this.getProvider(entity); if (this.operationsWithUpdate.indexOf(type) >= 0) { return this.withUpdate(resource, dataProvider(type, resource, params)); } return dataProvider(type, resource, params); }); } _getEntity(resource) { return modelProvider.getModel().then(model => { return model.data.find((entity) => entity.resourceName === resource); } ); } } export default new EntityDataProvider(); <file_sep>/src/generator/bulk-action-buttons.js import React, { Component, Fragment } from 'react'; import { BulkDeleteButton } from 'react-admin'; import ActionButton from '../component/action-button'; class BulkActionButtons extends Component { render() { console.log('props=', this.props); return ( <Fragment> {this.props.actions.map((actionDef) => React.createElement(ActionButton, { action: actionDef, ids: this.props.selectedIds, key: "_action_" + actionDef.title }))} {this.props.readOnly ? <span/> : <BulkDeleteButton {...this.props} />} </Fragment> ); } } function generateBulkActionButtons(listDef) { return React.createElement(BulkActionButtons, { actions: listDef.actions , readOnly: listDef.readOnly}); } export default generateBulkActionButtons; <file_sep>/src/api/customizable-dataprovider.js /** * Created by rbass on 8/6/18. * This data provider is supposed to bridge gap between typical server apis without pagination, sorting and filter, * and a client application with all these features. It does so by doing these actions on the client side. */ import simpleRestProvider from 'ra-data-simple-rest'; import authProvider from './authProvider'; import modelProvider from './modelprovider'; import mustache from 'mustache'; import { CREATE, GET_LIST, GET_MANY, GET_MANY_REFERENCE, GET_ONE, UPDATE } from 'react-admin'; class CustomizableDataProvider { constructor() { this.processRequest = this.processRequest.bind(this); } processRequest(type, resource, params) { // console.log('Processing ', type, resource, params); return this._getEntity(resource).then(entity => { if (entity.customEndpoints) { const endpointDef = this.getCustomEndpoint(type, entity, params); if (endpointDef) { return this.runCustomEndpoint(endpointDef, entity, params); } } return simpleRestProvider(entity.endpoint, authProvider.getHttpClient())(type, resource, params); }); } runCustomEndpoint(endpointDef, entity, params) { const url = this.buildCustomUrl(endpointDef, entity, params); const body = this.getBody(params); const headers = this.getHeaders(); const method = endpointDef.method || "GET"; const client = authProvider.getHttpClient(); return client(url, { method, body, headers }).then(data => { return { data: data.json, total: 1000 }; }); } getBody(params) { return JSON.stringify(params.data); } getHeaders() { return new Headers({ 'Content-Type': 'application/json' }); } buildCustomUrl(endpoint, entity, params) { let view = { limit: this._getLimit(params), offset: this._getOffset(params), id: params.id }; view = Object.assign(view, endpoint.params); const endpointUrl = (entity.customEndpoints.baseUrl || '') + endpoint.url; return mustache.render(endpointUrl, view); } getCustomEndpoint(type, entity, params) { const { customEndpoints } = entity; switch (type) { case GET_LIST: if (params.filter && customEndpoints.getBy) { for (let filterKey in params.filter) { if (params.filter.hasOwnProperty(filterKey) && customEndpoints.getBy.hasOwnProperty(filterKey)) { const by = customEndpoints.getBy[filterKey]; return { url: by.url, method: by.method, params: { [filterKey]: params.filter[filterKey] } } } } } return customEndpoints.list; case GET_ONE: return customEndpoints.get; case UPDATE: return customEndpoints.update; case CREATE: return customEndpoints.create; case GET_MANY: return Object.assign({ params: { offset: 0, limit: 1000 } }, customEndpoints.list); case GET_MANY_REFERENCE: return customEndpoints.getBy ? customEndpoints.getBy[params.target] : null; default: console.log('Operation not supported ', type, entity); return; } } _getLimit(params) { if (params && params.pagination) { return params.pagination.perPage; } } _getOffset(params) { if (params && params.pagination) { return (params.pagination.page - 1) * params.pagination.perPage; } } _getEntity(resource) { return modelProvider.getModel().then(model => { // console.log('data', model, resource); return model.data.find((entity) => entity.resourceName === resource); } ); } } export default new CustomizableDataProvider(); <file_sep>/src/component/action-button.js import React, { Component, Fragment } from 'react'; import { connect } from 'react-redux'; import { isSubmitting, submit } from 'redux-form'; import { Button, fetchEnd, fetchStart, showNotification, SimpleForm } from 'react-admin'; import { Dialog, DialogTitle, DialogContent, DialogActions } from '@material-ui/core'; import IconCancel from '@material-ui/icons/Cancel'; import generateIcon from '../generator/icon'; import endpointRunner from '../api/endpoint-runner'; import generateInput from '../generator/input'; import mustache from 'mustache'; const FORM_NAME = 'action-form'; class ActionButton extends Component { constructor(props) { super(props); this.state = { error: false, showDialog: false }; } handleClick = () => { if (this.props.action.confirm || this.props.action.inputs) { this.setState({ showDialog: true }); } else { this.runAction(); } }; handleCloseClick = () => { this.setState({ showDialog: false }); }; handleSaveClick = () => { const { submit } = this.props; // Trigger a submit of our custom quick create form // This is needed because our modal action buttons are oustide the form submit(FORM_NAME); }; runAction = () => { const { showNotification } = this.props; const { endpoint } = this.props.action; if (endpoint) { const ids = this.props.ids || [this.props.record.id]; endpointRunner.run(endpoint, { ids }) .then((response) => { response.text().then(text => { showNotification(response.status + ' ' + response.statusText + ' - ' + text); }); }); } this.setState({ isOpen: false }); }; handleSubmit = values => { const { fetchStart, fetchEnd, showNotification, action } = this.props; // Dispatch an action letting react-admin know a API call is ongoing fetchStart(); if (action.endpoint) { const ids = this.props.ids || [this.props.record.id]; endpointRunner.run(action.endpoint, { ids, body: JSON.stringify(values) }) .then((response) => { response.text().then(text => { showNotification(response.status + ' ' + response.statusText + ' - ' + text); }); }) .catch(error => { showNotification(error.message, 'error'); }) .finally(() => { // Dispatch an action letting react-admin know a API call has ended this.setState({ showDialog: false }); fetchEnd(); }); } }; render() { const { showDialog } = this.state; const { action } = this.props; return ( <Fragment> <Button label={action.title} onClick={this.handleClick}> {generateIcon(action.icon)} </Button> <Dialog fullWidth open={showDialog} onClose={this.handleCloseClick} aria-label={"Confirm " + action.title} > <DialogTitle>{"Confirm " + action.title}</DialogTitle> <DialogContent> {mustache.render(action.confirm || '', this.props)} <SimpleForm // We override the redux-form name to avoid collision with the react-admin main form form={FORM_NAME} // We override the redux-form onSubmit prop to handle the submission ourselves onSubmit={this.handleSubmit} // We want no toolbar at all as we have our modal actions toolbar={null}> {action.inputs ? action.inputs.map(generateInput) : null} </SimpleForm> </DialogContent> <DialogActions> <Button label="Confirm" onClick={this.handleSaveClick}> {generateIcon(action.icon)} </Button> <Button label="ra.action.cancel" onClick={this.handleCloseClick}> <IconCancel /> </Button> </DialogActions> </Dialog> </Fragment> ); } } const mapStateToProps = state => ({ isSubmitting: isSubmitting(FORM_NAME)(state) }); const mapDispatchToProps = { fetchEnd, fetchStart, showNotification, submit }; export default connect(mapStateToProps, mapDispatchToProps)( ActionButton ); <file_sep>/src/generator/list.js import React from 'react'; import { Datagrid, List } from 'react-admin'; import generateField from './field'; import generateFilters from './filters'; import generateBulkActionButtons from '../generator/bulk-action-buttons'; import ArrowsPagination from '../component/arrow-pagination'; function generateList(listDef, filtersDef) { if (!listDef) { return listDef; } return (props) => ( <List key='list' title={listDef.title} bulkActionButtons={generateBulkActionButtons(listDef)} {...props} filters={generateFilters(filtersDef)} pagination={<ArrowsPagination />}> <Datagrid> {listDef.fields.map((field) => generateField(field, 'list'))} </Datagrid> </List> ) } export default generateList; <file_sep>/removehash.sh mv build/static/js/main.*.js build/static/js/main.js mv build/static/js/main.*.js.map build/static/js/main.js.map mv build/static/css/main.*.css build/static/css/main.css mv build/static/css/main.*.css.map build/static/css/main.css.map head -n 1 build/static/js/main.js > tmp.tmp && mv tmp.tmp build/static/js/main.js echo " //# sourceMappingURL=main.js.map" >> build/static/js/main.js <file_sep>/src/generator/field.js import { EField } from '../meta/consts'; import React from 'react'; import generateIcon from './icon'; import withRangeStyles from './rangestyles'; import optionRenderer from '../component/option-renderer'; import ActionButton from '../component/action-button'; import {JsonView} from "../component/jsonView"; import {AvatarField} from "../component/avatar"; import { ArrayField, BooleanField, ChipField, Datagrid, DateField, EditButton, EmailField, FunctionField, ImageField, NumberField, ReferenceField, ReferenceManyField, ShowButton, SelectField, SingleFieldList, TextField, UrlField } from 'react-admin'; function generateField(field, context) { const rest = Object.assign({}, field); delete rest.rangeStyles; switch (field.type) { case EField.TextField: const ColoredTextField = withRangeStyles(field.rangeStyles)(TextField); return (<ColoredTextField {...rest}/>); case EField.ChipField: return (<ChipField {...field}/>); case EField.JsonField: return (<JsonView {...field}/>); case EField.EmailField: return (<EmailField {...field}/>); case EField.ReferenceField: rest.linkType = field.readOnly === true ? 'show' : 'edit'; return ( <ReferenceField {...rest}> {generateField(field.display)} </ReferenceField>); case EField.EditButton: return (<EditButton {...field}/>); case EField.ShowButton: return (<ShowButton {...field}/>); case EField.BooleanField: const ColoredBooleanField = withRangeStyles(field.rangeStyles)(BooleanField); return (<ColoredBooleanField {...rest}/>); case EField.DateField: return (<DateField {...field}/>); case EField.ImageField: return (<ImageField {...field}/>); case EField.IconField: return (<FunctionField {...rest} render={record => generateIcon(record[rest.source], { key: rest.key })}/>); case EField.NumberField: const ColoredNumberField = withRangeStyles(field.rangeStyles)(NumberField); return (<ColoredNumberField {...rest}/>); // See this for options: https://marmelab.com/react-admin/Fields.html#numberfield case EField.SelectField: const ColoredSelectField = withRangeStyles(field.rangeStyles)(SelectField); return (<ColoredSelectField optionText={optionRenderer} translateChoice={false} {...rest}/>); case EField.UrlField: const StyledUrlField = withRangeStyles(field.rangeStyles)(UrlField); return (<StyledUrlField {...field}/>); case EField.FunctionField: return (<FunctionField {...field}/>); case EField.ArrayField: return ( <ArrayField {...field}> <Datagrid> {field.fields.map(generateField)} </Datagrid> </ArrayField>); case EField.ReferenceMany: delete rest.source; delete rest.perPageList; delete rest.perPageEdit; rest.perPage = (context === 'list' ? (field.perPageList || 10) : (field.perPageEdit || 2000)); const linkParams = { linkType: field.readOnly === true ? 'show' : 'edit' }; return ( <ReferenceManyField {...rest}> <SingleFieldList {...linkParams}> {generateField(field.display)} </SingleFieldList> </ReferenceManyField> ); case EField.ActionField: return (<ActionButton {...rest}/>); case EField.AvatarField: return (<AvatarField {...rest}/>); case EField.BackgroundField: return (<ImageField {...rest}/>); default: throw new Error("Unknown field type " + field.type); } } export default generateField;
c811a5dbf03be1490d19cb062101bfbf97cba5d1
[ "JavaScript", "Shell" ]
24
JavaScript
roybass/raa
621b562054e1e0be216cb925461339edf098be67
988f0b4ca88a1cdf00645f0109005b005601bb66
refs/heads/master
<file_sep>import numpy as np import re import random import feedparser def loadDataSet(): postingList = [['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'], ['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'], ['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'], ['stop', 'posting', 'stupid', 'worthless', 'garbage'], ['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'], ['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']] classVec = [0, 1, 0, 1, 0, 1] # 1 is abusive, 0 not return postingList, classVec def createVocabList(dataSet): vocabSet = set([]) for document in dataSet: vocabSet = vocabSet | set(document) return list(vocabSet) def setOfWords2Vec(vocabList, inputSet): returnVec = [0] * len(vocabList) for word in inputSet: if word in vocabList: returnVec[vocabList.index(word)] = 1 else: print("the word %s not in vocabList" % word) return returnVec def bagOfWords2Vec(vocabList, inputSet): returnVec = [0] * len(vocabList) for word in inputSet: if word in vocabList: returnVec[vocabList.index(word)] += 1 else: print("the word %s not in vocablist" % word) return returnVec def trainNB0(trainMatrix, trainCatrgory): numDocument = len(trainMatrix) numWord = len(trainMatrix[0]) pAbusive = sum(trainCatrgory) / len(trainCatrgory) p1Num = np.ones(numWord) p0Num = np.ones(numWord) p1Denom = p0Denom = 2 for i in range(numDocument): if trainCatrgory[i] == 1: p1Num += trainMatrix[i] p1Denom += sum(trainMatrix[i]) else: p0Num += trainMatrix[i] p0Denom += sum(trainMatrix[i]) p1Vec = np.log(p1Num / p1Denom) p0Vec = np.log(p0Num / p0Denom) return p0Vec, p1Vec, pAbusive def classifyNB(Vec2Classify, p1Vec, p0Vec, pClass1): p1 = sum(Vec2Classify * p1Vec) + pClass1 p0 = sum(Vec2Classify * p0Vec) + (1 - pClass1) if p1 > p0: return 1 else: return 0 def testingNB(): listOPost, listClasses = loadDataSet() myVocabList = createVocabList(listOPost) trainMat = [] for i in listOPost: trainMat.append(setOfWords2Vec(myVocabList, i)) p0Vec, p1Vec, pAb = trainNB0(trainMat, listClasses) testEntry = ['love', 'my', 'dalmation'] thisDoc = setOfWords2Vec(myVocabList, testEntry) print("this Doc classify as ", classifyNB(thisDoc, p1Vec, p0Vec, pAb)) testEntry = ['stupid', 'garbage'] thisDoc = setOfWords2Vec(myVocabList, testEntry) print("this Doc classify as ", classifyNB(thisDoc, p1Vec, p0Vec, pAb)) def textParse(bigString): listOfTokens = re.split(r'\W+', bigString) return [token.lower() for token in listOfTokens if len(token) > 2] def spamText(): docList = [] classList = [] fullText = [] for i in range(1, 26): wordList = textParse(open('email/spam/%d.txt' % i).read()) docList.append(wordList) fullText.extend(wordList) classList.append(1) wordList = textParse(open('email/ham/%d.txt' % i).read()) docList.append(wordList) fullText.extend(wordList) classList.append(0) vocabList = createVocabList(docList) traingSet = list(range(50)) testSet = [] for i in range(10): randIndex = int(random.uniform(0, len(traingSet))) testSet.append(traingSet[randIndex]) del (traingSet[randIndex]) trainMat = [] trainClasses = [] for docIndex in traingSet: trainMat.append(setOfWords2Vec(vocabList, docList[docIndex])) trainClasses.append(classList[docIndex]) p0V, p1V, pAb = trainNB0(trainMat, trainClasses) errorCount = 0 for docIndex in testSet: wordVec = setOfWords2Vec(vocabList, docList[docIndex]) if classifyNB(wordVec, p1V, p0V, pAb) != classList[docIndex]: errorCount += 1 print("the error rate is ", errorCount / len(testSet)) def calMostFreq(vocabList, fullText): freqDict = {} for token in vocabList: freqDict[token] = fullText.count(token) sortedFreq = sorted(freqDict.items(), key=lambda item: item[1], reverse=True) return sortedFreq[:30] def localWords(feed1, feed0): doclist = [] classlist = [] fulltext = [] minLen = min(len(feed1['entries']), len(feed0['entries'])) for i in range(minLen): wordList = textParse(feed1['entries'][i]['summary']) doclist.append(wordList) fulltext.extend(wordList) classlist.append(1) wordList = textParse(feed0['entries'][i]['summary']) doclist.append(wordList) fulltext.extend(wordList) classlist.append(0) vocabList = createVocabList(doclist) top30Words = calMostFreq(vocabList, fulltext) for pairW in top30Words: if pairW[0] in vocabList: vocabList.remove(pairW[0]) trainingSet = list(range(2 * minLen)) testSet = [] for i in range(5): randIndex = int(random.uniform(0, len(trainingSet))) testSet.append(trainingSet[randIndex]) del (trainingSet[randIndex]) trainMat = [] trainClasses = [] for docIndex in trainingSet: trainMat.append(setOfWords2Vec(vocabList, doclist[docIndex])) trainClasses.append(classlist[docIndex]) p0V, p1V, pAb = trainNB0(trainMat, trainClasses) errorCount = 0 for docIndex in testSet: wordVec = bagOfWords2Vec(vocabList, doclist[docIndex]) if classifyNB(wordVec, p1V, p0V, pAb) != classlist[docIndex]: errorCount += 1 print("error rate is ", errorCount / len(testSet)) return vocabList, p0V, p1V if __name__ == "__main__": # testingNB() # mySent = 'This book is the best book on python or M.L. I have ever laid eyes upon.' # print(mySent.split()) # regEx = re.compile(r'\W+') # print(re.split(r'\W+', mySent)) # spamText() ny = feedparser.parse('http://www.nasa.gov/rss/dyn/image_of_the_day.rss') sf = feedparser.parse('http://sports.yahoo.com/nba/teams/hou/rss.xml') # print(ny['entries']) vocabList, p0V, p1V = localWords(ny, sf) topNY = [] topSF = [] for i in range(len(p0V)): if p0V[i] > -6.0: topSF.append((vocabList[i], p0V[i])) if p1V[i] > -6.0: topNY.append((vocabList[i], p1V[i])) sortedSF = sorted(topSF, key=lambda item: item[1], reverse=True) print("SF**SF**SF**SF**SF**SF**SF**SF**SF") for i in sortedSF: print(i[0]) sortedNY = sorted(topNY, key=lambda item: item[1], reverse=True) print("NY**NY**NY**NY**NY**NY**NY**NY**NY") for i in sortedNY: print(i[0]) <file_sep>import numpy as np import operator import matplotlib.pyplot as plt import os def createDataSet(): group = np.array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]]) labels = ['A', 'A', 'B', 'B'] return group, labels def classify0(inX, dataSet, labels, k): dataSetSize = dataSet.shape[0] diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet # 扩展输入向量 sqDiffMat = diffMat ** 2 sqDisstances = sqDiffMat.sum(axis=1) distances = sqDisstances ** 0.5 sortedDistIndicies = distances.argsort() classCount = {} for i in range(k): label = labels[sortedDistIndicies[i]] classCount[label] = classCount.get(label, 0) + 1 sortedClassCount = sorted(classCount.items(), key=lambda item: item[1]) return sortedClassCount[0][0] def file2matrix(Path): with open(Path) as f: dataMat = [] dataLabel = [] while True: data = f.readline() if not data: break data = data.strip('\n') data = data.split('\t') data = list(map(float, data)) dataMat.append(data[0:-1]) dataLabel.append(data[-1]) return np.array(dataMat), np.array(dataLabel) def autoNorm(dataSet): minVal = dataSet.min(0) maxVal = dataSet.max(0) ranges = maxVal - minVal normDataSet = np.zeros(dataSet.shape) m = dataSet.shape[0] normDataSet = dataSet - np.tile(minVal, (m, 1)) normDataSet = normDataSet / np.tile(ranges, (m, 1)) return normDataSet, ranges, minVal def datingClassTest(): rate = 0.1 DataSet, Label = file2matrix("datingTestSet2.txt") m = DataSet.shape[0] numTest = int(m * rate) normDataSet, ranges, minVal = autoNorm(DataSet) errorCount = 0 for i in range(numTest): label = classify0(normDataSet[i, :], normDataSet[numTest:, :], Label[numTest:], 5) print("predict label is %d, real label is %d" % (label, Label[i])) if label != Label[i]: errorCount += 1 print("the total error rate is %f" % (errorCount / numTest)) def img2Vec(filename): returnVec = np.zeros((1, 32 * 32)) with open(filename) as f: for i in range(32): data = f.readline() for j in range(32): returnVec[0, i * 32 + j] = data[j] return returnVec def handwritingClassTest(): files = os.listdir("trainingDigits") m = len(files) labels = [] trainDataset = np.zeros((m, 32 * 32)) for i in range(m): labels.append(int(files[i].split('_')[0])) trainDataset[i, :] = img2Vec("trainingDigits/" + files[i]) testFiles = os.listdir("testDigits") mTest = len(testFiles) errorCount = 0 for i in range(mTest): Label = int(testFiles[i].split('_')[0]) testDataSet = img2Vec("testDigits/" + testFiles[i]) predictLabel = classify0(testDataSet, trainDataset, labels, 3) print("the predict label is %s, the real label is %s" % (predictLabel, Label)) if predictLabel != Label: errorCount += 1 print("the error rate is %f" % (errorCount / mTest)) if __name__ == "__main__": # dataMat, dataLabel = file2matrix("datingTestSet2.txt") # fig = plt.figure(figsize=(6, 4)) # # s表示数据点大小,c表示颜色序列 # plt.scatter(dataMat[:, 0], dataMat[:, 1], s=15 * dataLabel, c=15 * dataLabel) # plt.show() # datingClassTest() handwritingClassTest() <file_sep>import math import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 def calShan(dataSet): m = len(dataSet) labelCount = {} for featVec in dataSet: label = featVec[-1] if label not in labelCount.keys(): labelCount[label] = 0 labelCount[label] += 1 shan = 0 for i in labelCount.keys(): prob = float(labelCount[i] / m) shan -= prob * math.log(prob, 2) return shan def splitDataSet(dataSet, axis, value): retDataSet = [] for featVec in dataSet: if featVec[axis] == value: reducedFeatVec = featVec[:axis] reducedFeatVec.extend(featVec[axis + 1:]) retDataSet.append(reducedFeatVec) return retDataSet def chooseBestFeatureToSplit(dataSet): numFeat = len(dataSet[0]) - 1 baseEntropy = calShan(dataSet) bestFeat = 0 bestEntropy = -1 for i in range(numFeat): FeatList = [example[i] for example in dataSet] uniqueFeat = set(FeatList) newEntropy = 0 for value in uniqueFeat: subDataSet = splitDataSet(dataSet, i, value) prob = float(len(subDataSet) / len(dataSet)) newEntropy += prob * calShan(subDataSet) if baseEntropy - newEntropy > bestEntropy: bestEntropy = baseEntropy - newEntropy bestFeat = i return bestFeat def majorityCnt(classList): classCount = {} for vote in classList: if vote not in classCount.keys(): classCount[vote] = 0 classCount[vote] += 1 sortClassCount = sorted(classCount.items(), key=lambda item: item[1], reverse=True) return sortClassCount[0][0] def createTree(dataSet, labels): classList = [example[-1] for example in dataSet] if classList.count(classList[0]) == len(classList): return classList[0] if len(dataSet[0]) == 1: return majorityCnt(classList) bestFeat = chooseBestFeatureToSplit(dataSet) bestFeatName = labels[bestFeat] del (labels[bestFeat]) featValue = [example[bestFeat] for example in dataSet] uniqueFeatValue = set(featValue) myTree = {bestFeatName: {}} for value in uniqueFeatValue: subLabel = labels[:] myTree[bestFeatName][value] = createTree(splitDataSet (dataSet, bestFeat, value), subLabel) return myTree def createDataSet(): dataSet = [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']] labels = ['no surfacing', 'flippers'] return dataSet, labels decisionNode = dict(boxstyle='sawtooth', fc="0.8") leafNode = dict(boxstyle='round4', fc="0.8") arrow_args = dict(arrowstyle='<-') def plotNode(nodeText, centerPt, parentPt, nodeType): createPlot.ax1.annotate(nodeText, xy=parentPt, xycoords='axes fraction', xytext=centerPt, textcoords='axes fraction', va='center', ha='center', bbox=nodeType, arrowprops=arrow_args) def createPlot(): fig = plt.figure(1, facecolor='white') fig.clf() createPlot.ax1 = plt.subplot(111, frameon=False) plotNode('决策节点', (0.5, 0.1), (0.1, 0.5), decisionNode) plotNode('叶节点', (0.8, 0.1), (0.3, 0.8), leafNode) plt.show() def getNumLeaf(myTree): numLeaf = 0 firstStr = list(myTree.keys())[0] secondTree = myTree[firstStr] for key in secondTree.keys(): if type(secondTree[key]).__name__ == 'dict': numLeaf += getNumLeaf(secondTree[key]) else: numLeaf += 1 return numLeaf def getTreeDepth(myTree): maxDeth = 0 firstStr = list(myTree.keys())[0] secondTree = myTree[firstStr] for key in secondTree.keys(): if type(secondTree[key]).__name__ == 'dict': thisDepth = 1 + getTreeDepth(secondTree[key]) else: thisDepth = 1 if thisDepth > maxDeth: maxDeth = thisDepth return maxDeth def plotMidText(cntrPt,parentPt,txtString): xMid = (parentPt[0]-cntrPt[0])/2.0+cntrPt[0] yMid = (parentPt[1]-cntrPt[1])/2.0+cntrPt[1] createPlot.ax1.text(xMid,yMid,txtString) def plotTree(myTree,parentPt,nodeTxt): numLeaf = getNumLeaf(myTree) depth = getTreeDepth(myTree) firstStr=list(myTree.keys())[0] cntrPt = (plotTree.xOff+(1.0+float(numLeaf))/2.0/plotTree.totalW,plotTree.yOff) plotMidText(cntrPt,parentPt,nodeTxt) plotNode(firstStr,cntrPt,parentPt,decisionNode) secondDict = myTree[firstStr] plotTree.yOff=plotTree.yOff-1.0/plotTree.totalD for key in secondDict.keys(): if type(secondDict[key]).__name__=='dict': plotTree(secondDict[key],cntrPt,str(key)) else: plotTree.xOff=plotTree.xOff+1.0/plotTree.totalW plotNode(secondDict[key],(plotTree.xOff,plotTree.yOff),cntrPt,leafNode) plotMidText((plotTree.xOff,plotTree.yOff),cntrPt,str(key)) plotTree.yOff = plotTree.yOff+1.0/plotTree.totalD def createPlot(inTree): fig = plt.figure(1,facecolor="white") fig.clf() axprops=dict(xticks=[],yticks=[]) createPlot.ax1=plt.subplot(111,frameon=False,**axprops) plotTree.totalW=float(getNumLeaf(inTree)) plotTree.totalD = float(getTreeDepth(inTree)) plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0 plotTree(inTree,(0.5,1.0),'') plt.show() def classify(inputTree,featLabels,testVec): firstStr = list(inputTree.keys())[0] secondDict=inputTree[firstStr] featIndex = featLabels.index(firstStr) for key in secondDict.keys(): if testVec[featIndex]==key: if type(secondDict[key]).__name__=='dict': classLabel = classify(secondDict[key],featLabels,testVec) else: classLabel = secondDict[key] return classLabel if __name__ == "__main__": # dataSet, labels = createDataSet() # myTree = createTree(dataSet, labels) # print(myTree) # # createPlot() # print(getTreeDepth(myTree)) # print(getNumLeaf(myTree)) # createPlot(myTree) lenses=[] with open("lenses.txt") as f: while True: inst=f.readline() if not inst: break lenses.append(inst.strip().split('\t')) print(lenses) lensesLabels = ['age','prescript','astigmatic','tearRate'] lensesTree = createTree(lenses,lensesLabels) print(lensesTree) createPlot(lensesTree) <file_sep>import math import numpy as np import matplotlib.pyplot as plt import random def loadData(): dataMat = [] dataLabel = [] with open('testSet.txt') as f: while True: data = f.readline() if not data: break data = data.strip().split() dataMat.append([1, float(data[0]), float(data[1])]) dataLabel.append(int(data[-1])) return dataMat, dataLabel def sigmod(inX): return 1.0 / (1 + np.exp(-inX)) def gradAscent(dataSet, dataLabel): dataMatSet = np.matrix(dataSet) dataMatLabel = np.matrix(dataLabel).transpose() m, n = dataMatSet.shape w = np.ones((n, 1)) alpha = 0.001 maxCycle = 500 for i in range(maxCycle): h = sigmod(dataMatSet * w) error = dataMatLabel - h w = w + alpha * dataMatSet.transpose() * error return w def stocGradAscent(dataSet, dataLabel, numIter=150): m = len(dataSet) n = len(dataSet[0]) weight = np.ones(n) for j in range(numIter): dataIndex = list(range(m)) for i in range(m): alpha = 4 / (1.0 + j + i) + 0.01 randIndex = int(random.uniform(0, len(dataIndex))) h = sigmod(sum(dataSet[randIndex] * weight)) error = dataLabel[randIndex] - h weight = weight + [alpha * error * i for i in dataSet[randIndex]] del (dataIndex[randIndex]) return weight def plotBestFilt(weights): dataMat, dataLabel = loadData() xcord0 = [] ycord0 = [] xcord1 = [] ycord1 = [] for i in range(len(dataMat)): if dataLabel[i] == 0: xcord0.append(dataMat[i][1]) ycord0.append(dataMat[i][2]) elif dataLabel[i] == 1: xcord1.append(dataMat[i][1]) ycord1.append(dataMat[i][2]) fig = plt.figure(figsize=(6, 4)) ax = fig.add_subplot(111) ax.scatter(xcord0, ycord0, s=30, c='red', marker='s') ax.scatter(xcord1, ycord1, s=30, c='blue') x = np.arange(-3.0, 3.0, 0.1) y = np.ravel((-weights[0] - weights[1] * x) / weights[2]) print(x) print(y) ax.plot(x, y) plt.xlabel('X1') plt.ylabel('X2') plt.show() def classifyVec(inX, weight): prob = sigmod(sum(inX * weight)) if prob > 0.5: return 1 return 0 def colicTest(): frTrain = open("horseColicTraining.txt") frTest = open("horseColicTest.txt") trainSet = [] trainLabel = [] for line in frTrain.readlines(): line = line.strip().split('\t') trainSet.append(list(map(float, line[:-1]))) trainLabel.append(float(line[-1])) trainWeight = stocGradAscent(trainSet, trainLabel, 500) errorCount = 0 numTestVec = 0 for line in frTest.readlines(): numTestVec += 1 line = line.strip().split('\t') lineArr = list(map(float, line[:-1])) if classifyVec(lineArr, trainWeight) != int(line[-1]): errorCount += 1 print("the error rate is ", errorCount / numTestVec) if __name__ == "__main__": dataSet, dataLabel = loadData() w = stocGradAscent(dataSet, dataLabel) print(w) plotBestFilt(w) colicTest() <file_sep>import numpy as np def loadSimpleData(): datMat = np.matrix([[1., 2.1], [2., 1.1], [1.3, 1.], [1., 1.], [2., 1.]]) classLabels = [1.0, 1.0, -1.0, -1.0, 1.0] return datMat, classLabels def strumpClassify(dataMat, dimen, threshVal, threshIneq): retArry = np.ones((dataMat.shape[0], 1)) if threshIneq == 'lt': retArry[dataMat[:, dimen] <= threshVal] = -1.0 else: retArry[dataMat[:, dimen] > threshVal] = -1.0 return retArry def buildStrump(dataArr, classLabels, D): dataMat = np.matrix(dataArr) labelMat = np.matrix(classLabels) m, n = dataMat.shape numStepSize = 10.0 bestStrump = {} bestClassEst = np.matrix(np.zeros((m, 1))) minError = np.inf for i in range(n): rangeMax = dataMat[:, i].max() rangeMin = dataMat[:, i].min() stepSize = (rangeMax - rangeMin) / numStepSize for j in range(-1, int(numStepSize + 1)): for Inequ in ['lt', 'gt']: threshVal = rangeMin + j * stepSize predictVal = strumpClassify(dataMat, i, threshVal, Inequ) errArr = np.matrix(np.ones((m, 1))) errArr[predictVal == labelMat.T] = 0 weightError = D.T * errArr print("split: dim: %d, thresh: %.2f, thersh ineqal: %s, the weighted error: %.3f" % (i, threshVal, Inequ, weightError)) if weightError < minError: minError = weightError bestClassEst = predictVal.copy() bestStrump['dim'] = i bestStrump['thresh'] = threshVal bestStrump['ineq'] = Inequ return bestStrump, minError, bestClassEst def adaBoostTrainDS(dataArr, classLabels, numIt=40): dataMat = np.matrix(dataArr) labelMat = np.matrix(classLabels) weakClassArr = [] m = dataMat.shape[0] D = np.matrix(np.ones((m, 1)) / m) aggClassEst = np.matrix(np.zeros((m, 1))) for i in range(numIt): bestStrump, error, classEst = buildStrump(dataArr, classLabels, D) print("D:", D.T) alpha = float(0.5 * np.log((1.0 - error) / max(error, 1e-6))) bestStrump['alpha'] = alpha weakClassArr.append(bestStrump) print("classEst is: ", classEst) expon = np.multiply(-1 * alpha * np.matrix(classLabels).T, classEst) D = np.multiply(D, np.exp(expon)) D = D / D.sum() aggClassEst += alpha * classEst print("aggClassEst is: ", aggClassEst.T) aggError = np.multiply(np.sign(aggClassEst) != np.matrix(classLabels).T, np.ones((m, 1))) errorRate = aggError.sum() / m print("the total error is ", errorRate) if errorRate == 0: break return weakClassArr def adaClassify(dataToClass, classifierArr): dataMat = np.matrix(dataToClass) m = dataMat.shape[0] aggClassEst = np.zeros((m, 1)) for i in range(len(classifierArr)): classEst = strumpClassify(dataMat, classifierArr[i].get('dim'), classifierArr[i].get('thresh'), classifierArr[i].get('ineq')) aggClassEst += classifierArr[i].get('alpha') * classEst return np.sign(aggClassEst) def loadDataSet(filename): dataMat = [] labelClass = [] fr = open(filename) for line in fr.readlines(): line = line.strip().split('\t') dataMat.append(list(map(float, line[:-1]))) labelClass.append(float(line[-1])) return dataMat, labelClass if __name__ == "__main__": # dataMat, classLabel = loadSimpleData() # classifyArr = adaBoostTrainDS(dataMat, classLabel, 9) # print(classifyArr) # print(adaClassify([0, 0], classifyArr)) dataArr, labelArr = loadDataSet('horseColicTraining2.txt') classifierArray = adaBoostTrainDS(dataArr, labelArr, 9) testArr, testLabel = loadDataSet('horseColicTest2.txt') prediction10 = adaClassify(testArr, classifierArray) errArr = np.matrix(np.ones((67, 1))) print(errArr[prediction10 != np.matrix(testLabel).T].sum())
3867902dadf8a12884de9869aef8fef893971327
[ "Python" ]
5
Python
sxx01/-
614bc09e7622d05420fc15c1edc481db167a7d2d
4315feec21de22674ee42eb822c0bd3ab524a405
refs/heads/master
<repo_name>nuasg/coursedj<file_sep>/public/js/services/mainService.js // js/services/mainService.js var app = angular.module('mainService', []); app.factory('ASG', function($http, $location) { var NOT_A_KEY; if ($location.$$host === 'localhost') { NOT_A_KEY = "<KEY>"; // DEBUG } else { NOT_A_KEY = "<KEY>"; // LIVE } return { getSubjects: function(term){ return $http.get('http://api.asg.northwestern.edu/subjects/?key=' + NOT_A_KEY+ '&term=' + term); }, getCourses: function(term, subject){ return $http.get('http://api.asg.northwestern.edu/courses/?key=' + NOT_A_KEY + '&term=' + term + '&subject=' + subject); }, getTerms: function() { return $http.get('https://api.asg.northwestern.edu/terms?key=' + NOT_A_KEY); } }; }); <file_sep>/README.md # coursedj A website created by the ASG Services Committee to help students select classes and plan their schedule. Powered with the Northwestern CAESAR API. Please direct all questions and feedback to <EMAIL>.<file_sep>/public/js/coreModule.js // public/js/coreModule.js var app = angular.module('CourseDJ', [ 'dhxScheduler', 'mainController', 'mainService', ]);
d745120aa83cbc18cbed7fe9ec633bfcfd09736b
[ "JavaScript", "Markdown" ]
3
JavaScript
nuasg/coursedj
4a7246226acd7d025df6e441f1070461c9de1023
5faa29cdf7a6e299d277a337dc4f807f59108944
refs/heads/main
<repo_name>liuyaxin99/Woocommerce<file_sep>/src/pages/menu/menu.ts import { Component, ViewChild} from '@angular/core'; import {NavController, NavParams, ModalController } from 'ionic-angular'; import {HomePage} from '../home/home'; import {Signup} from '../signup/signup'; import {Login} from '../login/login'; import {Cart} from '../cart/cart'; import * as WC from 'woocommerce-api'; import { ProductsByCategory } from '../products-by-category/products-by-category' import { Storage } from '@ionic/storage'; import{ WoocommerceProvider } from '../../providers/woocommerce' @Component({ selector: 'page-menu', templateUrl: 'menu.html', }) export class Menu { homePage: any; WooCommerce: any; categories: any[]; @ViewChild('content') childNavCtrl: NavController; loggedIn: boolean; user: any; constructor( public navCtrl: NavController, public navParams: NavParams, public storage: Storage, public modalCtrl: ModalController, private WP: WoocommerceProvider){ this.homePage = HomePage this.categories = []; this.user = []; this.WooCommerce = WP.init(); this.WooCommerce.getAsync("products/categories").then((data) => { console.log(JSON.parse(data.body).product_categories); let temp:any[] =JSON.parse(data.body).product_categories; for( let i = 0; i < temp.length; i ++){ if(temp[i].parent == 0){ if(temp[i].slug == "clothing"){ temp[i].icon = "shirt-outline"; } if(temp[i].slug == "music"){ temp[i].icon = "musical-notes-ouline"; } if(temp[i].slug == "uncategorized"){ temp[i].icon = "apps-outline"; } this.categories.push(temp[i]); } } },(err)=> { console.log(err) }) } ionViewDidEnter() { this.storage.ready().then(() => { this.storage.get("userLoginInfo").then((userLoginInfo) => { if (userLoginInfo != null) { console.log("User logged in..."); this.user = userLoginInfo.user; console.log(this.user); this.loggedIn = true; } else { console.log("No user found."); this.user = {}; this.loggedIn = false; } }) }) } openCategoryPage(category){ this.childNavCtrl.setRoot(ProductsByCategory, {"category": category}); } openPage(pageName: string) { if (pageName == "signup") { this.navCtrl.push(Signup); } if (pageName == "login") { this.navCtrl.push(Login); } if (pageName == 'logout') { this.storage.remove("userLoginInfo").then(() => { this.user = {}; this.loggedIn = false; }) } if (pageName == 'cart') { this.navCtrl.push(Cart); } } }
fb59c231377d1499d301451afb2eba3e9562724a
[ "TypeScript" ]
1
TypeScript
liuyaxin99/Woocommerce
7629c964dca6ee3d4409564923aaaf1b2e567fe5
c273c2dff16a39887d8541a16a98e31b463587f9
refs/heads/master
<repo_name>dldinternet/ec2dream<file_sep>/puppet/puppet_push.sh #!/bin/sh # # Customized pocketknife to run puppet apply on remote node # # Env Variable EC2_PUPPET_REPOSITORY puppet_repository # Env Variable EC2_PUPPET_PARAMETERS puppet_parameters # puppet_push # add extra pocketknife_puppet parameters by changeing the command line and # adding parameters before the $1 # -t <sudopassword> specify a sudo password # -d <modules_path> puppet modulespath separated by colons defaults to modules # -n don't delete the puppet repo after running puppet # -z don't upgrade the server packages before running puppet # -x <xtra options> add xtra options for puppet apply like --noop # echo "**********************************" echo "*** Calling pocketknife_puppet ***" echo "**********************************" cd $EC2_PUPPET_REPOSITORY echo pocketknife_puppet $EC2_PUPPET_PARAMETERS $1 pocketknife_puppet $EC2_PUPPET_PARAMETERS $1 <file_sep>/lib/Rackspace.rb require 'fog' require 'json' class Rackspace def initialize() @conn = {} data = File.read("#{ENV['EC2DREAM_HOME']}/lib/rackspace_config.json") @config = JSON.parse(data) end def api 'openstack' end def name 'rackspace' end def config @config end def conn(type) #Fog.mock! auth_url = "https://identity.api.rackspacecloud.com" vol_url = "https://blockstorage.api.rackspacecloud.com/v1" ec2_url = $ec2_main.settings.get('EC2_URL') if ec2_url != nil and ec2_url !="" region = "" sa = (ec2_url).split"." if sa.size>1 region = (sa[0]) end if region.downcase == "https://lon" auth_url = "https://lon.identity.api.rackspacecloud.com" vol_url = "https://lon.blockstorage.api.rackspacecloud.com/v1" end end if @conn[type] == nil begin case type when 'BlockStorage' @conn[type] = Fog::Rackspace::BlockStorage.new(:rackspace_username => $ec2_main.settings.get('AMAZON_ACCESS_KEY_ID'), :rackspace_api_key => $ec2_main.settings.get('AMAZON_SECRET_ACCESS_KEY'), :rackspace_auth_url => auth_url, :rackspace_endpoint => vol_url) when 'Compute' @conn[type] = Fog::Compute.new({:provider => "Rackspace", :rackspace_username => $ec2_main.settings.get('AMAZON_ACCESS_KEY_ID'), :rackspace_api_key => $ec2_main.settings.get('AMAZON_SECRET_ACCESS_KEY'), :rackspace_auth_url => auth_url, :rackspace_endpoint => ec2_url, :version => :v2 }) else nil end rescue reset_connection puts "ERROR: on #{type} connection to rackspace #{$!}" puts "check your keys in environment" end else @conn[type] end end def reset_connection @conn = {} end end<file_sep>/lib/dialog/LOC_EditDialog.rb require 'rubygems' require 'fox16' require 'common/EC2_Properties' require 'common/error_message' include Fox class LOC_EditDialog < FXDialogBox def initialize(owner, curr_item) puts " LOC_EditDialog.initialize" @saved = false @ec2_main = owner @magnifier = @ec2_main.makeIcon("magnifier.png") @magnifier.create @loc_server = {} super(@ec2_main, "Edit Local Server", :opts => DECOR_ALL, :width => 550, :height => 660) @frame5 = FXMatrix.new(self, 3, :opts => MATRIX_BY_COLUMNS|LAYOUT_FILL) FXLabel.new(@frame5, "Server" ) @loc_server['server'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT|TEXTFIELD_READONLY) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "Address" ) @loc_server['address'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "Address Port" ) @loc_server['address_port'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(@frame5, "(Default 22)" ) FXLabel.new(@frame5, "SSH User" ) @loc_server['ssh_user'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "SSH Password" ) @loc_server['ssh_password'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "SSH key" ) @loc_server['ssh_key'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) @loc_server['ssh_key_button'] = FXButton.new(@frame5, "", :opts => BUTTON_TOOLBAR) @loc_server['ssh_key_button'].icon = @magnifier @loc_server['ssh_key_button'].tipText = "Browse..." @loc_server['ssh_key_button'].connect(SEL_COMMAND) do dialog = FXFileDialog.new(@frame5, "Select pem file") dialog.patternList = [ "Pem Files (*.pem)" ] dialog.selectMode = SELECTFILE_EXISTING if dialog.execute != 0 @loc_server['ssh_key'].text = dialog.filename end end FXLabel.new(@frame5, "Putty Key" ) @loc_server['putty_key'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) @loc_server['putty_key_button'] = FXButton.new(@frame5, "", :opts => BUTTON_TOOLBAR) @loc_server['putty_key_button'].icon = @magnifier @loc_server['putty_key_button'].tipText = "Browse..." @loc_server['putty_key_button'].connect(SEL_COMMAND) do dialog = FXFileDialog.new(@frame5, "Select pem file") dialog.patternList = [ "Pem Files (*.ppk)" ] dialog.selectMode = SELECTFILE_EXISTING if dialog.execute != 0 @loc_server['putty_key'].text = dialog.filename end end FXLabel.new(@frame5, "Chef Node" ) @loc_server['chef_node'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "Puppet Manifest" ) @loc_server['puppet_manifest'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "Puppet Roles" ) @loc_server['puppet_roles'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "Windows Server" ) @loc_server['windows_server'] = FXComboBox.new(@frame5, 15, :opts => COMBOBOX_STATIC|COMBOBOX_NO_REPLACE|LAYOUT_LEFT) @loc_server['windows_server'].numVisible = 2 @loc_server['windows_server'].appendItem("true") @loc_server['windows_server'].appendItem("false") @loc_server['windows_server'].setCurrentItem(1) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "Tunnelling - Bastion Host" ) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "Local Port" ) @loc_server['local_port'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "Bastion Host" ) @loc_server['bastion_host'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "Bastion Port" ) @loc_server['bastion_port'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "Bastion User" ) @loc_server['bastion_user'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "Bastion Passwoird" ) @loc_server['bastion_password'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "Bastion SSH key" ) @loc_server['bastion_ssh_key'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) @loc_server['bastion_ssh_key_button'] = FXButton.new(@frame5, "", :opts => BUTTON_TOOLBAR) @loc_server['bastion_ssh_key_button'].icon = @magnifier @loc_server['bastion_ssh_key_button'].tipText = "Browse..." @loc_server['bastion_ssh_key_button'].connect(SEL_COMMAND) do dialog = FXFileDialog.new(@frame5, "Select pem file") dialog.patternList = [ "Pem Files (*.pem)" ] dialog.selectMode = SELECTFILE_EXISTING if dialog.execute != 0 @loc_server['bastion_ssh_key'].text = dialog.filename end end FXLabel.new(@frame5, "Bastion Putty Key" ) @loc_server['bastion_putty_key'] = FXTextField.new(@frame5, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) @loc_server['bastion_putty_key_button'] = FXButton.new(@frame5, "", :opts => BUTTON_TOOLBAR) @loc_server['bastion_putty_key_button'].icon = @magnifier @loc_server['bastion_putty_key_button'].tipText = "Browse..." @loc_server['bastion_putty_key_button'].connect(SEL_COMMAND) do dialog = FXFileDialog.new(@frame5, "Select pem file") dialog.patternList = [ "Pem Files (*.ppk)" ] dialog.selectMode = SELECTFILE_EXISTING if dialog.execute != 0 @loc_server['bastion_putty_key'].text = dialog.filename end end #FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "" ) FXLabel.new(@frame5, "" ) create = FXButton.new(@frame5, " &Save ", nil, self, ID_ACCEPT, FRAME_RAISED|LAYOUT_LEFT|LAYOUT_CENTER_X) FXLabel.new(@frame5, "" ) create.connect(SEL_COMMAND) do |sender, sel, data| if server.text == nil or server.text == "" error_message("Error","Server not specified") else save_local_server() if @saved == true self.handle(sender, MKUINT(ID_ACCEPT, SEL_COMMAND), nil) end end end r = get_local_server(curr_item) if r['server'] != nil and r['server'] != "" @loc_server['server'].text = r['server'] @loc_server['address'].text = r['address'] @loc_server['address_port'].text = r['address_port'] @loc_server['chef_node'].text = r['chef_node'] @loc_server['puppet_manifest'].text = r['puppet_manifest'] @loc_server['puppet_roles'].text = r['puppet_roles'] @loc_server['ssh_user'].text = r['ssh_user'] @loc_server['ssh_password'].text = r['ssh_password'] @loc_server['ssh_key'].text = r['ssh_key'] @loc_server['putty_key'].text = r['putty_key'] @loc_server['local_port'].text = r['local_port'] @loc_server['bastion_host'].text = r['bastion_host'] @loc_server['bastion_port'].text = r['bastion_port'] @loc_server['bastion_user'].text = r['bastion_user'] @loc_server['bastion_password'].text = r['bastion_password'] @loc_server['bastion_ssh_key'].text = r['bastion_ssh_key'] @loc_server['bastion_putty_key'].text = r['bastion_putty_key'] @loc_server['windows_server'].setCurrentItem(1) if r['windows_server'] == 'true' @loc_server['windows_server'].setCurrentItem(0) end end end def get_local_server(server) folder = "loc_server" properties = {} loc = EC2_Properties.new if loc != nil properties = loc.get(folder, server) end return properties end def save_local_server folder = "loc_server" loc = EC2_Properties.new if loc != nil begin properties = {} properties['server']=@loc_server['server'] properties['address']=@loc_server['address'] properties['address_port']=@loc_server['address_port'] properties['chef_node']=@loc_server['chef_node'] properties['puppet_manifest']=@loc_server['puppet_manifest'] properties['puppet_roles']=@loc_server['puppet_roles'] windows_server_value = "false" if @loc_server['windows_server'].itemCurrent?(0) windows_server_value = true end properties['windows_server']=windows_server_value properties['ssh_user']=@loc_server['ssh_user'] properties['ssh_password']=@loc_server['ssh_password'] properties['ssh_key']=@loc_server['ssh_key'] properties['putty_key']=@loc_server['putty_key'] properties['local_port']=@loc_server['local_port'] properties['bastion_host']=@loc_server['bastion_host'] properties['bastion_port']=@loc_server['bastion_port'] properties['bastion_user']=@loc_server['bastion_user'] properties['bastion_password']=@loc_server['bastion_password'] properties['bastion_ssh_key']=@loc_server['bastion_ssh_key'] properties['bastion_putty_key']=@loc_server['bastion_putty_key'] @saved = loc.save(folder, server, properties) if @saved == false error_message("Update Local Server Failed","Update Local Server Failed") return end rescue error_message("Update Local Server",$!) return end end end def saved @saved end def success @saved end end <file_sep>/lib/dialog/EC2_ChefEditDialog.rb require 'rubygems' require 'fox16' require 'common/error_message' include Fox class EC2_ChefEditDialog < FXDialogBox def initialize(owner, server, address, chef_node, ssh_user, private_key, password, platform="", local_port="") puts "EC2_ChefEditDialog #{server}, #{address}, #{chef_node}, #{ssh_user}, #{private_key}, #{password}, #{platform}, #{local_port}" @saved = false @ec2_main = owner settings = @ec2_main.settings parm = {} chef_repository = settings.get('CHEF_REPOSITORY') parm['chef_apply'] = settings.get('CHEF_APPLY') parm['chef_why_run'] = settings.get('CHEF_WHY_RUN') parm['chef_extra_options'] = settings.get('CHEF_EXTRA_OPTIONS') parm['chef_delete_repo'] = settings.get('CHEF_DELETE_REPO') parm['chef_sudo_password'] = settings.get('CHEF_SUDO_PASSWORD') parm['chef_upgrade_packages'] = settings.get('CHEF_UPGRADE_PACKAGES') @magnifier = @ec2_main.makeIcon("magnifier.png") @magnifier.create if chef_node == nil or chef_node == "" chef_node = server end ec2_server_name = server if address != nil and address != "" ec2_server_name = address end node_name = "#{chef_repository}/nodes/#{chef_node}.json" if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil if private_key != nil private_key = private_key.gsub('/','\\') end node_name = node_name.gsub('/','\\') end #if chef_repository == nil or chef_repository == "" # error_message("No Chef Repository","No CHEF_REPOSITORY specified in Settings") # return false #end if private_key == nil or private_key == "" and (password == nil or password == "") error_message("No ec2 ssh private key","No EC2_SSH_PRIVATE_KEY specified") return false end if !File.exists?(node_name) error_message("No Chef Node file","No Chef Node file #{node_name} for this server") return false end if ec2_server_name == nil or ec2_server_name == "" error_message("No Public of Private DSN","This Server does not have a Public or Private DSN") return false end short_name = ec2_server_name if ec2_server_name.size > 16 sa = (ec2_server_name).split"." if sa.size>1 short_name = sa[0] end end super(@ec2_main, "Chef", :opts => DECOR_ALL, :width => 500, :height => 275) page1 = FXVerticalFrame.new(self, LAYOUT_FILL, :padding => 0) frame1 = FXMatrix.new(page1, 3, :opts => MATRIX_BY_COLUMNS|LAYOUT_FILL) FXLabel.new(frame1, "Run Chef Solo" ) chef_apply = FXComboBox.new(frame1, 15, :opts => COMBOBOX_STATIC|COMBOBOX_NO_REPLACE|LAYOUT_LEFT) chef_apply.numVisible = 2 chef_apply.appendItem("true") chef_apply.appendItem("false") chef_apply.setCurrentItem(0) FXLabel.new(frame1, "" ) FXLabel.new(frame1, "Run Chef Solo --why-run" ) chef_why_run = FXComboBox.new(frame1, 15, :opts => COMBOBOX_STATIC|COMBOBOX_NO_REPLACE|LAYOUT_LEFT) chef_why_run.numVisible = 2 chef_why_run.appendItem("true") chef_why_run.appendItem("false") chef_why_run.setCurrentItem(1) FXLabel.new(frame1, "" ) FXLabel.new(frame1, "Extra Chef Solo options" ) chef_extra_options = FXTextField.new(frame1, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(frame1, "" ) FXLabel.new(frame1, "Delete Chef Repo" ) chef_delete_repo = FXComboBox.new(frame1, 15, :opts => COMBOBOX_STATIC|COMBOBOX_NO_REPLACE|LAYOUT_LEFT) chef_delete_repo.numVisible = 2 chef_delete_repo.appendItem("true") chef_delete_repo.appendItem("false") chef_delete_repo.setCurrentItem(1) FXLabel.new(frame1, "" ) FXLabel.new(frame1, "Sudo Password" ) chef_sudo_password = FXTextField.new(frame1, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(frame1, "" ) FXLabel.new(frame1, "Upgrade Packages" ) chef_upgrade_packages = FXComboBox.new(frame1, 15, :opts => COMBOBOX_STATIC|COMBOBOX_NO_REPLACE|LAYOUT_LEFT) chef_upgrade_packages.numVisible = 2 chef_upgrade_packages.appendItem("true") chef_upgrade_packages.appendItem("false") chef_upgrade_packages.setCurrentItem(0) FXLabel.new(frame1, "" ) frame2 = FXMatrix.new(page1, 1, :opts => MATRIX_BY_COLUMNS|LAYOUT_CENTER_X) chef_message = FXLabel.new(frame2, "Confirm Running of Chef-Solo for Node #{chef_node} on server #{short_name}", :opts => LAYOUT_CENTER_X ) FXLabel.new(frame2, "" ) frame3 = FXHorizontalFrame.new(page1,LAYOUT_FILL, :padding => 0) yes = FXButton.new(frame3, " &Yes ", nil, self, ID_ACCEPT, FRAME_RAISED|LAYOUT_LEFT|LAYOUT_CENTER_X) no = FXButton.new(frame3, " &No ", nil, self, ID_CANCEL, FRAME_RAISED|LAYOUT_CENTER_X|LAYOUT_SIDE_BOTTOM) no.connect(SEL_COMMAND) do |sender, sel, data| self.handle(sender, MKUINT(ID_ACCEPT, SEL_COMMAND), nil) end yes.connect(SEL_COMMAND) do |sender, sel, data| r = {} r['chef_apply']="false" if chef_apply.itemCurrent?(0) r['chef_apply']="true" end r['chef_why_run']="false" if chef_why_run.itemCurrent?(0) r['chef_why_run']="true" end r['chef_extra_options']=chef_extra_options.text r['chef_delete_repo']="false" if chef_delete_repo.itemCurrent?(0) r['chef_delete_repo']="true" end r['chef_sudo_password']=chef_sudo_password.text r['chef_upgrade_packages']="false" if chef_upgrade_packages.itemCurrent?(0) r['chef_upgrade_packages']="true" end settings.put('CHEF_APPLY',r['chef_apply']) settings.put('CHEF_WHY_RUN',r['chef_why_run']) settings.put('CHEF_EXTRA_OPTIONS',r['chef_extra_options']) settings.put('CHEF_DELETE_REPO',r['chef_delete_repo']) settings.put('CHEF_SUDO_PASSWORD',r['chef_sudo_password']) settings.put('CHEF_UPGRADE_PACKAGES',r['chef_upgrade_packages']) settings.save @saved = true if local_port == nil or local_port == "" ssh_user = "root" if ssh_user == nil or ssh_user == "" end chef_options = "-iv" if private_key != nil and private_key !="" chef_options = chef_options+"k #{private_key}" else chef_options = chef_options+"p #{password}" end if ssh_user != nil and ssh_user != "" chef_options = chef_options+" -s #{ssh_user}" end if local_port != nil and local_port != "" chef_options =chef_options+" -l #{local_port}" end if r['chef_apply'] != nil and r['chef_apply'] == "false" chef_options = chef_options+" -u " end if r['chef_why_run'] != nil and r['chef_why_run'] == "true" chef_options = chef_options+" -w " end if r['chef_extra_options'] != nil and r['chef_extra_options'] != "" chef_options = chef_options+" -x \"#{r['chef_extra_options']}\"" end if r['chef_delete_repo'] != nil and r['chef_delete_repo'] == "true" chef_options = chef_options+" -n " end if r['chef_sudo_password'] != nil and r['chef_sudo_password'] != "" chef_options = chef_options+" -t \"#{r['chef_sudo_password']}\"" end if r['chef_upgrade_packages'] != nil and r['chef_upgrade_packages'] == "false" chef_options = chef_options+" -z " end if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil if chef_repository != nil chef_repository = chef_repository.gsub('/','\\') end end ENV["EC2_CHEF_REPOSITORY"] = chef_repository ENV["EC2_CHEF_PARAMETERS"] = chef_options if `gem list pocketknife_ec2dream -i`.include?('false') puts "------>Installing pocketknife_ec2dream....." begin system "gem install --no-ri --no-rdoc pocketknife_ec2dream" rescue puts $! end end if `gem list pocketknife_windows -i`.include?('false') puts "------>Installing pocketknife_windows....." begin system "gem install --no-ri --no-rdoc pocketknife_windows" rescue puts $! end end if platform != "windows" if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil c = "cmd.exe /c \@start \"chef-solo #{chef_node} #{ec2_server_name}\" \"#{ENV['EC2DREAM_HOME']}/chef/chef_push.bat\" #{chef_node} #{ec2_server_name}" puts c system(c) else c = "#{ENV['EC2DREAM_HOME']}/chef/chef_push.sh #{chef_repository} #{chef_node} #{ec2_server_name} #{private_key}" puts c system(c) puts "return message #{$?}" end else # TO DO ****** # handle windows servers (only from windows clients) if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil ENV["EC2_CHEF_REPOSITORY"] = chef_repository ENV["EC2_SSH_PASSWORD"] = <PASSWORD> ssh_user = "root" if local_port == nil or local_port == "" c = "cmd.exe /c \@start \"chef-solo #{chef_node} #{ec2_server_name}\" \"#{ENV['EC2DREAM_HOME']}/chef/chef_push_win.bat\" #{chef_node} #{ec2_server_name} #{ssh_user} #{local_port}" puts c system(c) end end self.handle(sender, MKUINT(ID_ACCEPT, SEL_COMMAND), nil) end if parm['chef_apply'] != nil chef_apply.setCurrentItem(0) if parm['chef_apply'] == "true" chef_apply.setCurrentItem(1) if parm['chef_apply'] == "false" end if parm['chef_why_run'] != nil chef_why_run.setCurrentItem(0) if parm['chef_why_run'] == "true" chef_why_run.setCurrentItem(1) if parm['chef_why_run'] == "false" end chef_extra_options.text = parm['chef_extra_options'] if parm['chef_extra_options'] != nil if parm['chef_delete_repo'] != nil chef_delete_repo.setCurrentItem(0) if parm['chef_delete_repo'] == "true" chef_delete_repo.setCurrentItem(1) if parm['chef_delete_repo'] == "false" end chef_sudo_password.text = parm['chef_sudo_password'] if parm['chef_sudo_password'] != nil if parm['chef_upgrade_packages'] != nil chef_upgrade_packages.setCurrentItem(0) if parm['chef_upgrade_packages'] == "true" chef_upgrade_packages.setCurrentItem(1) if parm['chef_upgrade_packages'] == "false" end end def saved @saved end def success @saved end end <file_sep>/README.md ### EC2Dream - Build and Manage Cloud Servers Version 3.7.2 - Mar 2014 For installation see http://ec2dream.blogspot.co.uk/search/label/EC2Dream%20Installation EC2Dream is visual cloud computing admin for the Fog ruby cloud services library and combines Fog, Ruby into an open source devops platform supporting: * Local and Hosted Servers. * Amazon AWS. * Amazon compatible clouds: Eucalyptus, CloudStack. * Openstack Clouds: Rackspace Cloud Servers and HP Cloud. * Google Compute Engine * Cloud Foundry. * Vagrant. * Test Kitchen. It supports remote Chef Solo, Masterless Puppet and Test Kitchen to install software and applications via "one click". All using the one client graphical interface and running on Windows, Linux or Mac OSX clients. (It is written in Ruby using the FXRuby graphics library). ### Features include: * Multiple environments based on access key, region. * A tree view of your servers. * One click SSH, SCP and Remote Desktop access. * One click Chef testing of cookbooks. * One click deregister and delete Image. * Launch and terminate Servers * View Server's System log * Save Launch profile * Support for OpenStack HP Cloud and Rackspace including security groups, servers, keypairs, IP addresses, Block Storage volumes and * Snapshots. * Support for CloudFoundry * Support for Local Servers - Servers running in local virtualized environments like VMWare Player are supported and the Chef * integration will work. Ideal for testing chef cookbooks. * Support for Chef - one click testing of chef cookbooks via chef solo , support for Hosted Chef. Can pass chef runlist in userdata at startup * Support for Puppet - one click testing via masterless puppet * Support for ssh tunnelling allow support of servers in Amazon VPC. * Support for Amazon AWS, Eucalyptus and Cloudstack * Support for Test Kitchen ### It contains: * Ruby and Fog for scripting. * Linux servers scripts in ruby. * PuTTY for Windows SSH access. * winSCP for Windows remote file copying. * launchRDP for launching Windows remote desktop. * tar.exe for Windows chef repository copying <file_sep>/chef/chef_push.sh #!/bin/sh # # Customized pocketknife to run chef-solo on remote node # # chef_push chef_repository chef_node ec2_server_name private_key [ssh_user] # To set a chef version to install add -j <version> to the end of the pocketknife command where <version> is 11.4.2 for example # echo "***************************" echo "*** Calling pocketknife ***" echo "***************************" rm $1/nodes/$3.json cp $1/nodes/$2.json $1/nodes/$3.json cd $1 if [ "$5" = "" ]; then echo "pocketknife -ivk $4 $3" pocketknife -ivk $4 $3 else if [ "$6" = "" ]; then echo "pocketknife -ivk $4 -s $5 $3" pocketknife -ivk $4 -s $5 $3 else echo "pocketknife -ivk $4 -s $5 -l $6 $3" pocketknife -ivk $4 -s $5 -l $6 $3 fi fi rm $1/nodes/$3.json <file_sep>/lib/EC2_Server_kit.rb class EC2_Server # # kitchen server methods # def kit_load(instance,driver,provisioner,last_action) puts "server.kit_load #{instance},#{driver},#{provisioner},#{last_action}" @type = "kit" @frame1.hide() @frame3.hide() @frame4.hide() @frame6.hide() @frame5.hide() @frame7.show() @page1.width=300 @kit_server['instance'].text = instance @kit_server['driver'].text = driver @kit_server['provisioner'].text = provisioner @kit_server['last_action'].text = last_action @kit_server['chef_repository'].text = @ec2_main.settings.get('CHEF_REPOSITORY') @kit_server['chef_foodcritic'].text = @ec2_main.settings.get('CHEF_FOODCRITIC') @kit_server['chef_rspec_test'].text = @ec2_main.settings.get('CHEF_RSPEC_TEST') end def kit_refresh data = kitchen_cmd('list',@kit_server['instance'].text) puts "*** data #{data}" if data != nil and data[0] !=nil @kit_server['instance'].text = data[0]['Instance'] @kit_server['driver'].text = data[0]['Driver'] @kit_server['provisioner'].text = data[0]['Provisioner'] @kit_server['last_action'].text = data[0]['Last-Action'] @kit_server['chef_repository'].text = @ec2_main.settings.get('CHEF_REPOSITORY') @kit_server['chef_foodcritic'].text = @ec2_main.settings.get('CHEF_FOODCRITIC') @kit_server['chef_rspec_test'].text = @ec2_main.settings.get('CHEF_RSPEC_TEST') end end def kit_ssh(utility='ssh') r = kitchen_cmd('config',@kit_server['instance'].text) username = 'root' username = r['username'] if r['username'] != nil and r['username'] != "" username = @kit_server['ssh_user'].text if @kit_server['ssh_user'].text != nil and @kit_server['ssh_user'].text != "" password = nil password = '<PASSWORD>' if @kit_server['driver'].text == 'Vagrant' private_key = nil private_key = @ec2_main.settings.get('EC2_SSH_PRIVATE_KEY') if @kit_server['driver'].text != 'Vagrant' putty_key = nil putty_key = @ec2_main.settings.get('PUTTY_PRIVATE_KEY') if @kit_server['driver'].text != 'Vagrant' if r != nil if utility == 'scp' scp(@kit_server['instance'].text, r['hostname'], username, private_key, putty_key, password,r['port']) else ssh(@kit_server['instance'].text, r['hostname'], username, private_key, putty_key, password,r['port']) end end end def kit_rdp end def kit_winscp kit_ssh('scp') end def kit_edit kitchen_cmd('edit') end def kit_create kitchen_cmd('create',@kit_server['instance'].text,@kit_debug) end def kit_log dialog = KIT_LogSelectDialog.new(@ec2_main) dialog.execute end def kit_destroy kitchen_cmd('destroy',@kit_server['instance'].text,@kit_debug) end def kit_converge kitchen_cmd('converge',@kit_server['instance'].text,@kit_debug) end def kit_verify kitchen_cmd('verify',@kit_server['instance'].text,@kit_debug) end def kit_test kitchen_cmd('test',@kit_server['instance'].text,@kit_debug) end def kit_debug if @kit_debug @kit_debug=false FXMessageBox.information($ec2_main.tabBook,MBOX_OK,"Kitchen Debug Logging","Kitchen Debug Logging set off") else @kit_debug=true FXMessageBox.information($ec2_main.tabBook,MBOX_OK,"Kitchen Debug Logging","Kitchen Debug Logging set on") end end def kit_foodcritic kitchen_cmd('foodcritic',@kit_server['chef_foodcritic'].text) end def kit_rspec_test kitchen_cmd('rspec',@kit_server['chef_rspec_test'].text) end end<file_sep>/lib/dialog/EC2_PuppetEditDialog.rb require 'rubygems' require 'fox16' require 'common/error_message' include Fox class EC2_PuppetEditDialog < FXDialogBox def initialize(owner, server, address, puppet_manifest, ssh_user, private_key, password, platform, local_port, puppet_roles) puts "puppet #{server}, #{address}, #{puppet_manifest}, #{ssh_user}, #{private_key}, #{password}, #{platform}, #{local_port}, #{ puppet_roles}" @saved = false @ec2_main = owner settings = @ec2_main.settings parm = {} puppet_repository = settings.get('PUPPET_REPOSITORY') parm['puppet_module_path'] = settings.get('PUPPET_MODULE_PATH') parm['puppet_apply'] = settings.get('PUPPET_APPLY') parm['puppet_apply_noop'] = settings.get('PUPPET_APPLY_NOOP') parm['puppet_extra_options'] = settings.get('PUPPET_EXTRA_OPTIONS') parm['puppet_delete_repo'] = settings.get('PUPPET_DELETE_REPO') parm['puppet_sudo_password'] = settings.get('PUPPET_SUDO_PASSWORD') parm['puppet_upgrade_packages'] = settings.get('PUPPET_UPGRADE_PACKAGES') @magnifier = @ec2_main.makeIcon("magnifier.png") @magnifier.create if puppet_manifest == nil or puppet_manifest == "" puppet_manifest = 'init.pp' end ec2_server_name = server if address != nil and address != "" ec2_server_name = address end #node_name = "#{chef_repository}/nodes/#{chef_node}.json" if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil if puppet_repository != nil puppet_repository = puppet_repository.gsub('/','\\') end if private_key != nil private_key = private_key.gsub('/','\\') end #node_name = node_name.gsub('/','\\') end if puppet_repository == nil or puppet_repository == "" error_message("No Puppet Repository","No PUPPET_REPOSITORY specified in Settings") return false end if private_key == nil or private_key == "" and (password == nil or password == "") error_message("No ec2 ssh private key","No EC2_SSH_PRIVATE_KEY specified") return false end #if !File.exists?(node_name) # error_message("No Chef Node file","No Chef Node file #{node_name} for this server") # return false #end if ec2_server_name == nil or ec2_server_name == "" error_message("No Public of Private DSN","This Server does not have a Public or Private DSN") return false end short_name = ec2_server_name if ec2_server_name.size > 16 sa = (ec2_server_name).split"." if sa.size>1 short_name = sa[0] end end super(@ec2_main, "Puppet", :opts => DECOR_ALL, :width => 550, :height => 275) page1 = FXVerticalFrame.new(self, LAYOUT_FILL, :padding => 0) frame1 = FXMatrix.new(page1, 3, :opts => MATRIX_BY_COLUMNS|LAYOUT_FILL) FXLabel.new(frame1, "Puppet Module Path" ) puppet_module_path = FXTextField.new(frame1, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(frame1, "(separated by colons)" ) FXLabel.new(frame1, "Run Puppet Apply" ) puppet_apply = FXComboBox.new(frame1, 15, :opts => COMBOBOX_STATIC|COMBOBOX_NO_REPLACE|LAYOUT_LEFT) puppet_apply.numVisible = 2 puppet_apply.appendItem("true") puppet_apply.appendItem("false") puppet_apply.setCurrentItem(0) FXLabel.new(frame1, "" ) FXLabel.new(frame1, "Run Puppet Apply --noop" ) puppet_apply_noop = FXComboBox.new(frame1, 15, :opts => COMBOBOX_STATIC|COMBOBOX_NO_REPLACE|LAYOUT_LEFT) puppet_apply_noop.numVisible = 2 puppet_apply_noop.appendItem("true") puppet_apply_noop.appendItem("false") puppet_apply_noop.setCurrentItem(1) FXLabel.new(frame1, "" ) FXLabel.new(frame1, "Extra Puppet apply options" ) puppet_extra_options = FXTextField.new(frame1, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(frame1, "" ) FXLabel.new(frame1, "Delete Puppet Repo" ) puppet_delete_repo = FXComboBox.new(frame1, 15, :opts => COMBOBOX_STATIC|COMBOBOX_NO_REPLACE|LAYOUT_LEFT) puppet_delete_repo.numVisible = 2 puppet_delete_repo.appendItem("true") puppet_delete_repo.appendItem("false") puppet_delete_repo.setCurrentItem(1) FXLabel.new(frame1, "" ) FXLabel.new(frame1, "Sudo Password" ) puppet_sudo_password = FXTextField.new(frame1, 40, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_RIGHT) FXLabel.new(frame1, "" ) FXLabel.new(frame1, "Upgrade Packages" ) puppet_upgrade_packages = FXComboBox.new(frame1, 15, :opts => COMBOBOX_STATIC|COMBOBOX_NO_REPLACE|LAYOUT_LEFT) puppet_upgrade_packages.numVisible = 2 puppet_upgrade_packages.appendItem("true") puppet_upgrade_packages.appendItem("false") puppet_upgrade_packages.setCurrentItem(0) FXLabel.new(frame1, "" ) frame2 = FXMatrix.new(page1, 1, :opts => MATRIX_BY_COLUMNS|LAYOUT_CENTER_X) puppet_message = FXLabel.new(frame2, "Server #{server} #{short_name} - Confirm Running Puppet Apply\n for Manifest #{puppet_manifest} and Puppet Roles #{puppet_roles} ", :opts => LAYOUT_CENTER_X ) FXLabel.new(frame2, "" ) frame3 = FXHorizontalFrame.new(page1,LAYOUT_FILL, :padding => 0) yes = FXButton.new(frame3, " &Yes ", nil, self, ID_ACCEPT, FRAME_RAISED|LAYOUT_LEFT|LAYOUT_CENTER_X) no = FXButton.new(frame3, " &No ", nil, self, ID_CANCEL, FRAME_RAISED|LAYOUT_CENTER_X|LAYOUT_SIDE_BOTTOM) no.connect(SEL_COMMAND) do |sender, sel, data| self.handle(sender, MKUINT(ID_ACCEPT, SEL_COMMAND), nil) end yes.connect(SEL_COMMAND) do |sender, sel, data| r = {} r['puppet_module_path']=puppet_module_path.text r['puppet_apply']="false" if puppet_apply.itemCurrent?(0) r['puppet_apply']="true" end r['puppet_apply_noop']="false" if puppet_apply_noop.itemCurrent?(0) r['puppet_apply_noop']="true" end r['puppet_extra_options']=puppet_extra_options.text r['puppet_delete_repo']="false" if puppet_delete_repo.itemCurrent?(0) r['puppet_delete_repo']="true" end r['puppet_sudo_password']=puppet_sudo_password.text r['puppet_upgrade_packages']="false" if puppet_upgrade_packages.itemCurrent?(0) r['puppet_upgrade_packages']="true" end settings.put('PUPPET_MODULE_PATH',r['puppet_module_path']) settings.put('PUPPET_APPLY',r['puppet_apply']) settings.put('PUPPET_APPLY_NOOP',r['puppet_apply_noop']) settings.put('PUPPET_EXTRA_OPTIONS',r['puppet_extra_options']) settings.put('PUPPET_DELETE_REPO',r['puppet_delete_repo']) settings.put('PUPPET_SUDO_PASSWORD',r['puppet_sudo_password']) settings.put('PUPPET_UPGRADE_PACKAGES',r['puppet_upgrade_packages']) settings.save @saved = true puppet_options = "-iv" if private_key != nil and private_key !="" puppet_options = puppet_options+"k #{private_key}" else puppet_options = puppet_options+"p #{password}" end puppet_options = puppet_options+" -m #{puppet_manifest}" if ssh_user != nil and ssh_user != "" puppet_options = puppet_options+" -s #{ssh_user}" end if local_port != nil and local_port != "" puppet_options = puppet_options+" -l #{local_port}" end if puppet_roles != nil and puppet_roles != "" roles = puppet_roles.split(',') facts = "" i=0 roles.each do |r| i=i+1 if facts != "" facts=facts+",role_name#{i}=#{r}" else facts=facts+"role_name#{i}=#{r}" end end puppet_options = puppet_options+" -f \"#{facts}\"" end if r['puppet_module_path'] != nil and r['puppet_module_path'] != "" puppet_options = puppet_options+" -d \"#{r['puppet_module_path']}\"" end if r['puppet_apply'] != nil and r['puppet_apply'] == "false" puppet_options = puppet_options+" -u " end if r['puppet_apply_noop'] != nil and r['puppet_apply_noop'] == "true" puppet_options = puppet_options+" -o " end if r['puppet_extra_options'] != nil and r['puppet_extra_options'] != "" puppet_options = puppet_options+" -x \"#{r['puppet_extra_options']}\"" end if r['puppet_delete_repo'] != nil and r['puppet_delete_repo'] == "true" puppet_options = puppet_options+" -n " end if r['puppet_sudo_password'] != nil and r['puppet_sudo_password'] != "" puppet_options = puppet_options+" -t \"#{r['puppet_sudo_password']}\"" end if r['puppet_upgrade_packages'] != nil and r['puppet_upgrade_packages'] == "false" puppet_options = puppet_options+" -z " end puppet_options = puppet_options+" -e hiera.yaml" ENV["EC2_PUPPET_REPOSITORY"] = puppet_repository ENV["EC2_PUPPET_PARAMETERS"] = puppet_options if `gem list pocketknife_puppet -i`.include?('false') puts "------>Installing pocketknife_puppet....." begin system "gem install --no-ri --no-rdoc pocketknife_puppet" rescue puts $! end end if platform != "windows" if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil c = "cmd.exe /c \@start \"puppet apply #{ec2_server_name}\" \"#{ENV['EC2DREAM_HOME']}/puppet/puppet_push.bat\" #{ec2_server_name}" puts c system(c) else c = "#{ENV['EC2DREAM_HOME']}/puppet/puppet_push.sh #{ec2_server_name}" puts c system(c) puts "return message #{$?}" end else # handle windows servers (only from windows clients) #if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil # ENV["EC2_CHEF_REPOSITORY"] = chef_repository # ENV["EC2_SSH_PASSWORD"] = <PASSWORD> # c = "cmd.exe /c \@start \"chef-solo #{puppet_manifest} #{ec2_server_name}\" \"#{ENV['EC2DREAM_HOME']}/chef/chef_push_win.bat\" #{puppet_manifest} #{ec2_server_name} #{ssh_user} #{local_port}" # puts c # system(c) #end end self.handle(sender, MKUINT(ID_ACCEPT, SEL_COMMAND), nil) end puppet_module_path.text = parm['puppet_module_path'] if parm['puppet_module_path'] != nil if parm['puppet_apply'] != nil puppet_apply.setCurrentItem(0) if parm['puppet_apply'] == "true" puppet_apply.setCurrentItem(1) if parm['puppet_apply'] == "false" end if parm['puppet_apply_noop'] != nil puppet_apply_noop.setCurrentItem(0) if parm['puppet_apply_noop'] == "true" puppet_apply_noop.setCurrentItem(1) if parm['puppet_apply_noop'] == "false" end puppet_extra_options.text = parm['puppet_extra_options'] if parm['puppet_extra_options'] != nil if parm['puppet_delete_repo'] != nil puppet_delete_repo.setCurrentItem(0) if parm['puppet_delete_repo'] == "true" puppet_delete_repo.setCurrentItem(1) if parm['puppet_delete_repo'] == "false" end puppet_sudo_password.text = parm['puppet_sudo_password'] if parm['puppet_sudo_password'] != nil if parm['puppet_upgrade_packages'] != nil puppet_upgrade_packages.setCurrentItem(0) if parm['puppet_upgrade_packages'] == "true" puppet_upgrade_packages.setCurrentItem(1) if parm['puppet_upgrade_packages'] == "false" end end def saved @saved end def success @saved end end <file_sep>/lib/common/chef.rb def chef(server, address, chef_node, ssh_user, private_key, password, platform="", local_port="") puts "chef #{server}, #{address}, #{chef_node}, #{ssh_user}, #{private_key}, #{password}, #{platform}, #{local_port}" # private_key = @ec2_main.settings.get('EC2_SSH_PRIVATE_KEY') #chef_node = @secgrp #if @server['Chef_Node'].text != nil and @server['Chef_Node'].text != "" # chef_node = @server['Chef_Node'].text #end # ec2_server_name = @server['Public_DSN'].text # ssh_user = @server['EC2_SSH_User'].text chef_repository = $ec2_main.settings.get('CHEF_REPOSITORY') chef_foodcritic = $ec2_main.settings.get('CHEF_FOODCRITIC') chef_rspec_test = $ec2_main.settings.get('CHEF_RSPEC_TEST') chef_apply = $ec2_main.settings.get('CHEF_APPLY') chef_why_run = $ec2_main.settings.get('CHEF_WHY_RUN') chef_extra_options = $ec2_main.settings.get('CHEF_EXTRA_OPTIONS') chef_delete_repo = $ec2_main.settings.get('CHEF_DELETE_REPO') chef_sudo_password = $ec2_main.settings.get('CHEF_SUDO_PASSWORD') chef_upgrade_packages = $ec2_main.settings.get('CHEF_UPGRADE_PACKAGES') if chef_node == nil or chef_node == "" chef_node = server end ec2_server_name = server if address != nil and address != "" ec2_server_name = address end node_name = "#{chef_repository}/nodes/#{chef_node}.json" if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil if chef_repository != nil chef_repository = chef_repository.gsub('/','\\') end if private_key != nil private_key = private_key.gsub('/','\\') end node_name = node_name.gsub('/','\\') end if chef_repository == nil or chef_repository == "" error_message("No Chef Repository","No CHEF_REPOSITORY specified in Settings") return false end if private_key == nil or private_key == "" and (password == nil or password == "") error_message("No ec2 ssh private key","No EC2_SSH_PRIVATE_KEY specified") return false end if !File.exists?(node_name) error_message("No Chef Node file","No Chef Node file #{node_name} for this server") return false end if ec2_server_name == nil or ec2_server_name == "" error_message("No Public of Private DSN","This Server does not have a Public or Private DSN") return false end short_name = ec2_server_name if ec2_server_name.size > 16 sa = (ec2_server_name).split"." if sa.size>1 short_name = sa[0] end end answer = FXMessageBox.question($ec2_main.tabBook,MBOX_YES_NO,"Confirm Chef Solo","Confirm Running of Chef-Solo for Node #{chef_node} on server #{short_name}") if answer == MBOX_CLICKED_YES if local_port == nil or local_port == "" ssh_user = "root" if ssh_user == nil or ssh_user == "" end chef_options = "-iv" if private_key != nil and private_key !="" chef_options = chef_options+"k #{private_key}" else chef_options = chef_options+"p #{password}" end if ssh_user != nil and ssh_user != "" chef_options = chef_options+" -s #{ssh_user}" end if local_port != nil and local_port != "" chef_options =chef_options+" -l #{local_port}" end if chef_foodcritic != nil and chef_foodcritic != "" chef_options = chef_options+" -f \"#{chef_foodcritic}\"" end if chef_rspec_test != nil and chef_rspec_test != "" chef_options = chef_options+" -r \"#{chef_rspec_test}\"" end if chef_apply != nil and chef_apply == "false" chef_options = chef_options+" -u " end if chef_why_run != nil and chef_why_run == "true" chef_options = chef_options+" -w " end if chef_extra_options != nil and chef_extra_options != "" chef_options = chef_options+" -x \"#{chef_extra_options}\"" end if chef_delete_repo != nil and chef_delete_repo == "true" chef_options = chef_options+" -n " end if chef_sudo_password != nil and chef_sudo_password != "" chef_options = chef_options+" -t \"#{chef_sudo_password}\"" end if chef_upgrade_packages != nil and chef_upgrade_packages == "false" chef_options = chef_options+" -z " end ENV["EC2_CHEF_REPOSITORY"] = chef_repository ENV["EC2_CHEF_PARAMETERS"] = chef_options if platform != "windows" if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil c = "cmd.exe /c \@start \"chef-solo #{chef_node} #{ec2_server_name}\" \"#{ENV['EC2DREAM_HOME']}/chef/chef_push.bat\" #{chef_node} #{ec2_server_name}" puts c system(c) else c = "#{ENV['EC2DREAM_HOME']}/chef/chef_push.sh #{chef_repository} #{chef_node} #{ec2_server_name} #{private_key}" puts c system(c) puts "return message #{$?}" end else # TO DO ****** # handle windows servers (only from windows clients) if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil ENV["EC2_CHEF_REPOSITORY"] = chef_repository ENV["EC2_SSH_PASSWORD"] = <PASSWORD> ssh_user = "root" if local_port == nil or local_port == "" c = "cmd.exe /c \@start \"chef-solo #{chef_node} #{ec2_server_name}\" \"#{ENV['EC2DREAM_HOME']}/chef/chef_push_win.bat\" #{chef_node} #{ec2_server_name} #{ssh_user} #{local_port}" puts c system(c) end end return true end return false end <file_sep>/lib/dialog/EC2_SystemDialog.rb require 'rubygems' require 'fox16' require 'net/http' require 'resolv' require 'common/error_message' include Fox class EC2_SystemDialog < FXDialogBox def initialize(owner) puts "SystemDialog.initialize" @ec2_main = owner @valid_loc = false @settings = @ec2_main.settings @loc = "" @remloc = "" local_repository = "#{ENV['EC2DREAM_HOME']}/env" if !File.directory? local_repository puts "creating....#{local_repository}" Dir.mkdir(local_repository) @settings.put_system("REPOSITORY_LOCATION","") defaults @settings.save_system() elsif File.exists?(ENV['EC2DREAM_HOME']+"/env/system.properties") @loc = @settings.get_system("REPOSITORY_LOCATION") @remloc = @settings.get_system("REPOSITORY_REMOTE") if @loc == ENV['EC2DREAM_HOME']+"/env" @loc = "" end end super(owner, "Environment Repository", :opts => DECOR_ALL, :width => 600, :height => 250, :x => 300, :y => 200 ) page1 = FXVerticalFrame.new(self, LAYOUT_FILL, :padding => 0) frame1a = FXMatrix.new(page1, 1, :opts => MATRIX_BY_COLUMNS|LAYOUT_FILL) FXLabel.new(frame1a, "The Environment Repository is where configuration is stored." ) FXLabel.new(frame1a, "Checking Local Environment Repository stores the information inside the ruby directory structure." ) FXLabel.new(frame1a, "For production use a repository location and create backups." ) FXLabel.new(frame1a, "NOTE: You must first create the directory using Windows Explorer or the command line" ) frame1 = FXMatrix.new(page1, 3, :opts => MATRIX_BY_COLUMNS|LAYOUT_FILL) FXLabel.new(frame1, "" ) local_check = FXCheckButton.new(frame1,"Local Environment Repository", :opts => ICON_BEFORE_TEXT|LAYOUT_SIDE_BOTTOM|LAYOUT_FILL_X) FXLabel.new(frame1, "" ) FXLabel.new(frame1, "Repository Location" ) location = FXTextField.new(frame1, 60, nil, 0, :opts => FRAME_SUNKEN|LAYOUT_FILL_X|LAYOUT_FILL_COLUMN) location_button = FXButton.new(frame1, "", :opts => BUTTON_TOOLBAR) magnifier = @ec2_main.makeIcon("magnifier.png") magnifier.create location_button.icon = magnifier location_button.tipText = "Browse..." location_button.connect(SEL_COMMAND) do if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil location.text = FXDirDialog.getOpenDirectory(frame1, "Select Repository Location", "C:/") else location.text = FXDirDialog.getOpenDirectory(frame1, "Select Repository Location", "/") end end if @loc != nil and @loc != "" @local = false location.text = @loc local_check.setCheck(false) location.enable location_button.enable else @local = true location.text = "" local_check.setCheck(true) location.disable location_button.disable end local_check.connect(SEL_COMMAND) do if @local == false @local = true location.text = "" location.disable location_button.disable else @local = false if @remloc != nil and @remloc.length>0 location.text= @remloc else location.text = "" end location.enable location_button.enable end end FXLabel.new(frame1, "" ) ok = FXButton.new(frame1, " &OK ", nil, self, ID_ACCEPT, FRAME_RAISED|LAYOUT_LEFT|LAYOUT_CENTER_X) FXLabel.new(frame1, "" ) ok.connect(SEL_COMMAND) do |sender, sel, data| @valid_loc = true if @local == false envs = nil begin envs = Dir.entries(location.text) rescue @valid_loc = false error_message("Repository Location does not exist",$!) end end if @valid_loc == true if @local == false @settings.put_system("REPOSITORY_LOCATION",location.text) @settings.put_system("REPOSITORY_REMOTE",location.text) else @settings.put_system("REPOSITORY_LOCATION","") end defaults @settings.put_system('ENVIRONMENT','') @settings.put_system('AUTO','false') @settings.save_system() self.handle(sender, MKUINT(ID_ACCEPT, SEL_COMMAND), nil) end end end def selected return @valid_loc end def defaults if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil @settings.put_system('EXTERNAL_EDITOR',"notepad") # default to notepad @settings.put_system('EXTERNAL_BROWSER',"C:\\Program Files\\Internet Explorer\\iexplore.exe") else if RUBY_PLATFORM.index("linux") != nil @settings.put_system('EXTERNAL_EDITOR',"gedit") # default to vi @settings.put_system('EXTERNAL_BROWSER',"/usr/bin/firefox") else @settings.put_system('EXTERNAL_EDITOR',"xterm -e /Applications/TextEdit.app/Contents/MacOS/TextEdit") @settings.put_system('EXTERNAL_BROWSER',"open") end end @settings.put_system('TIMEZONE',"UTC") end end <file_sep>/puppet/puppet_repo/Puppetfile forge "http://forge.puppetlabs.com" mod "puppetlabs/apache" mod "ripienaar/concat" mod "puppetlabs/stdlib" mod "neillturner/role", "0.0.4"<file_sep>/lib/common/button_config.rb def button_config(sender,icon,tip) sender.enabled = true sender.icon = icon sender.tipText = tip end<file_sep>/lib/dialog/EC2_InstanceModifyDialog.rb require 'rubygems' require 'fox16' require 'net/http' require 'resolv' require 'common/error_message' include Fox class EC2_InstanceModifyDialog < FXDialogBox def initialize(owner, instance_id) puts "InstanceModifyDialog.initialize" @ec2_main = owner @modified = false @orig_server = {} @server = {} @ec2_main.serverCache.refresh(instance_id) @cache = @ec2_main.serverCache.instance(instance_id) super(owner, "Modify Instance", :opts => DECOR_ALL, :width => 600, :height => 350) @page1 = FXVerticalFrame.new(self, LAYOUT_FILL, :padding => 0) @frame1 = FXMatrix.new(@page1, 3, :opts => MATRIX_BY_COLUMNS|LAYOUT_FILL) FXLabel.new(@frame1, "Instance ID" ) @server['Instance_ID'] = FXTextField.new(@frame1, 60, nil, 0, :opts => TEXTFIELD_READONLY) @server['Instance_ID'].text = instance_id FXLabel.new(@frame1, "" ) FXLabel.new(@frame1, "Instance Type" ) @server['Instance_Type'] = FXTextField.new(@frame1, 60, nil, 0, :opts => FRAME_SUNKEN) @server['Instance_Type'].text = get_attribute(instance_id,"instanceType") @orig_server['Instance_Type'] = @server['Instance_Type'].text @server['Instance_Type_Button'] = FXButton.new(@frame1, "", :opts => BUTTON_TOOLBAR) @magnifier = @ec2_main.makeIcon("magnifier.png") @magnifier.create @server['Instance_Type_Button'].icon = @magnifier @server['Instance_Type_Button'].tipText = "Select Instance Type" @server['Instance_Type_Button'].connect(SEL_COMMAND) do @dialog = EC2_InstanceDialog.new(@ec2_main) @dialog.execute type = @dialog.selected if type != nil and type != "" @server['Instance_Type'].text = type end end FXLabel.new(@frame1, "Kernel" ) @server['Kernel'] = FXTextField.new(@frame1, 60, nil, 0, :opts => FRAME_SUNKEN) @server['Kernel'].text = get_attribute(instance_id,"kernelId") @orig_server['Kernel'] = @server['Kernel'].text FXLabel.new(@frame1, "" ) FXLabel.new(@frame1, "Ramdisk" ) @server['Ramdisk'] = FXTextField.new(@frame1, 60, nil, 0, :opts => FRAME_SUNKEN) @server['Ramdisk'].text = get_attribute(instance_id,"ramdiskId") @orig_server['Ramdisk'] = @server['Ramdisk'].text FXLabel.new(@frame1, "" ) FXLabel.new(@frame1, "User Data" ) @server['User_Data'] = FXTextField.new(@frame1, 60, nil, 0, :opts => FRAME_SUNKEN) @server['User_Data'].text = "" # get_attribute(instance_id,"userData") @orig_server['User_Data'] = @server['User_Data'].text FXLabel.new(@frame1, "" ) FXLabel.new(@frame1, "User Data File") @server['User_Data_File'] = FXTextField.new(@frame1, 60, nil, 0, :opts => FRAME_SUNKEN) @server['User_Data_File_Button'] = FXButton.new(@frame1, "", :opts => BUTTON_TOOLBAR) @server['User_Data_File_Button'].icon = @magnifier @server['User_Data_File_Button'].tipText = "Browse..." @server['User_Data_File_Button'].connect(SEL_COMMAND) do dialog = FXFileDialog.new(@frame1, "Select User Data file") dialog.patternList = [ "Pem Files (*.*)" ] dialog.selectMode = SELECTFILE_EXISTING if dialog.execute != 0 @server['User_Data_File'].text = dialog.filename end end FXLabel.new(@frame1, "Disable Api Termination" ) @server['Disable_Api_Termination'] = FXComboBox.new(@frame1, 15, :opts => COMBOBOX_NO_REPLACE|LAYOUT_LEFT) @server['Disable_Api_Termination'].numVisible = 2 @server['Disable_Api_Termination'].appendItem("true") @server['Disable_Api_Termination'].appendItem("false") @server['Disable_Api_Termination'].setCurrentItem(0) disable_api = get_attribute(instance_id,"disableApiTermination") disable_api = disable_api.to_s @orig_server['Disable_Api_Termination'] = disable_api if disable_api == "true" @server['Disable_Api_Termination'].setCurrentItem(0) else @server['Disable_Api_Termination'].setCurrentItem(1) end FXLabel.new(@frame1, "" ) FXLabel.new(@frame1, " Instance Init Shutdown" ) @server['Instance_Initiated_Shutdown_Behavior'] = FXComboBox.new(@frame1, 15, :opts => COMBOBOX_NO_REPLACE|LAYOUT_LEFT) @server['Instance_Initiated_Shutdown_Behavior'].numVisible = 2 @server['Instance_Initiated_Shutdown_Behavior'].appendItem("stop") @server['Instance_Initiated_Shutdown_Behavior'].appendItem("terminate") @server['Instance_Initiated_Shutdown_Behavior'].setCurrentItem(0) instance_init_shut = get_attribute(instance_id,"instanceInitiatedShutdownBehavior") instance_init_shut = instance_init_shut.to_s @orig_server['Instance_Initiated_Shutdown_Behavior'] = instance_init_shut if instance_init_shut == "stop" @server['Instance_Initiated_Shutdown_Behavior'].setCurrentItem(0) else @server['Instance_Initiated_Shutdown_Behavior'].setCurrentItem(1) end FXLabel.new(@frame1, "" ) FXLabel.new(@frame1, " Source/Dest Check" ) @server['Source_Dest_Check'] = FXComboBox.new(@frame1, 15, :opts => COMBOBOX_NO_REPLACE|LAYOUT_LEFT) @server['Source_Dest_Check'].numVisible = 2 @server['Source_Dest_Check'].appendItem("true") @server['Source_Dest_Check'].appendItem("false") @server['Source_Dest_Check'].setCurrentItem(0) source_dest_check = get_attribute(instance_id,"sourceDestCheck") source_dest_check = source_dest_check.to_s @orig_server['Source_Dest_Check'] = source_dest_check if source_dest_check == "true" @server['Instance_Initiated_Shutdown_Behavior'].setCurrentItem(0) else @server['Instance_Initiated_Shutdown_Behavior'].setCurrentItem(1) end FXLabel.new(@frame1, "" ) FXLabel.new(@frame1, "Root Device Name" ) @server['Root_Device_Name'] = FXTextField.new(@frame1, 60, nil, 0, :opts => TEXTFIELD_READONLY) @server['Root_Device_Name'].text = get_attribute(instance_id,"rootDeviceName") @orig_server['Root_Device_Name'] = @server['Root_Device_Name'].text FXLabel.new(@frame1, "" ) @frame2 = FXMatrix.new(self, 3, :opts => MATRIX_BY_COLUMNS|LAYOUT_FILL) @frame2 = FXHorizontalFrame.new(@page1,LAYOUT_FILL, :padding => 0) FXLabel.new(@frame2, "" ) modify = FXButton.new(@frame2, " &Modify ", nil, self, ID_ACCEPT, FRAME_RAISED|LAYOUT_LEFT|LAYOUT_CENTER_X) FXLabel.new(@frame2, "" ) modify.connect(SEL_COMMAND) do |sender, sel, data| modify_instance if @modified == true self.handle(sender, MKUINT(ID_ACCEPT, SEL_COMMAND), nil) end end end def modify_instance modify_attribute(@server['Instance_ID'].text,'InstanceType.Value',@server['Instance_Type'].text, @orig_server['Instance_Type']) modify_attribute(@server['Instance_ID'].text,'Kernel.Value',@server['Kernel'].text, @orig_server['Kernel']) modify_attribute(@server['Instance_ID'].text,'Ramdisk.Value',@server['Ramdisk'].text, @orig_server['Ramdisk']) modify_attribute(@server['Instance_ID'].text,'UserData.Value',@server['User_Data'].text, @orig_server['User_Data']) if @server['User_Data_File'].text != nil and @server['User_Data_File'].text != "" fn = @server['User_Data_File'].text d = "" begin f = File.open(fn, "r") d = f.read f.close rescue puts "ERROR: could not read user data file" error_message("Attribute Error","Could not read User Data File") return end modify_attribute(@server['Instance_ID'].text,'UserData.Value',d,"") end disable_api = "true" if @server['Disable_Api_Termination'].itemCurrent?(1) disable_api = "false" end modify_attribute(@server['Instance_ID'].text,'DisableApiTermination.Value',disable_api, @orig_server['Disable_Api_Termination']) instance_init_shut = "stop" if @server['Instance_Initiated_Shutdown_Behavior'].itemCurrent?(1) instance_init_shut = "terminate" end modify_attribute(@server['Instance_ID'].text,'InstanceInitiatedShutdownBehavior.Value',instance_init_shut, @orig_server['Instance_Initiated_Shutdown_Behavior']) #modify_attribute(@server['Instance_ID'].text,'RootDeviceName',@server['Root_Device_Name'].text, @orig_server['Root_Device_Name']) end def modify_attribute(instance,attr,value,orig_value) if orig_value != value begin puts "attr #{attr} value #{value} orig_value #{orig_value}" if attr == 'DisableApiTermination.Value' bvalue = false bvalue = true if attr == 'DisableApiTermination.Value' and value == "true" @ec2_main.environment.servers.modify_instance_attribute(instance,attr,bvalue) else @ec2_main.environment.servers.modify_instance_attribute(instance,attr,value) end orig_value = value @modified = true rescue error_message("Modify Instance Attribute Failed",$!) end end end def get_attribute(instance,attr) value = "" if @cache != nil and @cache != "" value = @cache[attr] if @cache[attr] != nil puts "instance attribute #{attr} not found" if @cache[attr] == nil else error_message("Instance Error","Instance #{instance} not found") end return value end def saved @modified end def modified @modified end def success @modified end end<file_sep>/chef/old_chef-repo/test/integration/default/serverspec/localhost/mycompany_webserver_spec.rb require 'spec_helper' describe 'mycompany webserver' do it 'should be running the httpd server' do case RSpec.configuration.os when "Debian" expect(service 'apache2').to be_running expect(service 'apache2').to be_enabled else expect(service 'httpd').to be_running expect(service 'httpd').to be_enabled end end describe port(80) do it { should be_listening } end end<file_sep>/chef/old_chef-repo/Berksfile site :opscode cookbook 'aws' cookbook 'apache2' cookbook 'base' , path: 'site-cookbooks/base' cookbook 'mycompany_webserver' , path: 'site-cookbooks/mycompany_webserver'<file_sep>/lib/data/Data_flavors.rb require 'rubygems' require 'fox16' require 'net/http' require 'resolv' require 'fog' class Data_flavors def initialize(owner) puts "Data_flavors.initialize" @ec2_main = owner end # List Instance Types or Flavours # # Returns a array of strings containing instance types or flavor in openstack terminology # def all data = [] if @ec2_main.settings.openstack conn = @ec2_main.environment.connection if conn != nil begin x = conn.flavors.all x.each do |y| vcpu = nil begin vcpu = y.vcpus rescue vcpu = nil end if vcpu != nil data.push("#{y.id} (#{y.name} Mem: #{y.ram}MB Disk: #{y.disk}GB VCPU: #{y.vcpus}VCPUs)") else data.push("#{y.id} (#{y.name} Mem: #{y.ram}MB Disk: #{y.disk}GB)") end end rescue puts "ERROR: getting all flavors #{$!}" end else raise "Connection Error" end elsif @ec2_main.settings.google conn = @ec2_main.environment.connection if conn != nil begin response = conn.list_machine_types($google_zone) if response.status == 200 x = response.body['items'] x.each do |r| data.push("#{r['name']} ( Mem: #{r['memoryMb']}MB Disks: #{r['maximumPersistentDisks']} Disk Size: #{r['maximumPersistentDisksSizeGb']}GB CPUs: #{r['guestCpus']})") end else data = [] end rescue puts "ERROR: getting all flavors #{$!}" end else raise "Connection Error" end else data.push('t1.micro (EBS only Micro 32 or 64-bit, 613 MB, up to 2 compute unit)') data.push('m1.small (Small 32 or 64-bit, 1.7 GB, 1 compute unit)') data.push('m1.medium (Medium 32 or 64-bit, 3.75 GB, 2 compute unit)') data.push('m1.large (Large 64-bit, 7.5 GB, 4 compute unit)') data.push('m1.xlarge (Extra Large 64-bit, 15 GB, 8 compute unit)') data.push('m3.xlarge (EBS Only Extra Large 64-bit, 15 GB, 13 compute unit)') data.push('m3.2xlarge (EBS Only Extra Double Large 64-bit, 30 GB, 26 compute unit)') data.push('m2.xlarge (High Memory Extra Large 64-bit, 17.1 GB, 6.5 compute unit)') data.push('m2.2xlarge (High Memory Double Extra Large 64-bit, 34.2 GB, 13 compute unit)') data.push('m2.4xlarge (High Memory Quadruple Large 64-bit, 68.4 GB, 26 compute unit)') data.push('c1.medium (Compute optimized CPU Medium 32 or 64-bit, 1.7 GB, 5 compute unit)') data.push('c1.xlarge (Compute optimized CPU Extra Large 64-bit, 7 GB, 20 compute unit)') data.push('c3.xlarge (Compute optimized Extra Large 64-bit, 3.75 GB, 7 compute unit)') data.push('c3.2xlarge (Compute optimized Double Extra Large 64-bit, 7 GB, 14 compute unit)') data.push('c3.4xlarge (Compute optimized Quadruple Large 64-bit, 15 GB, 28 compute unit)') data.push('c3.8xlarge (Compute optimized Eight Large 64-bit, 30 GB, 55 compute unit)') data.push('i2.xlarge (High I/O 1x800 GB SSD, 30.5 GB, 14 compute unit)') data.push('i2.2xlarge (High I/O 2x800 GB SSD, 61 GB, 27 compute unit)') data.push('i2.4xlarge (High I/O 4x800 GB SSD, 122 GB, 53 compute unit)') data.push('i2.8xlarge (High I/O 8x800 GB SSD, 244 GB, 104 compute unit)') data.push('cc1.4xlarge (Cluster Compute Quadruple Extra Large 64-bit, 23 GB, 33.5 compute unit. 10GBit network)') data.push('cc2.8xlarge (Cluster Compute Eight Extra Large 64-bit, 60.5 GB, 88 compute unit. 10GBit network)') data.push('g2.2xlarge (Cluster GPU Quadruple Extra Large 64-bit, 15 GB, 26compute unit.)') data.push('cg1.4xlarge (Cluster GPU Quadruple Extra Large 64-bit, 22 GB, 33.5 compute unit. 10GBit network)') data.push('hi1.4xlarge (High I/O Quadruple Extra Large 64-bit, 60.5 GB, 2x1024GB SSD, 35 compute unit. 10GBit network)') data.push('hs1.8xlarge (High I/O Quadruple Extra Large 64-bit, 117 GB, 24x2048GB SSD, 35 compute unit. 10GBit network)') end return data end end<file_sep>/lib/common/puppet.rb def puppet(server, address, puppet_manifest, ssh_user, private_key, password, platform="", local_port="", puppet_roles="" ) # private_key = @ec2_main.settings.get('EC2_SSH_PRIVATE_KEY') #chef_node = @secgrp #if @server['Chef_Node'].text != nil and @server['Chef_Node'].text != "" # chef_node = @server['Chef_Node'].text #end # ec2_server_name = @server['Public_DSN'].text # ssh_user = @server['EC2_SSH_User'].text puppet_repository = $ec2_main.settings.get('PUPPET_REPOSITORY') puppet_module_path = $ec2_main.settings.get('PUPPET_MODULE_PATH') puppet_syntax_check = $ec2_main.settings.get('PUPPET_SYNTAX_CHECK') puppet_rspec_test = $ec2_main.settings.get('PUPPET_RSPEC_TEST') puppet_apply = $ec2_main.settings.get('PUPPET_APPLY') puppet_apply_noop = $ec2_main.settings.get('PUPPET_APPLY_NOOP') puppet_extra_options = $ec2_main.settings.get('PUPPET_EXTRA_OPTIONS') puppet_delete_repo = $ec2_main.settings.get('PUPPET_DELETE_REPO') puppet_sudo_password = $ec2_main.settings.get('PUPPET_SUDO_PASSWORD') puppet_upgrade_packages = $ec2_main.settings.get('PUPPET_UPGRADE_PACKAGES') if puppet_manifest == nil or puppet_manifest == "" puppet_manifest = 'init.pp' end ec2_server_name = server if address != nil and address != "" ec2_server_name = address end #node_name = "#{chef_repository}/nodes/#{chef_node}.json" if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil if puppet_repository != nil puppet_repository = puppet_repository.gsub('/','\\') end if private_key != nil private_key = private_key.gsub('/','\\') end #node_name = node_name.gsub('/','\\') end if puppet_repository == nil or puppet_repository == "" error_message("No Puppet Repository","No PUPPET_REPOSITORY specified in Settings") return false end if private_key == nil or private_key == "" and (password == nil or password == "") error_message("No ec2 ssh private key","No EC2_SSH_PRIVATE_KEY specified") return false end #if !File.exists?(node_name) # error_message("No Chef Node file","No Chef Node file #{node_name} for this server") # return false #end if ec2_server_name == nil or ec2_server_name == "" error_message("No Public of Private DSN","This Server does not have a Public or Private DSN") return false end short_name = ec2_server_name if ec2_server_name.size > 16 sa = (ec2_server_name).split"." if sa.size>1 short_name = sa[0] end end answer = FXMessageBox.question($ec2_main.tabBook,MBOX_YES_NO,"Server - #{server} #{short_name}","Server #{server} #{short_name} - Confirm Running Puppet Apply\n for Manifest #{puppet_manifest} and Puppet Roles #{puppet_roles} ") if answer == MBOX_CLICKED_YES puppet_options = "-iv" if private_key != nil and private_key !="" puppet_options = puppet_options+"k #{private_key}" else puppet_options = puppet_options+"p #{password}" end puppet_options = puppet_options+" -m #{puppet_manifest}" if ssh_user != nil and ssh_user != "" puppet_options = puppet_options+" -s #{ssh_user}" end if local_port != nil and local_port != "" puppet_options = puppet_options+" -l #{local_port}" end if puppet_roles != nil and puppet_roles != "" roles = puppet_roles.split(',') facts = "" i=0 roles.each do |r| i=i+1 if facts != "" facts=facts+",role_name#{i}=#{r}" else facts=facts+"role_name#{i}=#{r}" end end puppet_options = puppet_options+" -f \"#{facts}\"" end if puppet_module_path != nil and puppet_module_path != "" puppet_options = puppet_options+" -d \"#{puppet_module_path}\"" end if puppet_syntax_check != nil and puppet_syntax_check != "" puppet_options = puppet_options+" -y \"#{puppet_syntax_check}\"" end if puppet_rspec_test != nil and puppet_rspec_test != "" puppet_options = puppet_options+" -r \"#{puppet_rspec_test}\"" end if puppet_apply != nil and puppet_apply == "false" puppet_options = puppet_options+" -u " end if puppet_apply_noop != nil and puppet_apply_noop == "true" puppet_options = puppet_options+" -o " end if puppet_extra_options != nil and puppet_extra_options != "" puppet_options = puppet_options+" -x \"#{puppet_extra_options}\"" end if puppet_delete_repo != nil and puppet_delete_repo == "true" puppet_options = puppet_options+" -n " end if puppet_sudo_password != nil and puppet_sudo_password != "" puppet_options = puppet_options+" -t \"#{puppet_sudo_password}\"" end if puppet_upgrade_packages != nil and puppet_upgrade_packages == "false" puppet_options = puppet_options+" -z " end puppet_options = puppet_options+" -e hiera.yaml" ENV["EC2_PUPPET_REPOSITORY"] = puppet_repository ENV["EC2_PUPPET_PARAMETERS"] = puppet_options if platform != "windows" if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil c = "cmd.exe /c \@start \"puppet apply #{ec2_server_name}\" \"#{ENV['EC2DREAM_HOME']}/puppet/puppet_push.bat\" #{ec2_server_name}" puts c system(c) else c = "#{ENV['EC2DREAM_HOME']}/puppet/puppet_push.sh #{ec2_server_name}" puts c system(c) puts "return message #{$?}" end else # handle windows servers (only from windows clients) #if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil # ENV["EC2_CHEF_REPOSITORY"] = chef_repository # ENV["EC2_SSH_PASSWORD"] = <PASSWORD> # c = "cmd.exe /c \@start \"chef-solo #{puppet_manifest} #{ec2_server_name}\" \"#{ENV['EC2DREAM_HOME']}/chef/chef_push_win.bat\" #{puppet_manifest} #{ec2_server_name} #{ssh_user} #{local_port}" # puts c # system(c) #end end return true end return false end <file_sep>/puppet/puppet_repo/README.md # Puppet Roles and Hiera Parameter Hierachy This is a design pattern to implement roles like Chef and separate class parameters into a parameter hierachy also like chef. Set up to 4 role_names in Facter for the server. -set up to 4 role_names in Facter -the role class gets called from the site.pp -the role::<role_name> classes called for each role and the classes executed -the class parameters are resolved in the hiera hierachy: nodes/%{hostname} roles/%{role_name1} roles/%{role_name2} roles/%{role_name3} roles/%{role_name4} modules/%{module_name} common -role parameters can be stored in the roles/%{role_name} and can be overriden for parameter values for the node,roles, module or common. parameters that are common to all roles can be stored in the common file This can be tested by running in masterless puppet export FACTER_role_name1=base export FACTER_role_name2=webserver puppet apply --modulepath ./modules manifests/site.pp This will also be able to run in puppet master, just need to decide how to set the FACTER_role_nameX NOTE: This still need so additional error checking and more testing. <file_sep>/lib/Servers.rb require 'json' class Servers def initialize() @conn = {} data = File.read("#{ENV['EC2DREAM_HOME']}/lib/servers_config.json") @config = JSON.parse(data) end def api '' end def name '' end def config @config end def conn(type) nil end def reset_connection @conn = {} end end<file_sep>/lib/common/command_runner.rb def command_runner(server, address, command, ssh_user, private_key, password, platform="", local_port="") if private_key == nil or private_key == "" and (password == nil or password == "") error_message("No ec2 ssh private key","No EC2_SSH_PRIVATE_KEY specified") return false end ec2_server_name = server if address != nil and address != "" ec2_server_name = address end if ec2_server_name == nil or ec2_server_name == "" error_message("No Public or Private DSN","This Server does not have a Public or Private DSN") return false end short_name = ec2_server_name if ec2_server_name.size > 16 sa = (ec2_server_name).split"." if sa.size>1 short_name = sa[0] end end answer = FXMessageBox.question($ec2_main.tabBook,MBOX_YES_NO,"Confirm Execute Command","Confirm Running of #{command} on server #{short_name}") if answer == MBOX_CLICKED_YES if RUBY_PLATFORM.index("mswin") != nil or RUBY_PLATFORM.index("i386-mingw32") != nil if private_key != nil private_key = private_key.gsub('/','\\') end if local_port != nil and local_port != "" c = "start \"run command on #{ec2_server_name}\" cmd.exe /k ruby \"#{ENV['EC2DREAM_HOME']}/lib/common/command_rye.rb\" localhost -l #{local_port} -u #{ssh_user} -k \"#{private_key}\" -c \"#{command}\"" else c = "start \"run command on #{ec2_server_name}\" cmd.exe /k ruby \"#{ENV['EC2DREAM_HOME']}/lib/common/command_rye.rb\" #{ec2_server_name} -u #{ssh_user} -k \"#{private_key}\" -c \"#{command}\"" end puts c system(c) else c = "ruby #{ENV['EC2DREAM_HOME']}/lib/common/command_rye.rb #{ec2_server_name} -u #{ssh_user} -k \"#{private_key}\" -c \"#{command}\"" puts c system(c) end return true end return false end
fd370072eb7908501eee4bf5b9d7f1f38f6e5581
[ "Markdown", "Ruby", "Shell" ]
20
Shell
dldinternet/ec2dream
354445e8abeb35db63d634e22103acc31c2e76af
508dea282b19c15f4bf641da75afe64acece7e96
refs/heads/master
<repo_name>suhas-ds/mlops-project1<file_sep>/get_model.py """ This script will be used by the user to tell the structure of classifier model we have to train and modify, then we save the model structure in a file model.data, which will be used later by make_model.py to write the real code for the classifier and then model.data will be modified by modify_model, which will tweak them model structure according to our needs """ #pickle module to load and save model.data import pickle import os modelStructure = {} #save the model def SaveModel(): with open('model.data','wb') as f: pickle.dump(modelStructure,f) # Add fully connected layers def MakeFC(): loop = True """ tmp = input('Do you want to add a Conv2D or MaxPool layer (y/n) ') if tmp == 'y': loop = True else: loop = False # add conv2d or max layer while loop: x = input("\n Add a layer \n\t 1. Conv2D \n\t 2. MaxPool \n\t") if x == '1': filters = input('filters') activation = input('Activation 1. Relu 2. Sigmoid 3. tanh 4. Softmax ') elif x == '2': pass else: pass print('Add more layers ? : (y / n) ') """ print('\nAdding a flatting layer for dense layers ') modelStructure.update({'flatten' : 'Flatten'}) loop = True print('\nSoftmax layer will be added automatically in the last \n') print('Add a dense layer :: ') dlCount = 0 # Add a dense layer while loop: dlCount += 1 neurons = int(input('Enter Neurons in this layer : ')) activation = input('Activation Function 1. Relu 2. Sigmoid ') if activation == '1': activation = 'relu' elif activation == '2': activation = 'sigmoid' else: activation = 'relu' modelStructure.update({'DL' + str(dlCount) : {'Dense' : neurons, 'activation' : activation}}) tmp = input('Add more layers ? : (y / n) ') if tmp == 'y': loop = True else: loop = False dlCount += 1 print('Adding dense layer with softmax function by default') modelStructure.update({'DL' + str(dlCount) : {'Dense' : 0, 'activation' : 'softmax'}}) tmp = input('No of epochs : ') if not tmp.isnumeric(): print('\nusing default epoch as 5 \n') tmp = 5 modelStructure.update({'epochs' : tmp}) tmp = input('\nlearning Rate : ') if not tmp.isnumeric(): print('\nusing default learningRate as 0.001 \n') tmp = '0.001' modelStructure.update({'learningRate' : tmp}) modelStructure.update({'DenseLayers' : dlCount}) print('\n') print('\n') for i in modelStructure: print(i,' : ',modelStructure[i]) print('\n\t|\n') SaveModel() def FC(): useDefault = input('\n\tUse default FC HEAD with Flatten -> \n\tDense(512,relu) -> \n\tDense(1024,relu) -> \n\tDense(num_classes,softmax) -> \n\tepochs = 10 -> \n\tLearning Rate = 0.01 \n\n ( y / n ) ') if useDefault == 'y': modelStructure.update({'flatten' : 'Flatten'}) modelStructure.update({'DL1' : {'Dense' : 512,'activation' : 'relu'}}) modelStructure.update({'DL2' : {'Dense' : 1024,'activation' : 'relu'}}) modelStructure.update({'DL3' : {'Dense' : 0,'activation' : 'softmax'}}) modelStructure.update({'epochs' : 10}) modelStructure.update({'learningRate' : '0.001'}) modelStructure.update({'DenseLayers' : 3}) SaveModel() print('\n') print('\n') for i in modelStructure: print(i,' : ',modelStructure[i]) print('\n\t|\n') elif useDefault == 'n': MakeFC() #set VGG in model.data def SetVGG(): fineTuning = input('Do you want to use fine tuning (y/n) for VGG ') modelStructure.update({'model' :'VGG'}) if fineTuning == 'y': modelStructure.update({'fineTuning' : 'y'}) elif fineTuning == 'n': modelStructure.update({'fineTuning' : 'n'}) else: print('using default no for fineTuning ') modelStructure.update({'fineTuning' : 'n'}) FC() #set mobile net for transfer learning in model.data def SetMobileNet(): fineTuning = input('Do you want to use fine tuning (y/n) for MobileNet ') modelStructure.update({'model' : 'MobileNet'}) if fineTuning == 'y': modelStructure.update({'fineTuning' : 'y'}) elif fineTuning == 'n': modelStructure.update({'fineTuning' : 'n'}) else: print('using default no for fineTuning ') modelStructure.update({'fineTuning' : 'n'}) FC() def tfLearningFunction(): modelTF = input('Do you want to use VGG (1) or MobileNet (2) ') if modelTF == '1': SetVGG() elif modelTF == '2': SetMobileNet() else: print('Using default MobileNet for Transfer Learning ') SetMobileNet() def FromScratch(): print("Not supported yet, use transfer learning only") #Ask whether you want transfer learning or create a model from scratch (which is not yet supported) and then save it in model.data, model.data holds the data using a dictionary print('Welcome Message ') tfLearning = input('Do you want Transfer Learning (1) or Make model from scratch (2) ') if tfLearning == '1': modelStructure.update({'tf' : 'yes'}) tfLearningFunction() elif tfLearning == '2': modelStructure.update({'tf' : 'no'}) FromScratch() else: print('Using default Transfer learning') tfLearningFunction() #providing the permissions to edit model.data file os.system('sudo chmod o+wrx model.data') #after we had made the model.data we push it back to git along with dataset for the classifier os.system('git add *') os.system("git commit -m 'added model.data'") os.system('git push -f origin master') <file_sep>/modify_model.py import os import pickle maxAccuracy = -1 accuracy = None #no of different models tried var = 0 #reading the accuracy of the last model from history file with open('result','r') as f: accuracy = float(f.read()) print('accuracy after 0 : ',accuracy) # we will try increasing epochs # adding more Dense layers # change learning rate #save the history of and the best model trained in the folder from docker if accuracy > maxAccuracy: maxAccuracy = accuracy os.system('sudo docker cp ml:/tf/history ./Besthistory') os.system('sudo docker cp ml:/tf/classifier.h5 ./bestClassifier.h5') modelStructure = [] #change the model until we get accuracy greater than 80 perecent #change the model until we had run all different versions of it while(accuracy < 0.8 and var < 7): if accuracy > maxAccuracy: maxAccuracy = accuracy os.system('sudo docker cp ml:/tf/history .') os.system('sudo docker cp ml:/tf/classifier.h5 .') os.system('sudo docker cp ml:/tf/result .') with open('result','r') as f: accuracy = float(f.read()) print('accuracy after ' + str(var) + ' : ',accuracy) with open('model.data','rb') as f: modelStructure = pickle.load(f) var += 1 #increase epochs if var == 1: ep = int(modelStructure['epochs']) + 1 modelStructure.update({'epochs' : ep}) elif var == 2: ep = int(modelStructure['epochs']) + 1 modelStructure.update({'epochs' : ep}) elif var == 3: ep = int(modelStructure['epochs']) + 1 modelStructure.update({'epochs' : ep}) #INCREASE FC LAYERS elif var == 4: dlCount = int(modelStructure['DenseLayers']) modelStructure.update({'DL' + str(dlCount) : {'Dense' : 256, 'activation' : 'relu'}}) dlCount = int(modelStructure['DenseLayers']) + 1 modelStructure.update({'DenseLayers' : dlCount}) elif var == 5: dlCount = int(modelStructure['DenseLayers']) modelStructure.update({'DL' + str(dlCount) : {'Dense' : 512, 'activation' : 'relu'}}) dlCount = int(modelStructure['DenseLayers']) + 1 modelStructure.update({'DenseLayers' : dlCount}) elif var == 6: dlCount = int(modelStructure['DenseLayers']) modelStructure.update({'DL' + str(dlCount) : {'Dense' : 1024, 'activation' : 'relu'}}) dlCount = int(modelStructure['DenseLayers']) + 1 modelStructure.update({'DenseLayers' : dlCount}) #CHANGE LEARNING RATE elif var == 7: lr = float(modelStructure['learningRate']) if lr <= 0.001: lr = 0.01 else: lr = 0.001 modelStructure.update({'learningRate' : str(lr)}) #SAVE THE NEW MODEL.DATA with open('model.data','wb') as f: pickle.dump(modelStructure,f) #RUN THE MAKE_MODEL.PY AGAIN AND THEN RUN THE NEW MODEL IN DOCKER os.system("python3 make_model.py") os.system('sudo docker exec ml python3 /tf/ml_model.py') #PRINT THE MAX ACCURACY print('max accuracy is ',maxAccuracy) <file_sep>/README.md # MLOps- Machine Learning and DevOps Integration MLOps (a compound of “machine learning” and “operations”) is a practice for collaboration and communication between data scientists and operations professionals to help manage production ML (or deep learning) lifecycle. For Detailed documentation: https://medium.com/@piyushdavda/mlops-machine-learning-and-devops-integration-eb4b3239e88b <file_sep>/make_model.py #for loading the model import pickle modelStructure = {} code = [] #loading the model with open('model.data','rb') as f: modelStructure = pickle.load(f) #printing the model, you can check console in jenkins for i in modelStructure: print(i) #assigning learning rate and epochs from the model.data #REMEMBER : modle.data stores data as dictionary lr = (modelStructure['learningRate']) ep = (modelStructure['epochs']) #these string will be joined together to make the final model or ml_model.py file #We are using triple quotes to preserve the format in which string is stored #you can read about this on google importLibs = """ import pickle import os from keras.applications import vgg16 from keras.applications import MobileNet import keras from keras.models import Model from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten, GlobalAveragePooling2D """ #lines to add if VGG is selected getDataVGG = """ img_rows, img_cols = 224,224 from keras.preprocessing.image import ImageDataGenerator train_data_dir = 'dataset/train/' validation_data_dir = 'dataset/test/' # Let's use some data augmentaiton train_datagen = ImageDataGenerator( rescale=1./255, rotation_range=45, width_shift_range=0.3, height_shift_range=0.3, horizontal_flip=True, fill_mode='nearest') validation_datagen = ImageDataGenerator(rescale=1./255) # set our batch size (typically on most mid tier systems we'll use 16-32) batch_size = 32 train_generator = train_datagen.flow_from_directory( train_data_dir, target_size=(img_rows, img_cols), class_mode='categorical') validation_generator = validation_datagen.flow_from_directory( validation_data_dir, target_size=(img_rows, img_cols), class_mode='categorical') """ #Set variabls num_classes epochs and learning rate variables = "lr = " + str(lr) + '\nep = ' + str(ep) + '\nol = train_generator.num_classes' model = "" #checking which model is used for transfer learning if modelStructure['model'] == 'VGG': model = """ model = vgg16.VGG16(weights='imagenet',include_top = False,input_shape = (img_rows, img_cols, 3)) model.save('vggtop.h5')""" else: model = """ model = MoileNet(weights='imagenet',include_top = False,input_shape = (img_rows, img_cols, 3)) model.save('MobileNet.h5')""" fineTune = "\n" #checking if fineTuning is set to yes or no, and add respective lines if modelStructure['fineTuning'] == 'n': fineTune = """ for l in model.layers: l.trainable = False """ makeModel = """ top_model = model.output top_model = Flatten()(top_model) """ #string that adds layers addLayers = "" #total no of layers are stored in denseLayers in model.data for i in range(modelStructure['DenseLayers'] - 1): tmp = "\ntop_model = Dense(" + str(modelStructure['DL' + str(i+1)]['Dense']) + ",activation=" + "'" + (modelStructure['DL' + str(i+1)]['activation']) + "'" + ")(top_model)" addLayers += tmp tmp = "\ntop_model = Dense(ol,activation='softmax')(top_model)" addLayers += tmp #general lines to compile test and train the model finalModel = """ \nnmodel = Model(inputs = model.input, outputs = top_model) """ compileModel = """ \nnmodel.compile(loss = 'categorical_crossentropy' ,optimizer = keras.optimizers.Adam(learning_rate = lr), metrics = ['accuracy'])""" #Enter the number of training and validation samples here trainModel = """ \nhistory = nmodel.fit_generator( train_generator, epochs = ep, validation_data = validation_generator, validation_steps = validation_generator.samples // batch_size) """ #here we save our model's accuracy of our model in history accuracy=""" try: os.system('touch result') except: pass with open('result','w') as f: f.write(str(history.history['accuracy'][-1])) """ #create the ml_model.py and add the above all lines try: os.system('sudo touch ml_model.py') except: pass with open('ml_model.py','w') as f: f.write(importLibs) f.write(getDataVGG) f.write(variables) f.write(model) f.write(fineTune) f.write(makeModel) f.write(addLayers) f.write(finalModel) f.write(compileModel) f.write(trainModel) f.write(accuracy) f.close() #output the code for checking if everything is working fine, see the logs in jenknins console output for this import os os.system('sudo chmod o+wrx model.data') os.system('cat ml_model.py')
68aee0959c3416411e489d76f588314d24623cd8
[ "Markdown", "Python" ]
4
Python
suhas-ds/mlops-project1
963ecc079326fa5292cac4cc3d611726c4442f62
e2e70643af684a941d18b13728e46d8ca725b372
refs/heads/master
<file_sep>({ loadparam : function(component, event, controller) { var actionGetCity = component.get("c.getCity"); actionGetCity.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { component.set("v.searchCity", response.getReturnValue()); } }); $A.enqueueAction(actionGetCity); var checkInDate = new Date(); var checkOutDate = new Date(); checkOutDate.setDate(checkInDate.getDate() + 1); component.set("v.checkInDate", checkInDate.toISOString().split('T')[0]); component.set("v.checkOutDate", checkOutDate.toISOString().split('T')[0]); }, loadRoomsByParam : function(component, event, controller) { var searchParamHotelCity = document.getElementById("hotelSearchCity").value; var searchParamCheckIn = document.getElementById("reservationCheckInDate").valueAsDate; var searchParamCheckOut = document.getElementById("reservationCheckOutDate").valueAsDate; if (searchParamCheckIn >= searchParamCheckOut) { alert('Check out Date cannot be less then Check in Date') return; }; var searchParamCapacity = document.getElementById("count").value; Number.parseInt(searchParamCapacity); var searchAction = component.get("c.getRooms"); searchAction.setParams({checkIn : searchParamCheckIn, checkOut : searchParamCheckOut, city : searchParamHotelCity, capacity : searchParamCapacity}); searchAction.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { var roomsMap = []; var rooms = response.getReturnValue(); if (rooms == null) { alert('Missed required fields'); } else { for(var key in rooms){ roomsMap.push({hotel:JSON.parse(key).Hotel__r.Name, capacity:JSON.parse(key).Capacity__c, services:rooms[key], roomId:JSON.parse(key).Id}); } component.set("v.rooms", roomsMap); } } }); $A.enqueueAction(searchAction); }, bookRoom : function(component, event, controller) { var element = event.target; var roomId = element.value var reservationCheckInDate = document.getElementById("reservationCheckInDate").valueAsDate; var reservationCheckOutDate = document.getElementById("reservationCheckOutDate").valueAsDate; var actionReservation = component.get("c.reservationRoom"); actionReservation.setParams({roomId : roomId, checkIn : reservationCheckInDate, checkOut : reservationCheckOutDate }); actionReservation.setCallback(this, function(response) { var state = response.getState(); var successResult = response.getReturnValue(); if (successResult == false) { alert ('Cannot update product'); } else { alert ('Success'); } }); $A.enqueueAction(actionReservation); var someAction = component.get("c.loadRoomsByParam"); $A.enqueueAction(someAction); } })
75fc7e299692b123698ea5a59fbd604d34436cd1
[ "JavaScript" ]
1
JavaScript
navsegdasha/HotelsProject
e6aafe76a26ce8a5e346efceeb5e5863ed915fe8
25fb286c7b611fccf888e671736b653af66ca2c5
refs/heads/master
<file_sep>const Result = require('./constants/result'); const Sequelize = require('sequelize'); const Constant = require('./constants/constant'); async function connectDatabase(dbName, user, pass, ip) { const db = new Sequelize(dbName, user, pass, { host: ip, dialect: 'mssql', operatorsAliases: '0', // Bắt buộc phải có dialectOptions: { options: { encrypt: false } }, pool: { max: 5, min: 0, acquire: 30000, idle: 10000 }, define: { timestamps: false, freezeTableName: true } }); db.authenticate() .then(() => console.log('Ket noi thanh cong')) .catch(err => console.log(err.message)); return db; } module.exports = { // config: { // user: 'sa', // password: '<PASSWORD>', // server: 'localhost', // database: 'AGELESS_QLNB', // options: { // encrypt: false, // }, // }, config: { user: 'sa', password: '<PASSWORD>', server: 'dbdev.namanphu.vn', database: 'FollowYoutube_DB', // GELESS_QLNB con demo options: { encrypt: false, }, }, // configDBCustomer: { // user: 'sa', // password: '<PASSWORD>', // server: 'localhost', // database: 'CustomerUser', // options: { // encrypt: false, // }, // }, connectDatabase: async function () { const db = new Sequelize(this.config.database, this.config.user, this.config.password, { host: this.config.server, dialect: 'mssql', operatorsAliases: '0', // Bắt buộc phải có dialectOptions: { options: { encrypt: false } }, pool: { max: 5, min: 0, acquire: 30000, idle: 10000 }, define: { timestamps: false, freezeTableName: true } }); db.authenticate() .then(() => console.log('Ket noi thanh cong')) .catch(err => console.log(err.message)); return db; }, // ----------------------------------------------------------------------------------------------------------------------------------------------------------- checkServerInvalid: async function (userID) { let customer; try { await connectDatabase(this.config.database, this.config.user, this.config.password, this.config.server).then(async dbCustomer => { let user = await mUser(dbCustomer).findOne({ where: { ID: userID } }) customer = await mCustomer(dbCustomer).findOne({ where: { ID: user.IDCustomer } }) await dbCustomer.close() }) if (customer) { let db = await connectDatabase(customer.DatabaseName, customer.UsernameDB, customer.PassworDB, customer.ServerIP); return db; } else return null; } catch (error) { console.log(error); return null; } }, // ----------------------------------------------------------------------------------------------------------------------------------------------------------- updateTable: async function (listObj, table, id) { let updateObj = {}; for (let field of listObj) { updateObj[field.key] = field.value } try { await table.update(updateObj, { where: { ID: id } }); return Promise.resolve(1); } catch (error) { console.log(error); return Promise.reject(error); } } }<file_sep>const Sequelize = require('sequelize'); module.exports = function(db) { var table = db.define('tblVideoManager', { ID: { type: Sequelize.BIGINT, primaryKey: true, autoIncrement: true }, Name: Sequelize.STRING, ViewVideo: Sequelize.INTEGER, Likes: Sequelize.INTEGER, Title: Sequelize.STRING, CreateDate: Sequelize.DATE, EditDate: Sequelize.DATE, Type: Sequelize.STRING, Status: Sequelize.STRING, Duration: Sequelize.FLOAT, channelID: Sequelize.STRING, VideoID: Sequelize.STRING, PlaylistID: Sequelize.STRING, Description: Sequelize.STRING, LinkImage: Sequelize.STRING, }); return table; }<file_sep>const Sequelize = require('sequelize'); module.exports = function (db) { var table = db.define('tblPointManager', { ID: { type: Sequelize.BIGINT, primaryKey: true, autoIncrement: true }, TotalPoint: Sequelize.FLOAT, IDUser: Sequelize.BIGINT, PlusPoints: Sequelize.FLOAT, MinusPoints: Sequelize.FLOAT, Reason: Sequelize.STRING, ViewDuration: Sequelize.FLOAT, CreateDate: Sequelize.DATE, EditDate: Sequelize.DATE, StartTime: Sequelize.NOW, EndTime: Sequelize.NOW, }); return table; }<file_sep>const Constant = require('../constants/constant'); const Op = require('sequelize').Op; const Result = require('../constants/result'); var moment = require('moment'); var mtblPointManager = require('../tables/tblPointManager') var database = require('../database'); async function deleteRelationshiptblPointManager(db, listID) { await mtblPointManager(db).destroy({ where: { ID: { [Op.in]: listID } } }) } module.exports = { deleteRelationshiptblPointManager, // get_detail_tbl_point_manager detailtblPointManager: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { mtblPointManager(db).findOne({ where: { ID: body.id } }).then(data => { if (data) { var obj = { id: data.ID, name: data.Name, code: data.Code, } var result = { obj: obj, status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, } res.json(result); } else { res.json(Result.NO_DATA_RESULT) } }) } catch (error) { res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // add_tbl_point_manager addtblPointManager: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { mtblPointManager(db).create({ TotalPoint: body.totalPoint ? body.totalPoint : null, IDUser: body.userID ? body.userID : null, PlusPoints: body.plusPoints ? body.plusPoints : null, MinusPoints: body.minusPoints ? body.minusPoints : null, Reason: body.reason ? body.reason : null, IDVideoView: body.videoViewID ? body.videoViewID : null, ViewDuration: body.viewDuration ? body.viewDuration : null, CreateDate: body.createDate ? body.createDate : null, EditDate: body.editDate ? body.editDate : null, StartTime: body.startTime ? body.startTime : null, EndTime: body.endTime ? body.endTime : null, }).then(data => { var result = { status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, } res.json(result); }) } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // update_tbl_point_manager updatetblPointManager: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { let update = []; if (body.reason || body.reason === '') update.push({ key: 'Reason', value: body.reason }); if (body.totalPoint || body.totalPoint === '') { if (body.totalPoint === '') update.push({ key: 'TotalPoint', value: null }); else update.push({ key: 'TotalPoint', value: body.totalPoint }); } if (body.userID || body.userID === '') { if (body.userID === '') update.push({ key: 'IDUser', value: null }); else update.push({ key: 'IDUser', value: body.userID }); } if (body.plusPoints || body.plusPoints === '') { if (body.plusPoints === '') update.push({ key: 'PlusPoints', value: null }); else update.push({ key: 'PlusPoints', value: body.plusPoints }); } if (body.minusPoints || body.minusPoints === '') { if (body.minusPoints === '') update.push({ key: 'MinusPoints', value: null }); else update.push({ key: 'MinusPoints', value: body.minusPoints }); } if (body.videoViewID || body.videoViewID === '') { if (body.videoViewID === '') update.push({ key: 'IDVideoView', value: null }); else update.push({ key: 'IDVideoView', value: body.videoViewID }); } if (body.viewDuration || body.viewDuration === '') { if (body.viewDuration === '') update.push({ key: 'ViewDuration', value: null }); else update.push({ key: 'ViewDuration', value: body.viewDuration }); } if (body.createDate || body.createDate === '') { if (body.createDate === '') update.push({ key: 'CreateDate', value: null }); else update.push({ key: 'CreateDate', value: body.createDate }); } if (body.editDate || body.editDate === '') { if (body.editDate === '') update.push({ key: 'EditDate', value: null }); else update.push({ key: 'EditDate', value: body.editDate }); } if (body.startTime || body.startTime === '') { if (body.startTime === '') update.push({ key: 'StartTime', value: null }); else update.push({ key: 'StartTime', value: body.startTime }); } if (body.endTime || body.endTime === '') { if (body.endTime === '') update.push({ key: 'EndTime', value: null }); else update.push({ key: 'EndTime', value: body.endTime }); } database.updateTable(update, mtblPointManager(db), body.id).then(response => { if (response == 1) { res.json(Result.ACTION_SUCCESS); } else { res.json(Result.SYS_ERROR_RESULT); } }) } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // delete_tbl_point_manager deletetblPointManager: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { let listID = JSON.parse(body.listID); await deleteRelationshiptblPointManager(db, listID); var result = { status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, } res.json(result); } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // get_list_tbl_point_manager getListtblPointManager: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { var whereOjb = []; // if (body.dataSearch) { // var data = JSON.parse(body.dataSearch) // if (data.search) { // where = [ // { FullName: { [Op.like]: '%' + data.search + '%' } }, // { Address: { [Op.like]: '%' + data.search + '%' } }, // { CMND: { [Op.like]: '%' + data.search + '%' } }, // { EmployeeCode: { [Op.like]: '%' + data.search + '%' } }, // ]; // } else { // where = [ // { FullName: { [Op.ne]: '%%' } }, // ]; // } // whereOjb = { // [Op.and]: [{ [Op.or]: where }], // [Op.or]: [{ ID: { [Op.ne]: null } }], // }; // if (data.items) { // for (var i = 0; i < data.items.length; i++) { // let userFind = {}; // if (data.items[i].fields['name'] === 'HỌ VÀ TÊN') { // userFind['FullName'] = { [Op.like]: '%' + data.items[i]['searchFields'] + '%' } // if (data.items[i].conditionFields['name'] == 'And') { // whereOjb[Op.and].push(userFind) // } // if (data.items[i].conditionFields['name'] == 'Or') { // whereOjb[Op.or].push(userFind) // } // if (data.items[i].conditionFields['name'] == 'Not') { // whereOjb[Op.not] = userFind // } // } // } // } // } let stt = 1; mtblPointManager(db).findAll({ offset: Number(body.itemPerPage) * (Number(body.page) - 1), limit: Number(body.itemPerPage), where: whereOjb, order: [ ['ID', 'DESC'] ], }).then(async data => { var array = []; data.forEach(element => { var obj = { stt: stt, id: Number(element.ID), totalPoint: element.TotalPoint ? element.TotalPoint : '', userID: element.IDUser ? element.IDUser : '', plusPoints: element.PlusPoints ? element.PlusPoints : '', minusPoints: element.MinusPoints ? element.MinusPoints : '', reason: element.Reason ? element.Reason : '', videoViewID: element.IDVideoView ? element.IDVideoView : '', viewDuration: element.ViewDuration ? element.ViewDuration : '', createDate: element.CreateDate ? element.CreateDate : '', editDate: element.EditDate ? element.EditDate : '', startTime: element.StartTime ? element.StartTime : '', endTime: element.EndTime ? element.EndTime : '', } array.push(obj); stt += 1; }); var count = await mtblPointManager(db).count({ where: whereOjb, }) var result = { array: array, status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, all: count } res.json(result); }) } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, }<file_sep>const cryptoJS = require('crypto-js'); var moment = require('moment'); var arrCallStatus = [ { id: 1, name: 'Không trả lời' }, { id: 2, name: 'Bận' }, { id: 3, name: 'Nhầm số' }, { id: 4, name: 'Tin nhắn' }, { id: 5, name: 'Cúp máy' }, { id: 6, name: 'Đã kết nối' }, ] var arrTastType = [ { id: 1, name: 'Cuộc gọi' }, { id: 2, name: 'Email' }, { id: 3, name: 'Gặp mặt' } ] var arrMailStatus = [ { id: 1, name: 'Đã gửi' }, { id: 2, name: 'Đã nhận' }, { id: 3, name: 'Đã trả lời' }, { id: 4, name: 'Nhầm email' } ] var dayInWeek = ["Chủ nhật", "Thứ 2", "Thứ 3", "Thứ 4", "Thứ 5", "Thứ 6", "Thứ 7"]; module.exports = { toDatetimeHour: function (time) { if (time) { var hour = moment(time).hours(); return hour + ":00, " + moment(time).format('DD/MM/YYYY'); } else return null }, toHour: function (time) { if (time) { return moment(time).hours() + ":00"; } else return null }, toDatetimeDay: function (time) { console.log(time); if (time) { var day = dayInWeek[moment(time).days()]; return day + ", " + moment(time).format('DD/MM/YYYY'); } else return null }, toDay: function (time) { if (time) { return dayInWeek[moment(time).days()]; } else return null }, toDatetimeMonth: function (time) { if (time) { return "Tháng " + moment(time).format('MM/YYYY'); } else return null }, toMonth: function (time) { if (time) { return "T" + moment(time).format('MM/YYYY'); } else return null }, toDatetime: function (time) { if (time) return moment(time).format('DD/MM/YYYY HH:mm'); else return null }, callStatus: function (type) { var obj = arrCallStatus.find(item => { return item.id == type }); if (obj) { return obj.name } else return '' }, mailStatus: function (type) { var obj = arrMailStatus.find(item => { return item.id == type }); if (obj) { return obj.name } else return '' }, taskType: function (type) { var obj = arrTastType.find(item => { return item.id == type }); if (obj) { return obj.name } else return '' }, encryptKey(value) { var key = "<KEY>"; key = cryptoJS.MD5(key).toString(); var keyHex = cryptoJS.enc.Hex.parse(key); var options = { mode: cryptoJS.mode.ECB, padding: cryptoJS.pad.Pkcs7 }; var textWordArray = cryptoJS.enc.Utf8.parse(value); var encrypted = cryptoJS.TripleDES.encrypt(textWordArray, keyHex, options); var base64String = encrypted.toString(); return base64String; }, decryptKey(value) { var key = "<KEY>"; key = cryptoJS.MD5(key).toString(); var keyHex = cryptoJS.enc.Hex.parse(key); var options = { mode: cryptoJS.mode.ECB, padding: cryptoJS.pad.Pkcs7 }; var resultArray = cryptoJS.TripleDES.decrypt({ ciphertext: cryptoJS.enc.Base64.parse(value) }, keyHex, options); return resultArray.toString(cryptoJS.enc.Utf8); }, handleWhereClause: async function (listObj) { let obj = {}; for (let field of listObj) { obj[field.key] = field.value } return obj }, arrayToObj(array) { let obj = {}; for (let field of array) { obj[field.key] = field.value } return obj; } }<file_sep>const Constant = require('../constants/constant'); const Op = require('sequelize').Op; const Result = require('../constants/result'); var moment = require('moment'); var mtblHistoryReviewVideo = require('../tables/tblHistoryReviewVideo') var database = require('../database'); var mtblVideoManager = require('../tables/tblVideoManager') var mtblAccount = require('../tables/tblAccount') async function deleteRelationshiptblHistoryReviewVideo(db, listID) { await mtblHistoryReviewVideo(db).destroy({ where: { ID: { [Op.in]: listID } } }) } module.exports = { deleteRelationshiptblHistoryReviewVideo, // add_tbl_history_review_video addtblHistoryReviewVideo: (req, res) => { let body = req.body; let now = moment().format('YYYY-MM-DD HH:mm:ss.SSS'); database.connectDatabase().then(async db => { if (db) { try { let history = await mtblHistoryReviewVideo(db).findOne({ where: { VideoID: body.videoID, UserID: body.userID, } }) let videoTitle = await mtblVideoManager(db).findOne({ where: { VideoID: body.videoID } }) if (!history) { mtblHistoryReviewVideo(db).create({ VideoID: body.videoID ? body.videoID : null, UserID: body.userID ? body.userID : null, ReviewDate: now, UserViews: 0, VideoTitle: videoTitle.Title, }) } else { await mtblHistoryReviewVideo(db).update({ ReviewDate: now, VideoTitle: videoTitle.Title, }, { where: { ID: history.ID } }) } await mtblHistoryReviewVideo(db).findAll({ offset: 0, limit: 10, where: { UserID: body.userID }, order: [ ['ReviewDate', 'DESC'] ], }).then(async data => { var array = []; let stt = 1; console.log(data.length); for (var history = 0; history < data.length; history++) { let videoDetail = await mtblVideoManager(db).findOne({ where: { VideoID: data[history].VideoID } }) var obj = { stt: stt, id: Number(data[history].ID), videoID: data[history].VideoID ? data[history].VideoID : '', userViews: data[history].UserViews ? data[history].UserViews : 0, nameVideo: videoDetail ? videoDetail.Name ? videoDetail.Name : '' : '', title: videoDetail ? videoDetail.Title ? videoDetail.Title : '' : '', description: videoDetail ? videoDetail.Description ? videoDetail.Description : '' : '', linkImage: videoDetail ? videoDetail.LinkImage ? videoDetail.LinkImage : '' : '', userID: data[history].UserID ? data[history].UserID : '', } array.push(obj); stt += 1; } var count = await mtblHistoryReviewVideo(db).count({ UserID: body.userID }) var result = { array: array, status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, all: count } res.json(result); }) } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // update_tbl_history_review_video updatetblHistoryReviewVideo: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { let update = []; if (body.userID || body.userID === '') update.push({ key: 'UserID', value: body.userID }); if (body.videoID || body.videoID === '') update.push({ key: 'VideoID', value: body.videoID }); database.updateTable(update, mtblHistoryReviewVideo(db), body.id).then(response => { if (response == 1) { res.json(Result.ACTION_SUCCESS); } else { res.json(Result.SYS_ERROR_RESULT); } }) } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // delete_tbl_history_review_video deletetblHistoryReviewVideo: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { let listID = JSON.parse(body.listID); await deleteRelationshiptblHistoryReviewVideo(db, listID); var result = { status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, } res.json(result); } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // get_history_review_video_of_staff getHistoryReviewVideoOfStaff: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { var whereOjb = []; // if (body.dataSearch) { // var data = JSON.parse(body.dataSearch) // if (data.search) { // where = [ // { FullName: { [Op.like]: '%' + data.search + '%' } }, // { Address: { [Op.like]: '%' + data.search + '%' } }, // { CMND: { [Op.like]: '%' + data.search + '%' } }, // { EmployeeCode: { [Op.like]: '%' + data.search + '%' } }, // ]; // } else { // where = [ // { FullName: { [Op.ne]: '%%' } }, // ]; // } // whereOjb = { // [Op.and]: [{ [Op.or]: where }], // [Op.or]: [{ ID: { [Op.ne]: null } }], // }; // if (data.items) { // for (var i = 0; i < data.items.length; i++) { // let userFind = {}; // if (data.items[i].fields['name'] === '<NAME>') { // userFind['FullName'] = { [Op.like]: '%' + data.items[i]['searchFields'] + '%' } // if (data.items[i].conditionFields['name'] == 'And') { // whereOjb[Op.and].push(userFind) // } // if (data.items[i].conditionFields['name'] == 'Or') { // whereOjb[Op.or].push(userFind) // } // if (data.items[i].conditionFields['name'] == 'Not') { // whereOjb[Op.not] = userFind // } // } // } // } // } let arrayOrder = [] if (body.type == 'admin') arrayOrder = [ ['UserViews', 'DESC'], ['VideoTitle', 'DESC'] ] else arrayOrder = [ ['ReviewDate', 'DESC'] ] let stt = 1; mtblHistoryReviewVideo(db).findAll({ offset: 10 * (Number(body.page) - 1), limit: 10, where: { UserID: body.userID }, order: arrayOrder, }).then(async data => { var array = []; for (var history = 0; history < data.length; history++) { let videoDetail = await mtblVideoManager(db).findOne({ where: { VideoID: data[history].VideoID } }) var obj = { stt: stt, id: Number(data[history].ID), videoID: data[history].VideoID ? data[history].VideoID : '', nameVideo: videoDetail ? videoDetail.Name ? videoDetail.Name : '' : '', title: videoDetail ? videoDetail.Title ? videoDetail.Title : '' : '', description: videoDetail ? videoDetail.Description ? videoDetail.Description : '' : '', linkImage: videoDetail ? videoDetail.LinkImage ? videoDetail.LinkImage : '' : '', userID: data[history].UserID ? data[history].UserID : '', userViews: data[history].UserViews ? data[history].UserViews : 0, reviewDate: data[history].ReviewDate ? data[history].ReviewDate : null, } array.push(obj); stt += 1; } var count = await mtblHistoryReviewVideo(db).count({ UserID: body.userID }) var result = { array: array, status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, all: count } res.json(result); }) } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // get_history_review_video_for_admin getHistoryReviewVideoForAdmin: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { var whereOjb = []; // if (body.dataSearch) { // var data = JSON.parse(body.dataSearch) // if (data.search) { // where = [ // { FullName: { [Op.like]: '%' + data.search + '%' } }, // { Address: { [Op.like]: '%' + data.search + '%' } }, // { CMND: { [Op.like]: '%' + data.search + '%' } }, // { EmployeeCode: { [Op.like]: '%' + data.search + '%' } }, // ]; // } else { // where = [ // { FullName: { [Op.ne]: '%%' } }, // ]; // } // whereOjb = { // [Op.and]: [{ [Op.or]: where }], // [Op.or]: [{ ID: { [Op.ne]: null } }], // }; // if (data.items) { // for (var i = 0; i < data.items.length; i++) { // let userFind = {}; // if (data.items[i].fields['name'] === '<NAME>') { // userFind['FullName'] = { [Op.like]: '%' + data.items[i]['searchFields'] + '%' } // if (data.items[i].conditionFields['name'] == 'And') { // whereOjb[Op.and].push(userFind) // } // if (data.items[i].conditionFields['name'] == 'Or') { // whereOjb[Op.or].push(userFind) // } // if (data.items[i].conditionFields['name'] == 'Not') { // whereOjb[Op.not] = userFind // } // } // } // } // } let stt = 1; mtblHistoryReviewVideo(db).findAll({ offset: 10 * (Number(body.page) - 1), limit: 10, where: { UserID: body.userID }, order: [ ['UserViews', 'DESC'], ['VideoTitle', 'DESC'] ], }).then(async data => { var array = []; for (var history = 0; history < data.length; history++) { let videoDetail = await mtblVideoManager(db).findOne({ where: { VideoID: data[history].VideoID } }) var obj = { stt: stt, id: Number(data[history].ID), videoID: data[history].VideoID ? data[history].VideoID : '', nameVideo: videoDetail ? videoDetail.Name ? videoDetail.Name : '' : '', title: videoDetail ? videoDetail.Title ? videoDetail.Title : '' : '', description: videoDetail ? videoDetail.Description ? videoDetail.Description : '' : '', linkImage: videoDetail ? videoDetail.LinkImage ? videoDetail.LinkImage : '' : '', userID: data[history].UserID ? data[history].UserID : '', userViews: data[history].UserViews ? data[history].UserViews : 1, reviewDate: data[history].ReviewDate ? data[history].ReviewDate : null, } array.push(obj); stt += 1; } var count = await mtblHistoryReviewVideo(db).count({ UserID: body.userID }) var result = { array: array, status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, all: count } res.json(result); }) } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, }<file_sep>module.exports = function(app) { // var checkToken = require('./constants/token'); var youtube = require('./controllers/youtube'); var uploadFile = require('./controllers/upload-file'); app.route('/convert_base64_to_image').post(uploadFile.converBase64ToImg); app.route('/delete_file_from_link').post(uploadFile.deletetblFileFromLink); app.route('/get_list_video_from_channel').post(youtube.getVideoFromchannel); app.route('/get_list_video_from_playlist').post(youtube.getVideoFromPlaylist); app.route('/get_list_playlist_from_channel').post(youtube.getListPlaylistFromchannel); app.route('/get_detail_video').post(youtube.getDetailVideoManager); var channel = require('./controllers/ctl-tblchannelManager') app.route('/add_tbl_channel_manager').post(channel.addtblchannelManager); app.route('/update_tbl_channel_manager').post(channel.updatetblchannelManager); app.route('/delete_tbl_channel_manager').post(channel.deletetblchannelManager); app.route('/get_list_tbl_channel_manager').post(channel.getListtblchannelManager); var accountManager = require('./controllers/ctl-tblAccount') app.route('/add_tbl_account').post(accountManager.addtblAccount); app.route('/get_detail_tbl_account').post(accountManager.detailtblAccount); app.route('/update_tbl_account').post(accountManager.updatetblAccount); app.route('/delete_tbl_account').post(accountManager.deletetblAccount); app.route('/get_list_tbl_account').post(accountManager.getListtblAccount); app.route('/plus_score_for_staff').post(accountManager.plusScoreForStaff); app.route('/minus_points_of_staff').post(accountManager.minusPointsOfStaff); app.route('/change_notification_status').post(accountManager.changeNotificationStatus); var videoManager = require('./controllers/ctl-tblVideoManager') app.route('/add_tbl_video_manager').post(videoManager.addtblVideoManager); app.route('/update_tbl_video_manager').post(videoManager.updatetblVideoManager); app.route('/delete_tbl_video_manager').post(videoManager.deletetblVideoManager); app.route('/get_list_tbl_video_manager').post(videoManager.getListtblVideoManager); app.route('/plus_likes').post(videoManager.plusLikes); app.route('/plus_views').post(videoManager.plusViews); var pointManager = require('./controllers/ctl-tblPointManager') app.route('/add_tbl_point_manager').post(pointManager.addtblPointManager); app.route('/update_tbl_point_manager').post(pointManager.updatetblPointManager); app.route('/delete_tbl_point_manager').post(pointManager.deletetblPointManager); app.route('/get_list_tbl_point_manager').post(pointManager.getListtblPointManager); var historyReviewVideo = require('./controllers/ctl-tblHistoryReviewVideo') app.route('/add_tbl_history_review_video').post(historyReviewVideo.addtblHistoryReviewVideo); app.route('/get_history_review_video_of_staff').post(historyReviewVideo.getHistoryReviewVideoOfStaff); app.route('/get_history_review_video_for_admin').post(historyReviewVideo.getHistoryReviewVideoForAdmin); }<file_sep>const Constant = require('../constants/constant'); module.exports = { ERROR_RESULT: { status: Constant.STATUS.FAIL, message: Constant.MESSAGE.SYS_ERROR }, ERROR_DATA: { status: Constant.STATUS.FAIL, message: Constant.MESSAGE.DATA_FAIL }, NO_DATA_RESULT: { status: Constant.STATUS.FAIL, message: Constant.MESSAGE.DATA_NOT_FOUND }, SYS_ERROR_RESULT: { status: Constant.STATUS.FAIL, message: Constant.MESSAGE.SYS_ERROR }, LOGIN_FAIL: { status: Constant.STATUS.FAIL, message: Constant.MESSAGE.LOGIN_FAIL }, ACTION_SUCCESS: { status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS }, NO_PERMISSION: { status: Constant.STATUS.FAIL, message: Constant.MESSAGE.NO_PERMISSION }, INVALID_USER: { status: Constant.STATUS.FAIL, message: Constant.MESSAGE.INVALID_USER }, } <file_sep>var fs = require('fs'); var { google } = require('googleapis'); var OAuth2 = google.auth.OAuth2; var readline = require('readline'); var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly']; var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/'; var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json'; const axios = require('axios'); const Result = require('../constants/result'); const Constant = require('../constants/constant'); var moment = require('moment'); const Op = require('sequelize').Op; function getNewToken(oauth2Client, callback) { var authUrl = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: SCOPES }); console.log('Authorize this app by visiting this url: ', authUrl); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Enter the code from that page here: ', function(code) { rl.close(); oauth2Client.getToken(code, function(err, token) { if (err) { console.log('Error while trying to retrieve access token', err); return; } oauth2Client.credentials = token; storeToken(token); callback(oauth2Client); }); }); } function getChannel(auth) { var service = google.youtube('v3'); service.channels.list({ auth: auth, part: 'snippet,contentDetails,statistics', forUsername: 'GoogleDevelopers' }, function(err, response) { if (err) { console.log('The API returned an error: ' + err); return; } var channels = response.data.items; if (channels.length == 0) { console.log('No channel found.'); } else { console.log('This channel\'s ID is %s. Its title is \'%s\', and ' + 'it has %s views.', channels[0].id, channels[0].snippet.title, channels[0].statistics.viewCount); } }); } const { YoutubeDataAPI } = require("youtube-v3-api") const API_KEY = '<KEY>'; const api = new YoutubeDataAPI(API_KEY); var search = require('youtube-search'); var ypi = require('youtube-channel-videos'); const getYoutubeChannelId = require('get-youtube-channel-id'); var mtblchannelManager = require('../tables/tblchannelManager') var mtblVideoManager = require('../tables/tblVideoManager') var database = require('../database'); const passport = require('passport') let keyApiYoutube = '<KEY>' async function checkAPIKeyAndChangeKey() { let arrayKey = [ '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', ] keyResult = '<KEY>' for (var key = 0; key < arrayKey.length; key++) { var strUrl = 'https://www.googleapis.com/youtube/v3/search?key=' + arrayKey[key] + '&channelId=UCswpuhr07BLpHpmt2vRa81A&part=snippet,id&order=date&maxResults=10&type=video' try { await axios.get(strUrl).then(data => { if (data) { keyResult = arrayKey[key] } }) break } catch (error) { console.log(error + ' '); continue } } // keyResult = '<KEY>' return keyResult } async function getDetailChannel(channelID) { let obj = {} keyApiYoutube = await checkAPIKeyAndChangeKey() console.log(keyApiYoutube); var strUrl = 'https://youtube.googleapis.com/youtube/v3/channels?part=snippet&key=' + keyApiYoutube + '&id=' await axios.get(strUrl + channelID).then(data => { if (data) { // console.log(data.data.items[0].snippet.thumbnails); if (data.data.items.length > 0) { obj['channelTitle'] = data.data.items[0].snippet.title; obj['channelId'] = channelID; obj['description'] = data.data.items[0].snippet.description; // obj['uriImg'] = data.data.items[0].snippet.thumbnails.default.url; // obj['uriImg'] = data.data.items[0].snippet.thumbnails.medium.url; obj['uriImg'] = data.data.items[0].snippet.thumbnails.high.url; } } }) return obj } async function getDetailVideo(videoID) { let result = {} keyApiYoutube = await checkAPIKeyAndChangeKey() var strUrl = 'https://youtube.googleapis.com/youtube/v3/videos?part=snippet&maxResults=20&key=' + keyApiYoutube + '&id=' await axios.get(strUrl + videoID).then(data => { if (data) { result = data.data.items[0] } }) return result } async function getDetailTBLVideoManager(videoID, playlistID) { let objResult = {} await database.connectDatabase().then(async db => { if (db) { let objWhere = { VideoID: videoID } await mtblVideoManager(db).findOne({ where: objWhere }).then(detailVideoManager => { objResult = { name: detailVideoManager.Name ? detailVideoManager.Name : '', viewVideo: detailVideoManager.ViewVideo, likes: detailVideoManager.Likes, createDate: detailVideoManager.CreateDate ? detailVideoManager.CreateDate : null, editDate: detailVideoManager.EditDate ? detailVideoManager.EditDate : null, type: detailVideoManager.Type ? detailVideoManager.Type : '', status: detailVideoManager.Status ? detailVideoManager.Status : '', duration: detailVideoManager.Duration, channelID: detailVideoManager.channelID ? detailVideoManager.channelID : null, videoID: detailVideoManager.VideoID ? detailVideoManager.VideoID : null, playListID: detailVideoManager.PlayListID ? detailVideoManager.PlayListID : null, title: detailVideoManager.Title ? detailVideoManager.Title : '', description: detailVideoManager.Description ? detailVideoManager.Description : '', linkImage: detailVideoManager.LinkImage ? detailVideoManager.LinkImage : '', } }) } }) return objResult } async function removeDiacritics(str) { var defaultDiacriticsRemovalMap = [ { 'base': 'A', 'letters': /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g }, { 'base': 'AA', 'letters': /[\uA732]/g }, { 'base': 'AE', 'letters': /[\u00C6\u01FC\u01E2]/g }, { 'base': 'AO', 'letters': /[\uA734]/g }, { 'base': 'AU', 'letters': /[\uA736]/g }, { 'base': 'AV', 'letters': /[\uA738\uA73A]/g }, { 'base': 'AY', 'letters': /[\uA73C]/g }, { 'base': 'B', 'letters': /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g }, { 'base': 'C', 'letters': /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g }, { 'base': 'D', 'letters': /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g }, { 'base': 'DZ', 'letters': /[\u01F1\u01C4]/g }, { 'base': 'Dz', 'letters': /[\u01F2\u01C5]/g }, { 'base': 'E', 'letters': /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g }, { 'base': 'F', 'letters': /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g }, { 'base': 'G', 'letters': /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g }, { 'base': 'H', 'letters': /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g }, { 'base': 'I', 'letters': /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g }, { 'base': 'J', 'letters': /[\u004A\u24BF\uFF2A\u0134\u0248]/g }, { 'base': 'K', 'letters': /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g }, { 'base': 'L', 'letters': /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g }, { 'base': 'LJ', 'letters': /[\u01C7]/g }, { 'base': 'Lj', 'letters': /[\u01C8]/g }, { 'base': 'M', 'letters': /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g }, { 'base': 'N', 'letters': /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g }, { 'base': 'NJ', 'letters': /[\u01CA]/g }, { 'base': 'Nj', 'letters': /[\u01CB]/g }, { 'base': 'O', 'letters': /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g }, { 'base': 'OI', 'letters': /[\u01A2]/g }, { 'base': 'OO', 'letters': /[\uA74E]/g }, { 'base': 'OU', 'letters': /[\u0222]/g }, { 'base': 'P', 'letters': /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g }, { 'base': 'Q', 'letters': /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g }, { 'base': 'R', 'letters': /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g }, { 'base': 'S', 'letters': /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g }, { 'base': 'T', 'letters': /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g }, { 'base': 'TZ', 'letters': /[\uA728]/g }, { 'base': 'U', 'letters': /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g }, { 'base': 'V', 'letters': /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g }, { 'base': 'VY', 'letters': /[\uA760]/g }, { 'base': 'W', 'letters': /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g }, { 'base': 'X', 'letters': /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g }, { 'base': 'Y', 'letters': /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g }, { 'base': 'Z', 'letters': /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g }, { 'base': 'a', 'letters': /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g }, { 'base': 'aa', 'letters': /[\uA733]/g }, { 'base': 'ae', 'letters': /[\u00E6\u01FD\u01E3]/g }, { 'base': 'ao', 'letters': /[\uA735]/g }, { 'base': 'au', 'letters': /[\uA737]/g }, { 'base': 'av', 'letters': /[\uA739\uA73B]/g }, { 'base': 'ay', 'letters': /[\uA73D]/g }, { 'base': 'b', 'letters': /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g }, { 'base': 'c', 'letters': /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g }, { 'base': 'd', 'letters': /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g }, { 'base': 'dz', 'letters': /[\u01F3\u01C6]/g }, { 'base': 'e', 'letters': /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g }, { 'base': 'f', 'letters': /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g }, { 'base': 'g', 'letters': /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g }, { 'base': 'h', 'letters': /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g }, { 'base': 'hv', 'letters': /[\u0195]/g }, { 'base': 'i', 'letters': /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g }, { 'base': 'j', 'letters': /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g }, { 'base': 'k', 'letters': /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g }, { 'base': 'l', 'letters': /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g }, { 'base': 'lj', 'letters': /[\u01C9]/g }, { 'base': 'm', 'letters': /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g }, { 'base': 'n', 'letters': /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g }, { 'base': 'nj', 'letters': /[\u01CC]/g }, { 'base': 'o', 'letters': /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g }, { 'base': 'oi', 'letters': /[\u01A3]/g }, { 'base': 'ou', 'letters': /[\u0223]/g }, { 'base': 'oo', 'letters': /[\uA74F]/g }, { 'base': 'p', 'letters': /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g }, { 'base': 'q', 'letters': /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g }, { 'base': 'r', 'letters': /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g }, { 'base': 's', 'letters': /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g }, { 'base': 't', 'letters': /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g }, { 'base': 'tz', 'letters': /[\uA729]/g }, { 'base': 'u', 'letters': /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g }, { 'base': 'v', 'letters': /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g }, { 'base': 'vy', 'letters': /[\uA761]/g }, { 'base': 'w', 'letters': /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g }, { 'base': 'x', 'letters': /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g }, { 'base': 'y', 'letters': /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g }, { 'base': 'z', 'letters': /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g } ]; for (var i = 0; i < defaultDiacriticsRemovalMap.length; i++) { str = str.replace(defaultDiacriticsRemovalMap[i].letters, defaultDiacriticsRemovalMap[i].base); } return str; } module.exports = { getDetailVideo, getDetailChannel, youtube: (res, req) => { var google = require('googleapis'); var OAuth2 = google.auth.OAuth2; var oauth2Client = new OAuth2( '799271801880-mdadv0f4rp7854rkb456fa25osspnu7c.apps.googleusercontent.com', 'X8yPFFhHYCLwRKLmM4EoBPSC', 'http://localhost:5000/oauthcallback' ); var youtube = google.youtube({ version: 'v3', auth: oauth2Client }); youtube.playlistItems.insert({ part: 'id,snippet', resource: { snippet: { playlistId: "YOUR_PLAYLIST_ID", resourceId: { videoId: "THE_VIDEO_ID_THAT_YOU_WANT_TO_ADD", kind: "youtube#video" } } } }, function(err, data, response) { if (err) { lien.end('Error: ' + err); } else if (data) { lien.end(data); } if (response) { console.log('Status code: ' + response.statusCode); } }); }, getListPlaylistFromchannel: async(req, res) => { var body = req.body; console.log(body); keyApiYoutube = await checkAPIKeyAndChangeKey() var strURL = 'https://youtube.googleapis.com/youtube/v3/playlists?key=' + keyApiYoutube var strPart = '&part=snippet&maxResults=20' var strIDPlaylist = '&channelId=' + body.channelID console.log(strURL + strPart + strIDPlaylist); await axios.get(strURL + strPart + strIDPlaylist).then(async data => { if (data) { var array = []; for (let playlist = 0; playlist < data.data.items.length; playlist++) { let countVideo = 0; await axios.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,id&order=date&maxResults=2&type=video&playlistId=' + data.data.items[playlist].id + '&key=' + keyApiYoutube).then(data => { countVideo = data.data.pageInfo.totalResults }) array.push({ name: data.data.items[playlist].snippet, id: data.data.items[playlist].id, countVideo: countVideo, }) } var result = { array: array, all: data.data.items.length } res.json(result); } else { res.json(Result.SYS_ERROR_RESULT) } }) }, getVideoFromPlaylist: async(req, res) => { var body = req.body; console.log(body); keyApiYoutube = await checkAPIKeyAndChangeKey() await database.connectDatabase().then(async db => { if (db) { var stringURL = 'https://www.googleapis.com/youtube/v3/playlistItems?key=' + keyApiYoutube var stringIDchannel = '&playlistId=' + body.playlistID var strPart = '&part=snippet,id&order=date' var maxResults = '&maxResults=10&type=video' var pageToken = '&pageToken=' + (body.nextPageToken ? body.nextPageToken : 'CAoQAA') var search = '&q=' + await removeDiacritics((body.searchKey ? body.searchKey : '')) let now = moment().format('YYYY-MM-DD HH:mm:ss.SSS'); search = search.replace(/ /g, '%20') search = search.replace(/[/]/g, '%2F') search = search.replace(/[|]/g, '%7C') if (body.searchKey && body.nextPageToken) { search = '' } if (body.searchKey) { pageToken = '' } if (body.nextPageToken) { search = '' } console.log(stringURL + stringIDchannel + strPart + maxResults + search); await axios.get(stringURL + stringIDchannel + strPart + maxResults).then(async data => { if (data) { var array = []; let prevPageToken = data.data.prevPageToken ? data.data.prevPageToken : ''; let nextPageToken = data.data.nextPageToken ? data.data.nextPageToken : ''; for (var detailVideo = 0; detailVideo < data.data.items.length; detailVideo++) { var objDetailVideo = {}; let objWhere = {} objWhere = { VideoID: data.data.items[detailVideo].snippet.resourceId.videoId } let chekVideoIDExist = await mtblVideoManager(db).findOne({ where: objWhere }) if (!chekVideoIDExist) { console.log(data.data.items[detailVideo].snippet.playlistId); await mtblVideoManager(db).create({ Name: data.data.items[detailVideo].kind, ViewVideo: 0, Likes: 0, CreateDate: data.data.items[detailVideo].snippet.publishedAt ? data.data.items[detailVideo].snippet.publishedAt : null, EditDate: now, Type: data.data.items[detailVideo].id.videoId ? 'Video' : 'Video', Status: data.data.items[detailVideo].liveBroadcastContent, Duration: 0, channelID: data.data.items[detailVideo].snippet.channelId, VideoID: data.data.items[detailVideo].snippet.resourceId.videoId, PlaylistID: data.data.items[detailVideo].snippet.playlistId, Title: data.data.items[detailVideo].snippet.title, Description: data.data.items[detailVideo].snippet.description, LinkImage: data.data.items[detailVideo].snippet.thumbnails.default ? data.data.items[detailVideo].snippet.thumbnails.default.url : null, }) objDetailVideo = { name: data.data.items[detailVideo].kind, viewVideo: 0, likes: 0, createDate: data.data.items[detailVideo].snippet.publishedAt ? data.data.items[detailVideo].snippet.publishedAt : null, editDate: now, type: data.data.items[detailVideo].id.videoId ? 'Video' : 'Playlist', status: data.data.items[detailVideo].liveBroadcastContent, duration: 0, channelID: data.data.items[detailVideo].snippet.channelId, videoID: data.data.items[detailVideo].snippet.resourceId.videoId, playlistID: data.data.items[detailVideo].snippet.playlistId, title: data.data.items[detailVideo].snippet.title, description: data.data.items[detailVideo].snippet.description, linkImage: data.data.items[detailVideo].snippet.thumbnails.default ? data.data.items[detailVideo].snippet.thumbnails.default.url : null, } } else { objDetailVideo = await getDetailTBLVideoManager(data.data.items[detailVideo].snippet.resourceId.videoId, data.data.items[detailVideo].snippet.playlistId) } array.push(objDetailVideo) } var result = { nextPageToken: nextPageToken, prevPageToken: prevPageToken, array: array, status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, all: data.data.items.length, } res.json(result); } else { res.json(Result.SYS_ERROR_RESULT) } }) } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // &order=viewCount // "nextPageToken": "CAIQAA", thay đổi vào pageToken=CAIQAA sẽ next trang // "prevPageToken": "CAEQAQ", // list=PLzXDRSq8o2GNnjHqr3z6P1LRFGw3RY0fB // channelId=UCpd1Gf-SZjc_5ce5vVq5FTg tìm kiếm theo channel // q=Preyta& tìm kiếm theo key // https://www.googleapis.com/youtube/v3/search?key=<KEY>&channelId=UCpd1Gf-SZjc_5ce5vVq5FTg&part=snippet,id&order=date&maxResults=10&q=Preyta&list=PLzXDRSq8o2GNnjHqr3z6P1LRFGw3RY0fB&type=video&pageToken=CAIQAA getVideoFromchannel: async(req, res) => { let body = req.body; keyApiYoutube = await checkAPIKeyAndChangeKey() await database.connectDatabase().then(async db => { if (db) { var stringURL = 'https://www.googleapis.com/youtube/v3/search?key=' + keyApiYoutube var stringIDchannel = '&channelId=' + body.channelID var strPart = '&part=snippet,id&order=date' var maxResults = '&maxResults=10&type=video' var pageToken = '&pageToken=' + (body.nextPageToken ? body.nextPageToken : 'CAoQAQ') var search = '&q=' + await removeDiacritics((body.searchKey ? body.searchKey : '')) let now = moment().format('YYYY-MM-DD HH:mm:ss.SSS'); search = search.replace(/ /g, '%20') search = search.replace(/[/]/g, '%2F') search = search.replace(/[|]/g, '%7C') if (body.searchKey && body.nextPageToken) { search = '' } if (body.searchKey) { pageToken = '' } if (!body.searchKey || body.searchKey == '') { search = '' } if (body.nextPageToken) { search = '' } console.log(stringURL + stringIDchannel + strPart + maxResults + pageToken + search, 123); await axios.get(stringURL + stringIDchannel + strPart + maxResults + pageToken + search).then(async data => { if (data) { var array = []; let prevPageToken = data.data.prevPageToken ? data.data.prevPageToken : ''; let nextPageToken = data.data.nextPageToken ? data.data.nextPageToken : ''; for (var detailVideo = 0; detailVideo < data.data.items.length; detailVideo++) { console.log(data.data.items[detailVideo]); var objDetailVideo = {}; let objWhere = {} if (data.data.items[detailVideo].id.videoId) { objWhere = { VideoID: data.data.items[detailVideo].id.videoId } } else { objWhere = { PlayListID: data.data.items[detailVideo].id.playlistId } } let chekVideoIDExist = await mtblVideoManager(db).findOne({ where: objWhere }) if (!chekVideoIDExist) { await mtblVideoManager(db).create({ Name: data.data.items[detailVideo].kind, ViewVideo: 0, Likes: 0, CreateDate: data.data.items[detailVideo].snippet.publishTime ? data.data.items[detailVideo].snippet.publishTime : null, EditDate: now, Type: data.data.items[detailVideo].id.videoId ? 'Video' : 'Playlist', Status: data.data.items[detailVideo].liveBroadcastContent, Duration: 0, channelID: data.data.items[detailVideo].snippet.channelId, VideoID: data.data.items[detailVideo].id.videoId, PlaylistID: data.data.items[detailVideo].id.playlistId, Title: data.data.items[detailVideo].snippet.title, Description: data.data.items[detailVideo].snippet.description, LinkImage: data.data.items[detailVideo].snippet.thumbnails.default.url, }) objDetailVideo = { name: data.data.items[detailVideo].kind, viewVideo: 0, likes: 0, createDate: data.data.items[detailVideo].snippet.publishTime ? data.data.items[detailVideo].snippet.publishTime : null, editDate: now, type: data.data.items[detailVideo].id.videoId ? 'Video' : 'Playlist', status: data.data.items[detailVideo].liveBroadcastContent, duration: 0, channelID: data.data.items[detailVideo].snippet.channelId, videoID: data.data.items[detailVideo].id.videoId, playListID: data.data.items[detailVideo].id.playlistId, title: data.data.items[detailVideo].snippet.title, description: data.data.items[detailVideo].snippet.description, linkImage: data.data.items[detailVideo].snippet.thumbnails.default.url, } } else { objDetailVideo = await getDetailTBLVideoManager(data.data.items[detailVideo].id.videoId, data.data.items[detailVideo].id.playlistId) } array.push(objDetailVideo) } var result = { nextPageToken: nextPageToken, prevPageToken: prevPageToken, array: array, status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, all: data.data.items.length, } res.json(result); } else { res.json(Result.SYS_ERROR_RESULT) } }) } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, getDetailVideoManager: async(req, res) => { var body = req.body; let results = await getDetailVideo(body.videoID) if (results) { var result = { result: results, status: Constant.STATUS.SUCCESS, message: '' } res.json(result); } else { var result = { status: Constant.STATUS.FAIL, message: 'Video không tồn tại !' } res.json(result); } } }<file_sep># nodejs-sendmail-services backend web send mail for Ageless <file_sep>var session = require('express-session') let app = require('express')(); let cors = require('cors'); let server = require('http').createServer(app); const express = require('express'); const bodyParser = require('body-parser') var socket = require('./api/socket-io'); app.use(session({ name: 'user_sid', secret: '00a2152372fa8e0e62edbb45dd82831a', resave: false, saveUninitialized: false, cookie: { expires: 600000, maxAge: 3000000, sameSite: true, secure: true, httpOnly: true } })) app.use(cors()) app.use(bodyParser.urlencoded({ limit: '100mb', extended: true })) app.use(bodyParser.json({ limit: '100mb' })) app.use(express.urlencoded({ extended: false })); const port = process.env.PORT || 5100 server.listen(port, function() { console.log('http://localhost:' + port); }); let routes = require('./api/router') //importing route // Initializes passport and passport sessions const passport = require('passport') app.use(passport.initialize()); app.use(passport.session()); routes(app) var io = require("socket.io")(server, { cors: { wsEngine: 'eiows', origin: ["http://dbdev.namanphu.vn:8692", "http://localhost:4200"], methods: ["GET", "POST"], credentials: true, } }) socket.sockketIO(io)<file_sep>const Constant = require('../constants/constant'); const Op = require('sequelize').Op; const Result = require('../constants/result'); var moment = require('moment'); var mtblchannelManager = require('../tables/tblchannelManager') var yotube = require('./youtube') var database = require('../database'); async function deleteRelationshiptblchannelManager(db, listID) { await mtblchannelManager(db).destroy({ where: { ID: { [Op.in]: listID } } }) } module.exports = { deleteRelationshiptblchannelManager, // get_detail_tbl_channel_manager detailtblchannelManager: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { mtblchannelManager(db).findOne({ where: { ID: body.id } }).then(data => { if (data) { var obj = { id: data.ID, name: data.Name ? data.Name : '', code: data.Code ? data.Code : '', editDate: data.EditDate ? data.EditDate : null, createDate: data.CreateDate ? data.CreateDate : null, } var result = { obj: obj, status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, } res.json(result); } else { res.json(Result.NO_DATA_RESULT) } }) } catch (error) { res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // add_tbl_channel_manager addtblchannelManager: async (req, res) => { let body = req.body; // let detailchannel = await channelManager.getURLAvatarchannel(body.code) let now = moment().format('YYYY-MM-DD HH:mm:ss.SSS'); database.connectDatabase().then(async db => { if (db) { try { mtblchannelManager(db).create({ Code: body.code ? body.code : '', Name: body.name ? body.name : '', CreateDate: now, EditDate: now, // Link: detailchannel ? detailchannel : '' }).then(data => { var result = { status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, } res.json(result); }) } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // update_tbl_channel_manager updatetblchannelManager: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { let now = moment().format('YYYY-MM-DD HH:mm:ss.SSS'); let update = []; if (body.code || body.code === '') update.push({ key: 'Code', value: body.code }); if (body.name || body.name === '') update.push({ key: 'Name', value: body.name }); // update.push({ key: 'CreateDate', value: now }); update.push({ key: 'EditDate', value: now }); database.updateTable(update, mtblchannelManager(db), body.id).then(response => { if (response == 1) { res.json(Result.ACTION_SUCCESS); } else { res.json(Result.SYS_ERROR_RESULT); } }) } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // delete_tbl_channel_manager deletetblchannelManager: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { let listID = JSON.parse(body.listID); await deleteRelationshiptblchannelManager(db, listID); var result = { status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, } res.json(result); } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // get_list_tbl_channel_manager getListtblchannelManager: async (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { var whereOjb = []; // if (body.dataSearch) { // var data = JSON.parse(body.dataSearch) // if (data.search) { // where = [{ // FullName: { // [Op.like]: '%' + data.search + '%' // } // }, // { // Address: { // [Op.like]: '%' + data.search + '%' // } // }, // { // CMND: { // [Op.like]: '%' + data.search + '%' // } // }, // { // EmployeeCode: { // [Op.like]: '%' + data.search + '%' // } // }, // ]; // } else { // where = [{ // FullName: { // [Op.ne]: '%%' // } // }, ]; // } // whereOjb = { // [Op.and]: [{ // [Op.or]: where // }], // [Op.or]: [{ // ID: { // [Op.ne]: null // } // }], // }; // if (data.items) { // for (var i = 0; i < data.items.length; i++) { // let userFind = {}; // if (data.items[i].fields['name'] === '<NAME>') { // userFind['FullName'] = { // [Op.like]: '%' + data.items[i]['searchFields'] + '%' // } // if (data.items[i].conditionFields['name'] == 'And') { // whereOjb[Op.and].push(userFind) // } // if (data.items[i].conditionFields['name'] == 'Or') { // whereOjb[Op.or].push(userFind) // } // if (data.items[i].conditionFields['name'] == 'Not') { // whereOjb[Op.not] = userFind // } // } // } // } // } let stt = 1; mtblchannelManager(db).findAll({ offset: Number(body.itemPerPage) * (Number(body.page) - 1), limit: Number(body.itemPerPage), where: whereOjb, order: [ ['ID', 'DESC'] ], }).then(async data => { var array = []; for (var i = 0; i < data.length; i++) { let detailchannel = await yotube.getDetailChannel(data[i].Code) detailchannel['id'] = data[i].ID; array.push(detailchannel) } var count = await mtblchannelManager(db).count({ where: whereOjb, }) var result = { array: array, status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, all: count } res.json(result); }) } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, // get_list_name_tbl_channel_manager getListNametblchannelManager: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { mtblchannelManager(db).findAll().then(data => { var array = []; data.forEach(element => { var obj = { id: Number(element.ID), name: element.Name ? element.Name : '', } array.push(obj); }); var result = { array: array, status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, } res.json(result); }) } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) } }<file_sep>const Constant = require('../constants/constant'); var database = require('../database'); const fs = require('fs'); module.exports = { converBase64ToImg: (req, res) => { let body = req.body; var base64Data = body.data.replace('data:image/jpeg;base64,', ""); base64Data = base64Data.replace(/ /g, '+'); var buf = new Buffer.from(base64Data, "base64"); var numberRandom = Math.floor(Math.random() * 1000000); nameMiddle = numberRandom.toString(); var dir = 'photo-' + nameMiddle + '.jpg'; require("fs").writeFile('C:/images_services/ageless_sendmail/' + dir, buf, function (err) { if (err) console.log(err + ''); }); var result = { link: 'http://dbdev.namanphu.vn:1357/ageless_sendmail/' + dir, name: body.data.name, status: Constant.STATUS.SUCCESS, message: Constant.MESSAGE.ACTION_SUCCESS, } res.json(result); }, deletetblFileFromLink: (req, res) => { let body = req.body; database.connectDatabase().then(async db => { if (db) { try { var file = body.link.replace("http://dbdev.namanphu.vn:1357/ageless_sendmail/", "") fs.unlink("C:/images_services/ageless_sendmail/" + file, (err) => { if (err) console.log(err); }); } catch (error) { console.log(error); res.json(Result.SYS_ERROR_RESULT) } } else { res.json(Constant.MESSAGE.USER_FAIL) } }) }, }
6fe0f1fc91a1398f73994888013b67ea52876b67
[ "JavaScript", "Markdown" ]
13
JavaScript
NAP-BN-Test/project_youtube_follow_nodejs
74f53b1927505f510f654e558452e979e62e753b
d10d89a1c5f78e3efd63f9862ca3864bf1a275e6
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BirdSpawner : MonoBehaviour { public Transform[] spawnPositions; public GameObject[] birds; public bool keepSpawning = true; public Transform flyingBirds; float PROBABILITY = 0.5f; public float spawnDelay = 0.5f; // Start is called before the first frame update void Start() { StartCoroutine("Spawn"); } IEnumerator Spawn() { while (keepSpawning) { float shouldSpawn = Random.Range(0f, 1f); if (shouldSpawn >= PROBABILITY || flyingBirds.childCount == 0) { GameObject originalObject = GetRandomBird(); Transform startTransform = GetRandomStartTransform(); GameObject birdObject = Instantiate(originalObject, flyingBirds); birdObject.transform.position = startTransform.position; } yield return new WaitForSeconds(spawnDelay); } } GameObject GetRandomBird() { int index = Random.Range(0, birds.Length); return birds[index]; } Transform GetRandomStartTransform() { int index = Random.Range(0, spawnPositions.Length); return spawnPositions[index]; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class InputHandler : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0) == true) { Vector3 ray = Camera.main.ScreenToWorldPoint(Input.mousePosition); RaycastHit2D hit = Physics2D.Raycast(ray, Vector2.zero); if (hit && hit.transform.gameObject.tag == "Bird") { GameObject hitObject = hit.transform.gameObject; hitObject.GetComponent<Bird>().enabled = false; hitObject.GetComponent<Rigidbody2D>().gravityScale = 10; } } } } <file_sep># tap-n-kill (2D Game Development Workshop Feb 2020) Preview: https://youtu.be/p1XiB6p0p4s ## Simple 2D Game demonstrating. * Parallax Scrolling. * Creating sprite-sheet based animations. * Using Colliders and rigidbody. ## Objective of the game * Not to allow the birds to reach the other end. * tap on the bird to kill them. ## Steps to Run the game: - open the project in Unity. - open the Scene "Game" - Tap on "Start" button - Hit Play
210ba6ed1e9f9dfdfcc82cd2d7a9cdec567c2105
[ "Markdown", "C#" ]
3
C#
5hivanand/tap-n-kill
a4c338f46fef4c9565a43568f14e128689917fe5
824b2ea81d6a370a07a2717261c839e7f57d40ab
refs/heads/master
<repo_name>apktool/LearnCPP<file_sep>/7.26.04.cpp /** * @file 7.26.04.cpp * @brief 嵌套类构造函数和析构函数的执行次序 * @author LiWenGang * @date 2016-07-26 */ #include<iostream> using namespace std; class Object{ public: Object(); ~Object(); }; class Container{ public: Container(); ~Container(); private: Object obj; }; int main(int argc, char* argv[]){ Container ct; return 0; } Object::Object(){ cout<<"Object ..."<<endl; } Object::~Object(){ cout<<"~Object ..."<<endl; } Container::Container(){ cout<<"Container ..."<<endl; } Container::~Container(){ cout<<"~Container"<<endl; } <file_sep>/9.25.02.cpp /** * @file 9.25.02.cpp * @brief 异常处理|try,catch;throw * @author LiWenGang * @date 2016-09-25 */ #include<iostream> #include<string> using std::cout; using std::endl; using std::string; class MyException{ public: MyException(const string& message); MyException(const MyException& other); ~MyException(); const char* what() const; private: string message_; }; double Divied(double x, double y){ if(y==0){ MyException e("divied by zero"); //当执行完throw语句时,局部对象e会被销毁 //throw MyException("divied by zero"); //不会调用拷贝构造函数 throw e; //调用一次拷贝构造函数 } return x/y; } int main(int argc, char* argv[]){ try{ cout<<Divied(5.0,0.0)<<endl; } catch(MyException& e){ cout<<e.what()<<endl; } return 0; } MyException::MyException(const string& message):message_(message){ cout<<"MyException(string& message)"<<endl; } MyException::MyException(const MyException& obj):message_(obj.message_){ cout<<"MyException(MyException& obj)"<<endl; } MyException::~MyException(){ cout<<"~MyException"<<endl; } const char* MyException::what() const{ return message_.c_str(); } /* * 异常发生之前创建的局部对象被销毁,这一过程被称为栈展开 * * 一个异常处理器一般只捕捉一种类型的异常 * 异常处理器的参数类型喝抛出异常的类型相同 * ...表示可以捕获任何异常 * * 如果没有合适的异常处理器,那么没有捕获的异常将调用terminte函数,terminate函数默认调用abort终止程序的执行 * 可以使用set_terminate函数指定terminate函数将调用的函数 */ /* * 沿着嵌套调用的链接向上查找,直至为异常找到一个catch字句。这个过程称之为栈展开。 * 抛出异常时,将暂停当前函数的执行,开始查找匹配的catch子句。首先检查throw本身是否在try块内部,如果是,检查与该try相关的catch子句,看是否可以处理该异常。如果不能处理,就退出当前函数,并且释放当前函数的内存并销毁局部对象,继续到上层的调用函数中查找,直到找到一个可以处理该异常的catch。这个过程称为栈展开(stack unwinding)。当处理该异常的catch结束之后,紧接着该catch之后的点继续执行。 * * 1. 为局部对象调用析构函数 * 如上所述,在栈展开的过程中,会释放局部对象所占用的内存并运行类类型局部对象的析构函数。但需要注意的是,如果一个块通过new动态分配内存,并且在释放该资源之前发生异常,该块因异常而退出,那么在栈展开期间不会释放该资源,编译器不会删除该指针,这样就会造成内存泄露。 * * 2. 析构函数应该从不抛出异常 * 在为某个异常进行栈展开的时候,析构函数如果又抛出自己的未经处理的另一个异常,将会导致调用标准库terminate函数。通常terminate函数将调用abort函数,导致程序的非正常退出。所以析构函数应该从不抛出异常。 * * 3. 异常与构造函数 * 构造函数可以抛出异常,如果在构造函数对象时发生异常,此时该对象可能只是被部分构造,要保证能够销毁这些已构造的成员。 * * 4. 未捕获的异常将会终止程序 * 不能不处理异常。如果找不到匹配的catch,程序就会调用库函数terminate。 */ <file_sep>/8.05.03.cpp /** * @file 8.05.03.cpp * @brief 继承|友元,构造函数调用次序 * @author LiWenGang * @date 2016-08-05 */ #include<iostream> using namespace std; class Base{ public: Base(); ~Base(); void Show(); private: int num_; }; class Inherit:public Base{ public: Inherit(); ~Inherit(); void Show(); private: int num_; }; int main(int argc,char* argv[]){ Inherit obj; obj.Show(); obj.Base::Show(); return 0; } void Base::Show(){ cout<<"Base::Show()"<<endl; } void Inherit::Show(){ cout<<"Inherit::show()"<<endl; } Base::Base():num_(10){ cout<<"default constructor|Base::Base()"<<endl; } Base::~Base(){ cout<<"destructor|Base::~Base()"<<endl; } Inherit::Inherit():num_(20){ cout<<"default constructor"<<endl; } Inherit::~Inherit(){ cout<<"destructor|Inherit::~Inherit()"<<endl; } /* * 基类没有默认构造函数的时候,基类的构造函数要在派生类构造函数初始化列表中调用 * 友元类不能被继承:A是B的友元类,C是A的派生类,但C不是B的友元类 * 友元关系是单向的:A是B的友元类,但B并不是A的友元类 * 友元关系是不能被传递的:A是B的友元类,B是C的友元类,但A不是C的友元类 * * 派生类对象的构造次序 * 先调用基类的对象成员的构造函数,然后调用基类构造函数,接着是派生类的对象成员的构造函数,最后是派生类自身的构造函数 * * 静态成员无所谓继承 */ /* * 必须要在构造函数的初始化列表中完成初始化的情况 * const成员 * 引用成员 * 类的对象成员没有默认构造函数的时候,只能够在类的构造函数初始化列表中调用该对象的构造函数进行初始化 * 基类没有默认构造函数的时候,基类的构造函数要在派生类构造函数初始化列表中调用 */ <file_sep>/8.03.04.cpp /** * @file 8.03.04.cpp * @brief 运算符重载|-> * @author LiWenGang * @date 2016-08-03 */ #include<iostream> using std::cout; using std::endl; class DBHelper{ public: DBHelper(); ~DBHelper(); void Open(); void Close(); void Query(); }; class DB{ public: DB(); ~DB(); DBHelper* operator-> (); private: DBHelper* m_db; }; int main(int argc, char* argv[]){ DB db; db->Open(); db->Query(); db->Close(); return 0; } DBHelper::DBHelper(){ cout<<"default constructor"<<endl; } DBHelper::~DBHelper(){ cout<<"destructor"<<endl; } DBHelper* DB::operator->(){ return m_db; } void DBHelper::Open(){ cout<<"Open DateBase"<<endl; } void DBHelper::Close(){ cout<<"Close DateBase"<<endl; } void DBHelper::Query(){ cout<<"Query DateBase"<<endl; } DB::DB(){ m_db=new DBHelper; } DB::~DB(){ delete m_db; } <file_sep>/8.08.02.cpp /** * @file 8.08.02.cpp * @brief 虚析构函数 * @author LiWenGang * @date 2016-08-08 */ #include<iostream> using namespace std; class Base{ public: Base(); virtual ~Base(); //如果一个类要作为多态基类,要将其析构函数定义成虚构函数 virtual void Fun1(); virtual void Fun2(); void Fun3(); }; class Derived:public Base{ public: Derived(); ~Derived(); virtual void Fun1(); virtual void Fun2(); void Fun3(); }; int main(int argc, char* argv[]){ Base* p=new Derived; p->Fun1(); delete p; return 0; } Base::Base(){ cout<<"Base::Base()"<<endl; } Base::~Base(){ cout<<"Base::~Base()"<<endl; } Derived::Derived(){ cout<<"Derived::Derived()"<<endl; } Derived::~Derived(){ cout<<"Derived::~Derived()"<<endl; } void Base::Fun1(){ cout<<"Base::Fun1()"<<endl; } void Base::Fun2(){ cout<<"Base::Fun2()"<<endl; } void Base::Fun3(){ cout<<"Base::Fun3()"<<endl; } void Derived::Fun1(){ cout<<"Derived::Fun1()"<<endl; } void Derived::Fun2(){ cout<<"Derived::Fun2()"<<endl; } void Derived::Fun3(){ cout<<"Derived::Fun3()"<<endl; } /* * 虚函数的动态绑定是通过虚表来实现的; * 包含虚函数的类前4个字节用于存放指向虚表的指针。 */ <file_sep>/7.24.09.cpp /** * @file 7.24.09.cpp * @brief const_cast * @author LiWenGang * @date 2016-07-24 */ #include<iostream> using namespace std; void fun(int&); int main(int argc, char* argv[]){ const int val=100; //int n=const_cast<int>(val); int n=val; cout<<"n="<<n<<endl; //int* p=&val; Error,无法从const int* 转换为 int* int*p=const_cast<int*>(&val); *p=200; cout<<"val="<<val<<endl; cout<<"*p="<<*p<<endl; const int num=200; //int &renum=num; //Error int &renum=const_cast<int&>(num); renum=300; cout<<"num="<<num<<endl; cout<<"renum="<<renum<<endl; fun(const_cast<int&>(num)); return 0; } void fun(int& number){ cout<<number<<endl; } /* * const_cast * 用来移除对象的常量性(cast away the constness) * const_cast一般用于指针或者引用 * 使用const_cast去除const限定的目的不是为了修改它的内容,通常是为了函数能够接受这个实际参数 */ <file_sep>/9.30.04.cpp /** * @file 9.30.04.cpp * @brief ofstream * @author LiWenGang * @date 2016-09-30 */ #include<cassert> #include<iostream> #include<fstream> using namespace std; int main(int argc, char* argv[]){ ofstream fout; fout.open("temp.cc"); /* * 上面两行等价于ofstream fout("temp.cc"); */ /* if(fout.is_open()){//判断打开状态 cout<<"Open success"<<endl; }else{ cout<<"Open failed"<<endl; }*/ /* if(fout.good()){//判断文件流 cout<<"Open success"<<endl; }else{ cout<<"Open failed"<<endl; }*/ /* if(fout){//ofstream类重载了一个类型转换运算符,将对象转换成类型指针。故可以将对象直接作为判定条件 cout<<"Open success"<<endl; }else{ cout<<"Open failed"<<endl; }*/ assert(fout);//使用断言的方式判断文件打开是否成功,若失败则会抛出错误 fout.close(); return 0; } <file_sep>/10.06.02.cpp /** * @file 10.06.02.cpp * @brief 八皇后问题 * @author LiWenGang * @date 2016-10-06 */ #include<iostream> #include<algorithm> #include<vector> #include<cmath> using namespace std; const int MAX=8; vector<int> board(MAX); void show_result(); int check_cross(); void put_chess(); int main(int argc, char* argv[]){ for(size_t i=0;i<board.size();i++){ board[i]=i; } put_chess(); return 0; } void show_result(){ for(size_t i=0;i<board.size();i++){ cout<<"("<<i<<","<<board[i]<<")"; } cout<<endl; } int check_cross(){ for(size_t i=0;i<board.size()-1;i++){ for(size_t j=i+1;j<board.size();j++){ if((j-i)==(size_t)abs(board[i]-board[j])){ return 1; } } } return 0; } void put_chess(){ while(next_permutation(board.begin(),board.end())){ if(!check_cross()){ show_result(); } } } /* * 1 2 3 4 5 6 7 8 * 使用next_permutation对上述八个数字做全排列 * 每个位置的下标作为y,每个位置的元素值做x,这样就会形成(y,x)的坐标 * - 若x=x,则表示两个元素在同一行 * - 若y=y,则表示两个元素在同一列 * - 若|xj-xi|=|yj-yi|,则表示两个元素在同一对角线 * 对所有的全排列按照上述方法遍历完成,即可得到最后结果 */ <file_sep>/10.06.06.cpp /** * @file 10.06.06.cpp * @brief IO流迭代器 * @author LiWenGang * @date 2016-10-06 */ #include<iostream> #include<algorithm> #include<vector> using namespace std; void ShowVec(vector<int> v); int main(int argc, char* argv[]){ int a[]={1,2,3,4,5}; vector<int> v(a,a+5); //标准库内部实现的时候,会调用push_back,因此传递给back_insert_iterator的容器必须有push_back操作才行。 back_insert_iterator<vector<int>> bii(v); *bii=6;//也可以是bii=6 ShowVec(v); vector<int> v2; back_insert_iterator<vector<int>> bii2(v2); copy(v.begin(),v.end(),bii2); ShowVec(v2); back_inserter(v)=7; ShowVec(v); copy(v.begin(),v.end(),back_inserter(v2)); ShowVec(v2); return 0; } void ShowVec(vector<int> v){ for(const auto& w:v){ cout<<w<<" "; } cout<<endl; } <file_sep>/10.06.09.cpp /** * @file 10.06.09.cpp * @brief stack|STL * @author LiWenGang * @date 2016-10-06 */ #include<iostream> #include<stack> #include<list> using namespace std; int main(int argc, char* argv[]){ //stack<int> s; stack<int,list<int>> s; for(int i=0;i<5;i++){ s.push(i); } while(!s.empty()){ cout<<s.top()<<" "; s.pop(); } cout<<endl; return 0; } <file_sep>/9.25.01.cpp /** * @file 9.25.01.cpp * @brief 异常处理 * @author LiWenGang * @date 2016-09-25 */ #include<iostream> using std::cout; using std::endl; double Divide(double a, double b); int main(int argc,char* argv[]){ try{ cout<<Divide(5.0,1.0)<<endl; cout<<Divide(5.0,0.0)<<endl; } catch(int){ cout<<"division by zero"<<endl; } } double Divide(double a, double b){ if(b==0){ throw 1; }else{ return a/b; } } <file_sep>/10.05.08.cpp /** * @file 10.05.08.cpp * @brief 已序区间算法|lower_bound,upper_bound * @author LiWenGang * @date 2016-10-05 */ #include<iostream> #include<algorithm> using namespace std; void print_element(int n); int main(int argc, char* argv[]){ int a[]={1,10,10,14,15,16}; vector<int> v(a,a+6); for_each(v.begin(),v.end(),print_element); cout<<endl; vector<int>::iterator it; it=lower_bound(v.begin(),v.end(),10); if(it!=v.end()){ cout<<it-v.begin()<<endl; } it=upper_bound(v.begin(),v.end(),10); if(it!=v.end()){ cout<<it-v.begin()<<endl; } return 0; } void print_element(int n){ cout<<n<<" "; } /* * lower_bound() 搜索第一个“大于等于给定值”的元素 * 如果要插入给定值,保持区间有序性,返回第一个可插入的位置 * upper_bound() 搜索第一个“大于给定值”的元素 * 如果要插入给定值,保持区间有序性,返回最后可插入的位置 * * 内部采用的是二分法查找的方式实现 */ <file_sep>/7.27.02.cpp /** * @file 7.27.02.cpp * @brief 深拷贝,浅拷贝 * @author LiWenGang * @date 2016-07-27 */ #include<iostream> #include<cstring> using std::cout; using std::endl; class String{ public: String(char* str); ~String(); String(const String& other); void Display(); private: char* m_str; }; int main(int argc, char* argv[]){ String str("AAA"); str.Display(); //String str1(str); /* 因为没有提供拷贝构造函数,因此调用的是默认的拷贝构造函数 而系统提供的默认拷贝构造函数实施的是浅拷贝,即str1.m_str=str.m_str 即不同对象的两个m_str指针会指向同一块内存,但是函数生命周期结束时会调用两次析构函数来释放内存, 即同一块内存会被释放两次,从而导致运行时错误 为了避免这种错误,需要自己定义拷贝构造函数,实施深拷贝便可 */ String str2(str); str2.Display(); /* * 这里自己定义了拷贝构造函数,实施深拷贝,因此不会出现运行时错误。 */ String str3=str2; str3.Display(); return 0; } String::String(char* str){ int len=strlen(str)+1; m_str=new char[len]; memset(m_str,0,len); strcpy(m_str,str); } String::~String(){ delete[] m_str; } String::String(const String& other){ int len=strlen(other.m_str)+1; m_str=new char[len]; memset(m_str,0,len); strcpy(m_str,other.m_str); } void String::Display(){ cout<<m_str<<endl; } <file_sep>/7.28.02.cpp /** * @file 7.28.02.cpp * @brief 类大小计算 * @author LiWenGang * @date 2016-07-28 */ #include<iostream> using std::cout; using std::endl; class Test{ public: Test(); ~Test(); private: int m_num; static int m_cnt; }; int main(int argc, char* argv[]){ cout<<sizeof(Test)<<endl; return 0; } /* * 类大小计算与结构体对齐原则一致 * 类的大小与数据成员有关与成员函数无关 * 类的大小与静态数据成员无关 * 虚函数对类的大小的影响 * 虚继承对类的大小的影响 */ <file_sep>/8.02.07.cpp /** * @file 8.02.07.cpp * @brief 赋值运算符重载(=)|非运算符重载(!)|String * @author LiWenGang * @date 2016-08-03 */ #include<iostream> #include<cstring> using std::cout; using std::endl; class String{ public: String(); ~String(); explicit String(const char* str); String(const String& obj); String& operator= (const String& obj); String& operator= (const char* str); bool operator! () const; void DisPlay(); private: char* m_str; }; int main(int argc, char* argv[]){ String obj("hello world"); obj.DisPlay(); String obj1(obj); obj1.DisPlay(); String obj2=obj; obj2.DisPlay(); String obj3; obj3="hello latex"; obj3.DisPlay(); String obj4("xxxxx"); bool notempty; notempty=!obj4; cout<<notempty<<endl; return 0; } String::String(){ cout<<"default constructor"<<endl; } String::~String(){ delete[] m_str; } String::String(const char* str){ int len=strlen(str)+1; m_str=new char(len); memset(m_str,0,len); strcpy(m_str,str); } String::String(const String& obj){ int len=strlen(obj.m_str)+1; m_str=new char(len); memset(m_str,0,len); strcpy(m_str,obj.m_str); } String& String::operator= (const String& obj){ if(m_str==obj.m_str){ return *this; } int len=strlen(obj.m_str); m_str=new char(len); memset(m_str,0,len); strcpy(m_str,obj.m_str); return *this; } String& String::operator= (const char* str){ int len=strlen(str)+1; m_str=new char(len); memset(m_str,0,len); strcpy(m_str,str); return *this; } bool String::operator!() const{ return strlen(m_str)!=0; } void String::DisPlay(){ cout<<m_str<<endl; } <file_sep>/7.24.06.cpp /** * @file 7.24.06.c * @brief 带默认形参值的函数 * @author LiWenGang * @date 2016-07-24 */ #include<iostream> using namespace std; int fun(int, int b=3); int main(int argc, char* argv[]){ cout<<fun(3)<<endl; cout<<fun(4,4)<<endl; return 0; } int fun(int a, int b){ return a+b; } /* * 函数没有声明时,在函数定义中指定形参的默认值 * 函数既有定义又有声明时,声明时指定后,定义后就不能再指定默认值 * 默认值的定义必须遵守从右到左的顺序,如果某个形参没有默认值,则它左边的参数就不能有默认值。 * 重载的函数中如果形参带有默认值时,可能产生二义性。比如 * int fun(int a=1,int b=2); * int fun(int a=1,int b=2,int c=3); */ <file_sep>/7.26.05.cpp /** * @file 7.26.05.cpp * @brief 嵌套类构造函数和析构函数的执行次序|构造函数初始化值列表 * @author LiWenGang * @date 2016-07-26 */ #include<iostream> using namespace std; class Object{ public: Object(int num); ~Object(); private: int m_num; }; class Container{ public: Container(int obj1, int obj2); ~Container(); private: Object m_obj1; Object m_obj2; }; int main(int argc, char* argv[]){ Container ct(30,40); return 0; } Object::Object(int num):m_num(num){ cout<<"Object ..."<<m_num<<endl; } Object::~Object(){ cout<<"~Object ..."<<m_num<<endl; } Container::Container(int obj1=10, int obj2=20):m_obj1(obj1),m_obj2(obj2){ cout<<"Container ..."<<endl; } Container::~Container(){ cout<<"~Container ..."<<endl; } /* * 对象的初始化顺序与初始化值列表中的顺序并没有关系,其顺序取决于其在类中的声明次序; * 如果一个类中嵌套的这个类中如果没有默认构造函数的话,一定要在外面的那个类的构造函数初始化值列表完成初始化操作 */ <file_sep>/8.04.01.cpp /** * @file 8.04.01.cpp * @brief string|构造函数 * @author LiWenGang * @date 2016-08-04 */ #include<iostream> #include<string> using std::string; using std::cout; using std::endl; int main(int argc, char* argv[]){ string s1; string s2("abcdefghijk"); cout<<s2<<endl; string s3("abcdefgh",4); cout<<s3<<endl; string s4(s3,2,4); cout<<s4<<endl; string s5(4,'c'); cout<<s5<<endl; string::iterator first=s2.begin()+1; string::iterator second=s2.end(); string s6(first,second); cout<<s6<<endl; return 0; } /* * 标准库类型: * * string 字符串 char* * vector 动态数组 静态数组[] * map key/value 内部是以树的形式存储的O(log2N) */ <file_sep>/8.03.01.cpp /** * @file 8.03.01.cpp * @brief 运算符重载|[]|+|+=|<<|>> * @author LiWenGang * @date 2016-08-03 */ #include<iostream> #include<cstring> using std::cout; using std::cin; using std::endl; using std::ostream; using std::istream; class String{ friend String operator+ (const String& obj1, const String& obj2); friend ostream& operator<< (ostream& os, const String& obj); friend istream& operator>> (istream& os, String& obj); public: String(); ~String(); explicit String(const char* str); String(const String& obj); String& operator= (const String& obj); String& operator= (const char* str); char& operator[] (const unsigned int index); const char& operator[] (const unsigned int index) const; String& operator+= (const String& obj); bool operator! () const; void DisPlay() const; private: char* m_str; }; int main(int argc, char* argv[]){ String obj("hello world"); obj.DisPlay(); String obj1(obj); obj1.DisPlay(); String obj2=obj; //等号运算符重载|= obj2.DisPlay(); String obj3; obj3="hello latex"; //等号运算符重载|= obj3.DisPlay(); String obj4("xxxxx"); bool notempty; notempty=!obj4; //非运算符重载|! cout<<notempty<<endl; char ch=obj[0]; cout<<ch<<endl; const String obj5("hello c++"); ch=obj[0]; cout<<ch<<endl; //obj5[0]='H'; //const修饰的类型不允许被修改,为了防止修改,引入了由const对[]限制的再次重载 obj5.DisPlay(); String obj6=obj5+obj4; //等号运算符重载|+ obj6.DisPlay(); obj3+=obj4; //加等运算符重载|+= obj3.DisPlay(); cout<<obj3<<endl; //输出重定向运算符重载|<< String obj7; cin>>obj7; //输入重定向运算符重载|>> cout<<obj7<<endl; return 0; } String::String(){ cout<<"default constructor"<<endl; } String::~String(){ delete[] m_str; } String::String(const char* str){ int len=strlen(str)+1; m_str=new char(len); memset(m_str,0,len); strcpy(m_str,str); } String::String(const String& obj){ int len=strlen(obj.m_str)+1; m_str=new char(len); memset(m_str,0,len); strcpy(m_str,obj.m_str); } String& String::operator= (const String& obj){ if(m_str==obj.m_str){ return *this; } int len=strlen(obj.m_str); m_str=new char(len); memset(m_str,0,len); strcpy(m_str,obj.m_str); return *this; } String& String::operator= (const char* str){ int len=strlen(str)+1; m_str=new char(len); memset(m_str,0,len); strcpy(m_str,str); return *this; } char& String::operator[] (const unsigned int index){ return const_cast<char&>(static_cast<const String&>(*this)[index]); //等价于调用下面的函数 //return m_str[index]; //上述语句等价于该条语句 } const char& String::operator[] (const unsigned int index) const{ return m_str[index]; } bool String::operator!() const{ return strlen(m_str)!=0; } String operator+ (const String& obj1, const String& obj2){ int len=strlen(obj1.m_str)+strlen(obj2.m_str)+1; char *newchar=new char(len); memset(newchar,0,len); strcpy(newchar,obj1.m_str); strcat(newchar,obj2.m_str); String tmp(newchar); delete newchar; return tmp; /* * String str= obj1; * str+=obj2; //调用+=重载运算符 * return str; */ } String& String::operator+= (const String& obj){ int len=strlen(m_str)+strlen(obj.m_str)+1; char* newstr=new char(len); memset(newstr,0,len); strcpy(newstr,m_str); strcat(newstr,obj.m_str); delete[] m_str; m_str=newstr; return *this; } ostream& operator<< (ostream& os, const String& obj){ os<<obj.m_str; return os; } istream& operator>> (istream& is, String& obj){ char tmp[1024]; cin>>tmp; obj=tmp; return is; } void String::DisPlay() const{ cout<<m_str<<endl; } <file_sep>/9.30.02.cpp /** * @file 9.30.02.cpp * @brief 单例模式,修复指针释放时错误 * @author LiWenGang * @date 2016-09-30 */ #include<iostream> #include<memory> using std::cout; using std::endl; using std::auto_ptr; class Singleton{ public: Singleton(); ~Singleton(); Singleton(const Singleton& obj)=delete; Singleton& operator= (const Singleton& obj)=delete; static Singleton* GetInstance(); private: static auto_ptr<Singleton> instance_; }; auto_ptr<Singleton>(Singleton::instance_); int main(int argc, char* argv[]){ Singleton* p1=Singleton::GetInstance(); Singleton* p2=Singleton::GetInstance(); cout<<(void*)p1<<endl; cout<<(void*)p2<<endl; return 0; } Singleton* Singleton::GetInstance(){ if(!instance_.get()){ instance_=auto_ptr<Singleton>(new Singleton); } return instance_.get(); } Singleton::Singleton(){ cout<<"constructor function"<<endl; } Singleton::~Singleton(){ cout<<"destructor function"<<endl; } <file_sep>/10.04.01.cpp /** * @file 10.04.01.cpp * @brief vector|capacity(),size() * @author LiWenGang * @date 2016-10-04 */ #include<iostream> #include<vector> using namespace std; int main(int argc, char* argv[]){ vector<int> v; v.push_back(1); cout<<v.size()<<" | "<<v.capacity()<<endl; v.push_back(1); cout<<v.size()<<" | "<<v.capacity()<<endl; v.push_back(1); cout<<v.size()<<" | "<<v.capacity()<<endl; v.push_back(1); cout<<v.size()<<" | "<<v.capacity()<<endl; v.push_back(1); cout<<v.size()<<" | "<<v.capacity()<<endl; v.push_back(1); cout<<v.size()<<" | "<<v.capacity()<<endl; v.push_back(1); cout<<v.size()<<" | "<<v.capacity()<<endl; v.push_back(1); cout<<v.size()<<" | "<<v.capacity()<<endl; return 0; } /* * vector * 增长capacity增长时候并不是呈线性增长,而是空间不足时,增长为原来的两倍;如果空间足够,则空间大小不变。 * 当然在不同平台下面的实现可能不一样。比如windows可能会一次增长原来的一半,即容量增长为原来的1.5倍 * capacity()>=size() * 即vector当前能够容纳的元素的个数会大于vector中当前存储的元素个数 */ <file_sep>/7.27.01.cpp /** * @file 7.27.01.cpp * @brief 拷贝构造函数分析 * @author LiWenGang * @date 2016-07-27 */ #include<iostream> using namespace std; class Test{ public: Test(); explicit Test(int num); Test(const Test& ob); ~Test(); private: int m_num; }; void TestFun1(const Test t); void TestFun2(const Test& t); Test TestFun3(const Test& t); const Test& TestFun4(const Test& t); int main(int argc, char* argv[]){ Test t1(10); //Test t2(t1); //TestFun1(t1); //TestFun2(t1); //TestFun3(t1); /* 函数TestFun3会返回一个对象,因为生命周期结束,所以该对象会被重新“赋值”给一个临时对象,但是因为该临时对象没有新的对象接管,所以该临时对象会被立刻销毁; 即cout出的结果会在析构函数之后 */ //Test t3=TestFun3(t1); /* 此处应当注意,直观的理解是函数TestFun3返回一个对象,然后使用该对象初始化对象t3。但实际上编译器并不是这么做的。 当TestFun3返回一个对象时,函数TestFun3的生命周期结束,编译器会生成一个临时对象,将TestFun3的返回对象赋值给改临时对象,故会调用一次拷贝构造函数; 当该临时对象重新“赋值”给对象t3时,编译器实际并没有做“赋值”处理,而是将该临时对象直接重命名为t3,所以并不会调用拷贝构造函数。 cout出的结果会在析构函数之前 */ //Test t4=TestFun4(t1); /* 此处应当注意,虽然运行结果与TestFun3的结果一致,但是两者的意义是不同的。因为TestFun4的形参和返回值都是引用,因此不会调用拷贝构造函数; 但是返回的引用在初始化对象t4时会调用一次拷贝构造函数 */ const Test& t5=TestFun4(t1); /* 此处应当注意,因为接收函数TestFun4返回值的变量本身就是引用,因此不会调用拷贝构造函数; */ cout<<"-----------"<<endl; return 0; } Test::Test(){ m_num=0; cout<<"Initialization Default Constructor|m_num="<<m_num<<endl; } Test::Test(int num){ m_num=num; cout<<"Initialization Constructor|m_num="<<m_num<<endl; } Test::Test(const Test& obj){ cout<<"Initialization Copy Constructor|m_num="<<m_num<<endl; m_num=obj.m_num; } Test::~Test(){ cout<<"Initialization Destructor|m_num="<<m_num<<endl; } void TestFun1(const Test t){ /* * 因为形参是对象,因此在使用的时候,会调用一次拷贝构造函数 */ } void TestFun2(const Test& t){ /* * 因为形参是引用,因此在使用的时候,不会调用一次拷贝构造函数 */ } Test TestFun3(const Test& t){ /* * 因为返回的是一个对象,该子函数生命周期完结时,系统会生成一个临时对象,故会调用一次拷贝构造函数 */ return t; } const Test& TestFun4(const Test& t){ return t; } /* * 使用一个对象初始化另一个对象,以值传递的方式传递或返回一个对象等操作会导致调用拷贝构造函数 * 1. 当函数的形参是类的对象,调用函数时,进行形参与实参结合时使用。这时要在内存新建立一个局部对象,并把实参拷贝到新的对象中。理所当然也调用拷贝构造函数。 * 2. 当函数的返回值是类对象,函数执行完成返回调用时使用。理由也是要建立一个临时对象中,再返回调用者。 */ <file_sep>/10.01.04.cpp /** * @file 10.01.04.cpp * @brief sstringstream|string和double之间的类型转换 * @author LiWenGang * @date 2016-10-01 */ #include<iostream> #include<sstream> #include<string> using namespace std; string dtostr(double x);//将double型转换为string类型 double strtod(const string& str);//将string类型转换为double型 int main(int argc,char* argv[]){ double x=10.01; string str=dtostr(x); cout<<str<<endl; string ch="10.01"; double y=strtod(ch); cout<<y<<endl; return 0; } string dtostr(double x){ ostringstream os; os<<x; return os.str(); } double strtod(const string& str){ istringstream is(str); double val; is>>val; return val; } <file_sep>/7.24.03.cpp /** * @file 7.24.03.cpp * @brief 作用域标识符:: * @author LiWenGang * @date 2016-07-24 */ #include<iostream> using namespace std; int var=100; int main(int argc, char* argv[]){ int var=50; cout<<var<<endl; cout<<::var<<endl; return 0; } <file_sep>/8.08.01.cpp /** * @file 8.08.01.cpp * @brief 虚函数 * @author LiWenGang * @date 2016-08-08 */ #include<iostream> using namespace std; class Base{ public: virtual void Fun1(); virtual void Fun2(); void Fun3(); }; class Derived:public Base{ public: virtual void Fun1(); virtual void Fun2(); void Fun3(); }; int main(int argc, char* argv[]){ Base* p; Derived d; p=&d; p->Fun1(); //Fun1是虚函数,基类指针指向派生类对象,调用的是派生类对象的虚函数 p->Fun2(); p->Fun3(); //Fun3不是虚函数,根据指针p实际类型调用相应类的成员函数 return 0; } void Base::Fun1(){ cout<<"Base::Fun1()"<<endl; } void Base::Fun2(){ cout<<"Base::Fun2()"<<endl; } void Base::Fun3(){ cout<<"Base::Fun3()"<<endl; } void Derived::Fun1(){ cout<<"Derived::Fun1()"<<endl; } void Derived::Fun2(){ cout<<"Derived::Fun2()"<<endl; } void Derived::Fun3(){ cout<<"Derived::Fun3()"<<endl; } /* * 多态性是指发出同样的消息被不同类型的对象接收时有可能导致完全不同的行为 * * 多态的实现 * ·函数重载 * ·运算符重载 * ·模板 * ·虚函数 * 前三种称之为静态多态(静态绑定) * 最后一种称为静态多态(动态绑定) * * 静态绑定:绑定过程中出现在编译阶段,在编译期就已确定要调用的函数 * 动态绑定:绑定过程工作在程序运行时执行,在程序运行时才确定要调用的函数 */ <file_sep>/7.28.01.cpp /** * @file 7.28.01.cpp * @brief 静态成员函数,静态成员 * @author LiWenGang * @date 2016-07-28 */ #include<iostream> using std::cout; using std::endl; class Test{ public: Test(int); ~Test(); void TestFun(); static void TestStaticFun(); private: static int m_x; int m_y; }; int Test::m_x=10; int main(int argc, char* argv[]){ Test t(100); t.TestFun(); return 0; } Test::Test(int y):m_y(y){ } void Test::TestFun(){ cout<<"m_x="<<m_x<<endl;// 非静态成员函数可以访问静态成员 } void Test::TestStaticFun(){ //cout<<"m_y="<<m_y<<endl;// 静态成员函数不可以访问非静态成员 } Test::~Test(){ } /* * 非static数据成员存在于类类型的每个对象中;static数据成员独立该类的任何对象存在,它是与类关联的对象,不与类对象关联 * 静态(static)成员函数没有this指针,因此静态成员函数不可以访问非静态成员 * 非静态成员函数可以访问静态成员 */ <file_sep>/10.01.06.cpp /** * @file 10.01.06.cpp * @brief 通过成员函数进行格式化输出 * @author LiWenGang * @date 2016-10-01 */ #include<iostream> using namespace std; int main(int argc,char* argv[]){ int n=64; double d=123.45; double d2=0.018; cout<<"=================宽度控制=================="<<endl; cout<<n<<'#'<<endl; cout.width(10);//宽度控制,不会影响下一个输出 cout<<n<<'#'<<n<<endl; cout<<"=================对齐控制=================="<<endl; cout.width(10); cout.setf(ios::left);//宽度控制,会影响下一个输出 cout<<n<<'#'<<endl; cout.width(10); cout<<n<<'#'<<endl; cout.width(10); cout.unsetf(ios::left); cout<<"=================填充控制=================="<<endl; cout.width(10); cout.fill('?');//填充控制,会影响下一个输出 cout<<n<<'#'<<endl; cout.width(10); cout.fill(' '); cout<<n<<'#'<<endl; cout<<"=================精度控制=================="<<endl; cout.precision(4);//保留4位有效数字 cout<<d<<endl; cout.precision(2); cout<<d2<<endl; cout.setf(ios::fixed); cout.precision(4);//小数点后保留4位 cout<<d<<endl; cout.precision(2); cout<<d2<<endl; cout<<"=================进制输出=================="<<endl; cout.setf(ios::showbase); cout<<n<<endl; cout.unsetf(ios::dec); cout.setf(ios::oct); cout<<n<<endl; cout.unsetf(ios::showbase); cout<<n<<endl; return 0; } <file_sep>/8.10.01.cpp /** * @file 8.10.01.cpp * @brief dynamic_cast,typeid * @author LiWenGang * @date 2016-08-10 */ #include<iostream> #include<typeinfo> using namespace std; class Shape{ public: virtual void Draw()=0; virtual ~Shape(); }; class Circle:public Shape{ public: void Draw(); }; class Square:public Shape{ public: void Draw(); }; int main(int argc, char* argv[]){ Shape *p; Circle c; p=&c; p->Draw(); if(dynamic_cast<Circle*>(p)){ cout<<"p is point of Circle object"<<endl; Circle* cp=dynamic_cast<Circle*>(p); //安全向下转型 cp->Draw(); }else if(dynamic_cast<Square*>(p)){ cout<<"p is point to a Square object"<<endl; }else{ cout<<"p is point to a Other object"<<endl; } cout<<typeid(*p).name()<<endl; cout<<typeid(Circle).name()<<endl; if(typeid(Circle).name()==typeid(*p).name()){ cout<<"p is point of Circle object"<<endl; ((Circle*)p)->Draw(); }else{ cout<<"p is point to a Other object"<<endl; } return 0; } Shape::~Shape(){ cout<<"Shape::~Shape()"<<endl; } void Circle::Draw(){ cout<<"Circle::Draw()"<<endl; } void Square::Draw(){ cout<<"Square::Draw()"<<endl; } /* * RTTI(runtime type information) * * static_cast 编译器认可的转型 * reinterpre_cast 用于编译器不认可的转型,不做任何的对齐操作 * const_cast 用于去除常量限定 * dynamic_cast 安全的向下转型 */ <file_sep>/8.04.04.cpp /** * @file 8.04.04.cpp * @brief string|example * @author LiWenGang * @date 2016-08-04 */ #include<iostream> #include<string> using namespace std; int main(int argc, char* argv[]){ string strinfo=" //*---Hello world---*//"; string strset="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; string::size_type first=strinfo.find_first_of(strset);//从前向后查找strinfo在strset中存在的第一个字符,若查找到,返回该位置 if(first==string::npos){ cout<<"not find any characters"<<endl; } string::size_type last=strinfo.find_last_of(strset);//从后向前查找strinfo在strset中存在的第一个字符,若查找到,返回该位置 if(last==string::npos){ cout<<"not find any characters"<<endl; } cout<<strinfo.substr(first,last-first+1)<<endl; return 0; } <file_sep>/10.06.03.cpp /** * @file 10.06.03.cpp * @brief 函数对象 * @author LiWenGang * @date 2016-10-06 */ #include<iostream> using namespace std; class FunObj{ public: void operator() (){ cout<<"hello world"<<endl; } void operator() (int cnt){ cout<<cnt<<endl; } }; int main(int argc, char* argv[]){ FunObj obj; obj();//仿函数 obj(88); FunObj()(); return 0; } <file_sep>/9.30.06.cpp /** * @file 9.30.06.cpp * @brief fstream * @author LiWenGang * @date 2016-10-01 */ #include<iostream> #include<string> #include<fstream> using namespace std; struct Test{ int a; int b; }; int main(int argc, char* argv[]){ /* fstream fout("temp.cc"); fout<<"abc"<<" "<<200; */ /* ifstream fin("temp.cc"); string s; int n; fin>>s>>n; cout<<s<<" "<<n<<endl; */ //----------------------------- /* char ch; for(int i=0;i!=26;++i){ ch='A'+i; fout.put(ch); } fout.close(); */ //----------------------------- /* ifstream fin("temp.cc"); while(fin.get(ch)){ cout<<ch; } cout<<endl; */ /* //binary那一项可以不用,以文本方式打开,但是写入的字符仍然是以二进制的方式写入文件 Test test{100,200}; ofstream fout("temp.cc",ofstream::out | ofstream::binary); fout.write(reinterpret_cast<char*>(&test),sizeof(Test)); fout.close(); Test test2; ifstream fin("temp.cc",ifstream::in | ifstream::binary); fin.read(reinterpret_cast<char*>(&test2),sizeof(Test)); cout<<test2.a<<" "<<test2.b<<endl; */ //尽管是以二进制模式打开文件,但是<<却是以文本方式写入的 ofstream fout("temp.cc",ofstream::out | ofstream::binary); fout<<"abc"<<200; return 0; } /* * 以文本方式打开文件,写入字符的时候,遇到\n会做转换,写入\r不做转换 * 如果以二进制方式打开文件写入字符的时候,\n不会做转换 * * windows平台,\n 转变为 \r\n * linux平台,保留不变 * mac系统,\n 转变为 \r * * 以文本方式打开文件,也可以写入二进制数据 * 以二进制方式打开文件,也可以写入文本; * * 写入的数据是二进制还是文本,与打开的方式无关,与使用的函数有关 * 要写入二进制数据,应该用write,读取应该使用read */ <file_sep>/7.26.07.cpp /** * @file 7.26.07.cpp * @brief 拷贝构造函数 * @author LiWenGang * @date 2016-07-26 */ #include<iostream> using namespace std; class Test{ public: Test(int num); Test(const Test& num); //拷贝构造函数 ~Test(); private: int m_num; }; int main(int argc, char* argv[]){ Test t1(10); Test t2(t1); //等价于Test t2=t1; return 0; } Test::Test(int num):m_num(num){ cout<<"Initalzing "<<m_num<<endl; } Test::Test(const Test& other):m_num(other.m_num){ cout<<"Initalzing with other "<<m_num<<endl; } Test::~Test(){ cout<<"Destroying "<<m_num<<endl; } <file_sep>/10.03.08.cpp /** * @file 10.03.08.cpp * @brief 对象的动态创建|采用模板方式实现 * @author LiWenGang * @date 2016-10-03 */ #include<iostream> #include<string> #include<vector> #include<map> using namespace std; class Shape; void DrawAllShape(const vector<Shape*>& v); void DeleteAllShape(const vector<Shape*>& v); class Shape{ public: virtual void Draw()=0; virtual ~Shape(); }; class Circle:public Shape{ public: void Draw(); ~Circle(); }; class Triangle:public Shape{ public: void Draw(); ~Triangle(); }; typedef void* (*CREATE_FUN)(); class DynObjectFactor{ public: static void* CreateObject(const string& name); static void Register(const string& name, CREATE_FUN func); private: static map<string, CREATE_FUN> mapCls_; }; map<string,CREATE_FUN>DynObjectFactor::mapCls_; template<typename T> class DelegatingClass{ public: DelegatingClass(const string& name){ DynObjectFactor::Register(name,&(DelegatingClass::NewInstance)); } static void* NewInstance(){ return new T; } }; #define REGISTER_CLASS(class_name) DelegatingClass<class_name> class##class_name(#class_name) int main(int argc, char* argv[]){ vector<Shape*> v; Shape* ps; ps=static_cast<Shape*>(DynObjectFactor::CreateObject("Circle")); v.push_back(ps); ps=static_cast<Shape*>(DynObjectFactor::CreateObject("Triangle")); v.push_back(ps); DrawAllShape(v); DeleteAllShape(v); return 0; } void DrawAllShape(const vector<Shape*>& v){ for(vector<Shape*>::const_iterator it=v.begin();it!=v.end();++it){ (*it)->Draw(); } } void DeleteAllShape(const vector<Shape*>& v){ for(vector<Shape*>::const_iterator it=v.begin();it!=v.end();++it){ delete(*it); } } Shape::~Shape(){ cout<<"Shape::~Shape()"<<endl; } void Circle::Draw(){ cout<<"Circle::Draw()"<<endl; } Circle::~Circle(){ cout<<"Circle::~Circle()"<<endl; } void Triangle::Draw(){ cout<<"Triangle::Draw()"<<endl; } Triangle::~Triangle(){ cout<<"Triangle::~Triangle()"<<endl; } REGISTER_CLASS(Circle); REGISTER_CLASS(Triangle); void* DynObjectFactor::CreateObject(const string& name){ map<string, CREATE_FUN>::const_iterator it; it=mapCls_.find(name); if(it==mapCls_.end()){ return NULL; }else{ return it->second(); } } void DynObjectFactor::Register(const string& name, CREATE_FUN func){ mapCls_[name]=func; } /* * 与8.09.02.cpp相同的功能,只是本程序使用模板实现而已 */ <file_sep>/10.06.04.cpp /** * @file 10.06.04.cpp * @brief 函数对象|类,算法 * @author LiWenGang * @date 2016-10-06 */ #include<iostream> #include<algorithm> #include<string> #include<vector> #include<map> using namespace std; class PrintObj{ public: void operator() (int n){ cout<<n<<" "; } }; class AddObj{ public: AddObj(int number):number_(number){} void operator() (int& n){ n+=number_; } private: int number_; }; class GreaterObj{ public: GreaterObj(int number):number_(number){} bool operator() (int cnt){ return cnt>3; } private: int number_; }; int main(int argc, char* argv[]){ map<int, string> mapTest; mapTest.insert(map<int,string>::value_type(1,"aaa")); mapTest.insert(map<int,string>::value_type(3,"ccc")); mapTest.insert(map<int,string>::value_type(2,"bbb")); for(map<int,string>::const_iterator it=mapTest.begin();it!=mapTest.end();++it){ cout<<it->first<<" | "<<it->second<<endl; } //-------------------------------------- int a[]={1,2,3,4,5}; vector<int> v(a,a+5); for_each(v.begin(),v.end(),PrintObj()); cout<<endl; for_each(v.begin(),v.end(),AddObj(5)); for_each(v.begin(),v.end(),PrintObj()); cout<<endl; cout<<count_if(a,a+5,GreaterObj(3))<<endl; return 0; } <file_sep>/8.03.05.cpp /** * @file 8.03.05.cpp * @brief 运算符重载|new|delete * @author LiWenGang * @date 2016-08-03 */ #include<iostream> using std::cout; using std::endl; class Test{ public: Test(); Test(const int num); Test(const Test& obj); void* operator new(size_t size); void operator delete(void* p); void operator delete(void* p, size_t size); void Display(); private: int m_num; }; int main(int argc, char* argv[]){ Test* obj=new Test(100); //new operator = operater new + 构造函数的调用 delete obj; obj->Display(); /* char chunk[10]; Test* obj1=new(chunk) Test(200); //placement new = operater new + 构造函数的调用 obj1->Display(); //此处实际上比不开辟新的内存,直接使用chunk这块内存区域 //Test* obj2=(Test*)chunk; //与下述语句等价,实现类型强制转化 Test* obj2=reinterpret_cast<Test*>(chunk); obj2->Display(); */ return 0; } Test::Test(const int num):m_num(num){ cout<<"constructor| Test::Test(const int num)"<<endl; } Test::Test(const Test& obj){ cout<<"constructor|Test::Test(const Test& obj)"<<endl; } void* Test::operator new(size_t size){ cout<<"new|void* Test::operator new(size_t size)"<<endl; void* p=malloc(size); return p; } void Test::operator delete(void* p){ cout<<"delete|void Test::operator delete(void* p)"<<endl; free(p); } void Test::operator delete(void* p, size_t size){ cout<<"void Test::operator delete(void* p, size_t size)"<<endl; free(p); } void Test::Display(){ cout<<m_num<<endl; } /* * new有三种用法: * new operator * operator new * placement new */ <file_sep>/8.02.03.cpp /** * @file 8.02.03.cpp * @brief 运算符重载|成员函数重载 * @author LiWenGang * @date 2016-08-02 */ #include<iostream> using std::cout; using std::endl; class ComPlex{ public: ComPlex(int a, int b); ~ComPlex(); ComPlex operator+ (const ComPlex& other); void Display() const; private: int m_a; int m_b; }; int main(int argc, char* argv[]){ ComPlex c1(1,2); ComPlex c2(3,4); ComPlex c3=c1+c2; c3.Display(); return 0; } ComPlex::ComPlex(int a, int b):m_a(a),m_b(b){ cout<<"constructor function"<<endl; } ComPlex::~ComPlex(){ cout<<"destructor function"<<endl; } ComPlex ComPlex::operator+ (const ComPlex& other){ int a=m_a+other.m_a; int b=m_b+other.m_b; return ComPlex(a,b); } void ComPlex::Display() const{ cout<<m_a<<"+"<<m_b<<"i"<<endl; } <file_sep>/8.05.01.cpp /** * @file 8.05.01.cpp * @brief 继承|公有继承、保护继承、私有继承 * @author LiWenGang * @date 2016-08-05 */ #include<iostream> class Base{ public: int x_; protected: int y_; private: int z_; }; class PublicInherit:public Base{ public: void Test(); private: int n_; }; class ProtectedInherit:protected Base{ public: void Test(); private: int n_; }; class PrivateInherit:private Base{ public: void Test(); private: int n_; }; int main(int argc, char* argv[]){ PublicInherit pub; pub.x_=100; //pub.y_=200; //pub.z_=300; ProtectedInherit prt; //prt.x_=100; //prt.y_=200; //prt.z_=300; PrivateInherit pvt; //pvt.x_=100; //pvt.y_=200; //pvt.z_=300; return 0; } void PublicInherit::Test(){ x_=10; y_=20; //z_=30; } void ProtectedInherit::Test(){ x_=10; y_=20; //z_=30; } void PrivateInherit::Test(){ x_=10; y_=20; //z_=30; } /* * 基类 范围大 抽象 * 派生类 范围小 具体 * * 公有继承的派生类可以访问基类的公有成员,保护成员,但不能访问基类的私有成员 * * 继承方式 | 基类成员特性 派生类成员特性 | 派生类对象是否能直接访问基类成员 * ---------|-------------------------------|---------------------------------- * 公有继承 | public public | 是 * | protected protected | 是 * | private | 否 * ---------|-------------------------------|--------------------------------- * 保护继承 | public protected | 是 * | protected protected | 是 * | private | 否 * ---------|-------------------------------|--------------------------------- * 私有继承 | public private | 是 * | protected private | 是 * | private | 否 */ <file_sep>/8.04.06.cpp /** * @file 8.04.06.cpp * @brief vector|成员函数 * @author LiWenGang * @date 2016-08-04 */ #include<iostream> #include<vector> using namespace std; int main(int argc, char* argv[]){ vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); cout<<v.back()<<endl; //打印最后一个元素 for(unsigned int i=0;i!=v.size();i++){ cout<<v[i]<<" "; } cout<<endl; v.erase(v.begin()+1); //移除第1个元素,从0开始编号 v.erase(v.begin(),v.begin()+2); //移除第0到第2个元素 for(vector<int>::iterator it=v.begin();it!=v.end();++it){ cout<<*it<<" "; } cout<<endl; return 0; } /* * STL六大组件: * 容器、迭代器、算法、函数对象、适配器、内存分配器 */ <file_sep>/10.03.05.cpp /** * @file 10.03.05.cpp * @brief 成员模板|不同类型之间的赋值 * @author LiWenGang * @date 2016-10-03 */ #include<iostream> using namespace std; template<typename T> class MyClass{ public: MyClass(){} ~MyClass(){} public: template<class X> MyClass(const MyClass<X>& x):value_(x.GetValue()){} template<class X> void Assign(const MyClass<X>& x) { value_=x.GetValue(); //value=x.value_;//本来可以使用这种方式直接完成赋值,但是如果参数类型不一致,则会出错 } T GetValue() const{ return value_; } private: T value_; }; int main(int argc, char* argv[]){ MyClass<double> d; MyClass<int> i; d.Assign(d); d.Assign(i);//将int型赋值给double型,如果不采用成员模板实现的话,会编译出错。 MyClass<double> d2(i);//采用构造函数的方式进行类型不匹配的赋值,因此需要自己重新定义构造函数 return 0; } <file_sep>/8.05.02.cpp /** * @file 8.05.02.cpp * @brief 继承|重定义 * @author LiWenGang * @date 2016-08-05 */ #include<iostream> using namespace std; class Base{ public: void show(); }; class Inherit:public Base{ public: void show(); }; int main(int argc, char* argv[]){ Inherit obj; obj.show(); obj.Base::show(); /* * 当基类与派生类中有相同的数据成员或成员函数时,会优先使用派生类的数据成员或成员函数 * 如需使用基类中的数据成员或成员函数,需要显式指定。 */ return 0; } void Base::show(){ cout<<"Base::show"<<endl; } void Inherit::show(){ cout<<"Inherit show"<<endl; } /* * 接口继承: * 基类的公有成员函数在派生类中仍然是公有的,话句话说是基类的接口成为了派生类的接口,因而将它称为接口继承 * 实现继承; * 对于私有、保护继承会导致基类的公有成员函数在派生类不再保持公有的属性,派生类将不再支持基类的公有接口,它希望能重用基类的实现而已,因此将它称为实现继承。 */ /* * 对基类数据成员的重定义 * 对基类成员函数的重定义---|---overwrite:与基类完全相同;与基类成员函数名相同 * |---override */ <file_sep>/10.03.06.cpp /** * @file 10.03.06.cpp * @brief typename * @author LiWenGang * @date 2016-10-03 */ #include<iostream> using namespace std; template <typename T> class MyClass{ private: //T::SubType* ptr_;//系统会以为SbuType是T的一个静态成员乘以ptr typename T::SubType* ptr_; }; class Test{ public: typedef int SubType; }; int main(int argc, char* argv[]){ MyClass<Test> mc; return 0; } <file_sep>/8.01.02.cpp /** * @file 8.01.02.cpp * @brief const对象 * @author LiWenGang * @date 2016-08-01 */ #include<iostream> using std::cout; using std::endl; class Test{ public: Test(int x); int GetX(); int GetX() const; private: int m_x; }; int main(int argc, char* argv[]){ const Test obj1(10); cout<<obj1.GetX()<<endl; Test obj2(20); cout<<obj2.GetX()<<endl; return 0; } Test::Test(int x):m_x(x){ m_x=x; } int Test::GetX(){ cout<<"Getx() | "; return m_x; } int Test::GetX() const{ cout<<"Getx() const | "; return m_x; } /* * const对象不能调用非const成员函数 */ <file_sep>/10.05.07.cpp /** * @file 10.05.07.cpp * @brief 变序性算法|rotate;排序算法|sort * @author LiWenGang * @date 2016-10-05 */ #include<iostream> #include<algorithm> using namespace std; void print_element(int n); bool my_greater(int a, int b); int main(int argc, char* argv[]){ int a[]={1,3,2,3,4,5}; vector<int> v(a,a+6); for_each(v.begin(),v.end(),print_element); cout<<endl; rotate(v.begin(),v.begin()+2,v.end()); for_each(v.begin(),v.end(),print_element); cout<<endl; sort(v.begin(),v.end()); for_each(v.begin(),v.end(),print_element); cout<<endl; sort(v.begin(),v.end(),my_greater); for_each(v.begin(),v.end(),print_element); cout<<endl; return 0; } void print_element(int n){ cout<<n<<" "; } bool my_greater(int a, int b){ return a>b; } <file_sep>/8.01.01.cpp /** * @file 8.01.01.cpp * @brief 单例模式 * @author LiWenGang * @date 2016-08-01 */ #include<iostream> using std::cout; using std::endl; //C++11标准 拷贝控制的实现 class Singleton{ public: Singleton(); ~Singleton(); Singleton(const Singleton& obj)=delete; Singleton& operator= (const Singleton& obj)=delete; static Singleton* GetInstance(); private: static Singleton* m_instance; }; /* class Singleton{ public: static Singleton* GetInstance(); ~Singleton(); private: Singleton(const Singleton& obj); //将拷贝构造函数声明为私有,可以有效防止对象的拷贝 Singleton& operator= (const Singleton& obj); //将等号运算符重载声明为私有,可以防止对象的拷贝 Singleton(); static Singleton* m_instance; }; */ Singleton* Singleton::m_instance; int main(int argc, char* argv[]){ Singleton* p1=Singleton::GetInstance(); Singleton* p2=Singleton::GetInstance(); cout<<(void*)p1<<endl; cout<<(void*)p2<<endl; /*禁止拷贝*/ //Singleton p3(*p1); //Singleton p4=*p2; return 0; } /** * @brief GetInstance() * * @return instance地址 * * @note * @see */ Singleton* Singleton::GetInstance(){ /* if(m_instance==NULL){ m_instance=new Singleton; } return m_instance; */ static Singleton instance; //为了保证一个类只有一个实例,必须采用static类型; return &instance; //这样实现的单例模式并不是线程安全的。 } Singleton::Singleton(){ cout<<"constructor function"<<endl; } Singleton::~Singleton(){ cout<<"destructor function"<<endl; } /* * 单例模式: * 保证一个类只有一个实例,并提供一个全局访问点 * 禁止拷贝 */ <file_sep>/10.05.04.cpp /** * @file 10.05.04.cpp * @brief 变动性算法|transform * @author LiWenGang * @date 2016-10-05 */ #include<iostream> #include<algorithm> #include<vector> #include<list> using namespace std; int fun(int a); int fun2(int a, int b); void print_element(int cnt); int main(int argc, char* argv[]){ int a[]={1,2,3,4,5}; vector<int> v(a,a+5); list<int> lst(5); list<int> str(2); transform(v.begin(),v.end(),lst.begin(),fun); for_each(lst.begin(),lst.end(),print_element); cout<<endl; transform(v.begin(),v.begin()+1,v.end()-2,str.begin(),fun2); for_each(str.begin(),str.end(),print_element); cout<<endl; return 0; } void print_element(int cnt){ cout<<cnt<<" "; } int fun(int a){ return 2*a; } int fun2(int a, int b){ return a+b; } <file_sep>/10.01.01.cpp /** * @file 10.01.01.cpp * @brief 含有string类型的文件写入 * @author LiWenGang * @date 2016-10-01 */ #include<iostream> #include<string> #include<fstream> using namespace std; struct Test{ int a; string b; string c; }; int main(int argc,char* argv[]){ Test t1; t1.a=1; t1.b="aaaaaaaaaabbbbbbbbcccccccccdddddddd"; t1.c="eeeeeeeeeeffffffffggggggggghhhhhhhh"; /* //采用这种方式的写入是有问题的,因为每次只能写入结构体大小的字符,如果存入太多字符,会导致程序运行时错误 ofstream fout("test.txt",ofstream::out|ofstream::binary); fout.write(reinterpret_cast<char*>(&t1),sizeof(Test)); fout.close(); */ //写入文件的内容 ofstream fout("test.txt",ofstream::out|ofstream::binary); fout.write((char*)&t1,sizeof(t1)); fout.write(t1.b.data(),t1.b.length()); fout.write(t1.c.data(),t1.c.length()); fout.close(); Test t2; ifstream fin("test.txt",ifstream::in|ifstream::binary); fin.read(reinterpret_cast<char*>(&t2),sizeof(Test)); cout<<t2.a<<" "<<t2.b<<" "<<t2.c<<endl; fin.close(); return 0; } <file_sep>/9.28.01.cpp /** * @file 9.28.01.cpp * @brief 内存泄露检测 * @author LiWenGang * @date 2016-09-28 */ #include<iostream> #include"debug_new.h" int main(int argc, char* argv[]){ int *p=new int; //delete p; int *q=new int[20]; delete[] q; return 0; } /* * g++ 9.28.01.cpp debug_new.cpp -o a.out -Wall -std=c++11 */ /* * 检测内存泄露: * 自己实现malloc,再里面进行跟踪 * 第三方工具: * Linux:valgrind,dmalloc,efence * windows:visual leak detector * 自己实现内存工具: * 自己重载operator new 和 operator delete 实现追踪 */ <file_sep>/8.02.01.cpp /** * @file 8.02.01.cpp * @brief friend|友元函数 * @author LiWenGang * @date 2016-08-02 */ #include<iostream> #include<cmath> using std::cout; using std::endl; class objection{ friend double Distance(const objection& obj1, const objection& obj2); public: objection(int x, int y); ~objection(); private: int m_x; int m_y; }; int main(int argc, char* argv[]){ objection obj1(3,4); objection obj2(6,8); cout<<Distance(obj1,obj2)<<endl; return 0; } objection::objection(int x, int y):m_x(x),m_y(y){ cout<<"construction"<<endl; } objection::~objection(){ cout<<"destructor"<<endl; } double Distance(const objection& obj1, const objection& obj2){ int dx=obj1.m_x-obj2.m_x; int dy=obj1.m_y-obj2.m_y; return sqrt(dx*dx+dy*dy); } /* * 友元是一种允许非类成员函数访问类的非公有成员的一种机制 * 可以把一个函数定义为类的友元(友元函数),也可以把整个类指定为另一个类的友元(友元类) * 友元在类作用域外定义,但它需要在类体中进行说明 * 友元函数不受类中的访问权限关键字限制,可以把它放在类的公有、私有、保护部分,结果一样 */ <file_sep>/10.06.05.cpp /** * @file 10.06.05.cpp * @brief 函数适配器 * @author LiWenGang * @date 2016-10-06 */ #include<iostream> #include<algorithm> #include<functional> #include<vector> using namespace std; //统计奇数元素的个数 bool IsOdd(int cnt); bool check(int num); int main(int argc, char* argv[]){ int a[]={1,2,3,4,5}; vector<int> v(a,a+5); cout<<count_if(v.begin(),v.end(),IsOdd)<<endl; //统计奇数元素的个数 //bind2nd将二元函数对象modulus转换为一元函数对象 //bind2nd(op,value)(param)相当于op(param,value) cout<<count_if(v.begin(),v.end(),bind2nd(modulus<int>(),2))<<endl; //统计大于2的元素个数 //bind1st(op,value)(param)相当于op(value,param) cout<<count_if(v.begin(),v.end(),bind1st(less<int>(),2))<<endl; //同于大于3的元素个数 vector<int>::iterator it; it=find_if(v.begin(),v.end(),not1(ptr_fun(check))); if(it!=v.end()){ cout<<*it<<endl; } return 0; } bool IsOdd(int cnt){ return cnt%2==1; } bool check(int num){ return num<3; } /* * * 函数适配器用于特化和扩展一元和二元函数对象,可以分为如下两类 * - 绑定器:将一个操作数绑定到给定值而将二元函数对象转换为一元函数对象 * bind1st, bind2nd * - 求反器:将谓词函数对象的真值求反 * not1, not2 */ <file_sep>/10.05.05.cpp /** * @file 10.05.05.cpp * @brief 变动性算法|replace,replace_copy,replace_copy_if * @author LiWenGang * @date 2016-10-05 */ #include<iostream> #include<algorithm> #include<vector> #include<list> using namespace std; void print_element(int cnt); bool fun(int a); int main(int argc, char* argv[]){ int a[]={1,2,3,4,5}; vector<int> v(a,a+5); //将值为3的元素替换为13 replace(v.begin(),v.end(),3,13); for_each(v.begin(),v.end(),print_element); cout<<endl; //拷贝的过程执行替换,原空间的元素不会发生变化 list<int> lst(5); replace_copy(v.begin(),v.end(),lst.begin(),13,3); for_each(v.begin(),v.end(),print_element); cout<<endl; for_each(lst.begin(),lst.end(),print_element); cout<<endl; //将lst中小于10的元素替换为0 replace_copy_if(v.begin(),v.end(),lst.begin(),fun,0); for_each(lst.begin(),lst.end(),print_element); cout<<endl; return 0; } void print_element(int cnt){ cout<<cnt<<" "; } bool fun(int a){ return a<10; } <file_sep>/10.03.02.cpp /** * @file 10.03.02.cpp * @brief 使用模板实现栈 * @author LiWenGang * @date 2016-10-03 */ #include<iostream> #include<stdexcept> template<typename T> class Stack{ public: explicit Stack(int maxSize); ~Stack(); void Push(const T& elem); void Pop(); T& Top(); const T& Top() const; bool Empty() const; private: T* elems_; int maxSize_; int top_; }; template<typename T> Stack<T>::Stack(int maxSize):maxSize_(maxSize),top_(-1){ elems_=new T[maxSize_]; } template<typename T> Stack<T>::~Stack(){ delete[] elems_; } template<typename T> void Stack<T>::Push(const T& elem){ if(top_+1>=maxSize_){ throw std::out_of_range("Stack<>::Push() stack full"); } elems_[++top_]=elem; } template<typename T> void Stack<T>::Pop(){ if(top_+1==0){ throw std::out_of_range("Stack<>::Push() stack empty"); } --top_; } template<typename T> T& Stack<T>::Top(){ if(top_+1==0){ throw std::out_of_range("Stack<>::Push() stack empty"); } return elems_[top_]; } template <typename T> bool Stack<T>::Empty() const{ return top_+1==0; } int main(int argc,char* argv[]){ Stack<int> s(10); s.Push(1); s.Push(2); s.Push(3); while(!s.Empty()){ std::cout<<s.Top()<<std::endl; s.Pop(); } return 0; } <file_sep>/8.02.06.cpp /** * @file 8.02.06.cpp * @brief 后置++运算符重载 * @author LiWenGang * @date 2016-08-02 */ #include<iostream> using std::cout; using std::endl; class Integer{ //friend Integer operator++ (Integer& obj, int tmp); //友元函数的方式重载++ public: Integer(int num); ~Integer(); Integer operator++ (int tmp); ////成员函数的方式重载++ void Dispay(); private: int m_num; }; int main(int argc, char* argv[]){ Integer obj(10); Integer t=obj++; obj.Dispay(); t.Dispay(); return 0; } Integer::Integer(int num):m_num(num){ cout<<"constructor"<<endl; } Integer::~Integer(){ cout<<"destructor"<<endl; } //成员函数的方式重载++ Integer Integer::operator++ (int tmp){ Integer temp(m_num); m_num++; return temp; } /* //友元函数的方式重载++ Integer operator++ (Integer& obj ,int tmp){ Integer temp(obj.m_num); obj.m_num++; return temp; } */ void Integer::Dispay(){ cout<<m_num<<endl; } <file_sep>/8.02.04.cpp /** * @file 8.02.04.cpp * @brief 运算符重载|非成员函数(友元函数)重载 * @author LiWenGang * @date 2016-08-02 */ #include<iostream> using std::cout; using std::endl; class ComPlex{ public: ComPlex(int a, int b); ~ComPlex(); friend ComPlex operator+ (const ComPlex& c1,const ComPlex& c2); void Display() const; private: int m_a; int m_b; }; int main(int argc, char* argv[]){ ComPlex c1(1,2); ComPlex c2(3,4); ComPlex c3=c1+c2; c3.Display(); return 0; } ComPlex::ComPlex(int a, int b):m_a(a),m_b(b){ cout<<"constructor function"<<endl; } ComPlex::~ComPlex(){ cout<<"destructor function"<<endl; } ComPlex operator+ (const ComPlex& c1, const ComPlex& c2){ int a=c1.m_a+c2.m_a; int b=c1.m_a+c2.m_b; return ComPlex(a,b); } void ComPlex::Display() const{ cout<<m_a<<"+"<<m_b<<"i"<<endl; } /* * 运算符被重载后,其优先级和结合性不会发生改变 * 一般情况下,单目运算符最好重载为类的成员函数;双目运算符最好重载为类的友元函数 * 以下的双目运算符不能重载为类的友元函数: * = () [] -> * 类型转换运算符只能以成员函数方式重载 * 流运算符只能以友元的方式重载 */ <file_sep>/7.25.03.cpp /** * @file 7.25.03.cpp * @brief 作用域 * @author LiWenGang * @date 2016-07-25 */ #include<iostream> using namespace std; int add(int x, int y); //函数原型作用域 int main(int argc, char* argv[]){ int num=30; //块作用域 { int num=30; //块作用域 } add(3,4); return 0; } int add(int x, int y){ //块作用域 return x+y; } /* * 作用域: * 文件作用域 * 块作用域:一般以"{}"为界限 * 函数原型作用域:函数声明部分的变量 * 函数作用域:一般仅对于goto语句而言的 * 类作用域 */ <file_sep>/9.10.01.cpp /** * @file 9.10.01.cpp * @brief String | 8.03.01.cpp * @author LiWenGang * @date 2016-09-10 */ #include<iostream> #include<cstring> using std::cin; using std::cout; using std::endl; using std::ostream; using std::istream; class String{ friend ostream& operator<< (ostream& os, const String& obj); friend istream& operator>> (istream& os, String& obj); public: String(){}; String(const char* str); String(const String& obj); String operator+ (const String& obj); String& operator= (const String& obj); String& operator+= (const String& obj); bool operator== (const String &obj); bool operator! () const; char& operator[] (const unsigned int index); const char& operator[] (const unsigned int index) const; ~String(); void Display(); private: char* str_; }; int main(int argc, char* argv[]){ String s1("string s1"); s1.Display(); String s2(s1); s2.Display(); String s3="string s3"; s3.Display(); String s4=s1; s4.Display(); String s5="string s5"; s5+=" s5"; s5.Display(); String s6=s1+s5; s6.Display(); cout<<s6<<endl; String s7; cin>>s7; cout<<s7<<endl; String s8("string s8"); s1==s3?cout<<"equal"<<endl:cout<<"no equal"<<endl; cout<<s8[2]<<endl; return 0; } String::String(const char* str){ //cout<<"String::String(const char* str)"<<endl; int len=strlen(str)+1; str_=new char[len]; memset(str_,0,len); strcpy(str_,str); } String::String(const String& obj){ //cout<<"String::String(const String& obj)"<<endl; int len=strlen(obj.str_)+1; str_=new char[len]; memset(str_,0,len); strcpy(str_,obj.str_); } String String::operator+(const String& obj){ //cout<<"String String::operator+(const String& obj)"<<endl; int len=strlen(str_)+strlen(obj.str_)+1; char* newstr=new char[len]; memset(newstr,0,len); strcpy(newstr,str_); strcat(newstr,obj.str_); return newstr; } String& String::operator= (const String& obj){ //cout<<"String& String::operator= (const String& obj)"<<endl; int len=strlen(obj.str_)+1; str_=new char[len]; memset(str_,0,len); strcpy(str_,obj.str_); return *this; } String& String::operator+= (const String& obj){ //cout<<" String& String::operator+= (const String& obj)"<<endl; int len=strlen(str_)+strlen(obj.str_)+1; char* newstr=new char[len]; memset(newstr,0,len); strcpy(newstr,str_); strcat(newstr,obj.str_); delete[] str_; str_=newstr; return *this; } ostream& operator<< (ostream& os, const String& obj){ //cout<<"ostream& operator<< (ostream& os, const String& obj)"<<endl; os<<obj.str_; return os; } istream& operator>> (istream& is, String& obj){ //cout<<"istream& operator>> (istream& is, String& obj)"<<endl; char tmp[1024]; is>>tmp; obj=tmp; return is; } bool String::operator== (const String& obj){ //cout<<"bool String::operator== (const String& obj)"<<endl; if(strlen(str_)!=strlen(obj.str_)){ return false; } return strcmp(str_,obj.str_)==0?true:false; } bool String::operator! () const{ return strlen(str_)!=0; } char& String::operator[] (const unsigned int index){ return str_[index]; } const char& String::operator[] (const unsigned int index) const{ return str_[index]; } String::~String(){ delete[] str_; } void String::Display(){ cout<<str_<<endl; } <file_sep>/7.26.01.cpp /** * @file 7.26.01.cpp * @brief 构造函数,析构函数 * @author LiWenGang * @date 2016-07-26 */ #include<iostream> using namespace std; class Test{ public: /* * 如果没有显式的编写构造函数,系统会默认的添加不带参数的构造函数; * 如果显示的编写了构造函数,系统将不会添加默认构造函数 * 构造函数同样可以使用重载操作 */ Test(); Test(int num); /* * 析构函数不能被重载 * 如果没有定义析构函数,编译器会自动生成一个默认析构函数 */ ~Test(); void Display(); private: int m_num; }; int main(int argc, char* argv[]){ Test t1; t1.Display(); Test t2(10); t2.Display(); Test* t3=new Test(20); t3->Display(); delete t3; return 0; } Test::Test(){ m_num=0; } Test::Test(int num){ m_num=num; } Test::~Test(){ cout<<"Destroy "<<m_num<<endl; } void Test::Display(){ cout<<"num="<<m_num<<endl; } /* 构造函数: * * 构造函数是特殊的成员函数 * 创建类类型的新对象,系统自动会调用构造函数 * 构造函数是为了保证对象的每个数据成员都被正确初始化 * * 构造函数可以有任意类型和任意个数的参数,一个类可以有多个构造函数(重载) * 不带参数的构造函数(默认构造函数) */ /* * 析构函数: * * 没有返回类型 * 没有参数 * 默认析构函数是一个空函数。 */ <file_sep>/7.24.02.cpp /** * @file 7.24.02.cpp * @brief 结构体内存对齐 * @author LiWenGang * @date 2016-07-24 */ #include<iostream> using namespace std; #pragma pack(4) struct test{ char a; double b; }test_t; #pragma pack() int main(int argc, char* argv[]){ cout<<sizeof(test_t)<<endl; char* p; p=(char*)&test_t; cout<<(void*)p<<endl; p=&test_t.a; cout<<(void*)p<<endl; return 0; } /* * 结构体内存对齐 * 结构体的第一个成员与结构体变量的偏移量为0 * 其他成员需要对齐到某个数字(对齐数)的整数倍地址 * 对齐数取编译器预设的一个对齐整数与该成员大小的较小值 * 可以使用#pragma pack()来设置对齐数 * * 结构体总大小为对齐数的整数倍 */ <file_sep>/8.02.02.cpp /** * @file 8.02.02.cpp * @brief friend|友元类 * @author LiWenGang * @date 2016-08-02 */ #include<iostream> using std::cout; using std::endl; class Televersion{ friend class TeleControl; public: Televersion(int volume, int channel); ~Televersion(); private: int m_volume; int m_channel; }; class TeleControl{ public: int VolumeUP(Televersion&); int VolumeDown(Televersion&); int ChannelUP(Televersion&); int ChannelDown(Televersion&); }; int main(int argc, char* argv[]){ Televersion tv(3,4); TeleControl tc; cout<<tc.VolumeUP(tv)<<endl; cout<<tc.ChannelUP(tv)<<endl; return 0; } Televersion::Televersion(int volume, int channel):m_volume(volume),m_channel(channel){ cout<<"constructor funtion"<<endl; } Televersion::~Televersion(){ cout<<"destructor function"<<endl; } int TeleControl::VolumeUP(Televersion& tv){ return ++tv.m_volume; } int TeleControl::VolumeDown(Televersion& tv){ return --tv.m_volume; } int TeleControl::ChannelUP(Televersion& tv){ return ++tv.m_channel; } int TeleControl::ChannelDown(Televersion& tv){ return --tv.m_channel; } /* * 友元关系是单项的 * 友元关系不能被传递 * 友元关系不能被继承 */ <file_sep>/7.24.01.cpp #include<iostream> using namespace std; int main(int argc, char* argv[]){ const int a=100; //const int a; //Error,常量必须初始化 //a=200; //Error,常量不能重新被赋值 cout<<a<<endl; int b=22; const int *p; //const在*的左边,表示*p为常量,经由*p不能更改指针所指向的内容 p=&b; //const int *p=&b; //与上面的用法一致 //*p=200 //Error,常量不能重新被赋值 cout<<*p<<endl; int c=200; int * const q=&c; //const在*的右边,表示q是一个常量 //q=&b; //Error,常量不能重新被赋值 cout<<*q<<endl; return 0; } /* * const int *p // *p是一个常量,*p不能被修改;但是p可以被修改 * int* const p // p是一个常量,p不能被修改;但是*p可以被修改 */ /* * const定义的常量与#define定义的符号常量的区别: * 1. const定义的常量有类型,而#define定义的没有类型,编译可以对前者进行类型安全检查,而后者仅仅只是做简单替换 * 2. const定义的常量在编译时分配内存,而#define定义的常量是在预编译时进行替换,不分配内存。 * 3. 作用域不同,const定义的常变量的作用域为该变量的作用域范围。而#define定义的常量作用域为它的定义点到程序结束,当然也可以在某个地方用#undef取消 */ <file_sep>/9.30.03.cpp /** * @file 9.30.03.cpp * @brief istream,ostream * @author LiWenGang * @date 2016-09-30 */ #include<iostream> using namespace std; int main(int argc, char* argv[]){ /* int n1=100; int n2=200; cout<<n1<<" "<<n2<<endl; cout.put('H'); cout.put('i'); cout.put(' '); cout.put('H').put('i').put('\n'); char buf[]="test!--!"; cout.write(buf,5); cout.put('\n'); */ //---------------------------------------------- /* int n; char ch; cin>>n>>ch; cout<<"n="<<n<<" "<<"ch="<<ch<<endl; */ /* int n=cin.get();//获取一个字符,并返回ASCII字符 cout<<n<<endl; */ /* char ch1; char ch2; cin.get(ch1).get(ch2); cout<<ch1<<" "<<ch2<<endl; */ /* char buf[10]={0}; cin>>buf; //不接收换行符,遇到空格会停止 //cin.getline(buf,9); //不接收换行符,遇到空格并不停止 cout<<buf<<endl; */ /* char buf[10]; cin.read(buf,5); //读取满五个字节停止,无论空格还是换行,均会接收 cout<<buf<<endl; */ char c[10],c2,c3; c2=cin.get(); c3=cin.get(); cin.putback(c2); //将一个字符重新放入输入流中,比如输入123456789,此时c2=1,c3=2,剩余的流中会剩余“3456789”,执行此条语句后,又会将c2重新放入流中,最后流中会剩余13456789 cin.getline(&c[0],9); cout<<c<<endl; //---------------------------------------------- return 0; } <file_sep>/8.04.03.cpp /** * @file 8.04.03.cpp * @brief string|成员函数 * @author LiWenGang * @date 2016-08-04 */ #include<iostream> #include<string> using namespace std; int main(int argc, char* argv[]){ string s1="abc"; cout<<s1<<endl; s1[1]='B'; cout<<s1<<endl; string s2=s1+"def"+"ghi"; //前面两个必须有一个是对象 cout<<s2<<endl; s1==s2?cout<<"Same"<<endl:cout<<"diffrence"<<endl; return 0; } <file_sep>/10.05.02.cpp /** * @file 10.05.02.cpp * @brief 非变动性算法|for_each,min_element,max_element,find_if * @author LiWenGang * @date 2016-10-05 */ #include<iostream> #include<algorithm> #include<vector> using namespace std; void print_element(int cnt); bool greater_than_3(int cnt); int main(int argc, char* argv[]){ int a[]={1,2,3,4,5}; vector<int> v(a,a+5); vector<int>::iterator it; for(it=v.begin();it!=v.end();++it){ cout<<*it<<" "; } cout<<endl; for_each(v.begin(),v.end(),print_element); cout<<endl; it=min_element(v.begin(),v.end()); cout<<"the minnest number:"<<*it<<endl; it=max_element(v.begin(),v.end()); cout<<"the maxest number:"<<*it<<endl; it=find(v.begin(),v.end(),3); if(it!=v.end()){ cout<<"the position is "<<it-v.begin()<<endl; }else{ cout<<"Not find the number"<<endl; } it=find_if(v.begin(),v.end(),greater_than_3); if(it!=v.end()){ cout<<it-v.begin()<<endl; }else{ cout<<"not find"<<endl; } return 0; } void print_element(int cnt){ cout<<cnt<<" "; } bool greater_than_3(int cnt){ return cnt>3; } /* * 容器中的区间一般都是半闭半开区间,即左边是闭区间,右边是开区间 */ <file_sep>/7.24.07.cpp /** * @file 7.24.07.cpp * @brief 引用|const 引用 * @author LiWenGang * @date 2016-07-24 */ #include<iostream> using namespace std; int main(int argc, char* argv[]){ int val=100; cout<<val<<endl; int &refval=val; refval=200; cout<<val<<endl; const int num=1024; const int& renum=num; cout<<renum<<endl; //int &ref=num; Error, const int &ref=val; //const 引用可以指向一个非const类型 cout<<ref<<endl; return 0; } /* * 引用不是变量 * 引用仅仅只是变量的别名 * 引用没有自己独立的空间 * 对引用所做的改变本质上是对他所引用的变量的改变 * 引用在定义的使用必须初始化 * 引用一经初始化,不能重新指向其他变量 */ <file_sep>/8.08.03.cpp /** * @file 8.08.03.cpp * @brief 虚函数及其内存模型 * @author LiWenGang * @date 2016-08-08 */ #include<iostream> using namespace std; class Base{ public: virtual void Fun1(); virtual void Fun2(); int data1_; }; class Derived:public Base{ public: void Fun2(); virtual void Fun3(); int data2_; }; typedef void (*FUNC)(); int main(int argc, char* argv[]){ cout<<sizeof(Base)<<endl; cout<<sizeof(Derived)<<endl; //----------------------------------------- long** p; FUNC fun; Base b; p=(long**)&b; fun=(FUNC)p[0][0]; fun(); fun=(FUNC)p[0][1]; fun(); //----------------------------------------- Derived d; p=(long**)&d; fun=(FUNC)p[0][0]; fun(); fun=(FUNC)p[0][1]; fun(); fun=(FUNC)p[0][2]; fun(); //----------------------------------------- Base* pp=&d; pp->Fun2(); return 0; } void Base::Fun1(){ cout<<"Base::Fun1()"<<endl; } void Base::Fun2(){ cout<<"Base::Fun2()"<<endl; } void Derived::Fun2(){ cout<<"Derived::Fun2()"<<endl; } void Derived::Fun3(){ cout<<"Derived::Fun3()"<<endl; } /* * vptr:虚表指针 * vbtl:虚基类表 * Base vbtl * -> ------ ------------- * | vptr |->| Base::Fun1 | * ------ ------------ * |data1_| | Base::Fun2 | * ------ ------------ * * Base vbtl * -> ------ --------------- * | vptr |->| Base::Fun1 | * ------ --------------- * |data1_| | Derived::Fun2 | * ------ --------------- * |data2_| | Derived::Fun3 | * ------ --------------- */ <file_sep>/7.24.05.cpp /** * @file 7.24.05.cpp * @brief 函数重载 * @author LiWenGang * @date 2016-07-24 */ #include<iostream> using namespace std; void fun(int, int); void fun(double, double); int main(int argc, char* argv[]){ fun(3,4); fun(3.0,4.0); return 0; } void fun(int x, int y){ cout<<x+y<<endl; } void fun(double x, double y){ cout<<x+y<<endl; } /* * 相同的作用域,如果两个函数名称相同,而参数不同,我们把它们称为重载overload * 函数重载又称为函数的多态性(静态多态性) */ <file_sep>/7.26.06.cpp /** * @file 7.26.06.cpp * @brief 初始化成员列表|const成员初始化,引用成员初始化,无默认构造函数的对象成员初始化 * @author LiWenGang * @date 2016-07-26 */ #include<iostream> using namespace std; class Object{ public: Object(int num); ~Object(); void Display(); private: int m_num_1; const int m_num; int& m_num_2; }; int main(int argc, char* argv[]){ Object obj(10); obj.Display(); return 0; } Object::Object(int num=0):m_num_1(num),m_num(num),m_num_2(num){ cout<<"Object"<<endl; } Object::~Object(){ cout<<"~Object"<<endl; } void Object::Display(){ cout<<"int m_num_1="<<m_num_1<<endl; cout<<"const int m_num="<<m_num<<endl; cout<<"int& m_num_2="<<m_num_2<<endl; } /* * const 成员的初始化只能在构造函数初始化成员列表中完成; * 引用成员的初始化只能在构造函数初始化成员列表中完成; * 对象成员(对象所对应的类没有默认构造函数),对象成员的初始化也只能在构造函数初始化成员列表中完成; */ <file_sep>/10.06.01.cpp /** * @file 10.06.01.cpp * @brief 变序算法|next_permutation * @author LiWenGang * @date 2016-10-06 */ #include<iostream> #include<algorithm> #include<vector> using namespace std; void print_element(int cnt); int main(int argc, char* argv[]){ int a[]={1,2,3,4}; vector<int> v(a,a+4); for_each(v.begin(),v.end(),print_element); cout<<endl; //打印1,2,3,4的全排列 while(next_permutation(v.begin(),v.end())){ for_each(v.begin(),v.end(),print_element); cout<<endl; } return 0; } void print_element(int cnt){ cout<<cnt<<" "; } <file_sep>/7.25.02.cpp /** * @file 7.25.02.cpp * @brief 内联成员函数,成员函数的重载 * @author LiWenGang * @date 2016-07-25 */ #include<iostream> using namespace std; class Test{ public: int add(int a, int b); //成员函数的重载 void Init(); void Init(int x); void Init(int x, int y); void Init(int x, int y, int z); void Display(); private: int m_x; int m_y; int m_z; }; int main(int argc, char* argv[]){ Test ch; cout<<ch.add(3,4)<<endl; Test t; t.Init(); t.Display(); t.Init(3); t.Display(); t.Init(3,4); t.Display(); t.Init(3,4,5); t.Display(); return 0; } inline int Test::add(int a, int b){ return a+b; } void Test::Init(){ m_x=0; m_y=0; m_z=0; } void Test::Init(int x){ m_x=x; m_y=0; m_z=0; } void Test::Init(int x, int y){ m_x=x; m_y=y; m_z=0; } void Test::Init(int x, int y, int z){ m_x=x; m_y=y; m_z=z; } void Test::Display(){ cout<<"x="<<m_x<<"y="<<m_y<<"z="<<m_z<<endl; } /* inline函数的实现方式 * 1.在类中直接实现成员函数 * 2.在实现成员函数的时候,显式的使用inline注明成员函数 */ <file_sep>/9.11.01.cpp /** * @file 9.11.01.cpp * @brief 统计单词出现的次数,但是不统计exclude中包括的常见单词 * @author LiWenGang * @date 2016-09-11 */ #include<iostream> #include<string> #include<map> #include<set> using namespace std; int main(int argc, char* argv[]){ map<string, size_t> maplist; set<string> exclude={ "the", "but", "and", "or", "an", "a" }; string word; while(cin>>word){ if(exclude.find(word)==exclude.end()) ++maplist[word]; } for(const auto& w:maplist){ cout<<w.first<<" occurs "<<w.second<<" times "<<endl; } return 0; } <file_sep>/10.05.06.cpp /** * @file 10.05.06.cpp * @brief 移除性算法|remove * @author LiWenGang * @date 2016-10-05 */ #include<iostream> #include<algorithm> using namespace std; void print_element(int n); int main(int argc, char* argv[]){ int a[]={1,3,2,3,4,5}; vector<int> v(a,a+6); for_each(v.begin(),v.end(),print_element); cout<<endl; //remove并不做物理删除,仅从逻辑上删除;要想实现物理删除可以配合erase使用 //remove(v.begin(),v.end(),3);//删除3 v.erase(remove(v.begin(),v.end(),3),v.end()); for_each(v.begin(),v.end(),print_element); cout<<endl; return 0; } void print_element(int n){ cout<<n<<" "; } /* * 首先查找给定值第一个位置,然后遍历后面的元素,将非移除元素拷贝到前面,覆盖前面的元素 */ <file_sep>/7.27.04.cpp /** * @file 7.27.04.cpp * @brief static * @author LiWenGang * @date 2016-07-27 */ #include<iostream> using std::cout; using std::endl; class CountedObject{ public: CountedObject(); ~CountedObject(); static int cnt; //静态成员的引用性声明,对于int和char型的,可以直接在引用性声明这里完成初始化操作,但其他类型不可以 static const int num=0; //对于static const的话,可以不需要“静态成员的定义性声明”,比较特殊 }; int CountedObject::cnt=0; //静态成员的定义性声明 int main(int argc, char* argv[]){ cout<<CountedObject::cnt<<endl; CountedObject obj1; //cout<<obj1.cnt<<"||"<<obj1.num<<endl; //使用使用(“对象.静态成员”)的方式访问静态成员,但是不建议。 //因为静态成员是属于该类的,如果采用这种方式访问的话,会导致程序可读性变差 cout<<CountedObject::cnt<<endl; CountedObject* ptr=new CountedObject; cout<<CountedObject::cnt<<endl; delete ptr; cout<<CountedObject::cnt<<endl; return 0; } CountedObject::CountedObject(){ ++cnt; } CountedObject::~CountedObject(){ --cnt; } /* * 非static数据成员存在于类类型的每个对象中,static数据成员独立该类的任意对象存在,它是与类关联的对象,不与类对象关联。即不同的对象共享同一静态数据成员 */ <file_sep>/10.01.02.cpp /** * @file 10.01.02.cpp * @brief seekg,tellg * @author LiWenGang * @date 2016-10-01 */ #include<cassert> #include<iostream> #include<fstream> using namespace std; int main(int argc,char* argv[]){ ifstream fin("test.txt"); assert(fin); char ch; fin.seekg(2); fin.get(ch); cout<<ch<<endl; fin.seekg(-2,ios::end); fin.get(ch); cout<<ch<<endl; fin.seekg(0,ios::end); streampos pos=fin.tellg(); cout<<pos<<endl; fin.close(); return 0; } /* * tellp:获取输出的文件流指针的当前位置,以字节为单位 * tellg:获取输入的文件流指针的当前位置,以字节为单位 */ /* * 目前存在的问题,seekg中定位到的位置,本来-1应该是最后一个字符,但是经过验证-2才会定位到最后一个字节,也就是说在写入的字节后面会多出两个不可见的字符。 */ <file_sep>/7.26.03.cpp /** * @file 7.26.03.cpp * @brief 转换构造函数,explicit * @author LiWenGang * @date 2016-07-26 */ #include<iostream> using namespace std; class Test{ public: Test(); //explicit Test(int num); Test(int num); ~Test(); private: int m_num; }; int main(int argc, char* argv[]){ Test t(10); t=20; /* * 将20这个整数赋值给t对象 * 1. 调用转换构造函数将20这个整数转化成类类型(生成一个临时对象) * 2. 将临时对象赋值给t对象,调用的是“=”运算符 * 3. 赋值成功之后,会迅速将该临时对象销毁,即调用一次析构函数 */ Test s=30; // 等价于Test(30),这里的“=”并不是运算符, s=40; //赋值操作 return 0; } Test::Test(){ m_num=10; cout<<"Initializing default"<<endl; } Test::Test(int num){ m_num=num; cout<<"Initializing "<<m_num<<endl; } Test::~Test(){ cout<<"Destroy "<<m_num<<endl; } /* * explicit: * 编译器不会把声明为explicit的构造函数用于隐式转化,它只能在程序代码中显式创建对象 */ <file_sep>/10.05.01.cpp /** * @file 10.05.01.cpp * @brief 迭代器|vector,list * @author LiWenGang * @date 2016-10-05 */ #include<iostream> #include<vector> #include<list> using namespace std; int main(int argc, char* argv[]){ vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); //迭代器 vector<int>::iterator it; for(it=v.begin();it!=v.end();++it){ cout<<*it<<" "; } cout<<endl; //反向迭代器 vector<int>::reverse_iterator ti; for(ti=v.rbegin();ti!=v.rend();++ti){ cout<<*ti<<" "; } cout<<endl; //-------------------------------------------------- list<int> lst; lst.push_back(5); lst.push_back(6); lst.push_back(7); list<int>::iterator it2; for(it2=lst.begin();it2!=lst.end();++it2){ cout<<*it2<<" "; } cout<<endl; return 0; } /* * 每种容器都实现了自己的迭代器; * 有些容器还实现了仅属于自己的迭代器 */ <file_sep>/8.07.01.cpp /** * @file 8.07.01.cpp * @brief 虚继承|虚基类 * @author LiWenGang * @date 2016-08-07 */ #include<iostream> using namespace std; class Furniture{ public: Furniture(int weight); ~Furniture(); int weight_; }; class Bed:virtual public Furniture{ public: Bed(int weight); ~Bed(); void Sleep(); int weight_; }; class Sofa:virtual public Furniture{ public: Sofa(int weight); ~Sofa(); void Watch(); int weight_; }; class SofaBed:public Bed, public Sofa{ public: SofaBed(int weight); ~SofaBed(); void FoldIn(); void FoldOut(); int weight_; }; int main(int argc, char* argv[]){ SofaBed sf(10); sf.Watch(); sf.Sleep(); return 0; } void Bed::Sleep(){ cout<<"Sleeping.."<<endl; } void Sofa::Watch(){ cout<<"Watching.."<<endl; } void SofaBed::FoldIn(){ cout<<"FoldIn.."<<endl; } void SofaBed::FoldOut(){ cout<<"FoldOut.."<<endl; } Furniture::Furniture(int weight):weight_(weight){ cout<<"Furniture()"<<endl; } SofaBed::SofaBed(int weight):Bed(weight),Sofa(weight),Furniture(weight){ cout<<"SofaBed()"<<endl; FoldIn(); } Bed::Bed(int weight):Furniture(weight){ cout<<"Bed()"<<endl; } Sofa::Sofa(int weight):Furniture(weight){ cout<<"Sofa()"<<endl; } Furniture::~Furniture(){ cout<<"~Furniture()"<<endl; } Sofa::~Sofa(){ cout<<"~Sofa()"<<endl; } Bed::~Bed(){ cout<<"~Bed()"<<endl; } SofaBed::~SofaBed(){ cout<<"~SofaBed()"<<endl; } /* * 虚基类用于拥有共同基类的场合 * 主要用来解决多继承时可能发生的同一基类继承多次而产生的二义性问题; * 为最远的派生类提供唯一的基类成员,而不重复产生多次拷贝; * 钻石继承体系 * * 虚基类的成员是由最远派生类的构造函数通过调用虚基类的构造函数进行初始化的; * 在整个继承结构中,直接或间接继承虚基类的所有派生类,都必须在构造函数的成员初始化列表中给出对虚基类的构造函数的调用。如果为列出,则表示调用该虚基类的默认构造函数; * 在建立对象时,只有最远派生类的构造函数调用虚基类的构造函数,该派生类的其他基类对虚基类构造函数的调用被忽略。 */ <file_sep>/10.05.03.cpp /** * @file 10.05.03.cpp * @brief 变动性算法|for_each,copy,copy_backward * @author LiWenGang * @date 2016-10-05 */ #include<iostream> #include<algorithm> #include<vector> #include<list> using namespace std; void print_element(int cnt); void add_3(int& n); int main(int argc, char* argv[]){ int a[]={1,2,3,4,5}; vector<int> v(a,a+5); for_each(v.begin(),v.end(),print_element); cout<<endl; for_each(v.begin(),v.end(),add_3); for(const auto& i:v){ cout<<i<<" "; } cout<<endl; list<int> lst(12); for_each(lst.begin(),lst.end(),print_element); cout<<endl; //从前往后拷贝 copy(v.begin(),v.end(),lst.begin()); for_each(lst.begin(),lst.end(),print_element); cout<<endl; //从后往前拷贝 copy_backward(v.begin(),v.end(),lst.end()); for_each(lst.begin(),lst.end(),print_element); cout<<endl; return 0; } void print_element(int cnt){ cout<<cnt<<" "; } void add_3(int& n){ n+=3; } /* * for_each是否是变动性算法,取决于第三个参数是否会修改容器里面的值 */ <file_sep>/9.30.01.cpp /** * @file 9.30.01.cpp * @brief 模拟实现智能指针 * @author LiWenGang * @date 2016-09-30 */ #include<iostream> class Node{ public: Node(); ~Node(); void Calc() const; }; class NodePtr{ public: explicit NodePtr(Node* ptr=0):ptr_(ptr){}; ~NodePtr(){ delete ptr_; }; NodePtr(NodePtr& other):ptr_(other.Release()){} Node& operator* () const{ return *Get(); } Node* operator-> () const{ return Get(); } NodePtr& operator= (NodePtr& other){ Reset(other.Release()); return* this; } Node* Get() const{ return ptr_; } Node* Release(){ Node* tmp=ptr_; ptr_=0; return tmp; } void Reset(Node* ptr=0){ if(ptr_!=ptr){ delete ptr_; } ptr_=ptr; } private: Node* ptr_; }; int main(int argc, char* argv[]){ NodePtr np(new Node); np->Calc(); NodePtr np2(np); NodePtr np3=np; return 0; } Node::Node(){ std::cout<<"Node..."<<std::endl; } Node::~Node(){ std::cout<<"~Node..."<<std::endl; } void Node::Calc() const{ std::cout<<"Node::Calc..."<<std::endl; } /* * 裸指针 * * 解决空悬指针,内存泄露,重复释放等问题 */ <file_sep>/8.08.04.cpp /** * @file 8.08.04.cpp * @brief 虚函数与对象切割|overload,overwrite,override * @author LiWenGang * @date 2016-08-08 */ #include<iostream> using namespace std; class CObject{ public: virtual void Serialize(); }; class CDocument:public CObject{ public: void func(); virtual void Serialize(); int data1_; }; class CMyDoc:public CDocument{ public: virtual void Serialize(); int data2_; }; int main(int argc, char* argv[]){ CMyDoc mydoc; CMyDoc* pmydoc=new CMyDoc; cout<<"#1 testing"<<endl; mydoc.func(); cout<<"#2 testing"<<endl; ((CDocument*)(&mydoc))->func(); cout<<"#3 testing"<<endl; pmydoc->func(); cout<<"#4 testing"<<endl; ((CDocument)mydoc).func(); //mydoc对象强制转换为CDocument对象,向上转型 //完全将派生类对象转换成了基类对象 return 0; } void::CObject::Serialize(){ cout<<"CObject::Serialize"<<endl; } void CDocument::func(){ cout<<"CDocument::func()"<<endl; Serialize(); } void CDocument::Serialize(){ cout<<"CDocument::Serialize()"<<endl; } void CMyDoc::Serialize(){ cout<<"CMyDoc::Serialize()"<<endl; } /* * 成员函数被重载的特征:overload * 相同的范围 * 函数名称相同 * 参数不相同 * virtual关键字可有可无 * 覆盖是指派生类函数覆盖基类函数,其区别如下:overwrite * 不同的范围 * 函数名字相同 * 参数相同 * 基类函数必须有virtual关键字 * 重定义(派生来与基类):override * 不同的范围(分别位于派生类与基类) * 函数名与参数都相同,无virtual关键字 * 函数名相同,参数不同,virtual可有可无 */ <file_sep>/7.24.10.cpp /** * @file 7.24.10.cpp * @brief static_cast * @author LiWenGang * @date 2016-07-24 */ #include<iostream> using namespace std; int main(int argc, char* argv[]){ int cnt=static_cast<int>(3.14); cout<<"cnt="<<cnt<<endl; void *p=&cnt; int *q=static_cast<int*>(p); cout<<"*q="<<*q<<endl; return 0; } /* * 编译器隐式执行的任何类型转换都可以由static_cast完成 * 当一个较大的算术类型赋值给较小的类型时,可以用static_cast进行强制转换。 * 可以将void*指针转换为某一类型的指针 * 可以将基类指针转换为派生类指针 * 无法将const转化为nonconst,这个只有const_cast才可以办得到 */ <file_sep>/9.30.05.cpp /** * @file 9.30.05.cpp * @brief ifstream|constexpr * @author LiWenGang * @date 2016-09-30 */ #include<cassert> #include<iostream> #include<fstream> using namespace std; int main(int argc, char* argv[]){ ifstream fin("temp.cc"); assert(fin); fin.close(); constexpr int n=5; cout<<hex<<n<<endl; int A[n]={1,2,3,4,5}; for(auto& i:A){ cout<<A[i-1]<<endl; } return 0; } /* * ofstream:以out(写)模式打开,如果文件不存在,则创建 * ifstream:以in(读)模式打开,如果文件不存在,并不会创建 */ <file_sep>/10.05.09.cpp /** * @file 10.05.09.cpp * @brief 数值算法|accumulate * @author LiWenGang * @date 2016-10-05 */ #include<iostream> #include<algorithm> #include<numeric> using namespace std; void print_element(int n); int mult(int a, int b); int main(int argc, char* argv[]){ int a[]={1,2,3,4,5}; vector<int> v(a,a+5); for_each(v.begin(),v.end(),print_element); cout<<endl; //累加 cout<<accumulate(v.begin(),v.end(),0)<<endl; //累乘 cout<<accumulate(v.begin(),v.end(),1,mult)<<endl; return 0; } void print_element(int n){ cout<<n<<" "; } int mult(int a, int b){ return a*b; } <file_sep>/10.03.07.cpp /** * @file 10.03.07.cpp * @brief 单例模式|模板实现 * @author LiWenGang * @date 2016-10-03 */ #include<iostream> #include<cstdlib> using namespace std; template<typename T> class Singleton{ public: static T& GetInstance(){ /* static T instance; return instance; */ Init(); return* instance_; } Singleton()=delete; ~Singleton()=delete; Singleton(const Singleton& other)=delete; Singleton& operator= (const Singleton& other)=delete; private: static void Init(){ if(instance_==0){ instance_=new T; atexit(Destroy); } } static void Destroy(){ delete instance_; } static T* instance_; }; template<typename T> T* Singleton<T>::instance_=0; //---------------------------------------------------------- class ApplicationImpl{ public: ApplicationImpl(){ cout<<"ApplicationImpl..."<<endl; } ~ApplicationImpl(){ cout<<"~ApplicationImpl..."<<endl; } void Run(){ cout<<"Run"<<endl; } }; //包装的类 typedef Singleton<ApplicationImpl> Application; int main(int argc,char* argv[]){ Application::GetInstance().Run(); Application::GetInstance().Run(); return 0; } /* * 目前的单例模式并不属于线程安全,即如果多个线程同时操作的话,会导致单例模式失效 */ <file_sep>/8.07.02.cpp /** * @file 8.07.02.cpp * @brief 虚继承对C++对象内存模型造成的影响 * @note 这部分个人不是很明白 * @author LiWenGang * @date 2016-08-07 */ #include<iostream> using namespace std; class BB{ public: int bb_; }; class B1:virtual public BB{ public: int b1_; }; class B2:virtual public BB{ public: int b2_; }; class DD:public B1, public B2{ public: int dd_; }; int main(int argc, char* argv[]){ cout<<sizeof(BB)<<endl; cout<<sizeof(B1)<<endl; cout<<sizeof(DD)<<endl; //---------------------------- B1 objb1; cout<<&objb1<<endl; cout<<&objb1.b1_<<endl; cout<<&objb1.bb_<<endl; int **p=(int**)&objb1; cout<<p[0][0]<<endl; cout<<p[0][1]<<endl; //---------------------------- DD objdd; cout<<&objdd<<endl; cout<<&objdd.bb_<<endl; cout<<&objdd.b1_<<endl; cout<<&objdd.b2_<<endl; cout<<&objdd.dd_<<endl; int **q=(int**)&objdd; cout<<q[0][0]<<endl; cout<<q[0][1]<<endl; cout<<q[2][0]<<endl; cout<<q[2][1]<<endl; return 0; } /* * vbptr:虚基类表指针 * vbtl:虚基类表 * B1 vbtl * -> ----- ----- * |vbptr|->| 0 | 本类地址与虚基类表指针地址的差 * |-----| ----- * B1 | b1_ | | 8 | 虚基类地址与虚基类表指针地址的差 * |-----| ----- * BB | bb_ | * ----- * * DD vbtl * -> ----- ------ * |vbptr|->| 0 | 本类地址与虚基类表指针地址的差 * B1 |-----| ------ * | b1_ | | 20 | 虚基类地址与虚基类表指针地址的差 * |-----| ------ * |vbptr|->| 0 | 本类地址与虚基类表指针地址的差 * B2 |-----| ------ * | b2_ | | 12 | 虚基类地址与虚基类表指针地址的差 * |-----| ----- * DD | dd_ | * ----- * BB | bb_ | * ----- */ <file_sep>/10.03.04.cpp /** * @file 10.03.04.cpp * @brief 使用模板实现栈|适配器 * @author LiWenGang * @date 2016-10-03 */ #include<iostream> #include<stdexcept> #include<deque> using namespace std; template<typename T, typename CONT=deque<T>> class Stack{ public: Stack():elems_(){} ~Stack(){}; void Push(const T& elem){ elems_.push_back(elem); } void Pop(){ elems_.pop_back(); } T& Top(){ return elems_.back(); } const T& Top() const{ return elems_.back(); } bool Empty() const{ return elems_.empty(); } private: CONT elems_; }; int main(int argc,char* argv[]){ Stack<int> s; s.Push(1); s.Push(2); s.Push(3); while(!s.Empty()){ std::cout<<s.Top()<<std::endl; s.Pop(); } return 0; } /* * 这种Stack的实现方式使STL六大组件之一——适配器。 * 将现有类当作参数传递,从而实现代码的复用。C++中默认的stack的实现也是借助于适配器的方式实现的。 */ <file_sep>/10.03.01.cpp /** * @file 10.03.01.cpp * @brief 函数模板,模板函数重载,函数模板特化 * @author LiWenGang * @date 2016-10-03 */ #include<iostream> #include<cstring> using namespace std; //函数模板 template <typename T> const T& Max(const T& a, const T& b); //函数模板重载 template <typename T> const T& Max(const T& a, const T& b, const T& c); //非模板函数重载 const int& Max(const int& a, const int& b); //函数模板特化 template <> const char* const& Max(const char* const &a, const char* const &b); class Test{ friend bool operator< (const Test& t1, const Test& t2){ return true; } }; int main(int argc, char* argv[]){ cout<<Max(5.5,6.6)<<endl; cout<<Max(5,6)<<endl; cout<<Max('a','d')<<endl; Test t1,t2; Max(t1,t2);//因为Test类中提供了“<”运算符重载,因此可以比较对象的大小 cout<<Max("aaa","bbb")<<endl;//会调用函数模板特化 cout<<Max(12,34,56)<<endl;//会调用模板函数重载 cout<<Max('a',100)<<endl;//会调用非模板函数重载 cout<<Max(10,20)<<endl;//会优先调用非模板函数重载 cout<<Max<>(10,20)<<endl;//会强制调用模板函数|自动推导出max(const int&, const int&); cout<<Max<int>(10,20)<<endl;//会强制调用模板函数,但不会自动推导 return 0; } template <typename T> const T& Max(const T& a, const T& b){ return a<b?b:a; } template <typename T> const T& Max(const T& a, const T& b, const T& c){ return max(a,b)<c?c:max(a,b); } const int& Max(const int& a, const int& b){ return a<b?b:a; } template <> const char* const& Max(const char* const &a, const char* const &b){ return strcmp(a,b)<0?b:a; } /* * 普通函数只需要声明,即可顺利编译,而模板的编译则需要检查模板的定义 * 换句话说,对于模板不可以将模板的声明和定义分别放置在*.h和*.cc文件中,然后通过包含头文件的方式引入模板。 */ <file_sep>/8.04.07.cpp /** * @file 8.04.07.cpp * @brief map|增删改查 * @author LiWenGang * @date 2016-08-04 */ #include<iostream> #include<map> using namespace std; int main(int argc, char* argv[]){ map<string, int> maplist; map<string,int>::iterator it; //map的四种插入方式 maplist["aaa"]=100; maplist.insert(map<string,int>::value_type("bbb",200)); maplist.insert(pair<string,int>("ccc",300)); maplist.insert(make_pair("ddd",400)); for(map<string,int>::const_iterator it=maplist.begin();it!=maplist.end();++it){ cout<<it->first<<" "<<it->second<<endl; } //map的一种访问方式 int key_value=maplist["aaa"]; cout<<key_value<<endl; //map的一种修改方式 maplist["ddd"]=4000; //map的另一种修改方式 it=maplist.find("ccc"); if(it!=maplist.end()){ it->second=3000; }else{ cout<<"not found"<<endl; } //map的一种删除操作 maplist.erase("bbb"); //map的另一种删除操作 it=maplist.find("ccc"); if(it!=maplist.end()){ maplist.erase(it); }else{ cout<<"not found"<<endl; } for(map<string,int>::const_iterator it=maplist.begin();it!=maplist.end();++it){ cout<<it->first<<" "<<it->second<<endl; } return 0; } /* * 插入map容器内的元素默认是按照key从小到大的顺序排列的; * key类型一定要重载<<运算符 */ <file_sep>/10.06.12.cpp /** * @file 10.06.12.cpp * @brief vector|删除指定元素 * @author LiWenGang * @date 2016-10-06 */ #include<iostream> #include<vector> using namespace std; int main(int argc, char* argv[]){ int a[]={3,1,2,3,5}; vector<int> v(a,a+5); /* //这种方式删除错误,因为it被erase掉了,造成it成为了空指针,不能++ for(vector<int>::iterator it=v.begin();it!=v.end();++it){ if(*it==3){ v.erase(it); }else{ cout<<*it<<" "; } } cout<<endl; */ for(vector<int>::iterator it=v.begin();it!=v.end();){ if(*it==3){ it=v.erase(it); }else{ cout<<*it<<" "; ++it; } } cout<<endl; return 0; } <file_sep>/10.06.08.cpp /** * @file 10.06.08.cpp * @brief IO流迭代器|ostream_iterator,istream_iterator * @author LiWenGang * @date 2016-10-06 */ #include<iostream> #include<algorithm> #include<vector> #include<iterator> using namespace std; int main(int argc, char* argv[]){ int a[]={1,2,3,4,5}; vector<int> v(a,a+5); copy(v.begin(),v.end(),ostream_iterator<int>(cout," ")); cout<<endl; vector<int> v2; copy(istream_iterator<int>(cin),istream_iterator<int>(),back_inserter(v2)); copy(v2.begin(),v2.end(),ostream_iterator<int>(cout," ")); cout<<endl; return 0; } <file_sep>/10.01.03.cpp /** * @file 10.01.03.cpp * @brief string流|istringstream * @author LiWenGang * @date 2016-10-01 */ #include<iostream> #include<string> #include<sstream> using namespace std; int main(int argc,char* argv[]){ string line; string word; while(getline(cin,line)){ istringstream iss(line); while(iss>>word){ cout<<word<<"#"; } cout<<endl; } return 0; } <file_sep>/8.04.05.cpp /** * @file 8.04.05.cpp * @brief string|去除空格 * @author LiWenGang * @date 2016-08-04 */ #include<iostream> #include<string> using namespace std; class StringUtil{ public: static void LTrim(string& str); static void RTrim(string& str); static void Trim(string& str); }; int main(int argc, char* argv[]){ string str; str=" Hello wolrd "; StringUtil::LTrim(str); cout<<"["<<str<<"]"<<endl; str=" Hello wolrd "; StringUtil::RTrim(str); cout<<"["<<str<<"]"<<endl; str=" Hello wolrd "; StringUtil::Trim(str); cout<<"["<<str<<"]"<<endl; return 0; } void StringUtil::LTrim(string& str){ string drop=" \t"; str.erase(0,str.find_first_not_of(drop)); } void StringUtil::RTrim(string& str){ string drop=" \t"; str.erase(str.find_last_not_of(drop)+1,string::npos); } void StringUtil::Trim(string& str){ LTrim(str); RTrim(str); } <file_sep>/7.24.04.cpp /** * @file 7.24.04.cpp * @brief new,delete * @author LiWenGang * @date 2016-07-24 */ #include<iostream> using namespace std; int main(int argc, char* argv[]){ int* p=new int; //分配一个整数空间 4KB cout<<*p<<endl; delete p; int *q=new int(20); //分配一个整数空间 4kB 同时完成赋值 cout<<*q<<endl; delete q; int *r=new int[10]; //分配一个连续的10个整数空间 40KB cout<<*r<<endl; delete[] r; return 0; } /* * new一个新对象 * 内存分配(operator new) * 调用构造函数 * delete释放一个对象 * 调用析构函数 * 释放内存(operator delete) */ <file_sep>/10.06.10.cpp /** * @file 10.06.10.cpp * @brief queue|STL * @author LiWenGang * @date 2016-10-06 */ #include<iostream> #include<queue> using namespace std; int main(int argc, char* argv[]){ queue<int> q; for(int i=0;i<5;i++){ q.push(i); } while(!q.empty()){ cout<<q.front()<<" "; q.pop(); } cout<<endl; return 0; } <file_sep>/8.01.03.cpp /** * @file 8.01.03.cpp * @brief mutable * @author LiWenGang * @date 2016-08-01 */ #include<iostream> using std::cout; using std::endl; class Test{ public: Test(); ~Test(); void OutPut() const; int OutPutCnt() const; private: mutable int m_cnt; }; int main(int argc, char* argv[]){ Test obj; obj.OutPut(); cout<<obj.OutPutCnt()<<endl; return 0; } Test::Test():m_cnt(0){ cout<<"constructor"<<endl; } Test::~Test(){ cout<<"destructor"<<endl; } /** * @brief OutPut() * * @note 此处m_cnt之所以可以被修改,主要原因是因为m_cnt是被mutable所修饰 * @see mutable */ void Test::OutPut() const{ m_cnt++; } int Test::OutPutCnt() const{ return m_cnt; } <file_sep>/8.09.01.cpp /** * @file 8.09.01.cpp * @brief 纯虚函数,抽象基类 * @author LiWenGang * @date 2016-08-09 */ #include<iostream> #include<vector> using namespace std; class Shape{ public: virtual void Draw()=0; virtual ~Shape(); }; class Circle:public Shape{ public: void Draw(); ~Circle(); }; class Square:public Shape{ public: void Draw(); ~Square(); }; void DrawAllShapes(const vector<Shape*> &v){ vector<Shape*>::const_iterator it; for(it=v.begin();it!=v.end();++it){ (*it)->Draw(); } } void DeleteAllShapes(const vector<Shape*> &v){ vector<Shape*>::const_iterator it; for(it=v.begin();it!=v.end();++it){ delete(*it); } } int main(int argc,char* argv[]){ //Shape s; //Error,不能实例化抽象类 vector<Shape*> v; Shape* ps; ps=new Circle; v.push_back(ps); ps=new Square; v.push_back(ps); DrawAllShapes(v); DeleteAllShapes(v); return 0; } void Circle::Draw(){ cout<<"Circle::Draw()"<<endl; } Circle::~Circle(){ cout<<"Circle::~Circle"<<endl; } void Square::Draw(){ cout<<"Square::Draw()"<<endl; } Square::~Square(){ cout<<"Square::~Square()"<<endl; } Shape::~Shape(){ cout<<"Shape::~Shape()"<<endl; } /* * 虚函数: * 基类指针指向派生类对象,调用的是派生类的虚函数。这就使得我们可以以一致的观点来看待不同d派生类对象。 * * 在基类中不能给出有意义的虚函数定义,这时可以把它说明成纯虚函数,把它的定义留给派生类来做,纯虚函数不需要实现。当类中出现一个纯虚函数时,该类便为抽象基类 * 抽象类为抽象和设计的目的而声明,将有关的数据和行为组织在一个继承层次结构中,保证派生类具有要求的行为 * * 抽象类只能作为基类来使用 * 不能声明为抽象类的对象,可以声明抽象类的指针和引用 * 构造函数不能是虚函数,析构函数可以是虚函数 */ <file_sep>/8.03.02.cpp /** * @file 8.03.02.cpp * @brief 类型转换运算符 * @author LiWenGang * @date 2016-08-03 */ #include<iostream> using std::cout; using std::endl; class Integer{ public: Integer(int num); ~Integer(); operator int(); //类型转化运算符|将类类型转换为int void Display(); private: int m_num; }; int main(int argc, char* argv[]){ Integer obj(10); int num=obj; cout<<num<<endl; return 0; } Integer::Integer(int num):m_num(num){ cout<<"constructor"<<endl; } Integer::~Integer(){ cout<<"destructor"<<endl; } Integer::operator int(){ return m_num; } void Integer::Display(){ cout<<m_num<<endl; } /* * 类型转化运算符: * 必须是成员函数,不能是友元函数 * 没有参数 * 不能制定返回类型 * 函数原型:operator 类型名 (); */ <file_sep>/7.25.01.cpp /** * @file 7.25.01.cpp * @brief 类的基本实现 * @author LiWenGang * @date 2016-07-25 */ #include<iostream> using namespace std; class Clock{ public: void init(int hour, int minute, int second); void dispaly(); void update(); int GetHour(); int GetMinute(); int GetSecond(); void SetHour(int hour); void SetMinute(int minute); void SetSecond(int second); private: int m_hour; int m_minute; int m_second; }; void Clock::init(int hour, int minute, int second){ m_hour=hour; m_minute=minute; m_second=second; } void Clock::dispaly(){ cout<<m_hour<<":"<<m_minute<<":"<<m_second<<endl; } void Clock::update(){ m_second++; if(m_second==60){ m_minute++; m_second=0; } if(m_minute==60){ m_hour++; m_minute=0; } if(m_hour==24){ m_hour=0; } } int Clock::GetHour(){ return m_hour; } int Clock::GetMinute(){ return m_minute; } int Clock::GetSecond(){ return m_second; } void Clock::SetHour(int hour){ m_hour=hour; } void Clock::SetMinute(int minute){ m_minute=minute; } void Clock::SetSecond(int second){ m_second=second; } //----------------------------------------------- int main(int argc, char* argv[]){ Clock ch; ch.init(16,46,25); ch.dispaly(); ch.update(); ch.dispaly(); cout<<ch.GetHour()<<":"<<ch.GetMinute()<<":"<<ch.GetSecond()<<endl; ch.SetHour(17); ch.SetMinute(10); ch.SetSecond(20); ch.dispaly(); return 0; } <file_sep>/7.25.04.cpp /** * @file 7.25.04.cpp * @brief 嵌套类 * @author LiWenGang * @date 2016-07-25 */ #include<iostream> using namespace std; class Outer{ public: //private: class Inner{ public: void Fun(); }; public: Inner obj; void Fun(); }; int main(int argc, char* argv[]){ Outer o; o.Fun(); Outer::Inner i; i.Fun(); return 0; } void Outer::Fun(){ cout<<"Outer::Fun ..."<<endl; obj.Fun(); } void Outer::Inner::Fun(){ cout<<"Innter::Fun ..."<<endl; } /* 从作用域的角度看,嵌套类被隐藏在外围类之中,该类名只能在外围类中使用。如果在外围类的作用域使用该类名时,需要加名字限定。 * 嵌套类中的成员函数可以在它的类体外定义。 * 嵌套类的成员函数对外围类的成员没有访问权,反之亦然。 * 嵌套类仅仅只是语法上的嵌入 */ <file_sep>/8.04.02.cpp /** * @file 8.04.02.cpp * @brief string|成员函数 * @author LiWenGang * @date 2016-08-04 */ #include<iostream> #include<string> using std::string; using std::cout; using std::endl; int main(int argc, char* argv[]){ string str("hello world"); cout<<str<<endl; cout<<str.size()<<endl; //字符串大小 cout<<str.length()<<endl; //字符串长度 cout<<str.empty()<<endl; //字符串是否为空 cout<<str.substr(6,5)<<endl; //截取子串(从第6个位置开始,到其后面的5个为止) cout<<str.substr(6,-1)<<endl; //截取子串(从第6个位置开始,到最后一个字符为止) string::size_type lpos=str.find('e',1); //从第1个位置开始查找'e' if(lpos==string::npos){ cout<<"not found"<<endl; }else{ cout<<"lpos="<<lpos<<endl; } string::size_type rpos=str.rfind('w',-1); //从最后一个位置向前查找'w' if(rpos==string::npos){ cout<<"not found"<<endl; }else{ cout<<"rpos="<<rpos<<endl; } cout<<str.replace(0,1,"H")<<endl; //替换str下标从0开始的1个字符串 cout<<str.insert(0,"Hello latex ")<<endl; //在str下标为0的位置前面添加"Hello latex" cout<<str.append(" Hello c++")<<endl; //在str的后面追加"Hello c++" return 0; } <file_sep>/8.09.02.cpp /** * @file 8.09.02.cpp * @brief 对象的动态创建 * @author LiWenGang * @date 2016-08-09 */ #include<iostream> #include<string> #include<vector> #include<map> #define REGISTER_CLASS(class_name) \ class class_name##Register{ \ public: \ static void* NewInstance(){ \ return new class_name; \ } \ private: \ static Register reg_; \ }; \ Register class_name##Register::reg_(#class_name, class_name##Register::NewInstance) using namespace std; class Shape; void DrawAllShape(const vector<Shape*>& v); void DeleteAllShape(const vector<Shape*>& v); class Shape{ public: virtual void Draw()=0; virtual ~Shape(); }; class Circle:public Shape{ public: void Draw(); ~Circle(); }; class Triangle:public Shape{ public: void Draw(); ~Triangle(); }; typedef void* (*CREATE_FUN)(); class DynObjectFactor{ public: static void* CreateObject(const string& name); static void Register(const string& name, CREATE_FUN func); private: static map<string, CREATE_FUN> mapCls_; }; map<string,CREATE_FUN>DynObjectFactor::mapCls_; class Register{ public: Register(const string& name, CREATE_FUN func); }; int main(int argc, char* argv[]){ vector<Shape*> v; Shape* ps; ps=static_cast<Shape*>(DynObjectFactor::CreateObject("Circle")); v.push_back(ps); ps=static_cast<Shape*>(DynObjectFactor::CreateObject("Triangle")); v.push_back(ps); DrawAllShape(v); DeleteAllShape(v); return 0; } void DrawAllShape(const vector<Shape*>& v){ for(vector<Shape*>::const_iterator it=v.begin();it!=v.end();++it){ (*it)->Draw(); } } void DeleteAllShape(const vector<Shape*>& v){ for(vector<Shape*>::const_iterator it=v.begin();it!=v.end();++it){ delete(*it); } } Shape::~Shape(){ cout<<"Shape::~Shape()"<<endl; } void Circle::Draw(){ cout<<"Circle::Draw()"<<endl; } Circle::~Circle(){ cout<<"Circle::~Circle()"<<endl; } void Triangle::Draw(){ cout<<"Triangle::Draw()"<<endl; } Triangle::~Triangle(){ cout<<"Triangle::~Triangle()"<<endl; } REGISTER_CLASS(Circle); REGISTER_CLASS(Triangle); void* DynObjectFactor::CreateObject(const string& name){ map<string, CREATE_FUN>::const_iterator it; it=mapCls_.find(name); if(it==mapCls_.end()){ return NULL; }else{ return it->second(); } } void DynObjectFactor::Register(const string& name, CREATE_FUN func){ mapCls_[name]=func; } Register::Register(const string& name, CREATE_FUN func){ DynObjectFactor::Register(name,func); } <file_sep>/10.01.05.cpp /** * @file 10.01.05.cpp * @brief 通过操纵子方式进行格式化输出 * @author LiWenGang * @date 2016-10-01 */ #include<iostream> #include<iomanip> using namespace std; int main(int argc,char* argv[]){ int n=64; double d=123.45; double d2=0.018; cout<<"=================宽度控制=================="<<endl; cout<<n<<'#'<<endl; cout<<setw(10)<<n<<'#'<<endl;//宽度控制,不会影响下一个输出 cout<<"=================对齐控制=================="<<endl; cout<<setw(10)<<setiosflags(ios::left)<<n<<'#'<<endl; cout<<setw(10)<<n<<'#'<<endl;//对齐控制,会影响下一个输出 cout<<setw(10)<<resetiosflags(ios::left)<<n<<'#'<<endl; cout<<"=================填充控制=================="<<endl; cout<<setw(10)<<setfill('?')<<n<<endl; cout<<setw(10)<<n<<endl; cout<<setw(10)<<setfill(' ')<<n<<endl; cout<<"=================精度控制=================="<<endl; cout<<setprecision(4)<<d<<endl;//保留4位有效数字 cout<<setprecision(2)<<d2<<endl; cout<<setiosflags(ios::fixed); cout<<setprecision(4)<<d<<endl;//小数点后保留4位 cout<<setprecision(2)<<d2<<endl; cout<<"=================进制输出=================="<<endl; cout<<oct<<n<<endl; cout<<hex<<n<<endl<<endl; cout<<setiosflags(ios::showbase); cout<<dec<<n<<endl; cout<<oct<<n<<endl; cout<<hex<<n<<endl<<endl; cout<<setbase(10)<<n<<endl; cout<<setbase(8)<<n<<endl; cout<<setbase(16)<<n<<endl; return 0; } <file_sep>/10.06.07.cpp /** * @file 10.06.07.cpp * @brief 迭代器|front_insert_iterator, front_inserter * @author LiWenGang * @date 2016-10-06 */ #include<iostream> #include<algorithm> #include<vector> #include<list> using namespace std; void ShowVec(list<int> v); int main(int argc, char* argv[]){ int a[]={1,2,3,4,5}; list<int> l(a,a+5); //front_insert_iterator内所传递的容器必须有push_front方法 front_insert_iterator<list<int>> fii(l); fii=0; ShowVec(l); list<int> l2; copy(l.begin(),l.end(),front_inserter(l2)); ShowVec(l2); return 0; } void ShowVec(list<int> l){ for(const auto& w:l){ cout<<w<<" "; } cout<<endl; } <file_sep>/8.05.04.cpp /** * @file 8.05.04.cpp * @brief 派生类到基类的转换|基类到派生类的转换 * @author LiWenGang * @date 2016-08-05 */ #include<iostream> #include<string> using namespace std; class Employee{ public: Employee(const string& name, int age, int deptno); private: string name_; int age_; int deptno_; }; class Manager:public Employee{ public: Manager(const string& name, int age, int deptno,int level); private: int level_; }; class Manager2:private Employee{ public: Manager2(const string& name, int age, int deptno,int level); private: int level_; }; int main(int argc, char* argv[]){ Employee* pe; Employee e1("zhang",22,25); pe=&e1; Manager* pm; Manager m1("li",21,25,1); pm=&m1; pe=&m1; //派生类对象指针可以转化为基类指针。将派生类对象看成基类对象。 //pm=&e1; //基类指针无法转化为派生类指针。无法将基类对象看成派生类对象。 e1=m1; //派生类对象可以转化为基类对象。将派生类对象看成基类对象。 //会产生对象切割(派生类特有成员消失):object slicing Manager2* pm2; Manager2 m2("wang",20,23,2); pm2=&m2; //pe=&m2; //私有或保护继承的时候,派生类对象指针不可以自动转化为基类对象指针 pe=reinterpret_cast<Employee*>(&m2); //e1=m2; //私有或保护继承的时候,派生类对象无法转化为基类对象。 //e1=reinterpret_cast<Employee>(m2); //即使类型强制转换也不行 //pm=pe; //基类指针不能转换为派生类指针 pm=reinterpret_cast<Manager*>(pe); //基类指针可以强制转换为派生类指针,但是不安全。 //注:这种转换与继承方式无关 //m1=e1; //基类对象不能转换为派生类对象,即使强制转换也不行 //如果一定要实现这种转换的话,可以考虑使用转换构造函数; return 0; } Employee::Employee(const string& name, int age, int deptno):name_(name),age_(age),deptno_(deptno){ } Manager::Manager(const string& name, int age, int deptno, int level):Employee(name,age,deptno),level_(level){ } /* * 当派生类以public方式继承基类时,编译器可自动执行的转化(向上转型upcasting安全转换) * 派生类对象指针自动转换为基类对象指针; * 派生类对象引用自动转化为基类对象引用; * 派生类对象自动转化为基类对象(特有的成员消失) * 当派生类以private/protected方式继承基类时 * 派生类对象指针(引用)转化为基类对象指针(引用)需要强制类型转化,但不能使用static_cast,要用reinterpret_cast * 不能把派生类对象强制转换为基类对象 */ /* * 向下转型downcasting转换 * 基类对象指针(引用)可用强制类型转换为派生类对象指针(引用),而基类对象无法执行这类转换 * 向下转型不安全,没有自动转换的机制 */ /* * static_cast 用于编译器认可的静态转换在: * 比如说从char到int;或者具有转换构造函数;或者重载了类型转换运算符 * reinterpret_cast 用于编译器不认可的静态转换: * 比如说从int*到int * const_cast 去除常量属性 * dynamic_cast 用于动态转换;安全的乡下转型 */ <file_sep>/8.02.05.cpp /** * @file 8.02.05.cpp * @brief 前置++运算符重载 * @author LiWenGang * @date 2016-08-02 */ #include<iostream> using std::cout; using std::endl; class Integer{ friend Integer& operator++ (Integer& obj); //友元函数的方式重载++ public: Integer(int num); ~Integer(); //Integer& operator++(); //成员函数的方式重载++ void Display(); private: int m_num; }; int main(int argc, char* argv[]){ Integer obj(10); ++obj; obj.Display(); return 0; } Integer::Integer(int num):m_num(num){ cout<<"constructor"<<endl; } Integer::~Integer(){ cout<<"destructor"<<endl; } /* //成员函数的方式重载++ Integer& Integer::operator++(){ ++m_num; return *this; } */ //友元函数的方式重载++ Integer& operator++ (Integer& obj){ ++obj.m_num; return obj; } void Integer::Display(){ cout<<m_num<<endl; } <file_sep>/10.06.11.cpp /** * @file 10.06.11.cpp * @brief priority_queue|STL * @author LiWenGang * @date 2016-10-06 */ #include<iostream> #include<queue> #include<iterator> using namespace std; int main(int argc, char* argv[]){ int a[]={5,1,2,4,3}; make_heap(a,a+5); copy(a,a+5,ostream_iterator<int>(cout," ")); cout<<endl; //优先级队列,默认值越大,优先级越高 priority_queue<int> q(a,a+5);//STL实现的时候,会构建一个堆,类似于堆排序的“堆” while(!q.empty()){ cout<<q.top()<<" "; q.pop(); } cout<<endl; //使用greater修改了优先级,值越小优先级越高 priority_queue<int, vector<int>, greater<int>> q1(a,a+5); while(!q1.empty()){ cout<<q1.top()<<" "; q1.pop(); } cout<<endl; make_heap(a,a+5,greater<int>());//大根堆 sort_heap(a,a+5,greater<int>()); copy(a,a+5,ostream_iterator<int>(cout," ")); cout<<endl; return 0; } <file_sep>/7.27.03.cpp /** * @file 7.27.03.cpp * @brief 空类默认产生的成员 * @author LiWenGang * @date 2016-07-27 */ #include<iostream> using std::cout; using std::endl; class Empty{ public: Empty* operator&(); const Empty* operator&() const; }; int main(int argc, char* argv[]){ Empty a; Empty*p=&a; //等价于e.operator&(); cout<<(void*)p<<endl; cout<<(void*)&a<<endl; const Empty b; const Empty* q=&b; cout<<(void*)q<<endl; cout<<(void*)&b<<endl; return 0; } Empty* Empty::operator&(){ return this; } const Empty* Empty::operator&() const{ return this; } /* * 空类默认产生的成员: * * class Empty { }; * Empty(); // 默认构造函数 * Empty( const Empty& ); // 默认拷贝构造函数 * ~Empty(); // 默认析构函数 * Empty& operator=( const Empty& ); // 默认赋值运算符 * Empty* operator&(); // 取址运算符 * const Empty* operator&() const; // 取址运算符 const * * 空类的所占内存大小为1KB */ <file_sep>/7.26.02.cpp /** * @file 7.26.02.cpp * @brief 构造函数|数组|new * @author LiWenGang * @date 2016-07-26 */ #include<iostream> using namespace std; class Test{ public: Test(); Test(int num); ~Test(); private: int m_num; }; int main(int argc, char* argv[]){ Test t1; Test t2(10); Test t3[2]={20,30}; Test* t4=new Test(40); delete t4; Test* t5=new Test[2]; delete[] t5; return 0; } Test::Test(){ m_num=0; cout<<"Initializing default"<<endl; } Test::Test(int num){ m_num=num; cout<<"num="<<num<<endl; } Test::~Test(){ cout<<"Destroying "<<m_num<<endl; } <file_sep>/10.03.03.cpp /** * @file 10.03.03.cpp * @brief 使用模板实现栈|非类型模板参数 * @author LiWenGang * @date 2016-10-03 */ #include<iostream> #include<stdexcept> template<typename T, int MAXSIZE> class Stack{ public: explicit Stack(); ~Stack(); void Push(const T& elem); void Pop(); T& Top(); const T& Top() const; bool Empty() const; private: T* elems_; int top_; }; template<typename T, int MAXSIZE> Stack<T,MAXSIZE>::Stack():top_(-1){ elems_=new T[MAXSIZE]; } template<typename T, int MAXSIZE> Stack<T,MAXSIZE>::~Stack(){ delete[] elems_; } template<typename T, int MAXSIZE> void Stack<T,MAXSIZE>::Push(const T& elem){ if(top_+1>=MAXSIZE){ throw std::out_of_range("Stack<>::Push() stack full"); } elems_[++top_]=elem; } template<typename T, int MAXSIZE> void Stack<T,MAXSIZE>::Pop(){ if(top_+1==0){ throw std::out_of_range("Stack<>::Push() stack empty"); } --top_; } template<typename T, int MAXSIZE> T& Stack<T,MAXSIZE>::Top(){ if(top_+1==0){ throw std::out_of_range("Stack<>::Push() stack empty"); } return elems_[top_]; } template<typename T, int MAXSIZE> bool Stack<T,MAXSIZE>::Empty() const{ return top_+1==0; } int main(int argc,char* argv[]){ Stack<int,10> s; s.Push(1); s.Push(2); s.Push(3); while(!s.Empty()){ std::cout<<s.Top()<<std::endl; s.Pop(); } return 0; } <file_sep>/7.24.08.cpp /** * @file 7.24.08.cpp * @brief 引用作为参数传递|引用作为返回值 * @author LiWenGang * @date 2016-07-24 */ #include<iostream> using namespace std; void swap(int&,int&); int& index(int); int c[]={0,1,2,3,4}; int main(int argc, char* argv[]){ int a=5; int b=6; swap(a,b); cout<<"a="<<a<<endl; cout<<"b="<<b<<endl; index(3)=100; cout<<"c[3]="<<c[3]<<endl; return 0; } void swap(int& x, int& y){ x=x^y; y=x^y; x=x^y; } int& index(int i){ return c[i]; } /* * 引用作参数时,函数的实参与形参在内存中共用存储单元,因此形参的变化会使实参同时变化。 * 函数返回引用的一个主要目的是可以将函数放在赋值运算符的左边。 * 不能返回对局部变量的引用,论其主要原因是因为当局部变量会在其执行完成后销毁内存空间,导致引用失败 */ /* * 值传递:实参初始化形参要分配空间,将实参内容拷贝到形参 * 引用传递:实参初始化形参时不分配空间 * 指针传递:本质是传递,实参初始化形参的时候,需要分配空间。如果需要修改指针的地址,单纯用指针传递是不行的。可以考虑使用指针的指针,或者指针的引用 */ <file_sep>/8.06.01.cpp /** * @file 8.06.01.cpp * @brief 多重继承 * @author LiWenGang * @date 2016-08-06 */ #include<iostream> using namespace std; class Bed{ public: Bed(int weight); void Sleep(); int weight_; }; class Sofa{ public: Sofa(int weight); void WatchTV(); int weight_; }; class SofaBed:public Bed, public Sofa{ public: SofaBed(); void FoldOut(); void FoldIn(); }; int main(int argc, char* argv[]){ SofaBed sofabed; //sofabed.weight_=10; //因为类SofaBed继承自类Bed和Sofa,而这两个类中都有weight_这个变量,从而导致sofabed.weight访问不明确,解决办法是显式指定类 sofabed.Bed::weight_=10; sofabed.Sofa::weight_=20; sofabed.WatchTV(); sofabed.FoldOut(); sofabed.Sleep(); return 0; } Sofa::Sofa(int weight):weight_(weight){ } SofaBed::SofaBed():Bed(0),Sofa(0){ FoldIn(); } Bed::Bed(int weight):weight_(weight){ } void Bed::Sleep(){ } void Sofa::WatchTV(){ cout<<"Watch TV..."<<endl; } void SofaBed::FoldOut(){ cout<<"FoldOut..."<<endl; } void SofaBed::FoldIn(){ cout<<"FoldIn..."<<endl; } /* * 单重继承:一个派生类最多只能有一个基类 * 多重继承:一个派生类可以有多个基类 * 派生类可以同时继承多个基类的成员,具有更好的软件复用性 * 可能会存在二义性,多个基类中可能包含同名变量或函数 * */
cfd10d4992df62a4708b94ee0009498987b09744
[ "C++" ]
109
C++
apktool/LearnCPP
7bc405320b243b140d516fd56b9c469b158dac9b
d67732d457e0bb6e70ef09b8c8861dea5d4fd44a
refs/heads/master
<file_sep>package io.renren.modules.banana.generator.service; import com.baomidou.mybatisplus.service.IService; import io.renren.common.utils.PageUtils; import io.renren.modules.banana.generator.entity.BananaGoodsCamiloEntity; import java.util.Map; /** * 商品卡密 * * @author chenweilong * @email <EMAIL> * @date 2018-12-24 20:54:53 */ public interface BananaGoodsCamiloService extends IService<BananaGoodsCamiloEntity> { PageUtils queryPage(Map<String, Object> params); } <file_sep>package io.renren.modules.banana.generator.entity; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import java.io.Serializable; import java.util.Date; /** * 商品卡密 * * @author chenweilong * @email <EMAIL> * @date 2018-12-24 20:54:53 */ @TableName("banana_goods_camilo") public class BananaGoodsCamiloEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 卡密id */ @TableId private Integer id; /** * 商品id */ private Integer goodsId; /** * 卡密 */ private String camilo; /** * 卡密 \r\n分割 */ @TableField(exist = false) private String textarea; /** * 状态0:未发放1:已发放 */ private Integer status; /** * 商品名称 */ private String goodsName; /** * 创建时间 */ private Date createTime; /** * 设置:卡密id */ public void setId(Integer id) { this.id = id; } /** * 获取:卡密id */ public Integer getId() { return id; } /** * 设置:商品id */ public void setGoodsId(Integer goodsId) { this.goodsId = goodsId; } /** * 获取:商品id */ public Integer getGoodsId() { return goodsId; } /** * 设置:卡密 */ public void setCamilo(String camilo) { this.camilo = camilo; } /** * 获取:卡密 */ public String getCamilo() { return camilo; } /** * 设置:状态0:未发放1:已发放 */ public void setStatus(Integer status) { this.status = status; } /** * 获取:状态0:未发放1:已发放 */ public Integer getStatus() { return status; } /** * 设置:商品名称 */ public void setGoodsName(String goodsName) { this.goodsName = goodsName; } /** * 获取:商品名称 */ public String getGoodsName() { return goodsName; } /** * 设置:创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取:创建时间 */ public Date getCreateTime() { return createTime; } public String getTextarea() { return textarea; } public void setTextarea(String textarea) { this.textarea = textarea; } } <file_sep>package io.renren.modules.banana.generator.service; import com.baomidou.mybatisplus.service.IService; import io.renren.common.utils.PageUtils; import io.renren.modules.banana.generator.entity.BananaUserEntity; import java.util.Map; /** * 用户表 * * @author chenweilong * @email <EMAIL> * @date 2018-12-24 20:54:53 */ public interface BananaUserService extends IService<BananaUserEntity> { PageUtils queryPage(Map<String, Object> params); } <file_sep>package io.renren.modules.banana.generator.controller; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import io.renren.modules.banana.generator.entity.BananaGoodsEntity; import io.renren.modules.banana.generator.service.BananaGoodsService; import io.renren.common.utils.PageUtils; import io.renren.common.utils.R; /** * 商品表 * * @author chenweilong * @email <EMAIL> * @date 2018-12-24 20:54:53 */ @RestController @RequestMapping("generator/bananagoods") public class BananaGoodsController { @Autowired private BananaGoodsService bananaGoodsService; /** * 列表 */ @RequestMapping("/listAll") @RequiresPermissions("generator:bananagoods:list") public R listAll(@RequestParam Map<String, Object> params){ List<BananaGoodsEntity> bananaGoodsEntities = bananaGoodsService.selectList(null); return R.data(bananaGoodsEntities); } /** * 列表 */ @RequestMapping("/list") @RequiresPermissions("generator:bananagoods:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = bananaGoodsService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{goddsid}") @RequiresPermissions("generator:bananagoods:info") public R info(@PathVariable("goddsid") Integer goddsid){ BananaGoodsEntity bananaGoods = bananaGoodsService.selectById(goddsid); return R.ok().put("bananaGoods", bananaGoods); } /** * 保存 */ @RequestMapping("/save") @RequiresPermissions("generator:bananagoods:save") public R save(@RequestBody BananaGoodsEntity bananaGoods){ bananaGoods.setCreateTime(new Date()); bananaGoodsService.insert(bananaGoods); return R.ok(); } /** * 修改 */ @RequestMapping("/update") @RequiresPermissions("generator:bananagoods:update") public R update(@RequestBody BananaGoodsEntity bananaGoods){ bananaGoodsService.updateById(bananaGoods); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") @RequiresPermissions("generator:bananagoods:delete") public R delete(@RequestBody Integer[] goddsids){ bananaGoodsService.deleteBatchIds(Arrays.asList(goddsids)); return R.ok(); } } <file_sep>package io.renren.common.utils; import cn.hutool.core.util.RandomUtil; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; import java.util.*; public class SendSms { //无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值 private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\""; //无需修改,用于格式化鉴权头域,给"Authorization"参数赋值 private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\""; public static void main(String[] args) { // System.out.println(RandomUtil.randomNumbers(6)); send("17839942480","123456"); } public static void send(String phone,String code) { //必填,请参考"开发准备"获取如下数据,替换为实际值 String url = "https://api.rtc.huaweicloud.com:10443/sms/batchSendSms/v1"; //APP接入地址+接口访问URI String appKey = "<KEY>"; //APP_Key String appSecret = "<KEY>"; //APP_Secret String sender = "csms18122401"; //签名通道号 String templateId = "a1e361c900bc40689a8e041c2e70d70f"; //模板ID //条件必填,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称 String signature = "香蕉充值"; //签名名称 //必填,全局号码格式(包含国家码),示例:+8615123456789,多个号码之间用英文逗号分隔 String receiver = "+86" + phone; //短信接收人号码 //选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告 String statusCallBack = ""; /** * 选填,使用无变量模板时请赋空值 String templateParas = ""; * 单变量模板示例:模板内容为"您的验证码是${NUM_6}"时,templateParas可填写为"[\"369751\"]" * 双变量模板示例:模板内容为"您有${NUM_2}件快递请到${TXT_32}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]" * 查看更多模板变量规则:常见问题>业务规则>短信模板内容审核标准 */ String templateParas = "[\""+code+"\"]"; //模板变量 //请求Body,普通模板,使用如下代码 //String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack); //请求Body,通用模板,使用如下代码 String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature); System.out.println("body is " + body); //请求Headers中的X-WSSE参数值 String wsseHeader = buildWsseHeader(appKey, appSecret); System.out.println("wsse header is " + wsseHeader); //如果JDK版本低于1.8,可使用如下代码 //为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题 //CloseableHttpClient client = HttpClients.custom() // .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // @Override // public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { // return true; // } // }).build()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); //如果JDK版本是1.8,可使用如下代码 //为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题 CloseableHttpClient client = null; try { client = HttpClients.custom() .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, (x509CertChain, authType) -> true).build()) .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .build(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } HttpResponse response = null; try { response = client.execute(RequestBuilder.create("POST")//请求方法POST .setUri(url) .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded") .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE) .addHeader("X-WSSE", wsseHeader) .setEntity(new StringEntity(body)).build()); } catch (IOException e) { e.printStackTrace(); } // System.out.println(response.toString()); // System.out.println(EntityUtils.toString(response.getEntity())); } /** * 构造请求Body体 for 普通模板 * @param sender * @param receiver * @param templateId * @param templateParas * @param statusCallbackUrl * @return */ static String buildRequestBody(String sender, String receiver, String templateId, String templateParas, String statusCallbackUrl) { List<NameValuePair> keyValues = new ArrayList<NameValuePair>(); keyValues.add(new BasicNameValuePair("from", sender)); keyValues.add(new BasicNameValuePair("to", receiver)); keyValues.add(new BasicNameValuePair("templateId", templateId)); keyValues.add(new BasicNameValuePair("templateParas", templateParas)); keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl)); //如果JDK版本是1.6,可使用:URLEncodedUtils.format(keyValues, Charset.forName("UTF-8")); return URLEncodedUtils.format(keyValues, StandardCharsets.UTF_8); } /** * 构造请求Body体 for 通用模板 * @param sender * @param receiver * @param templateId * @param templateParas * @param statusCallbackUrl * @param signature * @return */ static String buildRequestBody(String sender, String receiver, String templateId, String templateParas, String statusCallbackUrl, String signature) { List<NameValuePair> keyValues = new ArrayList<NameValuePair>(); keyValues.add(new BasicNameValuePair("from", sender)); keyValues.add(new BasicNameValuePair("to", receiver)); keyValues.add(new BasicNameValuePair("templateId", templateId)); keyValues.add(new BasicNameValuePair("templateParas", templateParas)); keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl)); keyValues.add(new BasicNameValuePair("signature", signature)); //如果JDK版本是1.6,可使用:URLEncodedUtils.format(keyValues, Charset.forName("UTF-8")); return URLEncodedUtils.format(keyValues, StandardCharsets.UTF_8); } /** * 构造X-WSSE参数值 * @param appKey * @param appSecret * @return */ static String buildWsseHeader(String appKey, String appSecret) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); String time = sdf.format(new Date()); String nonce = UUID.randomUUID().toString().replace("-", ""); byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret); String hexDigest = Hex.encodeHexString(passwordDigest); String passwordDigestBase64Str = Base64.encodeBase64String(hexDigest.getBytes(Charset.forName("utf-8"))); return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time); } }<file_sep>package io.renren.modules.banana.generator.entity; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import java.io.Serializable; import java.util.Date; /** * 用户-验证码 * * @author chenweilong * @email <EMAIL> * @date 2018-12-24 20:54:52 */ @TableName("banana_user_captcha") public class BananaUserCaptchaEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId private Integer id; /** * 验证码 */ private String code; /** * 过期时间 */ private Date expireTime; /** * 手机号 */ private String userPhone; /** * 创建时间 */ private Date createTime; /** * 设置:主键 */ public void setId(Integer id) { this.id = id; } /** * 获取:主键 */ public Integer getId() { return id; } /** * 设置:验证码 */ public void setCode(String code) { this.code = code; } /** * 获取:验证码 */ public String getCode() { return code; } /** * 设置:过期时间 */ public void setExpireTime(Date expireTime) { this.expireTime = expireTime; } /** * 获取:过期时间 */ public Date getExpireTime() { return expireTime; } /** * 设置:手机号 */ public void setUserPhone(String userPhone) { this.userPhone = userPhone; } /** * 获取:手机号 */ public String getUserPhone() { return userPhone; } /** * 设置:创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取:创建时间 */ public Date getCreateTime() { return createTime; } } <file_sep>package io.renren.modules.banana.generator.entity; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.enums.IdType; import io.renren.common.utils.SpringUtils; import io.renren.modules.banana.generator.service.BananaUserService; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.io.Serializable; import java.util.Date; /** * 订单表 * * @author chenweilong * @email <EMAIL> * @date 2018-12-24 20:54:53 */ @ApiModel("订单表") @TableName("banana_order") public class BananaOrderEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 订单id */ @TableId(type = IdType.ID_WORKER) @ApiModelProperty(value = "orderid") private String orderid; /** * 订单商品id */ @ApiModelProperty(value = "订单商品id") private Integer goodsid; /** * 商品名称 */ @ApiModelProperty(value = "商品名称") private String title; /** * 商品图片 */ @ApiModelProperty(value = "商品图片") private String pic; /** * 购买数量 */ @ApiModelProperty(value = "购买数量") private BigDecimal count; /** * 购买价钱 */ @ApiModelProperty(value = "购买价钱") private BigDecimal price; /** * 商品总价格 */ @ApiModelProperty(value = "商品总价格") private BigDecimal totalPrice; /** * 支付code */ @ApiModelProperty(value = "支付code") private String code; /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private Date createTime; /** * 支付时间 */ @ApiModelProperty(value = "支付时间") private Date paytime; /** * 支付方式1:微信2:支付宝 */ @ApiModelProperty(value = "支付方式1:微信2:支付宝") private Integer payType; /** * 充值账号 */ @ApiModelProperty(value = "充值账号") private String account; /** * 是否已经充值0:未充值 1:已经充值 */ @ApiModelProperty(value = "是否已经充值0:未充值 1:已经充值") private Integer status; /** * 该商品充值方式1:卡密2:自动充值3:手动充值 */ @ApiModelProperty(value = "该商品充值方式1:卡密2:自动充值3:手动充值") private Integer topUpWay; /** * 卡密 */ @ApiModelProperty(value = "卡密") private String password; /** * 充值官方网站 */ @ApiModelProperty(value = "充值官方网站") private String url; /** * 是否支付0未支付1已支付 */ @ApiModelProperty(value = "是否支付0未支付1已支付") private Integer isPay; /** * 用户id */ @ApiModelProperty(value = "用户id") private Integer userId; @TableField(exist = false) private BananaUserEntity bananaUserEntity; /** * 设置:订单id */ public void setOrderid(String orderid) { this.orderid = orderid; } /** * 获取:订单id */ public String getOrderid() { return orderid; } /** * 设置:订单商品id */ public void setGoodsid(Integer goodsid) { this.goodsid = goodsid; } /** * 获取:订单商品id */ public Integer getGoodsid() { return goodsid; } /** * 设置:商品名称 */ public void setTitle(String title) { this.title = title; } /** * 获取:商品名称 */ public String getTitle() { return title; } /** * 设置:商品图片 */ public void setPic(String pic) { this.pic = pic; } /** * 获取:商品图片 */ public String getPic() { return pic; } /** * 设置:购买数量 */ public void setCount(BigDecimal count) { this.count = count; } /** * 获取:购买数量 */ public BigDecimal getCount() { return count; } /** * 设置:购买价钱 */ public void setPrice(BigDecimal price) { this.price = price; } /** * 获取:购买价钱 */ public BigDecimal getPrice() { return price; } /** * 设置:商品总价格 */ public void setTotalPrice(BigDecimal totalPrice) { this.totalPrice = totalPrice; } /** * 获取:商品总价格 */ public BigDecimal getTotalPrice() { return totalPrice; } /** * 设置:支付code */ public void setCode(String code) { this.code = code; } /** * 获取:支付code */ public String getCode() { return code; } /** * 设置:创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取:创建时间 */ public Date getCreateTime() { return createTime; } /** * 设置:支付时间 */ public void setPaytime(Date paytime) { this.paytime = paytime; } /** * 获取:支付时间 */ public Date getPaytime() { return paytime; } /** * 设置:支付方式1:微信2:支付宝 */ public void setPayType(Integer payType) { this.payType = payType; } /** * 获取:支付方式1:微信2:支付宝 */ public Integer getPayType() { return payType; } /** * 设置:充值账号 */ public void setAccount(String account) { this.account = account; } /** * 获取:充值账号 */ public String getAccount() { return account; } /** * 设置:是否已经充值0:未充值 1:已经充值 */ public void setStatus(Integer status) { this.status = status; } /** * 获取:是否已经充值0:未充值 1:已经充值 */ public Integer getStatus() { return status; } /** * 设置:该商品充值方式1:卡密2:自动充值3:手动充值 */ public void setTopUpWay(Integer topUpWay) { this.topUpWay = topUpWay; } /** * 获取:该商品充值方式1:卡密2:自动充值3:手动充值 */ public Integer getTopUpWay() { return topUpWay; } /** * 设置:卡密 */ public void setPassword(String password) { this.password = password; } /** * 获取:卡密 */ public String getPassword() { return password; } /** * 设置:充值官方网站 */ public void setUrl(String url) { this.url = url; } /** * 获取:充值官方网站 */ public String getUrl() { return url; } public Integer getIsPay() { return isPay; } public void setIsPay(Integer isPay) { this.isPay = isPay; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public BananaUserEntity getBananaUserEntity() { if (userId != null) { BananaUserService bananaUserService = SpringUtils.getBean(BananaUserService.class); return bananaUserService.selectById(userId); } return bananaUserEntity; } public void setBananaUserEntity(BananaUserEntity bananaUserEntity) { this.bananaUserEntity = bananaUserEntity; } } <file_sep>package io.renren.modules.banana.generator.controller; import java.util.*; import io.renren.modules.banana.generator.entity.BananaGoodsEntity; import io.renren.modules.banana.generator.service.BananaGoodsService; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import io.renren.modules.banana.generator.entity.BananaGoodsCamiloEntity; import io.renren.modules.banana.generator.service.BananaGoodsCamiloService; import io.renren.common.utils.PageUtils; import io.renren.common.utils.R; /** * 商品卡密 * * @author chenweilong * @email <EMAIL> * @date 2018-12-24 20:54:53 */ @RestController @RequestMapping("generator/bananagoodscamilo") public class BananaGoodsCamiloController { @Autowired private BananaGoodsCamiloService bananaGoodsCamiloService; @Autowired private BananaGoodsService bananaGoodsService; /** * 列表 */ @RequestMapping("/list") @RequiresPermissions("generator:bananagoodscamilo:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = bananaGoodsCamiloService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") @RequiresPermissions("generator:bananagoodscamilo:info") public R info(@PathVariable("id") Integer id){ BananaGoodsCamiloEntity bananaGoodsCamilo = bananaGoodsCamiloService.selectById(id); return R.ok().put("bananaGoodsCamilo", bananaGoodsCamilo); } /** * 保存 */ @RequestMapping("/save") @RequiresPermissions("generator:bananagoodscamilo:save") public R save(@RequestBody BananaGoodsCamiloEntity bananaGoodsCamilo){ if (bananaGoodsCamilo == null) { return R.error("不能为空"); } if (bananaGoodsCamilo.getTextarea() == null || bananaGoodsCamilo.getTextarea().equals("")) { return R.error("卡密不能为空"); } String[] split = bananaGoodsCamilo.getTextarea().split("\n"); BananaGoodsEntity bananaGoodsEntity = bananaGoodsService.selectById(bananaGoodsCamilo.getGoodsId()); List<BananaGoodsCamiloEntity> bananaGoodsEntities = new ArrayList<>(); for (String s : split) { BananaGoodsCamiloEntity bananaGoodsCamiloEntity = new BananaGoodsCamiloEntity(); bananaGoodsCamiloEntity.setStatus(0); bananaGoodsCamiloEntity.setGoodsId(bananaGoodsEntity.getGoddsid()); bananaGoodsCamiloEntity.setGoodsName(bananaGoodsEntity.getTitle()); bananaGoodsCamiloEntity.setCreateTime(new Date()); bananaGoodsCamiloEntity.setCamilo(s); // bananaGoodsCamiloService.insert(bananaGoodsCamilo); bananaGoodsEntities.add(bananaGoodsCamiloEntity); } bananaGoodsCamiloService.insertBatch(bananaGoodsEntities,500); // bananaGoodsCamiloService.insertBatch(bananaGoodsEntities); return R.ok(); } /** * 修改 */ @RequestMapping("/update") @RequiresPermissions("generator:bananagoodscamilo:update") public R update(@RequestBody BananaGoodsCamiloEntity bananaGoodsCamilo){ BananaGoodsEntity bananaGoodsEntity = bananaGoodsService.selectById(bananaGoodsCamilo.getGoodsId()); bananaGoodsCamilo.setGoodsName(bananaGoodsEntity.getTitle()); bananaGoodsCamiloService.updateById(bananaGoodsCamilo); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") @RequiresPermissions("generator:bananagoodscamilo:delete") public R delete(@RequestBody Integer[] ids){ bananaGoodsCamiloService.deleteBatchIds(Arrays.asList(ids)); return R.ok(); } } <file_sep>package io.renren.modules.app.controller; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.RandomUtil; import cn.hutool.db.sql.Order; import com.baomidou.mybatisplus.mapper.EntityWrapper; import io.renren.common.utils.AliUtil; import io.renren.common.utils.PageUtils; import io.renren.common.utils.R; import io.renren.common.utils.WechatPayUtil; import io.renren.common.validator.Assert; import io.renren.common.validator.ValidatorUtils; import io.renren.modules.app.form.LoginForm; import io.renren.modules.app.service.UserService; import io.renren.modules.app.utils.JwtUtils; import io.renren.modules.banana.generator.entity.BananaGoodsCamiloEntity; import io.renren.modules.banana.generator.entity.BananaGoodsEntity; import io.renren.modules.banana.generator.entity.BananaOrderEntity; import io.renren.modules.banana.generator.entity.BananaUserEntity; import io.renren.modules.banana.generator.service.BananaGoodsCamiloService; import io.renren.modules.banana.generator.service.BananaGoodsService; import io.renren.modules.banana.generator.service.BananaOrderService; import io.renren.modules.banana.generator.service.BananaUserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.models.auth.In; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * APP登录授权 * * @author chenshun * @email <EMAIL> * @date 2017-03-23 15:31 */ @RestController @RequestMapping("/app/order") @Api("APP订单接口") public class AppOrderController { @Autowired private BananaGoodsService bananaGoodsService; @Autowired private BananaOrderService bananaOrderService; @Autowired private BananaGoodsCamiloService bananaGoodsCamiloService; @Autowired private BananaUserService bananaUserService; /** * 订单列表分页 */ @RequestMapping("info") @ApiOperation(value = "查询订单信息",notes = "根据订单id查询订单信息",response = BananaOrderEntity.class,httpMethod = "POST") @ApiImplicitParams({ @ApiImplicitParam(name = "orderid", value = "订单id", required = false, dataType = "int",paramType = "query"), }) public R info( @RequestParam(required = false) String orderid//订单id不能为空 ){ Assert.isNull(orderid,"订单id不能为空"); BananaOrderEntity bananaOrderEntity = bananaOrderService.selectById(orderid); return R.data(bananaOrderEntity); } /** * 订单列表分页 */ @RequestMapping("listPage") @ApiOperation(value = "订单列表分页",notes = "根据传入当前页面 每页数量查询订单列表",response = BananaOrderEntity.class,httpMethod = "POST") @ApiImplicitParams({ @ApiImplicitParam(name = "pagesize", value = "每页数量", required = false, dataType = "String",paramType = "query"), @ApiImplicitParam(name = "currentpage", value = "当前页面", required = false, dataType = "String",paramType = "query"), @ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "String",paramType = "query"), }) public R listPage( @RequestParam(required = false,defaultValue = "10") String pagesize,//每页数量 @RequestParam(required = false,defaultValue = "1") String currentpage,//当前页面 @RequestParam(required = false) Integer userId//用户id ){ Assert.isNull(userId,"用户id不能为空"); BananaUserEntity bananaUserEntity = bananaUserService.selectById(userId); if (bananaUserEntity == null) { return R.error(-1,"用户不存在"); } Map map = new HashMap(); map.put("page",currentpage); map.put("limit",pagesize); map.put("userId",userId); PageUtils pageUtils = bananaOrderService.queryPage(map); return R.data(pageUtils); } /** * 创建订单 */ @RequestMapping("createOrder") @ApiOperation(value = "创建订单接口",notes = "根据传入商品id,商品数量 充值账号,用户id创建商品订单",response = BananaOrderEntity.class,httpMethod = "POST") @ApiImplicitParams({ @ApiImplicitParam(name = "goodsid", value = "商品id", required = true, dataType = "String",paramType = "query"), @ApiImplicitParam(name = "count", value = "购买数量", required = true, dataType = "String",paramType = "query"), @ApiImplicitParam(name = "account", value = "充值账号", required = true, dataType = "String",paramType = "query"), @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String",paramType = "query"), @ApiImplicitParam(name = "isShare", value = "是否分享 0 未分享 1 已经分享", required = false, dataType = "String",paramType = "query"), }) public R createOrder( @RequestParam(required = false) Integer goodsid, @RequestParam(required = false) BigDecimal count, @RequestParam(required = false) String account, @RequestParam(required = false) Integer userId, @RequestParam(defaultValue = "0",required = false) Integer isShare//是否分享 0 未分享 1 已经分享 ){ // Assert.isBlank(account,"充值账号不能为空"); Assert.isNull(userId,"userId不能为空"); Assert.isNull(goodsid,"goodsid不能为空"); Assert.isNull(count,"count不能为空"); BananaGoodsEntity bananaGoodsEntity = bananaGoodsService.selectById(goodsid); if (bananaGoodsEntity == null) { R.error(-1,"商品id不存在"); } if (bananaGoodsEntity.getStatus() != 0) { return R.error(-1,"商品已经下架"); } BananaUserEntity bananaUserEntity = bananaUserService.selectById(userId); if (bananaUserEntity == null) { return R.error(-1,"用户不存在"); } if (bananaGoodsEntity.getTopUpWay() == 1){ EntityWrapper<BananaGoodsCamiloEntity> bananaGoodsCamiloEntityEntityWrapper = new EntityWrapper<>(); BananaGoodsCamiloEntity bananaGoodsCamiloEntity = new BananaGoodsCamiloEntity(); bananaGoodsCamiloEntity.setGoodsId(goodsid); bananaGoodsCamiloEntity.setStatus(0); bananaGoodsCamiloEntityEntityWrapper.setEntity(bananaGoodsCamiloEntity); int i = bananaGoodsCamiloService.selectCount(bananaGoodsCamiloEntityEntityWrapper); if (i < count.intValue()) { return R.error(-1,"该商品卡密库存不足"); } } if (count.doubleValue() < 1) { return R.error(-1,"购买数量不能小于1"); } BananaOrderEntity bananaOrderEntity = new BananaOrderEntity(); String orderid = "10" + RandomUtil.randomNumbers(9); bananaOrderEntity.setOrderid(orderid); bananaOrderEntity.setAccount(account);//充值账号 bananaOrderEntity.setUserId(userId);//用户id bananaOrderEntity.setCount(count);//数量 bananaOrderEntity.setCreateTime(new Date());//创建时间 bananaOrderEntity.setIsPay(0);//未支付 bananaOrderEntity.setGoodsid(goodsid);//商品id bananaOrderEntity.setCode(RandomUtil.simpleUUID());//支付code bananaOrderEntity.setTitle(bananaGoodsEntity.getTitle());//商品名称 bananaOrderEntity.setPic(bananaGoodsEntity.getPic());//商品图片 bananaOrderEntity.setStatus(0);//状态 0 未充值 bananaOrderEntity.setTopUpWay(bananaGoodsEntity.getTopUpWay());//充值方式 bananaOrderEntity.setUrl(bananaGoodsEntity.getExchangeAddress());//官网路径 if (isShare == 1) {//已经分享 bananaOrderEntity.setPrice(bananaGoodsEntity.getShaPrice());//分享单价 bananaOrderEntity.setTotalPrice(bananaOrderEntity.getPrice().multiply(bananaOrderEntity.getCount()));//总价 }else { bananaOrderEntity.setPrice(bananaGoodsEntity.getPrice());//分享单价 bananaOrderEntity.setTotalPrice(bananaOrderEntity.getPrice().multiply(bananaOrderEntity.getCount()));//总价 } bananaOrderService.insert(bananaOrderEntity); return R.ok().put("data",R.ok().put("orderid",bananaOrderEntity.getOrderid())); } /** * 支付成功 */ // @RequestMapping("paySuccess") // public R paySuccess(String code){//支付code // bananaOrderService.paySuccess(code); // return R.ok(); // } @RequestMapping("aliPay") @ApiOperation(value = "生成支付宝参数",notes = "根据订单id返回支付宝支付参数信息",response = BananaOrderEntity.class,httpMethod = "POST") @ApiImplicitParams({ @ApiImplicitParam(name = "orderid", value = "订单id", required = false, dataType = "int",paramType = "query"), }) public R aliPay( @RequestParam(required = false) String orderid ){ Assert.isNull(orderid,"orderid不能为空"); BananaOrderEntity bananaOrderEntity = bananaOrderService.selectById(orderid); if (bananaOrderEntity == null){ return R.error(-1,"订单不存在"); } bananaOrderEntity.setPayType(2);//设置支付宝支付 bananaOrderService.updateById(bananaOrderEntity);//修改支付宝支付 String map = AliUtil.appOrder("香蕉支付", bananaOrderEntity.getCode(), bananaOrderEntity.getTotalPrice()); return R.data(map); } @RequestMapping("wechatPay") @ApiOperation(value = "生成微信参数",notes = "根据订单id返回微信参数支付参数信息",response = BananaOrderEntity.class,httpMethod = "POST") @ApiImplicitParams({ @ApiImplicitParam(name = "orderid", value = "订单id", required = false, dataType = "nt",paramType = "query"), }) public R wechatPay( @RequestParam(required = false) String orderid ){ Assert.isNull(orderid,"orderid不能为空"); BananaOrderEntity bananaOrderEntity = bananaOrderService.selectById(orderid); if (bananaOrderEntity == null){ return R.error(-1,"订单不存在"); } bananaOrderEntity.setPayType(1);//设置微信支付 bananaOrderService.updateById(bananaOrderEntity);//修改为微信支付 Map<String, Object> map = WechatPayUtil.appOrder("香蕉支付", bananaOrderEntity.getCode(), bananaOrderEntity.getTotalPrice()); return R.data(map); } @RequestMapping("aliSuccess") public R aliSuccess( HttpServletRequest request ){ try { String code = AliUtil.payBack(request); if (code == null) { return R.error(-1,"支付异常"); } bananaOrderService.paySuccess(code); } catch (IOException e) { } return R.ok(); } @RequestMapping("wechatSuccess") public R wechatSuccess( HttpServletRequest request ){ try { String code = WechatPayUtil.payBack(request); if (code == null) { return R.error(-1,"支付异常"); } bananaOrderService.paySuccess(code); } catch (IOException e) { } return R.ok(); } } <file_sep>package io.renren.modules.banana.generator.dao; import io.renren.modules.banana.generator.entity.BananaOrderEntity; import com.baomidou.mybatisplus.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 订单表 * * @author chenweilong * @email <EMAIL> * @date 2018-12-24 20:54:53 */ @Mapper public interface BananaOrderDao extends BaseMapper<BananaOrderEntity> { } <file_sep>package io.renren.modules.banana.generator.controller; import java.util.Arrays; import java.util.Date; import java.util.Map; import cn.hutool.core.date.DateUtil; import com.baomidou.mybatisplus.mapper.EntityWrapper; import io.renren.common.utils.SpringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import io.renren.modules.banana.generator.entity.BananaUserEntity; import io.renren.modules.banana.generator.service.BananaUserService; import io.renren.common.utils.PageUtils; import io.renren.common.utils.R; /** * 用户表 * * @author chenweilong * @email <EMAIL> * @date 2018-12-24 20:54:53 */ @RestController @RequestMapping("generator/bananauser") public class BananaUserController { @Autowired private BananaUserService bananaUserService; /** * 列表 */ @RequestMapping("/list") @RequiresPermissions("generator:bananauser:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = bananaUserService.queryPage(params); BananaUserService bananaUserService = SpringUtils.getBean(BananaUserService.class); EntityWrapper<BananaUserEntity> bananaUserEntityEntityWrapper = new EntityWrapper<>(); bananaUserEntityEntityWrapper.where("last_time > {0}", DateUtil.format(new Date(),"yyyy-MM") + "-01 00:00:00"); int i = bananaUserService.selectCount(bananaUserEntityEntityWrapper); return R.ok().put("page", page).put("brisk",i); } /** * 信息 */ @RequestMapping("/info/{id}") @RequiresPermissions("generator:bananauser:info") public R info(@PathVariable("id") Integer id){ BananaUserEntity bananaUser = bananaUserService.selectById(id); return R.ok().put("bananaUser", bananaUser); } /** * 保存 */ @RequestMapping("/save") @RequiresPermissions("generator:bananauser:save") public R save(@RequestBody BananaUserEntity bananaUser){ bananaUserService.insert(bananaUser); return R.ok(); } /** * 修改 */ @RequestMapping("/update") @RequiresPermissions("generator:bananauser:update") public R update(@RequestBody BananaUserEntity bananaUser){ bananaUserService.updateById(bananaUser); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") @RequiresPermissions("generator:bananauser:delete") public R delete(@RequestBody Integer[] ids){ bananaUserService.deleteBatchIds(Arrays.asList(ids)); return R.ok(); } }
632a0d6176116bbd8be877fd209ece75a1e97898
[ "Java" ]
11
Java
chenweilong1022/banner
7d1a9cdb7d02cd526d918f95a7e21b0672074f51
2a23ebfba74f4252a4fce04f397ee05b7748e4b0
refs/heads/master
<file_sep>package com.huangxy.mcadapter; import android.view.View; /** * Created by huangxy on 2016/10/28. * https://github.com/GitSmark/McAdapter */ public class IAdapterView { public interface OnClickListener { void onClick(View view, int position); } public interface OnLongClickListener { boolean onLongClick(View view, int position); } public interface OnItemClickListener<T> { void onItemClick(IAdapterItem<?> parent, View view, int position, T item); } public interface OnItemLongClickListener<T> { boolean onItemLongClick(IAdapterItem<?> parent, View view, int position, T item); } } <file_sep>package com.huangxy.mcadapter; import android.view.View; import androidx.annotation.LayoutRes; /** * adapter的所有item必须实现此接口. * 通过返回{@link #getLayoutResId()}来自动初始化view,之后在{@link #onBindViews(View)}中就可以初始化item的内部视图了。<br> * * @author <NAME> * @date 2015/5/15 */ public interface IAdapterItem<T> { /** * @return item布局文件的layoutId */ @LayoutRes int getLayoutResId(); /** * 初始化views */ void onBindViews(final View root); /** * 设置view的参数,可以在这里设置事件监听,只执行一次 * 调用getBindModel()、getBindPosition()可获取Item对应数据及位置下标 */ void onSetViews(); /** * 根据数据来设置item的内部views * @param model 数据list内部的model */ void onUpdateViews(T model, int position); }<file_sep>package com.huangxy.mcadapter; /** * Created by huangxy on 2016/10/28. * https://github.com/GitSmark/McAdapter * 配合McAdapter和McRcvAdapter多布局时使用 */ public class McEntity<T> extends McAdapterModel { private Class<? extends IAdapterItem> adapterItem; private int itemType = 0; private T itemEntity; public McEntity(){} @Deprecated public McEntity(T itemEntity, int itemType){ this.itemEntity = itemEntity; this.itemType = itemType; } public McEntity(T itemEntity, Class<? extends IAdapterItem> adapterItem){ this.adapterItem = adapterItem; this.itemEntity = itemEntity; } @Override public Class<? extends IAdapterItem> getAdapterItem() { return adapterItem; } public void setAdapterItem(Class<? extends IAdapterItem> adapterItem) { this.adapterItem = adapterItem; } @Override public T getItemEntity() { return itemEntity; } public void setItemEntity(T itemEntity) { this.itemEntity = itemEntity; } @Deprecated public int getItemType() { return itemType; } @Deprecated public void setItemType(int itemType) { this.itemType = itemType; } } <file_sep>package com.huangxy.mcadapter; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import com.huangxy.mcadapter.adapterItem.McAdapterItem3; import com.huangxy.mcadapter.adapterItem.McAdapterItem4; import com.huangxy.mcadapter.adapterItem.McAdapterItem5; import com.huangxy.mcadapter.adapterItem.McAdapterItem6; import com.huangxy.mcadapter.adapterModel.TestEntity5; import com.huangxy.mcadapter.adapterModel.TestEntity6; import java.util.ArrayList; import java.util.List; public class MultiActivity extends AppCompatActivity { private RecyclerView recyclerView; private List<McEntity> list = new ArrayList<>(); private List<McAdapterModel> data = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_multi); data.add(new McEntity("111111", McAdapterItem3.class)); //使用通用的McEntity,并指定getAdapterItem类型 data.add(new McEntity("123123", McAdapterItem4.class)); data.add(new TestEntity5("123456")); //自定义adapterModel建议继承自McAdapterModel,并指定getAdapterItem类型 data.add(new TestEntity6("666666")); list.add(new McEntity("111111", 0)); //不建议直接实现IAdapterModel接口指定getItemType类型,不利于复用 list.add(new McEntity("123123", 1)); list.add(new McEntity(new TestEntity5("123456"), 2)); list.add(new McEntity(new TestEntity6("666666"), 3)); recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); //recyclerView.setAdapter(new McRcvAdapter(list, McAdapterItem3.class, McAdapterItem4.class, McAdapterItem5.class, McAdapterItem6.class)); recyclerView.setAdapter(new McRcvAdapter(data)); } }<file_sep>package com.huangxy.mcadapter; import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; /** * Created by huangxy on 2016/10/29. * https://github.com/GitSmark/McAdapter */ public class MainActivity extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.McAdapter_btn1).setOnClickListener(this); findViewById(R.id.McAdapter_btn2).setOnClickListener(this); findViewById(R.id.McAdapter_btn3).setOnClickListener(this); findViewById(R.id.McAdapter_btn4).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.McAdapter_btn1: ShowSample(1); break; case R.id.McAdapter_btn2: ShowSample(2); break; case R.id.McAdapter_btn3: ShowSample(3); break; case R.id.McAdapter_btn4: ShowSample(4); break; default: break; } } private void ShowSample(int sampleNum){ Intent intent = new Intent(this, SampleActivity.class); intent.putExtra("sampleNum", sampleNum); startActivity(intent); } } <file_sep>package com.huangxy.mcadapter.adapterItem; import android.widget.TextView; import com.huangxy.mcadapter.McAdapterItem; import com.huangxy.mcadapter.R; import com.huangxy.mcadapter.adapterModel.TestEntity6; import butterknife.BindView; /** * Created by huangxy on 2016/10/29. * https://github.com/GitSmark/McAdapter */ public class McAdapterItem6 extends McAdapterItem<TestEntity6> { @BindView(R.id.tv_item2) TextView tv; @Override public int getLayoutResId() { return R.layout.layout_item2; } @Override public void onUpdateViews(TestEntity6 model) { tv.setText(model.title); } }<file_sep>package com.huangxy.mcadapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import java.util.List; import butterknife.ButterKnife; /** * @author <NAME> * @date 2015/11/29 */ public abstract class CommonPagerAdapter<T extends IAdapterItem> extends BasePagerAdapter<View> implements IAdapter<T>{ private List<T> mData; LayoutInflater mInflater; public CommonPagerAdapter(List<T> data) { mData = data; } @Override public int getCount() { return mData.size(); } @Override protected View getViewFromItem(View item) { return item; } @Override protected View getWillBeAddedView(View item, int position) { return item; } @Override protected View getWillBeDestroyedView(View item, int position) { return item; } @Override public void setPrimaryItem(ViewGroup container, int position, @NonNull Object object) { // 这里应该放置数据更新的操作 if (object != currentItem) { IAdapterItem<T> item = ((IAdapterItem<T>) ((View) object).getTag()); item.onUpdateViews(mData.get(position), position); } super.setPrimaryItem(container, position, object); } @Override protected View onCreateItem(ViewGroup container, int position) { if (mInflater == null) { mInflater = LayoutInflater.from(container.getContext()); } IAdapterItem<T> item = onCreateItem(getItemType(position)); View view = mInflater.inflate(item.getLayoutResId(), null); view.setTag(item); // 万一你要用到这个item可以通过这个tag拿到 ButterKnife.bind(item, view);// 绑定ButterKnife item.onBindViews(view); item.onSetViews(); return view; } /** * 强烈建议返回string,int,bool类似的基础对象做type */ @Override public Object getItemType(int position) { return getItemType(mData.get(position)); } @Override public Object getItemType(T t) { return -1; // default } @Override public void setData(@NonNull List<T> data) { mData = data; notifyDataSetChanged(); } @Override public List<T> getData() { return mData; } @Override public T getItem(int position) { return mData.get(position); } } <file_sep># McAdapter ![Android Arsenal](https://img.shields.io/badge/Android%20%20%20%20%20Arsenal-%20McAdapter%20-brightgreen.svg?style=flat) [![](https://img.shields.io/badge/JitPack-1.3.0-blue.svg)](https://jitpack.io/#GitSmark/McAdapter) 一句话实现通用Adapter,支持ListView跟recyclerView的无缝切换 ------ | [ListView+GridView] | [RecyclerView] | [ViewPager] | | :----------------------------: | :------------------------------: | :---------------------------: | | `McAdapter`(CommonAdapter) | `McRcvAdapter`(CommonRcvAdapter) | CommonPagerAdapter | - [x] 支持多布局对应多种model - [x] item会根据内部type来做自动复用 - [x] 完美实现可拔插通用Adapter,支持item多处复用 - [x] 一个item仅会触发一次onBindViews()绑定视图,提升效率 - [x] 一个item仅会调用一次onItemAction(),避免重复建立listener - [x] 提供了getBindPosition()方法获取item对应的位置 - [x] 提供了getBindModel()方法获取item绑定的数据 - [x] 支持ButterKnife注入 Usage ----- 1. 在项目工程project下的build.gradle文件添加: ``` repositories { maven { url "https://jitpack.io" } } ``` 2. 在项目工程app下的build.gradle文件添加: ``` implementation 'com.github.GitSmark:McAdapter:1.3.0' ``` * 实现你的AdapterItem,建议使用McAdapterItem,如果只有一个布局也可直接继承自IAdapterItem ```java public class MyAdapterItem extends McAdapterItem<String> { private TextView tv; @Override public int getLayoutResId() { return R.layout.layout_item; } @Override public void onBindViews(View root) { tv = (TextView) root.findViewById(R.id.item); } @Override public void onUpdateViews(String model) { tv.setText(model); } @Override public void onItemAction(int position) {          //tv.setOnClickListener(this); } } ``` * 设置Adapter,McAdapterItem推荐配合McEntity多布局使用,支持添加监听事件,更多用法详见示例 ```java listview.setAdapter(new McAdapter(this, data, McAdapterItem1.class)); //添加监听 listview.setAdapter(new McAdapter(list, McAdapterItem3.class, McAdapterItem4.class)); //多布局 listview.setAdapter(new CommonAdapter(data) { @NonNull @Override public IAdapterItem onCreateItem(Object type) { return new McAdapterItem2(); } }); listview.setAdapter(new CommonAdapter<McEntity>(list, 2) { @Override public Object getItemType(McEntity obj) { return obj.getItemType(); } @NonNull @Override public IAdapterItem onCreateItem(Object type) { switch (((int) type)) { case 0: return new McAdapterItem3(); case 1: return new McAdapterItem4(); default: throw new IllegalArgumentException("Illegal type"); } } }); ``` Sample ------ ![Get it on Google Play](http://www.android.com/images/brand/get_it_on_play_logo_small.png) Contact -------- Have problem? Just [tweet me](https://twitter.com/huangxy) or [send me an email](mailto:<EMAIL>). Thanks originator [tianzhijiexian](https://github.com/tianzhijiexian/CommonAdapter) and my friend [chenyp](https://github.com/chenyp1994). License ---------- Copyright 2016 huangxy@GitSmark 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.
a44ca6322a6253a9579b9947fc5f82111fce44ec
[ "Markdown", "Java" ]
8
Java
GitSmark/McAdapter
3dd1d456e970ef512da732f2dcdc2702d1d1b378
e889eeb68ce62dce18bcc3b6169ba29a0ddaa62c
refs/heads/master
<file_sep><?php class ContactController { public function __construct() { } public function run() { include View . 'header.php'; include View . 'contact.php'; include View . 'footer.php'; } } ?> <file_sep><?php class TechEducationController{ public function __construct() { } public function run() { include View . 'header.php'; include View . 'tech-education.php'; include View . 'footer.php'; } } ?> <file_sep><?php // if(isset($_FILES['fileToUpload']) && $_FILES['fileToUpload']['error'] == 0) // { // if($_FILES['fileToUpload']['size']<= 4000000) // { // $infoFicher = pathinfo($_FILES['fileToUpload']['name']); // $extensionUpload = $infoFicher['extension']; // $extentionAutoriser = array ('jpg', 'jpeg', 'gif', 'png'); // if (in_array($extensionUpload, $extentionAutoriser)) // { // mkdir("upload/", 0777, true); // move_upload_file($_FILES['fileToUpload']['tmp_name'] 'upload/' . basename($_FILES['fileToUpload']['name'])); // // echo "L'envoi a bien été effectué!"; // // // } // } // } // else { // echo "erreur"; // } ?> <?php // Connexion à la base de données try { $bdd = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', 'root'); } catch(Exception $e) { die('Erreur : '.$e->getMessage()); } // Insertion du message à l'aide d'une requête préparée $req = $bdd->prepare('INSERT INTO Team (url_Img, Title, Descrip) VALUES(?, ?, ?)'); $req->execute(array($_POST['fileToUpload'], $_POST['name'], $_POST['message'])); // Redirection du visiteur vers la page du minichat // header('Location: formulaireEquipe.php'); ?> <file_sep><div class="container formulaireSelection"> <div class="row formulaireMain"> <div class="col-md-9 formulaireLeft"> <h3>Veuillez soumettre votre <span class="marron">Equipe</span> </h3> <p>Nous vous répondrons dans les meilleurs délais.</p> <form role="form" class=""enctype="multipart/form-data" action="?page=formulaireEquipe" method="post" > <div class="fichier"> <div class="form-group"> <label class="fichierok">Votre Fichier : <div class="fichierDiv"> <input type="hidden" name="MAX_FILE_SIZE" value="4000000" /> <input type="file" name="fichier" id="fileToUpload"> </div> </label> </div> </div> <div class="form-group"> <label>Nom : <input type="text" class="form-control" id="name" name="name" placeholder="Ex: Dupont" required> </label> </div> <br/> <div class="form-group"> <label>Description : <textarea class="form-control" name="message" type="textarea" id="message" maxlength="500" rows="7" cols="110"> </textarea> </label> </div> <input action ="?page=formulaireEquipe" type="submit" id="submit" name="submit" class="btn btn_success2 Send" value="Envoyer"/> </form> </div> </div> </div> <?php // Connexion à la base de données try { $bdd= new PDO ('mysql:host=localhost; dbname=test', 'root', 'root'); echo "connexion reussi"; } catch(Exception $e) { die('Erreur : '.$e->getMessage()); } $reponse=$bdd->query("SELECT * FROM Team"); while($donnees=$reponse->fetch()) { echo '<p>' . $donnees ['Title'] . '</p>'; } $reponse->closeCursor(); ?> <?php if(!empty($_FILES)) { $file_name = $_FILES['fichier']['name']; $file_extension = strrchr($file_name, "."); $file_tmp_name = $_FILES['fichier']['tmp_name']; $file_dest = 'upload/' .$file_name; //'files/' .$file_name; $extension_autorisees = array('.pdf', '.PDF', '.png'); var_dump(in_array($file_extension, $extension_autorisees)); if(in_array($file_extension, $extension_autorisees)){ if(move_uploaded_file($file_tmp_name, $file_dest)){ echo 'Fichier envoyé avec succès'; } else { echo "Une erreur est survenue lors de l'envoie du fichier"; } } else { echo "Seul les fichiers PDF sont autorisées"; } } ?> <file_sep><?php class SelectionProjetController{ public function __construct() { } public function run() { include View . 'header.php'; include View . 'selection-projet.php'; include View . 'footer.php'; } } ?> <file_sep># php-test-pictures <file_sep><?php define ('View', 'Views/'); define ('Controller', 'Controller/'); define ('Model', 'Model/'); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- favicon --> <link rel="shortcut icon" href="./img/favicon.ico" type="image/x-icon"> <link rel="icon" href="./img/favicon.ico" type="image/x-icon"> <!-- bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- caroussel --> <link rel="stylesheet" type="text/css" href="stylesheets/sass/style_carousel.css" /> <link rel="stylesheet" type="text/css" href="stylesheets/jquery.jscrollpane.css" media="all" /> <!-- fichier css --> <link rel="stylesheet" type="text/css" href="stylesheets/sass/style.css" /> <link rel="stylesheet" type="text/css" href="stylesheets/sass/contact.css" /> <link rel="stylesheet" type="text/css" href="stylesheets/sass/equipe.css" /> <link rel="stylesheet" type="text/css" href="stylesheets/sass/faq.css" /> <link rel="stylesheet" type="text/css" href="stylesheets/sass/logement.css" /> <link rel="stylesheet" type="text/css" href="stylesheets/sass/mission.css" /> <link rel="stylesheet" type="text/css" href="stylesheets/sass/valeur.css" /> <link rel="stylesheet" type="text/css" href="stylesheets/sass/selection-projet.css" /> <link rel="stylesheet" type="text/css" href="stylesheets/sass/formulaireSelection.css" /> <!-- google font => police de caracteres --> <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet"/> <link href="https://fonts.googleapis.com/css?family=Abel" rel="stylesheet"/> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300" rel="stylesheet"/> <!-- <link rel="stylesheet" href="../stylesheets/index.css"> <link rel="stylesheet" href="../stylesheets/footer.css"> <link rel="stylesheet" href="../stylesheets/icomoon.css"> <link rel="stylesheet" href="../stylesheets/nav.css"> --> <!-- <link rel="stylesheet" href="../stylesheets/tech.css"> <link rel="stylesheet" href="../stylesheets/logement.css"> <link rel="stylesheet" href="../stylesheets/sante.css"> --> <!-- CSS page projet --> <!-- <link rel="stylesheet" href="../stylesheets/projet_logement.css"> <link rel="stylesheet" href="../stylesheets/projet_tech.css"> <link rel="stylesheet" href="../stylesheets/projet_sante.css"> --> <!-- CSS MOBILE --> <link rel="stylesheet" href="../stylesheets/mobile.css"> <!-- titre --> <title>4wings</title> </head> <body> <?php include (Controller . 'routerController.php') ?> <file_sep><?php class SanteController{ public function __construct() { } public function run(){ include View . 'header.php'; include View . 'sante.php'; include View . 'footer.php'; } } ?> <file_sep><?php class AccueilController { public function __construct() { } public function run() { include View . 'header.php'; include View . 'accueil.php'; include View . 'footer.php'; } } ?> <file_sep><?php $page = isset($_GET['page']) ? htmlentities($_GET['page']) : 'default'; switch ($page) { case 'accueil': include(Controller . 'accueilController.php'); $controller = new AccueilController; break; case 'contact': include(Controller . 'contactController.php'); $controller = new ContactController(); break; case 'equipe': include(Controller . 'equipeController.php'); $controller = new EquipeController(); break; case 'faq': include(Controller . 'faqController.php'); $controller = new FaqController(); break; case 'logement': include(Controller . 'logementController.php'); $controller = new LogementController(); break; case 'mission': include(Controller . 'missionController.php'); $controller = new MissionController(); break; case 'projet-logement': include(Controller . 'projet-logementController.php'); $controller = new ProjetLogementController(); break; case 'projet-sante': include(Controller . 'projet-santeController.php'); $controller = new ProjetSanteController(); break; case 'projet-tech-education': include(Controller . 'projet-tech-educationController.php'); $controller = new ProjetTechEducationController(); break; case 'sante': include(Controller . 'santeController.php'); $controller = new SanteController(); break; case 'selection-projet': include(Controller . 'selection-projetController.php'); $controller = new SelectionProjetController(); break; case 'slider': include(Controller . 'sliderController.php'); $controller = new SliderController(); break; case 'tech-education': include(Controller . 'tech-educationController.php'); $controller = new TechEducationController(); break; case 'valeur': include(Controller . 'valeurController.php'); $controller = new ValeurController(); break; case 'formulaire': include(Controller . 'formulaireSelectionController.php'); $controller = new FormulaireSelectionController(); break; case 'formulaireEnvoi': include(Controller . 'formulaireEnvoiController.php'); $controller = new FormulaireEnvoi(); break; case 'formulaireEquipe'; include(Controller . 'formulaireEquipeController.php'); $controller = new FormulaireEquipe(); break; default: include(Controller . 'accueilController.php'); $controller = new AccueilController(); break; } $controller->run(); ?> <file_sep><?php class FormulaireEnvoi { public function __construct(){ } public function run() { include View . 'formulaireEnvoi.php'; } } ?> <file_sep><?php class FaqController { public function __construct(){ } public function run() { include View . 'header.php'; include View . 'faq.php'; include View . 'footer.php'; } } ?> <file_sep><?php $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = ""; $dbName = "4wings"; $db = new mysql($dbHost, $dbUsername, $dbPassword, $dbName); if ($db->conn) ?>
043f40697b8925ef02a7f58eeffd4c4f65203105
[ "Markdown", "PHP" ]
13
PHP
weichuan888/4wings-test
499b4376e4aeb759079d48db99668ef57106d85f
66a4b37381d8c577292d89ee83ad5d7b57e8cf43
refs/heads/master
<file_sep>import React from "react"; import { FaRegHandPaper } from "react-icons/fa"; const BuyCancel = () => { return ( <div> <div className="cancelPageOneBox"> <FaRegHandPaper size="5rem" className="buy" /> <div className="buyBox"> <h>Thanks for your help. Your opinion is really important to us</h> <div className="lastt"> <b>You subscription has been successfully canceled.</b> </div> </div> <div className="buyBtnBox"> <button className="buyBtn"> Done </button> </div> </div> </div> ); }; export default BuyCancel; <file_sep>import "./App.css"; import React, { useState } from "react"; import OrganizationInfo from "./components/OrganizationInfComponents/OrganizationInfo"; import Header from "./components/navbarCompoents/Header"; import Sidder from "./components/navbarCompoents/sidder"; import PlanDetails from "./components/planDetailsComponents/BasePlanDetails"; import Invoices from "./components/invoicesCompoents/Invoices"; import { useEffect } from "react"; import BasePayment from "./components/paymentCompoents/BasePayment"; import axios from "axios"; import Cancel from "./components/CancelCompoents/Cancel"; function App() { const [api, setApi] = useState([]); //At the beginning, api is an empty array const [isLoading, setLoading] = useState(true); const [isOpen, setIsOpen] = useState(false); // The REST API endpoint const API_URL = "https://mocki.io/v1/cffdf9e2-36af-42b7-ae34-6bc7f197169f"; // Define the function that fetches the data from API const fetchData = async () => { setLoading(true); const response = await axios.get(API_URL); setApi(response.data); setLoading(false); //change the state of isLoading to false so //that application knows that loading has completed and all is clear to render the data. }; // Trigger the fetchData after the initial render by using the useEffect hook useEffect(() => { fetchData(); }, []); /* make use of isLoading to either display the loading message or the requested data. The data will be displayed when isLoading is false, else a loading message will be shown on the screen */ if (isLoading) { return "Loading..."; } const handleOpen = (isOpen) => { setIsOpen(isOpen); }; return ( <div className="component-app"> <div className="page"> <div className="sidebar"> <Sidder onOpen={handleOpen} /> </div> <div className={`content ${isOpen && "open"}`}> <Header /> <div className="content-components"> <OrganizationInfo data={api} /> <PlanDetails data={api} /> <BasePayment data={api} /> <Invoices data={api} /> </div> {(api.organization.plan_details.plan_type === "Standard" || api.organization.plan_details.plan_type === "Enterprise") && ( <div className="content"> <Cancel /> </div> )} </div> </div> </div> ); } export default App; <file_sep>import Chart from "react-apexcharts"; import React from "react"; export default class Charts extends React.Component { constructor(props) { super(props); this.state = { optionsRadial: { plotOptions: { radialBar: { startAngle: 0, endAngle: 360, hollow: { margin: 0, size: "100%", background: "blue", image: undefined, imageOffsetX: 20, imageOffsetY: 20, position: "front", dropShadow: { enabled: true, top: 10, left: 0, blur: 1, opacity: 0.24, }, }, track: { background: "blue", strokeWidth: "90%", margin: 0, // margin is in pixels dropShadow: { enabled: true, top: -3, left: 0, blur: 4, opacity: 0.35, }, }, dataLabels: { showOn: "always", name: { offsetY: -10, show: true, color: "#85f", fontSize: "25px", }, value: { formatter: function (val) { return val; }, color: "#543", fontSize: "25px", show: true, }, }, }, }, fill: { type: "gradient", gradient: { shade: "dark", type: "horizontal", shadeIntensity: 0.75, gradientToColors: ["#ABE5A1"], inverseColors: true, opacityFrom: 1, opacityTo: 1, stops: [0, 100], }, }, stroke: { lineCap: "round", }, labels: [], }, seriesRadial: [this.props.percentage * 100], optionsRadial1: { plotOptions: { radialBar: { startAngle: 0, endAngle: 360, hollow: { margin: 0, size: "65%", background: "#fff", image: undefined, imageOffsetX: 0, imageOffsetY: 0, position: "front", dropShadow: { enabled: true, top: 1, left: 0, blur: 1, opacity: 0.24, }, }, track: { background: "#fff", strokeWidth: "37%", margin: 0, // margin is in pixels dropShadow: { enabled: true, top: -3, left: 0, blur: 4, opacity: 0.35, }, }, dataLabels: { showOn: "always", name: { offsetY: 0, show: true, color: "#888", fontSize: "25px", }, value: { formatter: function (val) { return val; }, color: "#888", fontSize: "25px", show: true, }, }, }, }, fill: { type: "gradient", colors: ["#FF00FF"], gradient: { shade: "dark", type: "horizontal", shadeIntensity: 0.5, gradientToColors: ["#43467F", "#BA55D3", "rgb(61, 61, 175)"], opacityFrom: 5, opacityTo: 5, stops: [0, 100], }, }, stroke: { lineCap: "round", }, labels: ["%"], }, }; } render() { return ( <Chart series={this.state.seriesRadial} options={this.state.optionsRadial1} color="#8a13478c" type="radialBar" width="300" align="center" /> ); } } <file_sep>import VISA from "./imgs/visatwo.PNG"; import "./payment.css"; import { useState } from "react"; import { FaTimes } from "react-icons/fa"; import React from "react"; import SlidingPane from "react-sliding-pane"; import UpdatePaymentMethod from "./UpdatePaymentMethod"; import Pay from "./imgs/pay.PNG"; const PaymentWithData = ({ apiData }) => { const [state, setState] = useState({ isPaneOpen: false, isPaneOpenLeft: false, }); return ( <div> <div className="headPlanDetPos"> <h>Current Payment Method</h> </div> <div className="boxPaymentData"> <div className="noPaymentBox"> <img className="visiImg" src={`${ apiData.organization.payment_method.cc_type === "VISA" ? VISA : Pay }`} /> <div className="paymentDatabox"> <div className="paymentDataboxA"> <b>{apiData.organization.payment_method.cc_type}</b> <div className="paymentDataboxAA"> <b>*{apiData.organization.payment_method.last_four_digits}</b> </div> </div> <div className="paymentDataboxB"> <h>{apiData.organization.payment_method.card_holder_name}</h> </div> </div> <div className="noPaymentDataBtnBox"> <button className="noPaymentDataBtn" onClick={() => setState({ isPaneOpenLeft: true })} > {" "} Update Method{" "} </button> </div> </div> <SlidingPane closeIcon={ <div> <FaTimes className="close" //style={{ color: "red", cursor: "pointer" }} /> <b className="titleAddPayment">Update Payment Method</b> </div> } isOpen={state.isPaneOpenLeft} //title="Hey, it is optional pane title. I can be React component too." from="right" width="500px" onRequestClose={() => setState({ isPaneOpenLeft: false })} > <UpdatePaymentMethod /> </SlidingPane> </div> </div> ); }; export default PaymentWithData; <file_sep>import React from "react"; import "./Navbar.css"; const Header = () => { return ( <div> <div className="boxHeader"> <div className="boxHeaderA"> <div className="titleHeader"> <b>Settings</b> </div> <div className="boxHeaderB"> <h className="general">General</h> <h className="disActive">User</h> <h className="disActive">Team</h> <h className="disActive">Localization</h> <h className="disActive">Exclude Lists</h> <div className="posAct"> <b className="activetitle">Usage & Billing</b> </div> </div> </div> </div> </div> ); }; export default Header; <file_sep>import "./OrganizationInfo.css"; const Input = ({ data, ...rest }) => { return ( <input type="text" name="name" className="Input" value={data} {...rest} /> ); }; export default Input; <file_sep>import Slider from "react-input-slider"; import React, { useState } from "react"; function SliderRange({ onChange, api }) { const [state, setState] = useState({ x: api.organization.plan_details.mua }); return ( <div> <div className="slider" style={{ marginTop: "30px", marginLeft: "260px", }} > <Slider styles={{ track: { backgroundColor: "gray", width: 800, }, active: { backgroundColor: "#ff0075;", }, thumb: { width: 30, height: 30, }, disabled: { opacity: 0.5, }, }} xstep={1} xmin={0} xmax={50000} // axis="x" x={state.x} onChange={({ x }) => { setState((state) => ({ ...state, x })); onChange(x); }} /> </div> </div> ); } export default SliderRange; <file_sep>import React from "react"; import { useState } from "react"; import { FaTimes } from "react-icons/fa"; import SlidingPane from "react-sliding-pane"; import BuyCancel from "./BuyCancel"; const ReasonsCancel = ({ resonsOfCancel = [] }) => { const [state, setState] = useState({ isPaneOpen: false, isPaneOpenLeft: false, }); return ( <div> <div className="cancelPageOneBox"> <div className="resonBox"> <h className="textCancelReson"> We re sorry to see you go. In order to process the cancelation, we need to ask you a few simple questions. This will help us improve the products for others. </h> </div> <div className="resonQuestion"> <b>Why have you decided to cancel your subscription?</b> </div> {resonsOfCancel.map((data, key) => { return ( <div key={key}> <div className="causesCancel"> <input className="inputCancel" value={data}></input> </div> </div> ); })} <div className="footerCancel"> <div className="btnCancel-AA"> <button className="btnCancelStyle">Don't Cancel</button> </div> <div className="btnUpdate"> <button className="btnCancelStyle-A" onClick={() => setState({ isPaneOpenLeft: true })} > Cancel Subscription </button> </div> </div> <SlidingPane closeIcon={ <div> <FaTimes className="close" /> <b className="titleAddPayment">Cancel Subscription</b> </div> } isOpen={state.isPaneOpenLeft} from="right" width="500px" onRequestClose={() => setState({ isPaneOpenLeft: false })} > <BuyCancel /> </SlidingPane> </div> </div> ); }; export default ReasonsCancel; <file_sep>import React from "react"; const PlaneType = ({ imgPlane, namePlane, price, pmonth, planBtn, reach, fetureS, talk, feturesAll = [], className, onClickStandard, classNameOfBtn, classNameOfBtnEn, }) => { return ( <div> <div className={className}> <div className="simgChange"> <img className="scimgg" src={imgPlane} alt="pic" /> </div> <div className="titChangeBox"> <b>{namePlane}</b> </div> <div className="standardBoxChange-A"> <b>{price}</b> </div> <div className="standardBoxChange-AA"> <b> {reach}</b> </div> <div className="standardBoxChange-B"> <h> {talk}</h> </div> <div className="standardBoxChange-B"> <h> {pmonth}</h> </div> <div className="bttnChnage"> <button className={`${ namePlane === "Standard" ? classNameOfBtn : classNameOfBtnEn } `} onClick={onClickStandard} > {planBtn} </button> </div> <div className="listst"> <b>{fetureS}</b> </div> {feturesAll.map((data) => { return ( <div className="listCh"> <b>* {data}</b> </div> ); })} </div> </div> ); }; export default PlaneType; <file_sep>import React from "react"; import "./Cancel.css"; import { useState } from "react"; import { FaTimes } from "react-icons/fa"; import SlidingPane from "react-sliding-pane"; import CancelPageOne from "./CancelPageOne"; const Cancel = () => { const [state, setState] = useState({ isPaneOpen: false, isPaneOpenLeft: false, }); return ( <div> <div className="boxCancel"> <div className="cancelHeader"> <b onClick={() => setState({ isPaneOpenLeft: true })}> {" "} CANCEL SUBSCRIPTION </b> </div> <h className="cancelTxt"> All future payments will be canceled. Your plan ends on 11/11/2021 </h> </div> <SlidingPane closeIcon={ <div> <FaTimes className="close" /> <b className="titleAddPayment">Cancel Subscription</b> </div> } isOpen={state.isPaneOpenLeft} from="right" width="500px" onRequestClose={() => setState({ isPaneOpenLeft: false })} > <CancelPageOne /> </SlidingPane> </div> ); }; export default Cancel; <file_sep>import React from "react"; import InputMask from "react-input-mask"; import { BsExclamation } from "react-icons/bs"; const UpdatePaymentMethod = () => { return ( <div> <h>Card Number</h> <div className="poss"> <InputMask class="inputPosUpdate" placeholder="Enter card number Here... " mask="9999 9999 9999 9999 9999" /> </div> <div className="boxCardHolderName"> <h>Card Holder Name</h> <div className="poss"> <input class="inputPosCardUpdate" placeholder="Cardholder name... " ></input> </div> </div> <div className="boxCardHolderName"> <h>Expiry Date</h> </div> <div className="boxCvvData"> <div className="poss"> <InputMask class="inputPosCvv" placeholder="MM" mask="99" /> <div className="line"> <h>--</h> </div> <div className="yy"> <InputMask class="inputPosCvv" placeholder="YY" mask="99" /> </div> </div> </div> <div className="cvvboxUpdate"> <h>CVV/CVC</h> <div className="cvvSpaceUpdate"> <InputMask class="inputPosCvv" placeholder="123" mask="999" /> <div className="iAdd"> <BsExclamation size="2.2rem" /> </div> </div> </div> <div className="footerUpdatePayment"> <div className="btnUpdateCancel"> <button className="btnCancelStyle">Cancel</button> </div> <div className="btnUpdate"> <button className="btnUpdateStyleA">Update</button> </div> </div> </div> ); }; export default UpdatePaymentMethod; <file_sep>import "./payment.css"; import NoPayment from "./imgs/pay.PNG"; import SlidingPane from "react-sliding-pane"; import React, { useState } from "react"; import { FaTimes } from "react-icons/fa"; import AddPaymentMethod from "./AddPaymentMethod"; const Payment = () => { const [state, setState] = useState({ isPaneOpen: false, isPaneOpenLeft: false, }); return ( <div> <div className="headPlanDetPos"> <h>Current Payment Method</h> </div> <div className="boxPayment"> <div className="noPaymentBox"> <img src={NoPayment} alt="pic" /> <div className="headerPay"> <b> No Payment Method Available</b> </div> <div className="noPaymentBtnBox"> <button className="noPaymentBtn" onClick={() => setState({ isPaneOpenLeft: true })} > {" "} Add Payment Method{" "} </button> </div> </div> <SlidingPane closeIcon={ <div> <FaTimes className="close" /> <b className="titleAddPayment">Add Payment Method</b> </div> } isOpen={state.isPaneOpenLeft} from="right" width="500px" onRequestClose={() => setState({ isPaneOpenLeft: false })} > <AddPaymentMethod /> </SlidingPane> </div> </div> ); }; export default Payment; <file_sep>import React from "react"; import Logouserpiolt from "./imgs/userpilot.PNG"; import { FaAngleRight, FaUserFriends } from "react-icons/fa"; import { FiBarChart } from "react-icons/fi"; import { useState } from "react"; import { DiChrome } from "react-icons/di"; import { FiLayers } from "react-icons/fi"; import { FiSettings } from "react-icons/fi"; import { BiAlignRight, BiAlignLeft } from "react-icons/bi"; const Sidder = ({ onOpen }) => { const [isClose, setIsColse] = useState(true); const [profileInfo, setProfileInfo] = useState(false); return ( <div> <div className={`${isClose ? "siderBoxClose" : "siderBox"}`}> <div className="BigsiderBox"> <div className="siderboxA"> <img src={Logouserpiolt} className="imglogouer" style={{ display: isClose ? "none" : "block" }} alt="pic" /> <BiAlignLeft size="2rem" className="imgClosIconClose" style={{ display: !isClose ? "none" : "block" }} onClick={() => { setIsColse(false); onOpen(true); }} ></BiAlignLeft> <BiAlignRight size="2rem" className="imgClosIconCloseBB" style={{ display: isClose ? "none" : "block" }} onClick={() => { setIsColse(true); onOpen(false); }} ></BiAlignRight> </div> <div className="siderboxB"> <FaUserFriends size="2rem" className={`${isClose ? "imgClosIconClose" : "imggesOpen"}`} ></FaUserFriends> <b className="txtSid" style={{ display: isClose ? "none" : "block" }} > PEOPLE </b> <FaAngleRight className="jj" size="1rem" onClick={() => { setProfileInfo(!profileInfo); }} style={{ display: isClose ? "none" : "block" }} ></FaAngleRight> {!isClose && profileInfo == true && ( <React.Fragment> <div className="boxInfoProfile"> <div className="InfoProfile"> <h>Users</h> </div> <div className="InfoProfileA"> <h>Companies</h> </div> <div className="InfoProfileA"> <h>Segments</h> </div> </div> </React.Fragment> )} </div> <div className="siderboxC"> <FiBarChart size="2rem" className={`${isClose ? "imgClosIconClose" : "imggesOpen"}`} > {" "} </FiBarChart> <b className="txtSid" style={{ display: isClose ? "none" : "block" }} > GROWTH INSIGHTS </b> </div> <div className="siderboxC"> <FiLayers size="2rem" className={`${isClose ? "imgClosIconClose" : "imggesOpen"}`} > {" "} </FiLayers> <b className="txtSid" style={{ display: isClose ? "none" : "block" }} > ENGAGEMENT LAYER </b> </div> <div className="siderboxC"> <DiChrome size="2rem" className={`${isClose ? "imgClosIconClose" : "imggesOpen"}`} /> <b className="txtSid" style={{ display: isClose ? "none" : "block" }} > NPS </b> </div> <div className="siderboxD"> <FiSettings size="2rem" className={`${isClose ? "imgClosIconClose" : "imggesOpen"}`} /> <b className="txtSid" style={{ display: isClose ? "none" : "block" }} > CONFIGURE </b> </div> </div> </div> </div> ); }; export default Sidder; <file_sep>import React from "react"; const PlanUsage = ({ application_name, production_usage, staging_usage }) => { return ( <div> <div className="planUsgeBox"> <div className="planUsgeBoxA"> <b className="namePlanUsge">{application_name}</b> <div className="planUsgeBoxB"> <h className="pUtextA">Production</h> <b className="pUtextB"> {production_usage} MAU</b> </div> <div className="planUsgeBoxB"> <h className="pUtextA">Staging</h> {staging_usage === "null" && ( <React.Fragment> <button className="btnUtextC"> upgrade</button> </React.Fragment> )} {staging_usage !== "null" && ( <React.Fragment> <b className="pUtextC"> {staging_usage} MAU</b> </React.Fragment> )} </div> </div> </div> </div> ); }; export default PlanUsage; <file_sep>import "./Invoices.css"; import OneInvoice from "./OneInvoice"; const Invoices = ({ data }) => { return ( <div> <div className="headPlanPos"> <h className="headIn">Invoices</h> </div> <div className="boxInvoices"> <div className="headerInv"> <div className="styldata"> <b>Date & TIME</b> </div> <div className="styldatatwo"> <b>PLAN</b> </div> <div className="styldatatwo"> <b>AMOUNT</b> </div> <div className="styldatatwo"> <b>DETAILS</b> </div> </div> {data.organization.invoices.map((data, key) => { return ( <div key={key}> <OneInvoice key={key} date_time={data.date_time} plan={data.plan} amount={data.amount} invoice_number={data.invoice_number} /> </div> ); })} </div> </div> ); }; export default Invoices; <file_sep>import React from "react"; import Select from "react-select"; const Selectemail = ({ optionsOfEmail, ...rest }) => { return ( <Select className="Sel" //Adds a className on the outer component. isMulti //Allows multiple value selection. options={optionsOfEmail} //Allows to include options in the select dropdown {...rest} /> ); }; export default Selectemail; <file_sep>import React from "react"; import { useState } from "react"; import PlaneType from "./PlaneType"; import SCImg from "./imgs/sCImg.PNG"; import ECImg from "./imgs/eCImg.PNG"; import SliderReact from "./RangeSlider"; import { FaTimes } from "react-icons/fa"; import SlidingPane from "react-sliding-pane"; import DowngradePlan from "./AllDowngradePlan"; import { BsExclamation } from "react-icons/bs"; const ChangePlan = ({ api }) => { const [sliderValue, setSliderValue] = useState( api.organization.plan_details.mua ); const [state, setState] = useState({ isPaneOpen: false, isPaneOpenLeft: false, }); const price_per_month = 399; const [price, setPrice] = useState(price_per_month); const DiscontPrice = (wayOfPayment) => { if (wayOfPayment === "monthly") { setPrice(price_per_month); } else { const newPrice = (price_per_month - price_per_month * 0.15).toFixed(2); setPrice(newPrice); } }; const isNotDowngrade = () => { return sliderValue >= api.organization.plan_details.mua; }; const features_standard_plan = [ "People & Trackin", "Growth Insights", "Engagement layer", "User Sentiment", "Reporting, Targeting & Customization", "Integrations", ]; const features_enterprise_plan = [ "Unlimited Seats", "Unlimited Feature Tags", "Phone Support & Priority Troubleshootin", "Security Audit", "Service Level Agreement (SLA)", ]; return ( <div> <div className="boxChangePlane"> <div className={`${ api.organization.plan_details.plan_type == "trial" ? "titl" : "titl-SE" }`} > <b>{`${ api.organization.plan_details.plan_type == "trial" ? "Turn your product into a growth engine" : `${ api.organization.plan_details.plan_type == "Standard" ? "Your current plan is Standard" : "Your current plan is Enterprise" }` }`}</b> </div> <div className="boxChangetwo"> <h className="textChnane">How would you like to pay?</h> <h className="textChnaneA">Monthly Active Users</h> <div className="ichange"> <div className="iIcon"> <BsExclamation size="1.8rem" /> </div> </div> </div> <div className="boxChangeth"> <div class="switches-container"> <input type="radio" id="switchMonthly" name="switchPlan" value="Monthly" checked="checked" /> <input type="radio" id="switchYearly" name="switchPlan" value="Yearly" /> <label for="switchMonthly" onClick={() => { DiscontPrice("monthly"); }} > Monthly </label> <label for="switchYearly" onClick={() => { DiscontPrice("yearly"); }} > Annually </label> <div class="switch-wrapper"> <div class="switch"> <div>Monthly</div> <div>Annually</div> </div> </div> </div> <div className="btnChangeSaveBox"> <button className="btnChangeSave"> Save 15% </button> </div> <div className="muaChange"> <h>{sliderValue}</h> </div> </div> <div> <SliderReact api={api} onChange={(value) => { setSliderValue(value); }} /> <div className="maxValue"> <b>50,000+</b> </div> </div> <div className="boxChangeFo"> <PlaneType data={api} className="standardBoxChange" imgPlane={SCImg} namePlane="Standard" price={price} pmonth="per month" planBtn={`${ api.organization.plan_details.plan_type === "Standard" ? `${ sliderValue == api.organization.plan_details.mua ? "Your Current Plan" : `${isNotDowngrade() ? "upgrade" : "downgrade"}` }` : "buy now" }`} onClickStandard={() => { if ( api.organization.plan_details.plan_type === "Standard" && !isNotDowngrade() ) { setState({ isPaneOpenLeft: true }); } }} classNameOfBtn={`${ api.organization.plan_details.plan_type === "Standard" ? isNotDowngrade() && sliderValue == api.organization.plan_details.mua ? "btnSchEqual" : isNotDowngrade() ? "btnSch" : "redDowngrade" : "btnSch" } `} feturesAll={features_standard_plan} /> <PlaneType data={api} className="EnterpriseBoxChange" imgPlane={ECImg} namePlane="Enterprise" reach="Reach out for pricing " talk="Let's talk" planBtn={`${ api.organization.plan_details.plan_type === "Enterprise" ? "Your Current Plan" : "Contact Us" }`} classNameOfBtnEn={`${ api.organization.plan_details.plan_type === "Enterprise" ? "btnEchEqual" : "btnEch" } `} fetureS="Everything in Standard +" feturesAll={features_enterprise_plan} /> <SlidingPane closeIcon={ <div> <FaTimes className="close" /> <b className="titleAddPayment">Downgrade your Plan</b> </div> } isOpen={state.isPaneOpenLeft} from="right" width="500px" onRequestClose={() => setState({ isPaneOpenLeft: false })} > <DowngradePlan /> </SlidingPane> </div> </div> </div> ); }; export default ChangePlan; <file_sep>import PaymentWithData from "./PaymentWithData"; import Payment from "./Payment"; const BasePayment = ({ data }) => { if (data && data.organization && data.organization.payment_method) { return ( <div> <PaymentWithData apiData={data} /> </div> ); } return ( //payment without data <Payment /> ); }; export default BasePayment; <file_sep>import React from "react"; import "./Invoices.css"; const OneInvoice = ({ date_time, plan, amount, invoice_number }) => { return ( <div> <div className="allInv"> <div className="posData"> <h>{date_time}</h> </div> <div className="posDataTwo"> <h>{plan}</h> </div> <div className="posDataTwo"> <h>${amount}</h> </div> <div className="posDataTwo"> <h>Invoice #{invoice_number}</h> <div className="download"> <h>View | Download</h> </div> </div> </div> </div> ); }; export default OneInvoice;
98119a332e1ea9f0179ecb15eb15a461c2a26ab3
[ "JavaScript" ]
19
JavaScript
MaysTaleeb98/Userpilot_Billing
e869a8ee70d568603b245b459d3d73daa2f752a6
bbd83aa5bca99e7876d72d23c835457b1ceb175e
refs/heads/master
<file_sep>package com.github.ar7ific1al.pokechat; // PokeChat v0.1a by Ar7ific1al import java.io.File; import java.util.HashMap; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import com.github.ar7ific1al.pokechat.commands.ChatChannelCommands; import com.github.ar7ific1al.pokechat.listeners.ChatListener; public class Main extends JavaPlugin { public static Log logger; public String version; public List<String> authors; public static File PartiesDir; public static File SettingsDir; public static File SettingsFile; public static HashMap<Player, String> AdminChannel = new HashMap<Player, String>(); public static HashMap<Player, String> GymChannel = new HashMap<Player, String>(); @Override public void onEnable(){ logger = new Log(); PluginManager pm = Bukkit.getServer().getPluginManager(); PluginDescriptionFile pdFile = this.getDescription(); version = pdFile.getVersion(); authors = pdFile.getAuthors(); Log.LogMessage(Log.ColorMessage("&7[&cPoke&fChat&7]&f v." + version + " enabled."), getServer().getConsoleSender()); if (!getDataFolder().exists()){ getDataFolder().mkdir(); } PartiesDir = new File(getDataFolder() + "/Parties"); SettingsDir = new File(getDataFolder() + "/Settings"); SettingsFile = new File(SettingsDir, "settings.yml"); if (!SettingsFile.exists()){ saveResource("Settings/settings.yml", false); } ChatChannelCommands channelCommands = new ChatChannelCommands(this); getCommand("ac").setExecutor(channelCommands); getCommand("gc").setExecutor(channelCommands); pm.registerEvents(new ChatListener(this), this); } @Override public void onDisable(){ } } <file_sep>package com.github.ar7ific1al.pokechat.commands; import java.io.FileNotFoundException; import java.io.IOException; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import com.github.ar7ific1al.pokechat.Log; import com.github.ar7ific1al.pokechat.Main; public class ChatChannelCommands implements CommandExecutor { Main plugin; public ChatChannelCommands(Main instance){ plugin = instance; Log.LogMessage(Log.ColorMessage("&7[&cPoke&fChat&7]&f ChatChannelCommands executor registered."), plugin.getServer().getConsoleSender()); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if (sender instanceof Player){ try{ if (args.length == 0){ if (label.equalsIgnoreCase("ac")) { if (sender.hasPermission("pokechat.chat.adminchat")) { if (!Main.AdminChannel.containsKey((Player) sender)){ Main.AdminChannel.put((Player)sender, ""); sender.sendMessage(Log.ColorMessage("&7[&cPoke&fChat&7]&f Admin Chat toggled &2ON")); } else if (Main.AdminChannel.containsKey((Player) sender)) { Main.AdminChannel.remove((Player) sender); sender.sendMessage(Log.ColorMessage("&7[&cPoke&fChat&7]&f Admin Chat toggled &4OFF")); } if (Main.GymChannel.containsKey((Player) sender)){ Main.GymChannel.remove((Player) sender); sender.sendMessage(Log.ColorMessage("&7[&cPoke&fChat&7]&f Gym Leader Chat toggled &4OFF")); } return true; } } else if (label.equalsIgnoreCase("gc")) { if (sender.hasPermission("pokechat.chat.gymleaderchat")) { if (!Main.GymChannel.containsKey((Player) sender)){ Main.GymChannel.put((Player)sender, ""); sender.sendMessage(Log.ColorMessage("&7[&cPoke&fChat&7]&f Gym Leader Chat toggled &2ON")); } else if (Main.GymChannel.containsKey((Player)sender)) { Main.GymChannel.remove((Player)sender); sender.sendMessage(Log.ColorMessage("&7[&cPoke&fChat&7]&f Gym Leader Chat toggled &4OFF")); } if (Main.AdminChannel.containsKey((Player)sender)){ Main.AdminChannel.remove((Player)sender); sender.sendMessage(Log.ColorMessage("&7[&cPoke&fChat&7]&f Admin Chat toggled &4OFF")); } return true; } } } else if (args.length >= 1) { if (label.equalsIgnoreCase("ac")) { if (sender.hasPermission("pokechat.chat.adminchat")) { FileConfiguration tmpfc = new YamlConfiguration(); tmpfc.load(Main.SettingsFile); String message = ""; for (int i = 0; i < args.length; i++){ message += args[i]; if (i != args.length) message += " "; } if (tmpfc.getBoolean("ChatChannels.Admin.AllowColors")) { message = Log.ColorMessage(message); } for (Player p : Bukkit.getServer().getOnlinePlayers()){ if (p.hasPermission("pokechat.chat.adminchat")){ p.sendMessage((Log.ColorMessage("&4[&7AC&4] " + sender.getName() + ": &f")) + message); } } } return true; } else if (label.equalsIgnoreCase("gc")){ if (sender.hasPermission("pokechat.chat.gymleaderchat")) { FileConfiguration tmpfc = new YamlConfiguration(); tmpfc.load(Main.SettingsFile); String message = ""; for (int i = 0; i < args.length; i++){ message += args[i]; if (i != args.length) message += " "; } if (tmpfc.getBoolean("ChatChannels.GymLeader.AllowColors")) { message = Log.ColorMessage(message); } for (Player p : Bukkit.getServer().getOnlinePlayers()){ if (p.hasPermission("pokechat.chat.gymleaderchat")){ p.sendMessage((Log.ColorMessage("&b[&7GC&b] " + sender.getName() + ": &f")) + message); } } } return true; } } }catch(ArrayIndexOutOfBoundsException ex){ } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidConfigurationException e) { e.printStackTrace(); } } else if (sender instanceof ConsoleCommandSender){ try{ if (args.length >= 1){ if (label.equalsIgnoreCase("ac")) { FileConfiguration tmpfc = new YamlConfiguration(); tmpfc.load(Main.SettingsFile); String message = ""; for (int i = 0; i < args.length; i++){ message += args[i]; if (i != args.length) message += " "; } if (tmpfc.getBoolean("ChatChannels.Admin.AllowColors")) { message = Log.ColorMessage(message); } for (Player p : Bukkit.getServer().getOnlinePlayers()){ if (p.hasPermission("pokechat.chat.adminchat")){ p.sendMessage((Log.ColorMessage("&4[&7AC&4] " + sender.getName() + ": &f")) + message); } } Bukkit.getServer().getConsoleSender().sendMessage((Log.ColorMessage("&4[&7AC&4] " + sender.getName() + ": &f")) + message); return true; } else if (label.equalsIgnoreCase("gc")){ FileConfiguration tmpfc = new YamlConfiguration(); tmpfc.load(Main.SettingsFile); String message = ""; for (int i = 0; i < args.length; i++){ message += args[i]; if (i != args.length) message += " "; } if (tmpfc.getBoolean("ChatChannels.GymLeader.AllowColors")) { message = Log.ColorMessage(message); } for (Player p : Bukkit.getServer().getOnlinePlayers()){ if (p.hasPermission("pokechat.chat.gymleaderchat")){ p.sendMessage((Log.ColorMessage("&b[&7GC&b] " + sender.getName() + ": &f")) + message); } } Bukkit.getServer().getConsoleSender().sendMessage((Log.ColorMessage("&b[&7GC&b] " + sender.getName() + ": &f")) + message); return true; } } }catch(ArrayIndexOutOfBoundsException | IOException | InvalidConfigurationException ex){ } } return false; } }
b1d7803b0b5b135e1aa09ee8bbaa71215f039665
[ "Java" ]
2
Java
Ar7ific1al/PokeChat
d9e11f40b65ef6c27016293da26becb78dd12650
626bf278a65c09374db489899ad2b6e937b9fc06
refs/heads/master
<file_sep>plugins { id 'java' id 'application' id 'com.github.johnrengelman.shadow' version '1.2.2' id "net.foragerr.jmeter" version "1.0-2.13" } repositories { jcenter() maven { url = 'https://oss.sonatype.org/content/repositories/snapshots/' } } ext { vertxVersion = '3.2.0' cassandraVersion = '3.0.0' jdeferredVersion = '1.2.4' } sourceCompatibility = '1.8' dependencies { compile "io.vertx:vertx-core:$vertxVersion" compile "io.vertx:vertx-web:$vertxVersion" compile "io.vertx:vertx-rx-java:$vertxVersion" compile "org.jdeferred:jdeferred-core:$jdeferredVersion" compile "com.datastax.cassandra:cassandra-driver-core:$cassandraVersion" } mainClassName = 'io.kozlowski.Main' shadowJar { classifier = 'fat' mergeServiceFiles { include 'META-INF/services/io.vertx.core.spi.VerticleFactory' } } task wrapper(type: Wrapper) { gradleVersion = '2.10' }<file_sep>vertx ===== # Running jMeter ``` $ ./gradlew jmReport $ ./gradlew jmGui ``` # Running cassandra Use [dash](https://github.com/IFTTT/dash).<file_sep>#!/bin/bash docker kill cassandra docker rm cassandra<file_sep>#!/bin/bash docker run -it --link cassandra:cassandra --rm cassandra:3.2 sh -c 'exec cqlsh "$CASSANDRA_PORT_9042_TCP_ADDR"'<file_sep>#!/bin/bash docker run -p 9042:9042 --name cassandra -d cassandra:3.2
7cc1fa29c4eecd693c2e2f6124f1ed8a0a2c6c30
[ "Markdown", "Shell", "Gradle" ]
5
Gradle
jkozlowski/vertx-test
905d80429c63d6e9fd04968d995e31c2aa3e05dd
ae51b599191a61603303a89c1fed7be7855c7dd7
refs/heads/master
<repo_name>Nicell/madhacks-2018<file_sep>/static/profile.js const client = algoliasearch('TBGMQ0SV5L', 'b1fe63a6f280ea84a773f7ec1f679c7d'); const index = client.initIndex('dev_pokedex'); const id = location.pathname.split('/').pop(); index.search({ query: id }, (err, content) => { const pokemon = content.hits[0]; const pkmName = (pokemon.ename.charAt(0).toUpperCase() + pokemon.ename.slice(1)).replace('é', 'e').replace('é', 'e').replace('♀', '').replace('♂', '').replace('\'', '').replace(' ', '_').replace('.', ''); document.getElementById("favicon").setAttribute("href", `/spr/${id}${pkmName}.png`) let types = ""; for (const type of pokemon.type) { types += `<span class="${type}">${type}</span>`; } const skills = {} for (const skillCategory of Object.keys(pokemon.skills)) { skills[skillCategory] = ''; for (const skillDef of pokemon.skills[skillCategory]) { skills[skillCategory] += ` <tr> <td>${skillDef.ename}</td> ${skillCategory === 'tm' ? `<td>${skillDef.tm}</td>` : ''} <td>${skillDef.category.charAt(0).toUpperCase() + skillDef.category.slice(1)}</td> <td>${skillDef.power ? skillDef.power : '-'}</td> <td>${skillDef.accuracy ? skillDef.accuracy : '-'}</td> <td>${skillDef.pp}</td> </tr> ` } } const template = ` <div class="identity"> <img src="/img/${id}${pkmName}.png"/> <span>${pkmName}</span> <div class="types">${types}</div> </div> <div class="stats"> <div class="section"> <span>Attack: ${pokemon.base.Attack}</span> <span>Defense: ${pokemon.base.Defense}</span> </div> <div class="section"> <span>Sp. Attack: ${pokemon.base["Sp.Atk"]}</span> <span>Sp. Defense: ${pokemon.base["Sp.Def"]}</span> </div> <div class="section"> <span>Speed: ${pokemon.base.Speed}</span> <span>HP: ${pokemon.base.HP}</span> </div> </div> <div class="moves"> ${pokemon.skills.tm ? ` <div> <span>TM</span> <table> <thead> <tr> <th>Name</th> <th>TM#</th> <th>Category</th> <th>Power</th> <th>Accuracy</th> <th>PP</th> </tr> </thead> <tbody> ${skills.tm} </tbody> </table> </div> ` : ''} ${pokemon.skills.transfer ? ` <div> <span>Transfer</span> <table> <thead> <tr> <th>Name</th> <th>Category</th> <th>Power</th> <th>Accuracy</th> <th>PP</th> </tr> </thead> <tbody> ${skills.transfer} </tbody> </table> </div> ` : ''} ${pokemon.skills.level_up ? ` <div> <span>Level Up</span> <table> <thead> <tr> <th>Name</th> <th>Category</th> <th>Power</th> <th>Accuracy</th> <th>PP</th> </tr> </thead> <tbody> ${skills.level_up} </tbody> </table> </div> ` : ''} ${pokemon.skills.egg ? ` <div> <span>Egg</span> <table> <thead> <tr> <th>Name</th> <th>Category</th> <th>Power</th> <th>Accuracy</th> <th>PP</th> </tr> </thead> <tbody> ${skills.egg} </tbody> </table> </div> ` : ''} </div> `; document.getElementById("profile").innerHTML = template; }); <file_sep>/server.js const express = require('express'); const http = require('http'); const app = express(); const routing = require('./routing.js')(app); app.use('/static', express.static('static')); app.use('/img', express.static('Pokemon-DB/img')); app.use('/spr', express.static('./Pokemon-DB/spr')); const server = new http.Server(app); server.listen(3000);<file_sep>/routing.js module.exports = (app) => { app.get('/', (req, res) => { res.sendFile('./home.html', {root: __dirname}); }); app.get('/pokemon/:id', (req, res) => { res.sendFile('./profile.html', {root: __dirname}); }); app.get('/gen/:num', (req, res) => { res.sendFile('./generation.html', {root: __dirname}); }) }<file_sep>/README.md # madhacks-2018 MadHacks 2018 Entry <file_sep>/static/main.js const client = algoliasearch('TBGMQ0SV5L', 'b1fe63a6f280ea84a773f7ec1f679c7d'); const index = client.initIndex('dev_pokedex'); const search = () => { const query = document.getElementById('query').value; let hits = ''; if (query.length !== 0) { index.search({ query: query }, (err, content) => { for (const hit of content.hits) { const ename = `<span>${hit._highlightResult.ename.value}</span>`; let types = ''; for (const type of hit._highlightResult.type) { const cleanType = type.value.replace('<em>', '').replace('</em>', ''); types += `<span class="${cleanType.toLowerCase()}">${type.value}</span>`; } const imgNum = ("00" + hit.id).slice(-3); const pkmName = (hit.ename.charAt(0).toUpperCase() + hit.ename.slice(1)).replace('é', 'e').replace('é', 'e').replace('♀', '').replace('♂', '').replace('\'', '').replace(' ', '_').replace('.', ''); const image = `<img src="/img/${imgNum}${pkmName}.png"/>` hits += `<a href="/pokemon/${imgNum}" target="_blank" class="hit">${image}${ename}<div class="types">${types}</div></a>`; } document.getElementById('hits').innerHTML = hits; }); } document.getElementById('hits').innerHTML = hits; }; const gens = () => { const generation = document.getElementById('gens').value; window.location.href = 'http://' + window.location.host + '/gen/' + generation; }
01cb9ee565aaa342e06219add3c556852b372057
[ "JavaScript", "Markdown" ]
5
JavaScript
Nicell/madhacks-2018
eae108719dd5f9711ba7ec0aae1f3e37f0c76727
b78ae1d2de41563c5df32528b8d2dc24681ad7ab
refs/heads/master
<repo_name>Lujie1996/fasthttp<file_sep>/examples/fileserver/generate_files.py import os import random import string def generate_big_random_letters(filename,size): """ generate big random letters/alphabets to a file :param filename: the filename :param size: the size in bytes :return: void """ chars = ''.join([random.choice(string.letters) for i in range(size)]) #1 with open(filename, 'w') as f: f.write(chars) pass if __name__ == '__main__': print 'start generating random files...' # n = input('Number of files: ') # s = input('File size (MB): ') # n = int(n) # s = int(s) n = 10 path = 'static/' os.mkdir(path, 0755); l = [1, 16, 128, 512, 1024] for s in l: size_in_byte = s * 1024 filename_prefix = str(s) + 'kb_' for i in range(n): total_path = path + filename_prefix + str(i) + ".txt" generate_big_random_letters(total_path, size_in_byte) print str(i + 1) + ' / ' + str(n) + ' files created..' print 'Random file generation finished.' + str(s) + "kb" <file_sep>/Dockerfile FROM amazonlinux RUN cd ~ \ && yum install git golang make python -y \ && git clone https://github.com/Lujie1996/fasthttp.git \ && cd fasthttp/examples/fileserver \ && make \ && rm -rvf static \ && python generate_files.py EXPOSE 80 81 82 83 84 ENTRYPOINT [ "./root/fasthttp/examples/fileserver/fileserver", "-addr=0.0.0.0:80", "-dir=/root/fasthttp/examples/fileserver/static"]
47d9cb8b2d10d984a22e6dd1b79627af79057f1f
[ "Python", "Dockerfile" ]
2
Python
Lujie1996/fasthttp
2db5ed52c10e90602f03ed0820453d794a27b4da
cfcb6040ad01d9d2b78e44e38134829735bc6397
refs/heads/main
<file_sep>import numpy as np class morphology_3d(): def __init__(self): pass def erosion(self,img,selem=np.array([[[False,False,False],[False,True,False],[False,False,False]],[[False,True,False],[True,True,True],[False,True,False]],[[False,False,False],[False,True,False],[False,False,False]]]),thresh=2): out=np.zeros_like(img) for i in range(len(img)): for j in range(len(img[0])): out[i][j] = self.erode_point(img,selem,i,j,thresh=thresh) return out def erode_point(self,img,selem,r,c,thresh): l1=len(selem)//2 l2=len(selem[0])//2 l3=len(selem[0][0])//2 val = img[r][c] arr_points=[] for i in range(-1*l1,l1): for j in range(-1*l2,l2): if (r+i>=0) and (r+i<len(img)) and (c+j>=0) and (c+j<len(img[0])): for k in range(-1*l3,l3): if selem[i+l1][j+l2][k+l3] ==1: if abs(img[r+i][c+j] - (img[r][c]+k))<thresh: arr_points.append(img[r+i][c+j]) return np.min(np.asarray(arr_points)) def dilation(self,img,selem=np.array([[[False,False,False],[False,True,False],[False,False,False]],[[False,True,False],[True,True,True],[False,True,False]],[[False,False,False],[False,True,False],[False,False,False]]]),thresh=2): out=np.zeros_like(img) for i in range(len(img)): for j in range(len(img[0])): out[i][j] = self.dilate_point(img,selem,i,j,thresh=thresh) img=out.copy() return out def dilate_point(self,img,selem,r,c,thresh): l1=len(selem)//2 l2=len(selem[0])//2 l3=len(selem[0][0])//2 val = img[r][c] arr_points=[] for i in range(-1*l1,l1): for j in range(-1*l2,l2): if (r+i>=0) and (r+i<len(img)) and (c+j>=0) and (c+j<len(img[0])): for k in range(-1*l3,l3): if selem[i+l1][j+l2][k+l3]==1: if abs(img[r+i][c+j] - (img[r][c]+k))<thresh: arr_points.append(img[r+i][c+j]) return np.max(np.asarray(arr_points)) def opening(self,selem): self.erosion(selem=selem) return self.dilation(selem=selem) def closing(self,selem): self.dilation(selem=selem) return self.erosion(selem=selem)
7847b73d7431dbc6ef4682058ae9031320881f3a
[ "Python" ]
1
Python
MPutterman/3D-Morphology
5474a481f92f475dc8d8360e274227dc886ad562
03d39578aafebb0d9fc14ca4592cd3c6539734a4
refs/heads/master
<file_sep>package com.webchat.event; /** * * @author <NAME> */ public class UserLoggedOutEvent { private String username; public UserLoggedOutEvent(String username) { this.username = username; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } <file_sep>package com.webchat.repository; import com.webchat.model.ChatMessage; import java.util.*; /** * * @author <NAME> */ public class ChatMessagesRepository { private List<ChatMessage> messages = Collections.synchronizedList(new ArrayList<ChatMessage>()); public void add(String sessionId, ChatMessage event) { messages.add(event); } public List<ChatMessage> getMessages() { return messages; } public void setMessages(List<ChatMessage> messages) { this.messages = messages; } } <file_sep>package com.webchat.service; import com.webchat.model.ChatRoom; import com.webchat.repository.ChatRoomRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.Optional; /** * * @author <NAME> */ @Service public class ChatRoomService { @Autowired @Qualifier("chatRoomRepository") private ChatRoomRepository chatRoomRepository; public Optional<String> getChatId( String senderId, String recipientId, boolean createIfNotExist) { String chatId = String.format("%s_%s", senderId, recipientId); return chatRoomRepository .getChatRoom(chatId) .map(ChatRoom::getChatId) .map(Optional::of) .orElseGet(() -> { if(!createIfNotExist) { return Optional.empty(); } ChatRoom senderRecipient = ChatRoom .builder() .chatId(chatId) .senderId(senderId) .recipientId(recipientId) .build(); ChatRoom recipientSender = ChatRoom .builder() .chatId(chatId) .senderId(recipientId) .recipientId(senderId) .build(); chatRoomRepository.add(chatId, senderRecipient); chatRoomRepository.add(chatId, recipientSender); return Optional.ofNullable(chatId); }); } } <file_sep>package com.webchat.event; import java.util.Optional; import com.webchat.repository.UsersRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.EventListener; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.web.socket.messaging.SessionConnectEvent; import org.springframework.web.socket.messaging.SessionDisconnectEvent; /** * Listener for {@link SessionConnectEvent} and {@link SessionDisconnectEvent}. * * @author <NAME> */ public class ActiveUserEventListener { @Autowired private UsersRepository usersRepository; @Autowired private SimpMessagingTemplate messagingTemplate; private String loginDestination; private String logoutDestination; /** * Create new {@link UserLoggedInEvent} and * add new user to the repository. */ @EventListener private void handleSessionConnected(SessionConnectEvent event) { SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage()); String username = headers.getUser().getName(); UserLoggedInEvent userLoggedInEvent = new UserLoggedInEvent(username); messagingTemplate.convertAndSend(loginDestination, userLoggedInEvent); usersRepository.add(headers.getSessionId(), userLoggedInEvent); } /** * Delete user from the repository. */ @EventListener private void handleSessionDisconnect(SessionDisconnectEvent event) { Optional.ofNullable(usersRepository.getParticipant(event.getSessionId())) .ifPresent(login -> { messagingTemplate.convertAndSend(logoutDestination, new UserLoggedOutEvent(login.getUsername())); usersRepository.removeParticipant(event.getSessionId()); }); } public void setLoginDestination(String loginDestination) { this.loginDestination = loginDestination; } public void setLogoutDestination(String logoutDestination) { this.logoutDestination = logoutDestination; } } <file_sep>package com.webchat.exception; /** * * @author <NAME> */ public class NoSessionIdException extends RuntimeException { public NoSessionIdException(String message) { super(message); } } <file_sep>package com.webchat.exception; /** * * @author <NAME> */ public class BannedUsersException extends RuntimeException { public BannedUsersException(String message) { super(message); } } <file_sep>package com.webchat.service; import com.webchat.model.ChatMessage; import com.webchat.model.MessageStatus; import com.webchat.repository.ChatPrivateMessagesRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; /** * * @author <NAME> */ @Service public class ChatMessageService { @Autowired private ChatPrivateMessagesRepository repository; @Autowired private ChatRoomService chatRoomService; public ChatMessage save(String sessionId, ChatMessage chatMessage) { chatMessage.setStatus(MessageStatus.RECEIVED); chatMessage.setChatId(sessionId); repository.add(sessionId,chatMessage); return chatMessage; } public long countNewMessages(String senderId, String recipientId) { return repository.countBySenderIdAndRecipientIdAndStatus( senderId, recipientId, MessageStatus.RECEIVED); } public List<ChatMessage> findChatMessages(String senderId, String recipientId) { Optional<String> chatId = chatRoomService.getChatId(senderId, recipientId, false); List<ChatMessage> messagesNew = repository.getMessage(chatId.get()); if(messagesNew.size() > 0) { updateStatuses(chatId.get(), MessageStatus.DELIVERED); } return messagesNew; } public List<ChatMessage> addMessageToList(List<ChatMessage> senderList, List<ChatMessage> recipientList) { return senderList.stream().collect(Collectors.toCollection(() -> recipientList)).stream().sorted(Comparator.comparing(ChatMessage::getTime)) .collect(Collectors.toList()); } private void updateStatuses(String chatId, MessageStatus status) { repository.getMessages().entrySet().stream() .map(Map.Entry::getValue) .filter(c -> c.iterator().next().getChatId().equals(chatId)) .peek(c -> c.iterator().next().setStatus(status)) .collect(Collectors.toList()); } } <file_sep>package com.webchat.configuration; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; /** * Configuration for broker and application destinations. Setting of the endpoint for Stomp Client. * * @author <NAME> */ @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { /** * Set the {@link MessageBrokerRegistry} to configure path for * application and broker. */ @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic", "/queue"); config.setApplicationDestinationPrefixes("/app", "/user"); config.setUserDestinationPrefix("/user"); } /** * Set the {@link StompEndpointRegistry} to configure endpoint for * Stomp client. */ @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/gs-guide-websocket").withSockJS(); } /** * Create a new {@link TomcatServletWebServerFactory} instance. */ @Bean ServletWebServerFactory servletWebServerFactory(){ return new TomcatServletWebServerFactory(); } } <file_sep>package com.webchat.repository; import com.webchat.model.ChatRoom; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; /** * * @author <NAME> */ public class ChatRoomRepository { private Map<String, ChatRoom> chatRoom = new ConcurrentHashMap<>(); public void add(String sessionId, ChatRoom event) { chatRoom.put(sessionId, event); } public Optional<ChatRoom> getChatRoom(String sessionId) { return Optional.ofNullable(chatRoom.get(sessionId)); } public void removeChatRoom(String sessionId) { chatRoom.remove(sessionId); } public Map<String, ChatRoom> getChatRoom() { return chatRoom; } public void setChatRoom(Map<String, ChatRoom> chatRoom) { this.chatRoom = chatRoom; } }
50aaff58f92bf3c70aac2c0316f0f9842ce6772e
[ "Java" ]
9
Java
AnnaLikhachova/WebSoket-Spring-Boot-AnimeJS
2d3c2f2812c6af95d700a76305fdf9039b0bfa13
7d8ea0c2a3ea378aa977ec0fdeb38a9bb150bdbf
refs/heads/master
<file_sep>#!/usr/bin/env python """Script to auto-generate our API docs. """ # stdlib imports import sys import re # local imports from apigen import ApiDocWriter # version comparison from distutils.version import LooseVersion as V #***************************************************************************** def abort(error): print('*WARNING* API documentation not generated: %s' % error) exit() if __name__ == '__main__': package = 'popeye' # Check that the 'image' package is available. If not, the API # documentation is not (re)generated and existing API documentation # sources will be used. try: __import__(package) except ImportError, e: abort("Can not import popeye") module = sys.modules[package] # Check that the source version is equal to the installed # version. If the versions mismatch the API documentation sources # are not (re)generated. This avoids automatic generation of documentation # for older or newer versions if such versions are installed on the system. installed_version = V(module.__version__) info_lines = open('../popeye/version.py').readlines() source_version = '.'.join([v.split('=')[1].strip(" '\n.").split('#')[0] for v in info_lines if re.match( '^_version_(major|minor|micro|extra)', v )]) print '***', source_version if source_version != installed_version: abort("Installed version does not match source version") outdir = 'reference' docwriter = ApiDocWriter(package, rst_extension='.rst') docwriter.package_skip_patterns += [r'\.version$', r'\.popeye$'] docwriter.write_api_docs(outdir) docwriter.write_index(outdir, 'index', relative_to='reference') print('%d files written' % len(docwriter.written_modules)) <file_sep>""" Base-classes for poulation encoding models and fits. """ import numpy as np import ctypes import sharedmem class PopulationModel(object): """ Abstract class which holds the PopulationModel """ def __init__(self, stimulus): self.stimulus = stimulus class PopulationFit(object): """ Abstract class which holds the PopulationFit """ def __init__(self, model, data): self.model = model self.data = data class StimulusModel(object): """ Abstract class which holds the StimulusModel """ def __init__(self, stim_arr, dtype): self.dtype = dtype self.stim_arr = sharedmem.empty(stim_arr.shape, dtype=self.dtype) self.stim_arr[:] = stim_arr[:] <file_sep>from __future__ import division import os import popeye.utilities as utils import numpy as np import numpy.testing as npt import nose.tools as nt from popeye.visual_stimulus import generate_coordinate_matrices, resample_stimulus def test_generate_coordinate_matrices(): # set some dummy display parameters pixels_across = 100 pixels_down = 100 ppd = 1.0 scale_factor = 1.0 # generate coordinates deg_x, deg_y = generate_coordinate_matrices(pixels_across,pixels_down,ppd,scale_factor) # assert nt.assert_true(np.sum(deg_x[0,0:50]) == np.sum(deg_x[0,50::])*-1) nt.assert_true(np.sum(deg_y[0:50,0]) == np.sum(deg_y[50::,0])*-1) # try the same with an odd number of pixels pixels_across = 101 pixels_down = 101 # generate coordinates deg_x, deg_y = generate_coordinate_matrices(pixels_across,pixels_down,ppd,scale_factor) # assert nt.assert_true(np.sum(deg_x[0,0:50]) == np.sum(deg_x[0,50::])*-1) nt.assert_true(np.sum(deg_y[0:50,0]) == np.sum(deg_y[50::,0])*-1) # try with another rescaling factor scale_factor = 0.5 # get the horizontal and vertical coordinate matrices deg_x, deg_y = generate_coordinate_matrices(pixels_across,pixels_down,ppd,scale_factor) # assert nt.assert_true(np.sum(deg_x[0,0:50]) == np.sum(deg_x[0,50::])*-1) nt.assert_true(np.sum(deg_y[0:50,0]) == np.sum(deg_y[50::,0])*-1) def test_resample_stimulus(): # set the downsampling rate scale_factor = 0.5 # create a stimulus stimulus = np.random.random((100,100,20)) # downsample the stimulus by 50% stimulus_coarse = resample_stimulus(stimulus,scale_factor) # grab the stimulus dimensions stim_dims = np.shape(stimulus) stim_coarse_dims = np.shape(stimulus_coarse) # assert nt.assert_true(stim_coarse_dims[0]/stim_dims[0] == scale_factor) nt.assert_true(stim_coarse_dims[1]/stim_dims[1] == scale_factor) nt.assert_true(stim_coarse_dims[2] == stim_dims[2]) <file_sep>import os import multiprocessing from itertools import repeat import numpy as np import numpy.testing as npt import nose.tools as nt from scipy.signal import fftconvolve import popeye.utilities as utils from popeye import dog, og from popeye.visual_stimulus import VisualStimulus, simulate_bar_stimulus, resample_stimulus def test_dog(): # stimulus features pixels_across = 800 pixels_down = 600 viewing_distance = 38 screen_width = 25 thetas = np.arange(0,360,45) num_steps = 20 ecc = 10 tr_length = 1.0 frames_per_tr = 1.0 scale_factor = 0.10 dtype = 'short' # create the sweeping bar stimulus in memory bar = simulate_bar_stimulus(pixels_across, pixels_down, viewing_distance, screen_width, thetas, num_steps, ecc) # resample the stimulus to 50% of original bar = resample_stimulus(bar, 0.50) # create an instance of the Stimulus class stimulus = VisualStimulus(bar, viewing_distance, screen_width, scale_factor, dtype) # initialize the gaussian model model = dog.DifferenceOfGaussiansModel(stimulus) # set the pRF params x = -5.2 y = 2.5 sigma_center = 1.2 sigma_surround = 2.9 beta_center = 2.5 beta_surround = 1.6 hrf_delay = -0.2 # create "data" data = dog.compute_model_ts(x, y, sigma_center, sigma_surround, beta_center, beta_surround, hrf_delay, stimulus.deg_x, stimulus.deg_y, stimulus.stim_arr, tr_length) # first fit the one gaussian search_bounds = ((-10,10),(-10,10),(0.25,5.25),(0.1,1e2),(-5,5)) fit_bounds = ((-12,12),(-12,12),(1/stimulus.ppd,12),(0.1,1e3),(-5,5)) og_fit = og.GaussianFit(model, data, search_bounds, fit_bounds, tr_length, (1,2,3), False, False) # then fit the two gaussian fit_bounds = ((-12,12),(-12,12),(1/stimulus.ppd,12),(1/stimulus.ppd,12),(0.1,1e2),(0.1,1e2),(-5,5),) dog_fit = dog.DifferenceOfGaussiansFit(og_fit, fit_bounds, True, False) # assert equivalence nt.assert_almost_equal(dog_fit.x, x) nt.assert_almost_equal(dog_fit.y, y) nt.assert_almost_equal(dog_fit.sigma_center, sigma_center) nt.assert_almost_equal(dog_fit.sigma_surround, sigma_surround) nt.assert_almost_equal(dog_fit.beta_center, beta_center) nt.assert_almost_equal(dog_fit.beta_surround, beta_surround) nt.assert_almost_equal(dog_fit.hrf_delay, hrf_delay) <file_sep>""" First pass at a stimulus model for abstracting the qualities and functionality of a stimulus into an abstract class. For now, we'll assume the stimulus model only pertains to visual stimuli on a visual display over time (i.e., 3D). Hopefully this can be extended to other stimuli with an arbitrary number of dimensions (e.g., auditory stimuli). """ from __future__ import division import ctypes import sharedmem import numpy as np from pylab import specgram from numpy.lib import stride_tricks from scipy.misc import imresize import nibabel from popeye.base import StimulusModel from popeye.onetime import auto_attr import popeye.utilities as utils def generate_spectrogram(signal, NFFT, Fs, noverlap): spectrogram, freqs, times, handle = specgram(signal,NFFT=NFFT,Fs=Fs,noverlap=noverlap); return spectrogram, freqs, times # This should eventually be VisualStimulus, and there would be an abstract class layer # above this called Stimulus that would be generic for n-dimentional feature spaces. class AuditoryStimulus(StimulusModel): """ Abstract class for stimulus model """ def __init__(self, stim_arr, NFFT, Fs, noverlap, tr_length, dtype): # this is a weird notation StimulusModel.__init__(self, stim_arr, dtype=dtype) # absorb the vars self.NFFT = NFFT self.Fs = Fs self.noverlap = noverlap self.tr_length = tr_length spectrogram, freqs, times = generate_spectrogram(self.stim_arr, self.NFFT, self.Fs, self.noverlap) self.spectrogram = sharedmem.empty(spectrogram.shape, dtype='float64') self.spectrogram[:] = spectrogram[:] self.freqs = sharedmem.empty(freqs.shape, dtype='float64') self.freqs[:] = freqs[:] self.times = sharedmem.empty(times.shape, dtype='float64') self.times[:] = times[:] <file_sep>#!/usr/bin/python """ Classes and functions for fitting Gaussian population encoding models """ from __future__ import division, print_function, absolute_import import time import gc import warnings warnings.simplefilter("ignore") import numpy as np import nibabel from scipy.stats import linregress from scipy.signal import fftconvolve from popeye.onetime import auto_attr import popeye.utilities as utils from popeye.base import PopulationModel, PopulationFit from popeye.spinach import generate_dog_timeseries, generate_og_timeseries, generate_og_receptive_field def recast_estimation_results(output, grid_parent): """ Recasts the output of the prf estimation into two nifti_gz volumes. Takes `output`, a list of multiprocessing.Queue objects containing the output of the prf estimation for each voxel. The prf estimates are expressed in both polar and Cartesian coordinates. If the default value for the `write` parameter is set to False, then the function returns the arrays without writing the nifti files to disk. Otherwise, if `write` is True, then the two nifti files are written to disk. Each voxel contains the following metrics: 0 x / polar angle 1 y / eccentricity 2 sigma 3 HRF delay 4 RSS error of the model fit 5 correlation of the model fit Parameters ---------- output : list A list of PopulationFit objects. grid_parent : nibabel object A nibabel object to use as the geometric basis for the statmap. The grid_parent (x,y,z) dim and pixdim will be used. Returns ------ cartes_filename : string The absolute path of the recasted prf estimation output in Cartesian coordinates. plar_filename : string The absolute path of the recasted prf estimation output in polar coordinates. """ # load the gridParent dims = list(grid_parent.shape) dims = dims[0:3] dims.append(8) # initialize the statmaps polar = np.zeros(dims) cartes = np.zeros(dims) # extract the prf model estimates from the results queue output for fit in output: if fit.__dict__.has_key('fit_stats'): cartes[fit.voxel_index] = (fit.x, fit.y, fit.sigma_center, fit.sigma_surround, fit.beta_center, fit.beta_surround, fit.hrf_delay, fit.fit_stats[2]) polar[fit.voxel_index] = (np.mod(np.arctan2(fit.x,fit.y),2*np.pi), np.sqrt(fit.x**2+fit.y**2), fit.sigma_center, fit.sigma_surround, fit.beta_center, fit.beta_surround, fit.hrf_delay, fit.fit_stats[2]) # get header information from the gridParent and update for the prf volume aff = grid_parent.get_affine() hdr = grid_parent.get_header() hdr.set_data_shape(dims) # recast as nifti nif_polar = nibabel.Nifti1Image(polar,aff,header=hdr) nif_polar.set_data_dtype('float32') nif_cartes = nibabel.Nifti1Image(cartes,aff,header=hdr) nif_cartes.set_data_dtype('float32') return nif_cartes, nif_polar def compute_model_ts(x, y, sigma_center, sigma_surround, beta_center, beta_surround, hrf_delay, deg_x, deg_y, stim_arr, tr_length): """ The objective function for GaussianFi class. Parameters ---------- x : float The model estimate along the horizontal dimensions of the display. y : float The model estimate along the vertical dimensions of the display. sigma_center : float The model estimate of the dispersion of the excitatory center. sigma_surround : float The model estimate of the dispersion of the inhibitory surround. beta_center : float The amplitude of the excitatory center. beta_surround : float The amplitude of the inhibitory surround. hrf_delay : float The model estimate of the relative delay of the HRF. The canonical HRF is assumed to be 5 s post-stimulus [1]_. tr_length : float The length of the repetition time in seconds. Returns ------- model : ndarray The model prediction time-series. References ---------- .. [1] <NAME>. (1999). Deconvolution of impulse response in event-related BOLD fMRI. NeuroImage 9: 416-429. """ # limiting cases for a center-surround receptive field if sigma_center >= sigma_surround: return np.inf if beta_center <= beta_surround: return np.inf # METHOD 1 # time-series for the center and surround stim_center, stim_surround = generate_dog_timeseries(deg_x, deg_y, stim_arr, x, y, sigma_center, sigma_surround) # scale them by betas stim_center *= beta_center stim_surround *= beta_surround # differnce them stim_dog = stim_center - stim_surround # # METHOD 2 # # scale the RFs, combine, then extract ts # rf_center = generate_og_receptive_field(deg_x, deg_y, x, y, sigma_center) # rf_center /= rf_center.max() # rf_center *= beta_center # # rf_surround = generate_og_receptive_field(deg_x, deg_y, x, y, sigma_surround) # rf_surround /= rf_surround.max() # rf_surround *= beta_surround # # rf_dog = rf_center - rf_surround # stim_dog = np.sum(np.sum(stim_arr * rf_dog[:,:,np.newaxis],axis=0),axis=0) # generate the hrf hrf = utils.double_gamma_hrf(hrf_delay, tr_length) # convolve it with the stimulus timeseries model = fftconvolve(stim_dog, hrf)[0:len(stim_dog)] return model def parallel_fit(args): """ This is a convenience function for parallelizing the fitting procedure. Each call is handed a tuple or list containing all the necessary inputs for instantiaing a `GaussianFit` class object and estimating the model parameters. Paramaters ---------- args : list/tuple A list or tuple containing all the necessary inputs for fitting the Gaussian pRF model. Returns ------- fit : `GaussianFit` class object A fit object that contains all the inputs and outputs of the Gaussian pRF model estimation for a single voxel. """ # unpackage the arguments og_fit = args[0] fit_bounds = args[1] auto_fit = args[2] verbose = args[3] uncorrected_rval = args[4] # fit the data fit = DifferenceOfGaussiansFit(og_fit, fit_bounds, auto_fit, verbose, uncorrected_rval) return fit class DifferenceOfGaussiansModel(PopulationModel): """ A Gaussian population receptive field model class """ def __init__(self, stimulus): """ A Gaussian population receptive field model [1]_. Paramaters ---------- stimulus : `VisualStimulus` class object A class instantiation of the `VisualStimulus` class containing a representation of the visual stimulus. References ---------- .. [1] <NAME>, <NAME>. (2008) Population receptive field estimates in human visual cortex. NeuroImage 39:647-660 """ PopulationModel.__init__(self, stimulus) class DifferenceOfGaussiansFit(PopulationFit): """ A Gaussian population receptive field fit class """ def __init__(self, og_fit, fit_bounds, auto_fit=True, verbose=True, uncorrected_rval=0.0): """ A Gaussian population receptive field model [1]_. Paramaters ---------- og_fit : `GaussianFit` class instance A `GaussianFit` object. This object does not have to be fitted already, as the fit will be performed inside the `DifferenceOfGaussiansFit` in any case. The `GaussianFit` is used as a seed for the `DifferenceOfGaussiansFit` search. fit_bounds : tuple A tuple containing the upper and lower bounds for each parameter in `parameters`. If a parameter is not bounded, simply use `None`. For example, `fit_bounds=((0,None),(-10,10),)` would bound the first parameter to be any positive number while the second parameter would be bounded between -10 and 10. auto-fit : bool A flag for automatically running the fitting procedures once the `GaussianFit` object is instantiated. verbose : bool A flag for printing some summary information about the model estiamte after the fitting procedures have completed. References ---------- .. [1] <NAME>, <NAME>. (2008) Population receptive field estimates in human visual cortex. NeuroImage 39:647-660 """ PopulationFit.__init__(self, og_fit.model, og_fit.data) self.og_fit = og_fit self.fit_bounds = fit_bounds self.tr_length = self.og_fit.tr_length self.voxel_index = self.og_fit.voxel_index self.auto_fit = auto_fit self.verbose = verbose self.uncorrected_rval = uncorrected_rval if self.auto_fit: tic = time.clock() self.og_fit.estimate if self.og_fit.fit_stats[2] > self.uncorrected_rval: self.estimate; self.fit_stats; toc = time.clock() msg = ("VOXEL=(%.03d,%.03d,%.03d) TIME=%.03d OG-RVAL=%.02f DoG-RVAL=%.02f" %(self.voxel_index[0], self.voxel_index[1], self.voxel_index[2], toc-tic, self.og_fit.fit_stats[2], self.fit_stats[2])) else: toc = time.clock() msg = ("VOXEL=(%.03d,%.03d,%.03d) TIME=%.03d OG-RVAL=%.02f" %(self.voxel_index[0], self.voxel_index[1], self.voxel_index[2], toc-tic, self.og_fit.fit_stats[2])) if self.verbose: print(msg) @auto_attr def estimate(self): return utils.gradient_descent_search((self.x0, self.y0, self.sigma_center0, self.sigma_surround0, self.beta_center0, self.beta_surround0, self.hrf0), (self.model.stimulus.deg_x, self.model.stimulus.deg_y, self.model.stimulus.stim_arr, self.tr_length), self.fit_bounds, self.data, utils.error_function, compute_model_ts) @auto_attr def x0(self): return self.og_fit.estimate[0] @auto_attr def y0(self): return self.og_fit.estimate[1] @auto_attr def sigma_center0(self): return self.og_fit.estimate[2] @auto_attr def sigma_surround0(self): return self.og_fit.estimate[2]*2 @auto_attr def beta_center0(self): return self.og_fit.estimate[3] @auto_attr def beta_surround0(self): return self.og_fit.estimate[3]/2 @auto_attr def hrf0(self): return self.og_fit.estimate[4] @auto_attr def x(self): return self.estimate[0] @auto_attr def y(self): return self.estimate[1] @auto_attr def sigma_center(self): return self.estimate[2] @auto_attr def sigma_surround(self): return self.estimate[3] @auto_attr def beta_center(self): return self.estimate[4] @auto_attr def beta_surround(self): return self.estimate[5] @auto_attr def hrf_delay(self): return self.estimate[6] @auto_attr def prediction(self): return compute_model_ts(self.x, self.y, self.sigma_center, self.sigma_surround, self.beta_center, self.beta_surround, self.hrf_delay, self.model.stimulus.deg_x, self.model.stimulus.deg_y, self.model.stimulus.stim_arr, self.tr_length) @auto_attr def fit_stats(self): return linregress(self.data, self.prediction) @auto_attr def rss(self): return np.sum((self.data - self.prediction)**2) @auto_attr def receptive_field(self): rf_center = generate_og_receptive_field(self.model.stimulus.deg_x, self.model.stimulus.deg_y, self.x, self.y, self.sigma_center) rf_surround = generate_og_receptive_field(self.model.stimulus.deg_x, self.model.stimulus.deg_y, self.x, self.y, self.sigma_surround) return rf_center*self.beta_center - rf_surround*self.beta_surround @auto_attr def hemodynamic_response(self): return utils.double_gamma_hrf(self.hrf_delay, self.tr_length) <file_sep>What is a PRF? ================ PRF stands for 'population receptive field'. In the most general sense, this is a quantitative model of the responses of the population of cells contained within an fMRI voxel (or other measurement of population activity, such as EEG, EcOG, etc.) that can interpret and predict the responses of this population to different stimuli. The use of PRF models was first pioneered by Dumoulin and Wandell [1]_ in analysis of visual responses of fMRI voxels in the early visual cortex. References ------------------- .. [1] <NAME>, and <NAME> (2008). Population receptive field estimates in human visual cortex. Neuroimage 39: 647-60. <file_sep>import os import popeye.utilities as utils import numpy as np import nose.tools as nt import numpy.testing as npt from scipy.special import gamma def test_normalize(): # create an array arr = np.arange(0,100) # create new bounds lo = -50 hi = 50 # rescale the array arr_new = utils.normalize(arr, lo, hi) # assert equivalence npt.assert_equal(np.min(arr_new), lo) npt.assert_equal(np.max(arr_new), hi) def test_error_function(): # create a parameter to estimate params = (1.248,10.584) # we don't need any additional arguments args = ('blah',) # we don't need to specify bounds for the error function fit_bounds = () # create a simple function to transform the parameters func = lambda x, y, arg: np.arange(x,x+100)*y # create a "response" response = func(params[0], params[1], args) # assert 0 error npt.assert_equal(utils.error_function(params,args,fit_bounds,response,func),0) def test_gradient_descent_search(): # create a parameter to estimate params = (1.248,10.584) # we don't need any additional arguments args = ('blah',) # we need to define some search bounds search_bounds = ((0,10),(5,15)) # we don't need to specify bounds for the error function fit_bounds = () # create a simple function to transform the parameters func = lambda x, y, arg: np.arange(x,x+100)*y # create a "response" response = func(params[0], params[1], args) # get the ball-park estimate p0 = utils.brute_force_search(args, search_bounds, fit_bounds, response, utils.error_function, func) # get the fine estimate estimate = utils.gradient_descent_search(p0, args, fit_bounds, response, utils.error_function, func) # assert that the estimate is equal to the parameter npt.assert_almost_equal(params, estimate) def test_brute_force_search(): # create a parameter to estimate params = (5,10) # we don't need any additional arguments args = ('blah',) # we need to define some search bounds search_bounds = ((0,10),(5,15)) # we don't need to specify bounds for the error function fit_bounds = () # create a simple function to transform the parameters func = lambda x, y, arg: np.arange(x,x+100)*y # create a "response" response = func(params[0], params[1], args) estimate = utils.brute_force_search(args, search_bounds, fit_bounds, response, utils.error_function, func) # assert that the estimate is equal to the parameter npt.assert_equal(params, estimate) def test_double_gamma_hrf(): """ Test voxel-wise gabor estimation function in popeye.estimation using the stimulus and BOLD time-series data that ship with the popeye installation. """ # set the TR length ... this affects the HRF sampling rate ... tr_length = 1.0 # compute the difference in area under curve for hrf_delays of -1 and 0 diff_1 = np.abs(np.sum(utils.double_gamma_hrf(-1, tr_length))-np.sum(utils.double_gamma_hrf(0, tr_length))) # compute the difference in area under curver for hrf_delays of 0 and 1 diff_2 = np.abs(np.sum(utils.double_gamma_hrf(1, tr_length))-np.sum(utils.double_gamma_hrf(0, tr_length))) npt.assert_almost_equal(diff_1, diff_2, 2) def test_randomize_voxels(): # set the dummy dataset size x_dim, y_dim, z_dim = 10, 10, 10 # create a dummy dataset with the dat = np.random.rand(x_dim, y_dim, z_dim) # mask and grab the indices xi,yi,zi = np.nonzero(dat>0.75) # create a random vector to resort the voxel indices rand_vec = np.random.rand(len(xi)) rand_ind = np.argsort(rand_vec) # resort the indices rand_xi, rand_yi, rand_zi = xi[rand_ind], yi[rand_ind], zi[rand_ind] # assert that all members of the original and resorted indices are equal nt.assert_true(set(xi) == set(rand_xi)) nt.assert_true(set(yi) == set(rand_yi)) nt.assert_true(set(zi) == set(rand_zi)) def test_zscore(): x = np.array([[1, 1, 3, 3], [4, 4, 6, 6]]) z = utils.zscore(x) npt.assert_equal(x.shape, z.shape) #Default axis is -1 npt.assert_equal(utils.zscore(x), np.array([[-1., -1., 1., 1.], [-1., -1., 1., 1.]])) #Test other axis: npt.assert_equal(utils.zscore(x, 0), np.array([[-1., -1., -1., -1.], [1., 1., 1., 1.]])) # Test the 1D case: x = np.array([1, 1, 3, 3]) npt.assert_equal(utils.zscore(x), [-1, -1, 1, 1]) def test_percent_change(): x = np.array([[99, 100, 101], [4, 5, 6]]) p = utils.percent_change(x) nt.assert_equal(x.shape, p.shape) nt.assert_almost_equal(p[0, 2], 1.0) ts = np.arange(4 * 5).reshape(4, 5) ax = 0 npt.assert_almost_equal(utils.percent_change(ts, ax), np.array( [[-100., -88.23529412, -78.94736842, -71.42857143, -65.2173913], [-33.33333333, -29.41176471, -26.31578947, -23.80952381, -21.73913043], [33.33333333, 29.41176471, 26.31578947, 23.80952381, 21.73913043], [100., 88.23529412, 78.94736842, 71.42857143, 65.2173913]])) ax = 1 npt.assert_almost_equal(utils.percent_change(ts, ax), np.array( [[-100., -50., 0., 50., 100.], [-28.57142857, -14.28571429, 0., 14.28571429, 28.57142857], [-16.66666667, -8.33333333, 0., 8.33333333, 16.66666667], [-11.76470588, -5.88235294, 0., 5.88235294, 11.76470588]])) <file_sep>""" First pass at a stimulus model for abstracting the qualities and functionality of a stimulus into an abstract class. For now, we'll assume the stimulus model only pertains to visual stimuli on a visual display over time (i.e., 3D). Hopefully this can be extended to other stimuli with an arbitrary number of dimensions (e.g., auditory stimuli). """ from __future__ import division import ctypes import gc import sharedmem import numpy as np from scipy.misc import imresize from scipy.io import loadmat from popeye.base import StimulusModel def generate_coordinate_matrices(pixels_across, pixels_down, ppd, scale_factor=1): """Creates coordinate matrices for representing the visual field in terms of degrees of visual angle. This function takes the screen dimensions, the pixels per degree, and a scaling factor in order to generate a pair of ndarrays representing the horizontal and vertical extents of the visual display in degrees of visual angle. Parameters ---------- pixels_across : int The number of pixels along the horizontal extent of the visual display. pixels_down : int The number of pixels along the vertical extent of the visual display. ppd: float The number of pixels that spans 1 degree of visual angle. This number is computed using the display width and the viewing distance. See the config.init_config for details. scale_factor : float The scale factor by which the stimulus is resampled. The scale factor must be a float, and must be greater than 0. Returns ------- deg_x : ndarray An array representing the horizontal extent of the visual display in terms of degrees of visual angle. deg_y : ndarray An array representing the vertical extent of the visual display in terms of degrees of visual angle. """ [X,Y] = np.meshgrid(np.arange(np.round(pixels_across*scale_factor)), np.arange(np.round(pixels_down*scale_factor))) deg_x = (X-np.round(pixels_across*scale_factor)/2)/(ppd*scale_factor) deg_y = (Y-np.round(pixels_down*scale_factor)/2)/(ppd*scale_factor) deg_x += 0.5/(ppd*scale_factor) deg_y += 0.5/(ppd*scale_factor) return deg_x, np.flipud(deg_y) def resample_stimulus(stim_arr, scale_factor=0.05): """Resamples the visual stimulus The function takes an ndarray `stim_arr` and resamples it by the user specified `scale_factor`. The stimulus array is assumed to be a three dimensional ndarray representing the stimulus, in screen pixel coordinates, over time. The first two dimensions of `stim_arr` together represent the exent of the visual display (pixels) and the last dimensions represents time (TRs). Parameters ---------- stim_arr : ndarray Array_like means all those objects -- lists, nested lists, etc. -- that can be converted to an array. scale_factor : float The scale factor by which the stimulus is resampled. The scale factor must be a float, and must be greater than 0. Returns ------- resampled_arr : ndarray An array that is resampled according to the user-specified scale factor. """ dims = np.shape(stim_arr) resampled_arr = np.zeros((dims[0]*scale_factor, dims[1]*scale_factor, dims[2])) for tr in np.arange(dims[-1]): # resize it f = imresize(stim_arr[:,:,tr], scale_factor, interp='cubic') # normalize it to the same range as the non-resampled frames f *= np.max(stim_arr[:,:,tr]) / np.max(f) resampled_arr[:,:,tr] = f return resampled_arr.astype('short') def gaussian_2D(X, Y, x0, y0, sigma_x, sigma_y, degrees, amplitude=1): """ A utility function for creating a two-dimensional Gaussian. This function served as the model for the Cython implementation of a generator of two-dimensional Gaussians. X : ndarray The coordinate array for the horizontal dimension of the display. Y : ndarray The coordinate array for the the vertical dimension of the display. x0 : float The location of the center of the Gaussian on the horizontal axis. y0 : float The location of the center of the Gaussian on the verticala axis. sigma_x : float The dispersion of the Gaussian over the horizontal axis. sigma_y : float The dispersion of the Gaussian over the vertical axis. degrees : float The orientation of the two-dimesional Gaussian (degrees). amplitude : float The amplitude of the two-dimensional Gaussian. Returns ------- gauss : ndarray The two-dimensional Gaussian. """ theta = degrees*np.pi/180 a = np.cos(theta)**2/2/sigma_x**2 + np.sin(theta)**2/2/sigma_y**2 b = -np.sin(2*theta)/4/sigma_x**2 + np.sin(2*theta)/4/sigma_y**2 c = np.sin(theta)**2/2/sigma_x**2 + np.cos(theta)**2/2/sigma_y**2 Z = amplitude*np.exp( - (a*(X-x0)**2 + 2*b*(X-x0)*(Y-y0) + c*(Y-y0)**2)) return Z def simulate_bar_stimulus(pixels_across, pixels_down, viewing_distance, screen_width, thetas, num_steps, ecc, blanks=True, threshold = 0.33): """ A utility function for creating a sweeping bar stimulus in memory. This function creates a standard retinotopic mapping stimulus, the sweeping bar. The user specifies some of the display and stimulus parameters. This is particularly useful for writing tests and simulating responses of visually driven voxels. pixels_across : int The number of pixels along the horizontal dimension of the display. pixels_down : int The number of pixels along the vertical dimension of the display. viewing_distance : float The distance between the participant and the display (cm). screen_width : float The width of the display (cm). This is used to compute the visual angle for determining the pixels per degree of visual angle. thetas : array-like An array containing the orientations of the bars that will sweep across the display. For example `thetas = np.arange(0,360,360/8)`. num_steps : int The number of steps the bar makes on each sweep through the visual field. ecc : float The distance from fixation each bar sweep begins and ends (degees). blanks : bool A flag determining whether there are blank periods inserted at the beginning and the end of the stimulus run. threshold : float The bar stimulus is created by thresholding a very oblong two-dimensional Gaussian at various orientations. Returns ------- bar : ndarray An array containing the bar stimulus. The array is three-dimensional, with the first two dimensions representing the size of the display and the third dimension representing time. """ # visuotopic stuff ppd = np.pi*pixels_across/np.arctan(screen_width/viewing_distance/2.0)/360.0 # degrees of visual angle deg_x, deg_y = generate_coordinate_matrices(pixels_across, pixels_down, ppd, 1.0) # initialize a counter tr_num = 0 # insert blanks if blanks: thetas = list(thetas) thetas.insert(0,-1) thetas.append(-1) # initialize the stimulus array bar_stimulus = np.zeros((pixels_down, pixels_across, len(thetas)*num_steps)) # main loop for theta in thetas: if theta != -1: # convert to radians theta_rad = theta * np.pi / 180 # get the starting point and trajectory start_pos = np.array([-np.cos(theta_rad)*ecc, -np.sin(theta_rad)*ecc]) end_pos = np.array([np.cos(theta_rad)*ecc, np.sin(theta_rad)*ecc]) run_and_rise = end_pos - start_pos; if np.mod(theta,90) == 0: sigma_x = 1 sigma_y = 100 else: sigma_x = 100 sigma_y = 1 # step through each position along the trajectory for step in np.arange(0,num_steps): # get the position of the bar at each step xy0 = run_and_rise * step/num_steps + start_pos # generate the gaussian Z = gaussian_2D(deg_x,deg_y,xy0[0],xy0[1],sigma_x,sigma_y,theta) # store and iterate bar_stimulus[:,:,tr_num] = Z tr_num += 1 else: for step in np.arange(0,num_steps): tr_num += 1 # digitize the bar stimulus bar = np.zeros_like(bar_stimulus) bar[bar_stimulus > threshold] = 1 bar = np.short(bar) return bar # This should eventually be VisualStimulus, and there would be an abstract class layer # above this called Stimulus that would be generic for n-dimentional feature spaces. class VisualStimulus(StimulusModel): """ A child of the StimulusModel class for visual stimuli. """ def __init__(self, stim_arr, viewing_distance, screen_width, scale_factor, dtype): """ A child of the StimulusModel class for visual stimuli. Paramaters ---------- stim_arr : ndarray An array containing the visual stimulus at the native resolution. The visual stimulus is assumed to be three-dimensional (x,y,time). viewing_distance : float The distance between the participant and the display (cm). screen_width : float The width of the display (cm). This is used to compute the visual angle for determining the pixels per degree of visual angle. scale_factor : float The downsampling rate for ball=parking a solution. The `stim_arr` is downsampled so as to speed up the fitting procedure. The final model estimates will be derived using the non-downsampled stimulus. """ StimulusModel.__init__(self, stim_arr, dtype) # absorb the vars self.viewing_distance = viewing_distance self.screen_width = screen_width self.scale_factor = scale_factor # ascertain stimulus features self.pixels_across = self.stim_arr.shape[1] self.pixels_down = self.stim_arr.shape[0] self.run_length = self.stim_arr.shape[2] self.ppd = np.pi*self.pixels_across/np.arctan(self.screen_width/self.viewing_distance/2.0)/360.0 # degrees of visual angle # create downsampled stimulus stim_arr_coarse = resample_stimulus(self.stim_arr,self.scale_factor) # generate the coordinate matrices deg_x, deg_y = generate_coordinate_matrices(self.pixels_across, self.pixels_down, self.ppd) deg_x_coarse, deg_y_coarse = generate_coordinate_matrices(self.pixels_across, self.pixels_down, self.ppd, self.scale_factor) # share the rest of the arrays ... self.deg_x = sharedmem.empty(deg_x.shape, dtype='float64') self.deg_x[:] = deg_x[:] self.deg_y = sharedmem.empty(deg_y.shape, dtype='float64') self.deg_y[:] = deg_y[:] self.deg_x_coarse = sharedmem.empty(deg_x_coarse.shape, dtype='float64') self.deg_x_coarse[:] = deg_x_coarse[:] self.deg_y_coarse = sharedmem.empty(deg_y_coarse.shape, dtype='float64') self.deg_y_coarse[:] = deg_y_coarse[:] self.stim_arr_coarse = sharedmem.empty(stim_arr_coarse.shape, dtype=self.dtype) self.stim_arr_coarse[:] = stim_arr_coarse[:] <file_sep>""" """ __docformat__ = 'restructuredtext' from .version import __version__ from . import visual_stimulus from . import utilities from . import og from . import dog from . import xvalidation <file_sep>.. Popeye documentation master file, created by sphinx-quickstart on Sat May 3 07:09:59 2014. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to Popeye's documentation! ================================== Contents: .. toctree:: :maxdepth: 2 prf getting_started reference/index Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` <file_sep>import os import multiprocessing from itertools import repeat import numpy as np import numpy.testing as npt import nose.tools as nt from scipy.signal import fftconvolve import popeye.utilities as utils import popeye.og as og from popeye.visual_stimulus import VisualStimulus, simulate_bar_stimulus def test_og_fit(): # stimulus features pixels_across = 800 pixels_down = 600 viewing_distance = 38 screen_width = 25 thetas = np.arange(0,360,45) num_steps = 20 ecc = 10 tr_length = 1.0 frames_per_tr = 1.0 scale_factor = 0.05 dtype='short' # create the sweeping bar stimulus in memory bar = simulate_bar_stimulus(pixels_across, pixels_down, viewing_distance, screen_width, thetas, num_steps, ecc) # create an instance of the Stimulus class stimulus = VisualStimulus(bar, viewing_distance, screen_width, scale_factor, dtype) # set up bounds for the grid search search_bounds = ((-10,10),(-10,10),(0.25,5.25),(0.1,1e2),(-5,5),) fit_bounds = ((-12,12),(-12,12),(1/stimulus.ppd,12),(0.1,1e3),(-5,5),) # initialize the gaussian model model = og.GaussianModel(stimulus) # generate a random pRF estimate x = -5.24 y = 2.58 sigma = 1.24 beta = 2.5 hrf_delay = -0.25 # create the "data" data = og.compute_model_ts(x, y, sigma, beta, hrf_delay, stimulus.deg_x, stimulus.deg_y, stimulus.stim_arr, tr_length) # fit the response fit = og.GaussianFit(model, data, search_bounds, fit_bounds, tr_length) # assert equivalence nt.assert_almost_equal(fit.x, x) nt.assert_almost_equal(fit.y, y) nt.assert_almost_equal(fit.sigma, sigma) nt.assert_almost_equal(fit.beta, beta) nt.assert_almost_equal(fit.hrf_delay, hrf_delay) def test_parallel_og_fit(): # stimulus features pixels_across = 800 pixels_down = 600 viewing_distance = 38 screen_width = 25 thetas = np.arange(0,360,45) num_steps = 20 ecc = 10 tr_length = 1.0 frames_per_tr = 1.0 scale_factor = 0.05 dtype='short' num_voxels = multiprocessing.cpu_count()-1 # create the sweeping bar stimulus in memory bar = simulate_bar_stimulus(pixels_across, pixels_down, viewing_distance, screen_width, thetas, num_steps, ecc) # create an instance of the Stimulus class stimulus = VisualStimulus(bar, viewing_distance, screen_width, scale_factor, dtype) # set up bounds for the grid search search_bounds = [((-10,10),(-10,10),(0.25,5.25),(0.1,1e2),(-5,5),)]*num_voxels fit_bounds = [((-12,12),(-12,12),(1/stimulus.ppd,12),(0.1,1e3),(-5,5),)]*num_voxels # make fake voxel indices indices = [(1,2,3)]*num_voxels # initialize the gaussian model model = og.GaussianModel(stimulus) # generate a random pRF estimate x = -5.24 y = 2.58 sigma = 1.24 beta = 2.5 hrf_delay = -0.25 # create the simulated time-series timeseries = [] for voxel in range(num_voxels): # create "data" data = og.compute_model_ts(x, y, sigma, beta, hrf_delay, stimulus.deg_x, stimulus.deg_y, stimulus.stim_arr, tr_length) # append it timeseries.append(data) # package the data structure dat = zip(repeat(model,num_voxels), timeseries, search_bounds, fit_bounds, repeat(tr_length,num_voxels), indices, repeat(True,num_voxels), repeat(True,num_voxels)) # run analysis pool = multiprocessing.Pool(multiprocessing.cpu_count()-1) output = pool.map(og.parallel_fit,dat) pool.close() pool.join() # assert equivalence for fit in output: nt.assert_almost_equal(fit.x, x) nt.assert_almost_equal(fit.y, y) nt.assert_almost_equal(fit.sigma, sigma) nt.assert_almost_equal(fit.beta, beta) nt.assert_almost_equal(fit.hrf_delay, hrf_delay)<file_sep>import os import multiprocessing from itertools import repeat import numpy as np import numpy.testing as npt import scipy.signal as ss import popeye.utilities as utils import popeye.gabor as gabor import popeye.gaussian as gaussian from popeye.visual_stimulus import simulate_bar_stimulus, VisualStimulus # def test_gabor_fit(): # # # stimulus features # pixels_across = 800 # pixels_down = 600 # viewing_distance = 38 # screen_width = 25 # tr_length = 1.0 # clip_number = 25 # roll_number = 0 # frames_per_tr = 8 # # movie = np.load('/Users/kevin/Desktop/battleship.npy') # # # create an instance of the Stimulus class # stimulus = VisualStimulus(movie, viewing_distance, screen_width, 0.10, clip_number, roll_number, frames_per_tr) # # # flush the movie # movie = [] # # # initialize the gabor model # gabor_model = gabor.GaborModel(stimulus) # # # generate a random gabor pRF estimate # estimate = np.double([1, 1, 1, 0.2, 284, 185, 0.25]) # # # generate the modeled BOLD response # response = gabor.compute_model_ts(estimate[0],estimate[1],estimate[2],estimate[3], # estimate[4],estimate[5],estimate[6], # stimulus.deg_x,stimulus.deg_y, # stimulus.stim_arr, tr_length, frames_per_tr, utils.zscore) # # # set the bounds for the parameter search # bounds = ((-10, 10),(-10, 10),(0.25,1.25),(-1,1),(0,360),(0,360),(0.01,2)) # # # fit the response # gabor_fit = gabor.GaborFit(response, gabor_model, bounds, tr_length, [0,0,0], 0, False, None, True) # # # assert equivalence # nt.assert_almost_equal(gabor_fit.x,estimate[0]) # nt.assert_almost_equal(gabor_fit.y,estimate[1]) # nt.assert_almost_equal(gabor_fit.sigma,estimate[2]) # nt.assert_almost_equal(gabor_fit.hrf_delay,estimate[3]) # # # def test_parallel_fit(): # # # stimulus features # pixels_across = 800 # pixels_down = 600 # viewing_distance = 38 # screen_width = 25 # thetas = np.arange(0,360,45) # num_steps = 20 # ecc = 10 # tr_length = 1.0 # num_voxels = 50 # tr_length = 1.0 # frames_per_tr = 1.0 # # # create the sweeping bar stimulus in memory # bar = simulate_bar_stimulus(pixels_across, pixels_down, viewing_distance, screen_width, thetas, num_steps, ecc) # # # create an instance of the Stimulus class # stimulus = VisualStimulus(bar, viewing_distance, screen_width, 0.05, 0, 0) # # # set up bounds for the grid search # bounds = [((-10,10),(-10,10),(0.25,5.25),(-5,5))]*num_voxels # indices = [(1,2,3)]*num_voxels # # # initialize the gabor model # gabor_model = gabor.GaborModel(stimulus) # # # generate a random pRF estimate # estimates = [(1,1,1,1)]*num_voxels # # # create the simulated time-series # timeseries = [] # for estimate in estimates: # response = MakeFastGaborPrediction(stimulus.deg_x, stimulus.deg_y, stimulus.stim_arr, estimate[0], estimate[1], estimate[2]) # hrf = utils.double_gamma_hrf(estimate[3], tr_length, frames_per_tr) # response = utils.zscore(np.convolve(response,hrf)[0:len(response)]) # timeseries.append(response) # # # package the data structure # dat = zip(timeseries, # repeat(gabor_model,num_voxels), # bounds, # repeat(tr_length,num_voxels), # indices, # repeat(0.20,num_voxels), # repeat(False,num_voxels)) # # # run analysis # num_cpus = multiprocessing.cpu_count()-1 # pool = multiprocessing.Pool(num_cpus) # output = pool.map(gabor.parallel_fit,dat) # pool.close() # pool.join() # # # assert equivalence # for gabor_fit,estimate in zip(output,estimates): # npt.assert_almost_equal(gabor_fit.x,estimate[0]) # npt.assert_almost_equal(gabor_fit.y,estimate[1]) # npt.assert_almost_equal(gabor_fit.sigma,estimate[2]) # npt.assert_almost_equal(gabor_fit.hrf_delay,estimate[3]) <file_sep>.. -*- mode: rst -*- |Travis|_ .. |Travis| image:: https://api.travis-ci.org/kdesimone/popeye.png?branch=master .. _Travis: https://travis-ci.org/kdesimone/popeye/ popeye ============ popeye is a Python module for estimating population receptive fields from from fMRI data built on top of SciPy and distributed under the 3-Clause BSD license. popeye is currently under development. 31 July 2013 <NAME> <EMAIL> Dependencies ============ popeye is tested to work under Python 2.7. The required dependencies to build the software are NumPy >= 1.6.2, SciPy >= 0.9, Nibabel >= 1.3.0, and Cython >= 0.18. For running the tests you need nose >= 1.1.2. Install ======= To install in your home directory, use:: python setup.py install --user To install for all users on Unix/Linux:: python setup.py build sudo python setup.py install<file_sep>[run] branch = True source = popeye include = popeye omit = */setup.py [report] include = popeye <file_sep>"""This module contains various utility methods that support functionality in other modules. The multiprocessing functionality also exists in this module, though that might change with time. """ from __future__ import division import sys, os, time import numpy as np import nibabel from scipy.misc import imresize from scipy.special import gamma from scipy.optimize import brute, fmin_powell from scipy.integrate import romb, trapz # normalize to a specific range def normalize(array, imin=-1, imax=1): """ A short-hand function for normalizing an array to a desired range. Parameters ---------- array : ndarray An array to be normalized. imin : float The desired minimum value in the output array. Default: -1 imax : float The desired maximum value in the output array. Default: 1 Returns ------- array : ndarray The normalized array with imin and imax as the minimum and maximum values. """ dmin = array.min() dmax = array.max() array -= dmin array *= imax - imin array /= dmax - dmin array += imin return array # generic gradient descent def gradient_descent_search(parameters, args, fit_bounds, data, error_function, objective_function): """ A generic gradient-descent error minimization function. The values inside `parameters` are used as a seed-point for a gradient-descent error minimization procedure [1]_. The user must also supply an `objective_function` for producing a model prediction and an `error_function` for relating that prediction to the actual, measured `data`. In addition, the user may also supply `fit_bounds`, containing pairs of upper and lower bounds for each of the values in parameters. If `fit_bounds` is specified, the error minimization procedure in `error_function` will return an Inf whether the parameters exceed the minimum or maxmimum values specified in `fit_bounds`. Parameters ---------- parameters : tuple A tuple of values representing a model setting. args : tuple Extra arguments to `objective_function` beyond those in `parameters`. fit_bounds : tuple A tuple containing the upper and lower bounds for each parameter in `parameters`. If a parameter is not bounded, simply use `None`. For example, `fit_bounds=((0,None),(-10,10),)` would bound the first parameter to be any positive number while the second parameter would be bounded between -10 and 10. data : ndarray The actual, measured time-series against which the model is fit. error_function : callable The error function that relates the model prediction to the measure data. The error function returns a float that represents the residual sum of squared errors between the prediction and the data. objective_function : callable The objective function that takes `parameters` and `args` and proceduces a model time-series. Returns ------- estimate : tuple The model solution given `parameters` and `objective_function`. References ---------- .. [1] <NAME>., <NAME>. (1963) A rapidly convergent descent method for minimization. Compututation Journal 6: 163-168. """ estimate, err, _, _, _, warnflag =\ fmin_powell(error_function, parameters, args=(args, fit_bounds, data, objective_function), full_output=True, disp=False) return estimate def brute_force_search(args, search_bounds, fit_bounds, data, error_function, objective_function): """ A generic brute-force grid-search error minimization function. The user specifies an `objective_function` and the corresponding `args` for generating a model prediction. The `brute_force_search` uses `search_bounds` to dictact the bounds for evenly sample the parameter space. In addition, the user must also supply `fit_bounds`, containing pairs of upper and lower bounds for each of the values in parameters. If `fit_bounds` is specified, the error minimization procedure in `error_function` will return an Inf whether the parameters exceed the minimum or maxmimum values specified in `fit_bounds`. The output of `brute_force_search` can be used as a seed-point for the fine-tuned solutions from `gradient_descent_search`. Parameters ---------- args : tuple Arguments to `objective_function` that yield a model prediction. search_bounds : tuple A tuple indicating the search space for the brute-force grid-search. The tuple contains pairs of upper and lower bounds for exploring a given dimension. For example `fit_bounds=((-10,10),(0,5),)` will search the first dimension from -10 to 10 and the second from 0 to 5. These values cannot be None. For more information, see `scipy.optimize.brute`. fit_bounds : tuple A tuple containing the upper and lower bounds for each parameter in `parameters`. If a parameter is not bounded, simply use `None`. For example, `fit_bounds=((0,None),(-10,10),)` would bound the first parameter to be any positive number while the second parameter would be bounded between -10 and 10. data : ndarray The actual, measured time-series against which the model is fit. error_function : callable The error function that relates the model prediction to the measure data. The error function returns a float that represents the residual sum of squared errors between the prediction and the data. objective_function : callable The objective function that takes `parameters` and `args` and proceduces a model time-series. Returns ------- estimate : tuple The model solution given `parameters` and `objective_function`. """ estimate, err, _, _ =\ brute(error_function, args=(args, fit_bounds, data, objective_function), ranges=search_bounds, Ns=5, finish=None, full_output=True, disp=False) return estimate # generic error function def error_function(parameters, args, bounds, data, objective_function, debug=False): """ A generic error function with bounding. Parameters ---------- parameters : tuple A tuple of values representing a model setting. args : tuple Extra arguments to `objective_function` beyond those in `parameters`. data : ndarray The actual, measured time-series against which the model is fit. objective_function : callable The objective function that takes `parameters` and `args` and proceduces a model time-series. debug : bool Useful for debugging a model, will print the parameters and error. Returns ------- error : float The residual sum of squared errors between the prediction and data. """ # check ifparameters are inside bounds for p, b in zip(parameters,bounds): # if not return an inf if b[0] and b[0] > p: return np.inf if b[1] and b[1] < p: return np.inf # merge the parameters and arguments ensemble = [] ensemble.extend(parameters) ensemble.extend(args) # compute the RSS error = np.sum((data-objective_function(*ensemble))**2) # print for debugging if debug: print(parameters, error) return error def double_gamma_hrf(delay, tr_length, frames_per_tr=1.0, integrator=trapz): """ The double-gamma hemodynamic reponse function (HRF) used to convolve with the stimulus time-series. The user specifies only the delay of the peak and under-shoot. The delay shifts the peak and under-shoot by a variable number of seconds. The other parameters are hard-coded. The HRF delay is modeled for each voxel independently. The double-gamme HRF and hard-coded values are based on previous work [1]_. Parameters ---------- delay : float The delay of the HRF peak and under-shoot. tr_length : float The length of the repetition time in seconds. integrator : callable The integration function for normalizing the units of the HRF so that the area under the curve is the same for differently delayed HRFs. Returns ------- hrf : ndarray The hemodynamic response function to convolve with the stimulus time-series. Reference ---------- <NAME>. (1999) Deconvolution of impulse response in event-related BOLD. fMRI. NeuroImage 9: 416-429. """ # add delay to the peak and undershoot params (alpha 1 and 2) # add delay to the peak and undershoot params (alpha 1 and 2) alpha_1 = 5.0/tr_length+delay/tr_length beta_1 = 1.0 c = 0.1 alpha_2 = 15.0/tr_length+delay/tr_length beta_2 = 1.0 t = np.arange(0,33/tr_length,tr_length/frames_per_tr) scale = 1 hrf = scale*( ( ( t ** (alpha_1) * beta_1 ** alpha_1 * np.exp( -beta_1 * t )) /gamma( alpha_1 )) - c * ( ( t ** (alpha_2 ) * beta_2 ** alpha_2 * np.exp( -beta_2 * t ))/gamma( alpha_2 ) ) ) if integrator: hrf /= integrator(hrf) return hrf def multiprocessor(targetMethod,stimData,funcData,metaData): """ Uses the multiprocessing toolbox to parallize the voxel-wise prf estimation across a user-specified number of cpus. Each voxel is treated as the atomic unit. Collections of voxels are sent to each of the user-specified allocated cpus for prf estimation. Currently, the strategy is to use multiprocessing.Process to start each batch of voxels on a given cpu. The results of each are written to a multiprocessing.Queue object, collected into a list of results, and returned to the user. Parameters ---------- stimData : dict A dictionary containing the stimulus array and other stimulus-related data. For details, see config.py funcData : ndarray A 4D numpy array containing the functional data to be used for the prf estimation. For details, see config.py metaData : dict A dictionary containing meta-data about the analysis being performed. For details, see config.py. Returns ------- output : list A list of multiprocessing.Queue objects that house the prf estimates for all the voxels analyzed as specified in `metaData`. The `output` will be a list whose length is equal to the number of cpus specified in `metaData`. """ # figure out how many voxels are in the mask & the number of jobs we have # allocated [xi,yi,zi] = metaData['voxels'] cpus = metaData['cpus'] # Set up the voxel lists for each job voxelLists = [] cutOffs = [int(np.floor(i)) for i in np.linspace(0,len(xi),cpus+1)] for i in range(len(cutOffs)-1): l = range(cutOffs[i],cutOffs[i+1]) voxelLists.append(l) # initialize Queues for managing the outputs of the jobs results_q = Queue() # start the jobs procs = [] for j in range(cpus): voxels = [xi[voxelLists[j]],yi[voxelLists[j]],zi[voxelLists[j]]] metaData['core_voxels'] = voxels p = Process(target=targetMethod,args=(stimData,funcData,metaData, results_q)) procs.append(p) p.start() # gather the outputs from the queue output = [] for i in range(len(procs)): output.append(results_q.get()) # close the jobs for p in procs: p.join() return output def percent_change(ts, ax=-1): """Returns the % signal change of each point of the times series along a given axis of the array time_series Parameters ---------- ts : ndarray an array of time series ax : int, optional (default to -1) the axis of time_series along which to compute means and stdevs Returns ------- ndarray the renormalized time series array (in units of %) Examples -------- >>> np.set_printoptions(precision=4) # for doctesting >>> ts = np.arange(4*5).reshape(4,5) >>> ax = 0 >>> percent_change(ts,ax) array([[-100. , -88.2353, -78.9474, -71.4286, -65.2174], [ -33.3333, -29.4118, -26.3158, -23.8095, -21.7391], [ 33.3333, 29.4118, 26.3158, 23.8095, 21.7391], [ 100. , 88.2353, 78.9474, 71.4286, 65.2174]]) >>> ax = 1 >>> percent_change(ts,ax) array([[-100. , -50. , 0. , 50. , 100. ], [ -28.5714, -14.2857, 0. , 14.2857, 28.5714], [ -16.6667, -8.3333, 0. , 8.3333, 16.6667], [ -11.7647, -5.8824, 0. , 5.8824, 11.7647]]) """ ts = np.asarray(ts) return (ts / np.expand_dims(np.mean(ts, ax), ax) - 1) * 100 def zscore(time_series, axis=-1): """Returns the z-score of each point of the time series along a given axis of the array time_series. Parameters ---------- time_series : ndarray an array of time series axis : int, optional the axis of time_series along which to compute means and stdevs Returns _______ zt : ndarray the renormalized time series array """ time_series = np.asarray(time_series) et = time_series.mean(axis=axis) st = time_series.std(axis=axis) sl = [slice(None)] * len(time_series.shape) sl[axis] = np.newaxis if sl == [None]: zt = (time_series - et)/st else: zt = time_series - et[sl] zt /= st[sl] return zt def randomize_voxels(voxels): """Returns a set of 3D coordinates that are randomized. Since the brain is highly spatially correlated and because computational time increases with increases in the prf size, we randomize the voxel order so that a particular core doesn't get stuck with a disproportionately high number of voxels whose sigma values are large. Parameters ---------- voxels : ndarray an array of voxel coordinates Returns _______ randomized_voxels : ndarray the shuffled voxel coordinates """ xi,yi,zi = voxels[:] randVec = np.random.rand(len(xi)) randInd = np.argsort(randVec) randomized_voxels = tuple((xi[randInd],yi[randInd],zi[randInd])) return randomized_voxels<file_sep>""" Cross-validation analysis of diffusion models """ from __future__ import division, print_function, absolute_import from copy import deepcopy import numpy as np def coeff_of_determination(data, model, axis=-1): """ Calculate the coefficient of determination for a model prediction, relative to data. Parameters ---------- data : ndarray The data model : ndarray The predictions of a model for this data. Same shape as the data. axis: int, optional The axis along which different samples are laid out (default: -1). Returns ------- COD : ndarray The coefficient of determination. This has shape `data.shape[:-1]` Notes ----- See: http://en.wikipedia.org/wiki/Coefficient_of_determination The coefficient of determination is calculated as: .. math:: R^2 = 100 * (1 - \frac{SSE}{SSD}) where SSE is the sum of the squared error between the model and the data (sum of the squared residuals) and SSD is the sum of the squares of the deviations of the data from the mean of the data (variance * N). """ residuals = data - model ss_err = np.sum(residuals ** 2, axis=axis) demeaned_data = data - np.mean(data, axis=axis)[..., np.newaxis] ss_tot = np.sum(demeaned_data **2, axis=axis) # Don't divide by 0: if np.all(ss_tot==0.0): return np.nan return 100 * (1 - (ss_err/ss_tot)) def kfold_xval(models, data, Fit, folds, fit_args, fit_kwargs): """ Perform k-fold cross-validation to generate out-of-sample predictions for each measurement. Parameters ---------- models : list of instances of Model A list containing the Model instances to be handed to Fit. If the length of `models` is 1, then it is assumed that `data` is composed of either a single run of data or of multiple runs with the same, repeated stimulus presented. data : ndarray Fit : the Fit class that will be instantiated with the left-in and left-out datasets. folds : int The number of divisions to apply to the data fit_args : Additional arguments to the model initialization fit_kwargs : Additional key-word arguments to the model initialization Notes ----- This function assumes that a prediction API is implemented in the Fit class from which a prediction is conducted. That is, the Fit object that gets generated upon fitting the model needs to have a `prediction` method, which receives a functional time-series and a Model class instance as input and produces a predicted signal as output. References ---------- .. [1] <NAME>., <NAME>. <NAME>., <NAME>., <NAME>., <NAME>., 2014. Evaluating the accuracy of diffusion models at multiple b-values with cross-validation. ISMRM 2014. """ # fold the data div_by_folds = np.mod(data.shape[-1], folds) # Make sure that an equal* number of samples get left out in each fold: if div_by_folds!= 0: msg = "The number of folds must divide the diffusion-weighted " msg += "data equally, but " msg = "np.mod(%s, %s) is %s"%(data.shape[-1], folds, div_by_folds) raise ValueError(msg) # number of samples per fold n_in_fold = data.shape[-1]/folds # iniitialize a prediciton. this may not be necessary in popeye prediction = np.zeros(data.shape[-1]) # We are going to leave out some randomly chosen samples in each iteration order = np.random.permutation(data.shape[-1]) # initilize a list of predictions predictions = [] dat = [] # Do the thing for k in range(folds): # Select the timepoints for this fold fold_mask = np.ones(data.shape[-1], dtype=bool) fold_idx = order[k*n_in_fold:(k+1)*n_in_fold] fold_mask[fold_idx] = False # Grab the left-in data and concatenate the runs left_in_data = np.reshape(data[...,fold_mask], data.shape[0]*2, order='F') # Grab the left-out data and concatenate the runs left_out_data = np.reshape(data[...,~fold_mask], data.shape[0]*2, order='F') # If there is only 1 model specified, repeat it over the concatenated functionals if len(models) == 1: # Grab the stimulus instance from one of the models stimulus = deepcopy(models[0].stimulus) # Tile it according to the number of runs ... stimulus.stim_arr = np.tile(stimulus.stim_arr.copy(), folds) stimulus.stim_arr_coarse = np.tile(stimulus.stim_arr_coarse.copy(), folds) # Create a new Model instance model = models[0].__class__(stimulus) # otherwise, concatenate each of the unique stimuli elif len(models) == data.shape[-1]: # Grab the stimulus instance from one of the models stimulus = deepcopy(models[fold_idx[0]].stimulus) # Grab the first model in the fold stim_arr_cat = stimulus.stim_arr stim_arr_coarse_cat = stimulus.stim_arr_coarse # Grab the remaining models in the fold for f in fold_idx[1::]: stim_arr_cat = np.concatenate((stim_arr_cat, models[f].stimulus.stim_arr.copy()), axis=-1) stim_arr_coarse_cat = np.concatenate((stim_arr_coarse_cat, models[f].stimulus.stim_arr_coarse.copy()), axis=-1) # Put the concatenated arrays into the Stimulus instance stimulus.stim_arr = stim_arr_cat stimulus.stim_arr_coarse = stim_arr_coarse_cat # Create a new Model instance model = models[0].__class__(stimulus) # initialize the left-in fit object ensemble = [] ensemble.append(model) ensemble.append(left_in_data) ensemble.extend(fit_args) ensemble.extend(fit_kwargs.values()) left_in_fit = Fit(*ensemble) # initialize the left-out fit object ensemble = [] ensemble.append(model) ensemble.append(left_out_data) ensemble.extend(fit_args) ensemble.extend(fit_kwargs.values()) left_out_fit = Fit(*ensemble) # run the left-in Fit left_out_fit.estimate = left_in_fit.estimate # store the prediction predictions.append(left_out_fit.prediction) # store the left-out data dat.append(left_out_fit.data) return dat, predictions <file_sep>from __future__ import division import time import numpy as np from scipy.ndimage.measurements import standard_deviation from scipy.optimize import fmin_powell, fmin def error_function(sigma,old_sigma,xs,ys,degX,degY,voxel_RF): if sigma <= 0: return np.inf if sigma > old_sigma: return np.inf neural_RF = MakeFastRFs(degX,degY,xs,ys,sigma) neural_RF /= np.max(neural_RF) error = np.sum((neural_RF-voxel_RF)**2) return error def simulate_neural_sigma(stimData,funcData,metaData,results_q,verbose=True): # grab voxel indices xi,yi,zi = metaData['core_voxels'] # initialize a list in which to store the results results = [] # printing niceties numVoxels = len(xi) voxelCount = 1 printLength = len(xi)/10 # grab the pRF volume pRF = funcData['pRF_cartes'] pRF_polar = funcData['pRF_polar'] # grab the 3D meshgrid for creating spherical mask around a seed voxel X,Y,Z = funcData['volume_meshgrid'][:] # main loop for xvoxel,yvoxel,zvoxel in zip(xi,yi,zi): # get a timestamp toc = time.clock() # grab the pRF estimate for the seed voxel x_0 = pRF[xvoxel,yvoxel,zvoxel,0] y_0 = pRF[xvoxel,yvoxel,zvoxel,1] s_0 = pRF[xvoxel,yvoxel,zvoxel,2] d_0 = pRF[xvoxel,yvoxel,zvoxel,3] old_sigma = s_0.copy() # recreate the voxel's pRF voxel_RF = MakeFastRF(stimData['degXFine'],stimData['degYFine'],x_0,y_0,s_0) voxel_RF /= np.max(voxel_RF) voxel_RF[np.isnan(voxel_RF)] = 0 # find all voxels within the neighborhood d = np.sqrt((X-xvoxel)**2 + (Y-yvoxel)**2 + (Z-zvoxel)**2) mask = np.zeros_like(d) mask[d <= 2] = 1 mask[xvoxel,yvoxel,zvoxel] = 0 [dx,dy,dz] = np.nonzero((mask==1) & (pRF[:,:,:,6]>0.20)) # compute the mean visuotopic scatter meanScatter = np.mean(np.sqrt((pRF[dx,dy,dz,0]-x_0)**2 + (pRF[dx,dy,dz,1]-y_0)**2))/2 # find all the pixels that are within the scatter range of the pRF [xpixels,ypixels] = np.nonzero((stimData['degXFine']-x_0)**2+(stimData['degYFine']-y_0)**2< meanScatter**2) if xpixels.any(): randPixels = np.random.randint(0,len(xpixels),metaData['neurons']) # grab the locations from the coordinate matrices xs = stimData['degXFine'][xpixels[randPixels],ypixels[randPixels]] ys = stimData['degYFine'][xpixels[randPixels],ypixels[randPixels]] # compute the neural sigma and the difference in size sigma_phat = fmin_powell(error_function,s_0,args=(old_sigma,xs,ys,stimData['degXFine'],stimData['degYFine'],voxel_RF),full_output=True,disp=False) percentChange = ((sigma_phat[0]-s_0)/s_0)*100 # get a timestamp tic = time.clock() # # print the details of the estimation for this voxel if verbose: percentDone = (voxelCount/numVoxels)*100 print("%.02d%% VOXEL=(%.03d,%.03d,%.03d) TIME=%.03E ERROR=%.03E OLD=%.03f NEW=%.03f DIFF=%+.02E%% SCATTER=%.02E" %(percentDone, xvoxel, yvoxel, zvoxel, tic-toc, sigma_phat[1], s_0, sigma_phat[0], percentChange, meanScatter)) # store the results results.append((xvoxel,yvoxel,zvoxel,sigma_phat[0],sigma_phat[1],meanScatter,percentChange)) # interate variable voxelCount += 1 # add results to the queue results_q.put(results) return results_q <file_sep>#!/usr/bin/python """ Classes and functions for fitting population encoding models """ from __future__ import division import time import warnings import gc warnings.simplefilter("ignore") import numpy as np from scipy.optimize import brute, fmin_powell from scipy.special import gamma from scipy.stats import linregress from scipy.signal import fftconvolve, decimate from scipy.misc import imresize from scipy.ndimage.filters import median_filter from scipy.integrate import romb, trapz from scipy.interpolate import interp1d import nibabel from popeye.onetime import auto_attr import popeye.utilities as utils from popeye.base import PopulationModel, PopulationFit from popeye.spinach import generate_strf_timeseries def recast_estimation_results(output, grid_parent, write=True): """ Recasts the output of the pRF estimation into two nifti_gz volumes. Takes `output`, a list of multiprocessing.Queue objects containing the output of the pRF estimation for each voxel. The pRF estimates are expressed in both polar and Cartesian coordinates. If the default value for the `write` parameter is set to False, then the function returns the arrays without writing the nifti files to disk. Otherwise, if `write` is True, then the two nifti files are written to disk. Each voxel contains the following metrics: 0 x / polar angle 1 y / eccentricity 2 sigma 3 HRF delay 4 RSS error of the model fit 5 correlation of the model fit Parameters ---------- output : list A list of PopulationFit objects. grid_parent : nibabel object A nibabel object to use as the geometric basis for the statmap. The grid_parent (x,y,z) dim and pixdim will be used. Returns ------ cartes_filename : string The absolute path of the recasted pRF estimation output in Cartesian coordinates. plar_filename : string The absolute path of the recasted pRF estimation output in polar coordinates. """ # load the gridParent dims = list(grid_parent.shape) dims = dims[0:3] dims.append(4) # initialize the statmaps nii_out = np.zeros(dims) # extract the pRF model estimates from the results queue output for fit in output: if fit.__dict__.has_key('fit_stats'): nii_out[fit.voxel_index] = (fit.center_freq, fit.bandwidth, fit.rss, fit.fit_stats[2]) # get header information from the gridParent and update for the pRF volume aff = grid_parent.get_affine() hdr = grid_parent.get_header() hdr.set_data_shape(dims) # recast as nifti nif = nibabel.Nifti1Image(nii_out,aff,header=hdr) nif.set_data_dtype('float32') return nif # this is actually not used, but it serves as the model for the cython function ... def gaussian_2D(X, Y, x0, y0, sigma_x, sigma_y, degrees, amplitude=1): theta = degrees*np.pi/180 a = np.cos(theta)**2/2/sigma_x**2 + np.sin(theta)**2/2/sigma_y**2 b = -np.sin(2*theta)/4/sigma_x**2 + np.sin(2*theta)/4/sigma_y**2 c = np.sin(theta)**2/2/sigma_x**2 + np.cos(theta)**2/2/sigma_y**2 Z = amplitude*np.exp( - (a*(X-x0)**2 + 2*b*(X-x0)*(Y-y0) + c*(Y-y0)**2)) return Z def gaussian_1D(freqs, center_freq, sd, integrator=trapz): gaussian = np.exp(-0.5 * ((freqs - (center_freq+1))/sd)**2) / (np.sqrt(2*np.pi) * sd) return gaussian def compute_model_ts_1D(center_freq, sd, times, freqs, spectrogram, tr_length, convolve=True): # invoke the gaussian # gaussian = gaussian_1D(freqs, center_freq, sd) # now create the stimulus time-series # stim = np.sum(gaussian[:,np.newaxis] * spectrogram,axis=0) stim = generate_strf_timeseries(freqs, spectrogram, center_freq, sd) # recast the stimulus into a time-series that i can decimate old_time = np.linspace(0,np.ceil(times[-1]),len(stim)) new_time = np.linspace(0,np.ceil(times[-1]),np.ceil(times[-1])*10) f = interp1d(old_time,stim) new_stim = f(new_time) # hard-set the hrf_delay hrf_delay = 0 # convolve it with the HRF hrf = utils.double_gamma_hrf(hrf_delay, tr_length, 10) model = fftconvolve(new_stim, hrf)[0:len(new_stim)] # for debugging if convolve: return utils.zscore(model) else: return utils.zscore(new_stim) # this method is used to simply multiprocessing.Pool interactions def parallel_fit(args): # unpackage the arguments model = args[0] data = args[1] search_bounds = args[2] fit_bounds = args[3] tr_length = args[4] voxel_index = args[5] auto_fit = args[6] verbose = args[7] # fit the data fit = SpectrotemporalFit(model, data, search_bounds, fit_bounds, tr_length, voxel_index, auto_fit, verbose) return fit class SpectrotemporalModel(PopulationModel): """ Gaussian population receptive field model. """ def __init__(self, stim_arr): # this is a weird notation PopulationModel.__init__(self, stim_arr) class SpectrotemporalFit(PopulationFit): def __init__(self, model, data, search_bounds, fit_bounds, tr_length, voxel_index=None, auto_fit=True, verbose=True): self.model = model self.data = data self.search_bounds = search_bounds self.fit_bounds = fit_bounds self.tr_length = tr_length self.voxel_index = voxel_index self.auto_fit = auto_fit self.verbose = verbose # just make sure that all data is inside the mask if self.auto_fit: tic = time.clock() self.ballpark_estimate; self.estimate; self.fit_stats; self.rss; toc = time.clock() # print to screen if verbose if self.verbose and ~np.isnan(self.rss) and ~np.isinf(self.rss): # we need a voxel index for the print if self.voxel_index is None: self.voxel_index = (0,0,0) # print print("VOXEL=(%.03d,%.03d,%.03d) TIME=%.03d RVAL=%.02f CENTER=%.05d SIGMA=%.05d" %(self.voxel_index[0], self.voxel_index[1], self.voxel_index[2], int(toc-tic), self.fit_stats[2], self.center_freq, self.bandwidth)) @auto_attr def ballpark_estimate(self): return utils.brute_force_search((self.model.stimulus.times, self.model.stimulus.freqs, self.model.stimulus.spectrogram, self.model.stimulus.tr_length), self.search_bounds, self.fit_bounds, self.data, utils.error_function, compute_model_ts_1D) @auto_attr def estimate(self): return utils.gradient_descent_search((self.f0, self.bw0), (self.model.stimulus.times, self.model.stimulus.freqs, self.model.stimulus.spectrogram, self.model.stimulus.tr_length), self.fit_bounds, self.data, utils.error_function, compute_model_ts_1D) @auto_attr def f0(self): return self.ballpark_estimate[0] @auto_attr def bw0(self): return self.ballpark_estimate[1] @auto_attr def beta0(self): return self.ballpark_estimate[2] # @auto_attr # def hrf0(self): # return self.ballpark_estimate[2] @auto_attr def center_freq(self): return self.estimate[0] @auto_attr def bandwidth(self): return self.estimate[1] @auto_attr def beta(self): return self.estimate[2] # @auto_attr # def hrf_delay(self): # return self.estimate[2] @auto_attr def prediction(self): return compute_model_ts_1D(self.center_freq, self.bandwidth, self.model.stimulus.times, self.model.stimulus.freqs, self.model.stimulus.spectrogram, self.model.stimulus.tr_length) @auto_attr def stim_timeseries(self): return compute_model_ts_1D(self.center_freq, self.bandwidth, self.model.stimulus.times, self.model.stimulus.freqs, self.model.stimulus.spectrogram, self.model.stimulus.tr_length, False) @auto_attr def fit_stats(self): return linregress(self.data, self.prediction) @auto_attr def rss(self): return np.sum((self.data - self.prediction)**2) @auto_attr def receptive_field(self): return gaussian_1D(self.model.stimulus.freqs, self.center_freq, self.bandwidth) <file_sep>""" First pass at a stimulus model for abstracting the qualities and functionality of a stimulus into an abstract class. For now, we'll assume the stimulus model only pertains to visual stimuli on a visual display over time (i.e., 3D). Hopefully this can be extended to other stimuli with an arbitrary number of dimensions (e.g., auditory stimuli). """ from __future__ import division import ctypes, gc import numpy as np from numpy.lib import stride_tricks from scipy.misc import imresize from popeye.onetime import auto_attr import nibabel from popeye.base import StimulusModel def compute_stft(signal, freq_window, overlap=0.5, window=np.hanning): win = window(freq_window) hop_size = int(freq_window - np.floor(overlap * freq_window)) # zeros at beginning (thus center of 1st window should be for sample nr. 0) samples = np.append(np.zeros(np.floor(freq_window/2.0)), signal) # cols for windowing cols = np.ceil( (len(samples) - freq_window) / float(hop_size)) + 1 # zeros at end (thus samples can be fully covered by frames) samples = np.append(samples, np.zeros(freq_window)) frames = stride_tricks.as_strided(samples, shape=(cols, freq_window), strides=(samples.strides[0]*hop_size, samples.strides[0])) frames *= win return np.fft.rfft(frames) def logscale_stft(stft, scale, timebins): # create stft with new freq bins log_stft = np.complex128(np.zeros([timebins, len(scale)])) for i in range(0, len(scale)): if i == len(scale)-1: log_stft[:,i] = np.sum(stft[:,scale[i]:], axis=1) else: log_stft[:,i] = np.sum(stft[:,scale[i]:scale[i+1]], axis=1) log_stft[log_stft == -np.inf] = 0 return log_stft def generate_spectrogram(log_stft, all_freqs, num_timepoints, tr_sampling_rate): s = 20.*np.log10(np.abs(log_stft)/10e-6) s[s == -np.inf] = 0 s = np.transpose(s) s /= np.max(s) # im = imresize(s,(len(all_freqs), num_timepoints * tr_sampling_rate)) return s def generate_coordinate_matrices(tr_times, all_freqs): return np.meshgrid(tr_times, all_freqs) def rescale_frequencies(stimulus, scale_factor): dims = stimulus.shape scale_x = np.int(dims[0]*scale_factor) scale_y = dims[1] dims = (scale_x,scale_y) return imresize(stimulus, dims) # This should eventually be VisualStimulus, and there would be an abstract class layer # above this called Stimulus that would be generic for n-dimentional feature spaces. class AuditoryStimulus(StimulusModel): """ Abstract class for stimulus model """ def __init__(self, stim_arr, tr_length, freq_window = 2**10, time_window = 0.1, freq_factor=1.0, sampling_rate=44100, tr_sampling_rate=10, scale_factor=1.0): # this is a weird notation StimulusModel.__init__(self, stim_arr) if time_window > tr_length / 2: print("You must give a time window size in seconds that is half your TR length or less.") return None # absorb the vars self.tr_length = tr_length # the TR in s self.freq_factor = freq_factor # the scaling factor of the freqs, i think its only for plotting self.sampling_rate = sampling_rate # the sampling rate of the wav self.tr_sampling_rate = tr_sampling_rate # the number of samples from a single TR self.scale_factor = scale_factor self.time_window = time_window # in s, this is the number of slices we'll make for each TR self.freq_window = freq_window stft = compute_stft(self.stim_arr, self.freq_window) self.stft = np.memmap('%s%s_%d.npy' %('/tmp/','stft',self.__hash__()),dtype = np.double, mode = 'w+',shape = np.shape(stft)) self.stft[:] = stft[:] log_stft = logscale_stft(self.stft, self.scale, self.timebins) self.log_stft = np.memmap('%s%s_%d.npy' %('/tmp/','log_stft',self.__hash__()),dtype = np.double, mode = 'w+',shape = np.shape(log_stft)) self.log_stft[:] = log_stft[:] spectrogram = generate_spectrogram(self.log_stft, self.all_freqs, self.num_timepoints, self.tr_sampling_rate) self.spectrogram = np.memmap('%s%s_%d.npy' %('/tmp/','spectrogram',self.__hash__()),dtype = np.double, mode = 'w+',shape = np.shape(spectrogram)) self.spectrogram[:] = spectrogram[:] time_coord, freq_coord = generate_coordinate_matrices(self.tr_times, self.all_freqs) self.time_coord = np.memmap('%s%s_%d.npy' %('/tmp/','time_coord',self.__hash__()),dtype = np.double, mode = 'w+',shape = np.shape(time_coord)) self.time_coord[:] = time_coord[:] self.freq_coord = np.memmap('%s%s_%d.npy' %('/tmp/','freq_coord',self.__hash__()),dtype = np.double , mode = 'w+',shape = np.shape(freq_coord)) self.freq_coord[:] = freq_coord[:] # create coarse versions of these # spectrogram_coarse = rescale_frequencies(spectrogram, self.scale_factor) # self.spectrogram_coarse = np.memmap('%s%s_%d.npy' %('/tmp/','spectrogram_coarse',self.__hash__()),dtype = np.double, mode = 'w+',shape = np.shape(spectrogram_coarse)) # self.spectrogram_coarse[:] = spectrogram_coarse[:] # # time_coord_coarse = rescale_frequencies(time_coord, self.scale_factor) # self.time_coord_coarse = np.memmap('%s%s_%d.npy' %('/tmp/','time_coord_coarse',self.__hash__()),dtype = np.double, mode = 'w+',shape = np.shape(time_coord_coarse)) # self.time_coord_coarse[:] = time_coord_coarse[:] # # freq_coord_coarse = rescale_frequencies(freq_coord, self.scale_factor) # self.freq_coord_coarse = np.memmap('%s%s_%d.npy' %('/tmp/','freq_coord_coarse',self.__hash__()),dtype = np.double, mode = 'w+',shape = np.shape(freq_coord_coarse)) # self.freq_coord_coarse[:] = time_coord_coarse[:] @auto_attr def num_timepoints(self): return np.int(self.stim_arr.shape[0]/self.sampling_rate) @auto_attr def tr_times(self): return np.linspace(self.all_freqs[0],self.all_freqs[-1],self.tr_sampling_rate) @auto_attr def scale(self): scale = np.linspace(0, 1, self.freqbins) ** self.freq_factor scale *= (self.freqbins-1)/max(scale) scale = np.unique(np.round(scale)) return scale @auto_attr def timebins(self): return np.shape(self.stft)[0] @auto_attr def freqbins(self): return np.shape(self.stft)[1] @auto_attr def all_freqs(self): return np.abs(np.fft.fftfreq(self.freqbins*2, 1./self.sampling_rate)[:self.freqbins+1]) @auto_attr def all_times(self): return np.arange(0,self.num_timepoints,self.time_window) <file_sep>Getting started ================= To get started using :mod:`popeye`, you will need to organize your data in the following manner: - You put the lime in the coconut. - Drink it all up. To run the analysis:: from popeye.base import PopulationModel, PopulationFit from popeye.stimulus import Stimulus # stimulus features pixels_across = 800 pixels_down = 600 viewing_distance = 38 screen_width = 25 thetas = np.arange(0,360,45) num_steps = 30 ecc = 10 tr_length = 1.0 # create the sweeping bar stimulus in memory bar = simulate_bar_stimulus(pixels_across, pixels_down, viewing_distance, screen_width, thetas, num_steps, ecc) # instantiate an instance of the Stimulus class stimulus = Stimulus(bar, viewing_distance, screen_width, 0.05, 0, 0) # set up bounds for the grid search bounds = ((-10, 10), (-10, 10), (0.25, 5.25), (-5, 5)) # initialize the gaussian model prf_model = prf.GaussianModel(stimulus) # generate the modeled BOLD response response = prf.MakeFastPrediction(stimulus.deg_x, stimulus.deg_y, stimulus.stim_arr, estimate[0], estimate[1], estimate[2]) hrf = prf.double_gamma_hrf(estimate[3], 1) response = utils.zscore(np.convolve(response, hrf)[0:len(response)]) # fit the response prf_fit = prf.GaussianFit(prf_model, response, bounds, tr_length) <file_sep>import os import multiprocessing from itertools import repeat import numpy as np import numpy.testing as npt import nose.tools as nt import scipy.signal as ss import popeye.utilities as utils from popeye import og import popeye.xvalidation as xval from popeye.visual_stimulus import VisualStimulus, simulate_bar_stimulus from popeye.spinach import generate_og_timeseries def test_coeff_of_determination(): # make up some data and a model data = np.arange(0,100) model = np.arange(0,100) # compute cod cod = xval.coeff_of_determination(data,model) # assert npt.assert_equal(cod, 100) def test_kfold_xval_repeated_runs(): # stimulus features pixels_across = 800 pixels_down = 600 viewing_distance = 38 screen_width = 25 thetas = np.arange(0,360,45) num_steps = 20 ecc = 10 tr_length = 1.0 scale_factor = 0.05 dtype = 'short' num_runs = 4 folds = 2 # create the sweeping bar stimulus in memory bar = simulate_bar_stimulus(pixels_across, pixels_down, viewing_distance, screen_width, thetas, num_steps, ecc) # create an instance of the Stimulus class stimulus = VisualStimulus(bar, viewing_distance, screen_width, scale_factor, dtype) # set up bounds for the grid search search_bounds = ((-10,10),(-10,10),(0.25,5.25),(0.1,1e2),(-5,5)) fit_bounds = ((-12,12),(-12,12),(1/stimulus.ppd,12),(0.1,1e3),(-5,5)) # initialize the gaussian model model = og.GaussianModel(stimulus) # generate a random pRF estimate x = -5.24 y = 2.58 sigma = 1.24 beta = 2.5 hrf_delay = -0.25 # create the args context for calling the Fit class fit_args = [search_bounds, fit_bounds, tr_length, [0,0,0]] fit_kwargs = {'auto_fit': False, 'verbose' : False} # create a series of "runs" data = np.zeros((stimulus.stim_arr.shape[-1],num_runs)) for r in range(num_runs): # fill out the data list data[:,r] = og.compute_model_ts(x, y, sigma, beta, hrf_delay, stimulus.deg_x, stimulus.deg_y, stimulus.stim_arr, tr_length) # get predictions out for each of the folds ... models = (model,) left_out_data, predictions = xval.kfold_xval(models, data, og.GaussianFit, folds, fit_args, fit_kwargs) # assert the coeff of determination is 100 for each prediction for k in range(folds): cod = xval.coeff_of_determination(left_out_data[k], predictions[k]) npt.assert_almost_equal(cod,100, 4) def test_kfold_xval_unique_runs(): # stimulus features pixels_across = 800 pixels_down = 600 viewing_distance = 38 screen_width = 25 thetas = np.arange(0,360,45) num_steps = 20 ecc = 10 tr_length = 1.0 frames_per_tr = 1.0 scale_factor = 0.05 dtype = 'short' num_runs = 4 folds = 2 # create the sweeping bar stimulus in memory bar = simulate_bar_stimulus(pixels_across, pixels_down, viewing_distance, screen_width, thetas, num_steps, ecc) # create an instance of the Stimulus class stimulus = VisualStimulus(bar, viewing_distance, screen_width, scale_factor, dtype=) # set up bounds for the grid search search_bounds = ((-10,10),(-10,10),(0.25,5.25),(-5,5),(0.1,1e2)) fit_bounds = ((-12,12),(-12,12),(1/stimulus.ppd,12),(-5,5),(0.1,1e2)) # initialize the gaussian model model = og.GaussianModel(stimulus) # generate a random pRF estimate x = -5.24 y = 2.58 sigma = 1.24 beta = 2.5 hrf_delay = -0.25 # create the args context for calling the Fit class fit_args = [search_bounds, fit_bounds, tr_length, [0,0,0],] fit_kwargs = {'auto_fit': False, 'verbose' : False} # create a series of "runs" data = np.zeros((stimulus.stim_arr.shape[-1],num_runs)) for r in range(num_runs): # fill out the data list data[:,r] = og.compute_model_ts(x, y, sigma, beta, hrf_delay, stimulus.deg_x, stimulus.deg_y, stimulus.stim_arr, tr_length) # get predictions out for each of the folds ... models = np.tile(model,num_runs) left_out_data, predictions = xval.kfold_xval(models, data, gaussian.GaussianFit, folds, fit_args, fit_kwargs) # assert the coeff of determination is 100 for each prediction for k in range(folds): cod = xval.coeff_of_determination(left_out_data[k], predictions[k]) npt.assert_almost_equal(cod,100, 4)<file_sep>import numpy as np import numpy.testing as npt import nose.tools as nt from popeye.visual_stimulus import generate_coordinate_matrices from popeye.spinach import generate_og_receptive_field, generate_og_timeseries def test_generate_og_receptive_field(): xpixels = 100 # simulated screen width ypixels = 100 # simulated screen height ppd = 1 # simulated visual angle scale_factor = 1.0 # simulated stimulus resampling rate xcenter = 0 # x coordinate of the pRF center ycenter = 0 # y coordinate of the pRF center sigma = 1 # width of the pRF test_value = 6 # this is the sum of a gaussian given 1 ppd # and a 1 sigma prf centered on (0,0) # generate the visuotopic coordinates dx,dy = generate_coordinate_matrices(xpixels, ypixels, ppd, scale_factor) # generate a pRF at (0,0) and 1 sigma wide rf = generate_og_receptive_field(dx, dy, xcenter, ycenter, sigma) # compare the volume of the pRF to a known value nt.assert_equal(np.round(np.sum(rf)), test_value) def test_generate_og_timeseries(): xpixels = 100 # simulated screen width ypixels = 100 # simulated screen height ppd = 1 # simulated visual angle scaleFactor = 1.0 # simulated stimulus resampling rate xcenter = 0 # x coordinate of the pRF center ycenter = 0 # y coordinate of the pRF center sigma = 10 # width of the pRF # generate the visuotopic coordinates dx,dy = generate_coordinate_matrices(xpixels, ypixels, ppd, scaleFactor) timeseries_length = 15 # number of frames to simulate our stimulus array # initialize the stimulus array stim_arr = np.zeros((xpixels, ypixels, timeseries_length)).astype('short') # make a circular mask appear for the first 5 frames xi,yi = np.nonzero(np.sqrt((dx-xcenter)**2 + (dy-ycenter)**2)<sigma) stim_arr[xi,yi,0:5] = 1 # make an annulus appear for the next 5 frames xi,yi = np.nonzero(np.sqrt((dx-xcenter)**2 + (dy-ycenter)**2)>sigma) stim_arr[xi,yi,5:10] = 1 # make a circular mask appear for the next 5 frames xi,yi = np.nonzero(np.sqrt((dx-xcenter)**2 + (dy-ycenter)**2)<sigma) stim_arr[xi,yi,10::] = 1 # make the response prediction response = generate_og_timeseries(dx, dy, stim_arr, xcenter, ycenter, sigma) # make sure the RSS is 0 step = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]) rval = np.corrcoef(response, step)[0, 1] # The voxel responds when the stimulus covers its PRF, so it perfectly # correlates with a step function: nt.assert_equal(round(rval, 3), 1)
2908ad85e9d5e57ddf5de642f0ed4288ad6a8b0c
[ "Python", "reStructuredText", "INI" ]
23
Python
mekman/popeye
772bfbdd00216edf17430473c28975096cd218a3
63b90e32618353ca022e590e8633d8a6cb818b25
refs/heads/master
<repo_name>residentpipe/Bang-Bang<file_sep>/Bang Bang/Assets/Scripts/Disparo.cs using UnityEngine; using System.Collections; using UnityEngine.UI; public class Disparo : MonoBehaviour { float Velocidad; Rigidbody2D bala; SpringJoint2D union; Vector3 mousePos; Vector3 objectPos; public Text texto; public GameObject sonido; public GameObject cañon; float Angulo; // Use this for initialization void Start () { bala = GetComponent<Rigidbody2D>(); union = GetComponent<SpringJoint2D>(); sonido = GameObject.FindGameObjectWithTag("audio_canon"); cañon= GameObject.FindGameObjectWithTag("canon"); } // Update is called once per frame void FixedUpdate() { string potencia = texto.text; Velocidad = float.Parse(potencia); if (Input.GetKeyDown(KeyCode.Space)) { sonido.GetComponent<AudioSource>().Play(); Destroy(union); mousePos = Input.mousePosition; mousePos.z = 0f; objectPos = Camera.main.WorldToScreenPoint(cañon.transform.position); mousePos.x = mousePos.x - objectPos.x; mousePos.y = mousePos.y - objectPos.y; Angulo = Mathf.Atan2(mousePos.y, mousePos.x); Vector2 fuerza = new Vector2(Velocidad * Mathf.Cos(Angulo), Velocidad * Mathf.Sin(Angulo)); bala.AddForce(fuerza); } } } <file_sep>/Bang Bang/Assets/Scripts/facebook.cs using UnityEngine; using System.Collections; using Facebook.Unity; using System.Collections.Generic; using UnityEngine.SceneManagement; using UnityEngine.UI; public class facebook : MonoBehaviour { public Text usuario; public Image foto; // Include Facebook namespace // Awake function from Unity's MonoBehavior void Awake() { if (!FB.IsInitialized) { // Initialize the Facebook SDK FB.Init(InitCallback, OnHideUnity); } else { // Already initialized, signal an app activation App Event FB.ActivateApp(); } } private void InitCallback() { if (FB.IsInitialized) { // Signal an app activation App Event FB.ActivateApp(); // Continue with Facebook SDK // ... } else { Debug.Log("Failed to Initialize the Facebook SDK"); } } private void OnHideUnity(bool isGameShown) { if (!isGameShown) { // Pause the game - we will need to hide Time.timeScale = 0; } else { // Resume the game - we're getting focus again Time.timeScale = 1; } } public void Login() { var perms = new List<string>() { "public_profile", "email", "user_friends" }; FB.LogInWithReadPermissions(perms, AuthCallback); } private void AuthCallback(ILoginResult result) { if (FB.IsLoggedIn) { // AccessToken class will have session details var aToken = Facebook.Unity.AccessToken.CurrentAccessToken; // Print current access token's User ID Debug.Log(aToken.UserId); // Print current access token's granted permissions foreach (string perm in aToken.Permissions) { Debug.Log(perm); } FB.API("/me?fields=first_name", HttpMethod.GET, MostrarNombre); FB.API("/me/picture?type=square&height=128&width=128", HttpMethod.GET, MostrarFoto); SceneManager.LoadScene("EscenaJuego"); } else { Debug.Log("User cancelled login"); } } public void MostrarNombre(IResult result) { if (result.Error == null) { usuario.text = (string)result.ResultDictionary["first_name"]; } } public void MostrarFoto(IGraphResult result) { if(result.Texture != null) { foto.sprite = Sprite.Create(result.Texture, new Rect(0,0,128,128), new Vector2()); }else { Debug.Log("no pic"); } } } <file_sep>/Bang Bang/Assets/Scripts/Choque.cs using UnityEngine; using System.Collections; public class Choque : MonoBehaviour { AudioSource sonidoexplosion; public GameObject Explosion; public GameObject cañon; // Use this for initialization void Awake() { sonidoexplosion = GetComponent<AudioSource>(); } void OnCollisionEnter2D(Collision2D col) { if (col.gameObject.tag == "cañonEnemigo") { GameObject cañonEnemigo = GameObject.FindGameObjectWithTag("cañonEnemigoPadre"); Explosion = (GameObject)Instantiate(Explosion); Explosion.transform.position = cañon.transform.position; Destroy(cañonEnemigo); sonidoexplosion.PlayDelayed(0.5f); GetComponent<Renderer>().enabled = false; Destroy(gameObject,4); } } } <file_sep>/Bang Bang/Assets/Scripts/movimientoFantasma.cs using UnityEngine; using System.Collections; public class movimientoFantasma : MonoBehaviour { // Use this for initialization public GameObject startPoint; public GameObject endPoint; public float velocidad; private bool haciaDer; void Start () { if (haciaDer) { transform.position = endPoint.transform.position; } else { transform.position = startPoint.transform.position; } } // Update is called once per frame void Update () { if (!haciaDer) { transform.position = Vector3.MoveTowards (transform.position, startPoint.transform.position, velocidad * Time.deltaTime); if(transform.position == startPoint.transform.position){ haciaDer = true; GetComponent<SpriteRenderer> ().flipX = true; } } else { transform.position = Vector3.MoveTowards (transform.position, endPoint.transform.position, velocidad * Time.deltaTime); if(transform.position == endPoint.transform.position){ haciaDer = false; GetComponent<SpriteRenderer> ().flipX = false; } } } }
e35833148eecf37ff733ca192f7e78b657e8ae08
[ "C#" ]
4
C#
residentpipe/Bang-Bang
6519bde9259584b96a1bb351aa621851218662b7
3b635fbb52ab331bf23d18254e2b061d833b36ca
refs/heads/main
<repo_name>Abdulrahman-Adel/Minimal-Computer-Hardware-Store<file_sep>/src/OrderPage.java import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import java.awt.Window; import java.awt.Color; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.DefaultComboBoxModel; import javax.swing.JTextField; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.event.PopupMenuListener; import javax.swing.event.PopupMenuEvent; import java.awt.event.ItemListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.ArrayList; import java.awt.event.ItemEvent; import javax.swing.JPanel; public class OrderPage { JFrame frame; private JPanel panel; private JPanel panel_1; private JPanel panel_2; private JPanel panel_3 ; private JTextField textField; private JTextField textField_1; private JButton btnNewButton; private JButton btnNewButton_1; private static ShoppingCart sC; private static Customer cS; private Order or; private String address; private String payment; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { OrderPage window = new OrderPage(cS, sC); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public OrderPage(Customer cs, ShoppingCart sc) { or = new Order(); cS = cs; sC = sc; initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 800, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel lblNewLabel = new JLabel("Shipping Info. :"); lblNewLabel.setForeground(new Color(0, 0, 128)); lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 16)); lblNewLabel.setBounds(111, 136, 125, 20); frame.getContentPane().add(lblNewLabel); JLabel lblPaymentDetails = new JLabel("Payment Details :"); lblPaymentDetails.setForeground(new Color(0, 0, 128)); lblPaymentDetails.setFont(new Font("Times New Roman", Font.BOLD, 16)); lblPaymentDetails.setBounds(111, 290, 125, 20); frame.getContentPane().add(lblPaymentDetails); btnNewButton = new JButton("New Shipping info."); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { btnNewButton.setVisible(false); btnNewButton_1.setVisible(false); Display_New_Address(); } }); btnNewButton.setForeground(new Color(0, 128, 0)); btnNewButton.setFont(new Font("Times New Roman", Font.BOLD, 14)); btnNewButton.setBounds(246, 131, 160, 25); frame.getContentPane().add(btnNewButton); btnNewButton_1 = new JButton("Use Saved Address"); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { btnNewButton.setVisible(false); btnNewButton_1.setVisible(false); Display_current_Address(); } }); btnNewButton_1.setForeground(new Color(0, 0, 0)); btnNewButton_1.setFont(new Font("Times New Roman", Font.BOLD, 14)); btnNewButton_1.setBounds(461, 134, 160, 25); frame.getContentPane().add(btnNewButton_1); JComboBox comboBox = new JComboBox(); comboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(e.getStateChange() == ItemEvent.SELECTED) { if(comboBox.getSelectedItem().toString().equals("Credit Card")) { payment = null; Display_Card_info(); } else if(comboBox.getSelectedItem().toString().equals("Cash")) { payment = "Cash,\t"+String.valueOf(sC.getTotal_price())+" L.E"; if(panel_2 != null) { if(panel_2.isVisible()) panel_2.setVisible(false); } Display_Amount(); } else { payment = "--Select--"; if(panel_2 != null) { if(panel_2.isVisible()) panel_2.setVisible(false); } if(panel_3 != null) { if(panel_3.isVisible()) panel_3.setVisible(false); } } } } }); comboBox.setModel(new DefaultComboBoxModel(new String[] {"--Select--", "Cash", "Credit Card"})); comboBox.setBounds(270, 291, 125, 20); frame.getContentPane().add(comboBox); JLabel lblNewLabel_1_2 = new JLabel("CHS"); lblNewLabel_1_2.setForeground(new Color(0, 128, 128)); lblNewLabel_1_2.setFont(new Font("Viner Hand ITC", Font.BOLD, 32)); lblNewLabel_1_2.setBounds(34, 23, 74, 52); frame.getContentPane().add(lblNewLabel_1_2); JButton btnNewButton_2 = new JButton("Confirm Order"); btnNewButton_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(check_info()) { or.setCart_ID(sC.getID()); or.generateID(); or.setPayment(payment); or.setShipping(address); try { ArrayList<Product> pl = sC.getProduct_list(); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3308/chs","root",""); for(int i = 0; i < sC.getLength(); i++) { Product pr = pl.get(i); String sql1 = "INSERT INTO product_list (Product_List_ID, Product_ID, Quantity)" + "VALUES ('"+sC.getID()+"', '"+pr.getID()+"', "+pr.getQuan()+")"; PreparedStatement posted1 = con.prepareStatement(sql1); posted1.executeUpdate(); } try { String sql = "INSERT INTO orders (Order_ID, Customer_ID, Full_Price, Shipping_Address, Product_List_ID, Payment_Method)" + "VALUES ('"+or.getOrder_ID()+"', '"+cS.getID()+"', "+sC.getTotal_price()+", '"+address+"', '"+sC.getID()+"', '"+payment+"')"; PreparedStatement posted = con.prepareStatement(sql); posted.executeUpdate(); try { ConfirmPage window = new ConfirmPage(cS, or, sC); window.frame.setVisible(true); frame.setVisible(false); } catch (Exception R) { R.printStackTrace(); } con.close(); } catch(Exception E) { E.printStackTrace(); } } catch(Exception E) { E.printStackTrace(); } } } }); btnNewButton_2.setForeground(new Color(255, 0, 0)); btnNewButton_2.setFont(new Font("Times New Roman", Font.BOLD, 16)); btnNewButton_2.setBounds(309, 380, 207, 52); frame.getContentPane().add(btnNewButton_2); } private void Display_New_Address() { panel_1.setBounds(220, 98, 473, 90); frame.getContentPane().add(panel_1); panel_1.setLayout(null); JLabel lblNewLabel_2 = new JLabel("Region :"); lblNewLabel_2.setBounds(10, 10, 85, 20); panel_1.add(lblNewLabel_2); lblNewLabel_2.setFont(new Font("Times New Roman", Font.BOLD, 14)); JComboBox comboBox_1 = new JComboBox(); comboBox_1.setBounds(10, 40, 125, 21); panel_1.add(comboBox_1); comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"--Select--", "Cairo", "Giza", "Alex"})); JLabel lblNewLabel_3 = new JLabel("Shipping Cost :"); lblNewLabel_3.setBounds(215, 10, 125, 20); panel_1.add(lblNewLabel_3); lblNewLabel_3.setFont(new Font("Times New Roman", Font.BOLD, 14)); JLabel lblNewLabel_4 = new JLabel("50 L.E"); lblNewLabel_4.setBounds(215, 39, 100, 20); panel_1.add(lblNewLabel_4); lblNewLabel_4.setFont(new Font("Times New Roman", Font.BOLD, 14)); address = comboBox_1.getSelectedItem().toString(); } private void Display_current_Address() { panel = new JPanel(); panel.setBounds(235, 100, 462, 94); frame.getContentPane().add(panel); panel.setLayout(null); JLabel lblNewLabel_5 = new JLabel("Address :"); lblNewLabel_5.setBounds(10, 10, 95, 20); panel.add(lblNewLabel_5); lblNewLabel_5.setFont(new Font("Times New Roman", Font.BOLD, 14)); address = cS.getAdd(); JLabel lblNewLabel_6 = new JLabel(address); lblNewLabel_6.setBounds(20, 40, 410, 25); panel.add(lblNewLabel_6); lblNewLabel_6.setFont(new Font("Times New Roman", Font.BOLD, 14)); } private void Display_Card_info() { panel_2 = new JPanel(); panel_2.setBounds(417, 238, 359, 103); frame.getContentPane().add(panel_2); panel_2.setLayout(null); JLabel lblNewLabel_1 = new JLabel("Credit Card no. :"); lblNewLabel_1.setBounds(10, 25, 125, 20); panel_2.add(lblNewLabel_1); lblNewLabel_1.setForeground(new Color(0, 0, 0)); lblNewLabel_1.setFont(new Font("Times New Roman", Font.BOLD, 14)); textField = new JTextField(); textField.setBounds(10, 55, 140, 20); panel_2.add(textField); textField.setColumns(10); JLabel lblNewLabel_1_1 = new JLabel("Holder Name. :"); lblNewLabel_1_1.setBounds(186, 25, 125, 20); panel_2.add(lblNewLabel_1_1); lblNewLabel_1_1.setForeground(Color.BLACK); lblNewLabel_1_1.setFont(new Font("Times New Roman", Font.BOLD, 14)); textField_1 = new JTextField(); textField_1.setBounds(186, 55, 140, 20); panel_2.add(textField_1); textField_1.setColumns(10); } private void Display_Amount() { panel_3 = new JPanel(); panel_3.setBounds(423, 252, 337, 90); frame.getContentPane().add(panel_3); panel_3.setLayout(null); JLabel lblNewLabel_7 = new JLabel("Amount :"); lblNewLabel_7.setFont(new Font("Times New Roman", Font.BOLD, 14)); lblNewLabel_7.setBounds(10, 10, 95, 13); panel_3.add(lblNewLabel_7); JLabel lblNewLabel_8 = new JLabel(String.valueOf(sC.getTotal_price())+" L.E"); lblNewLabel_8.setForeground(Color.RED); lblNewLabel_8.setFont(new Font("Times New Roman", Font.BOLD, 14)); lblNewLabel_8.setBounds(10, 39, 95, 28); panel_3.add(lblNewLabel_8); } private boolean check_info() { if(payment == null) { if(textField_1.getText().matches("^(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-7][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$")) { payment = "Credit Card,\t"+textField_1.getText(); } else { JOptionPane.showMessageDialog(null, "Enter A Valid Credit Card Number!!"); return false; } } else if(payment == "--Select--") { JOptionPane.showMessageDialog(null, "Choose a valid payment method"); return false; } if(address == null || address.equals("--Select--")) { JOptionPane.showMessageDialog(null, "Please Enter your address!!"); return false; } return true; } } <file_sep>/Database/chs.sql -- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3308 -- Generation Time: Jul 15, 2021 at 10:36 PM -- Server version: 5.7.31 -- PHP Version: 7.3.21 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `chs` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- DROP TABLE IF EXISTS `admin`; CREATE TABLE IF NOT EXISTS `admin` ( `Admin_ID` varchar(256) NOT NULL, `Email` varchar(256) DEFAULT NULL, `Password` varchar(256) DEFAULT NULL, `Full_Name` varchar(256) DEFAULT NULL, `Salary` double NOT NULL, PRIMARY KEY (`Admin_ID`), UNIQUE KEY `Email` (`Email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`Admin_ID`, `Email`, `Password`, `Full_Name`, `Salary`) VALUES ('02113ec9-2536-4174-acf0-93350bdb5ee1', '<EMAIL>', '<PASSWORD>$', '<PASSWORD>', 1550), ('180f969a-18f0-40d6-8d16-0bf7e26bce51', '<EMAIL>', 'Osama033013$', '<NAME>', 1550); -- -------------------------------------------------------- -- -- Table structure for table `customer` -- DROP TABLE IF EXISTS `customer`; CREATE TABLE IF NOT EXISTS `customer` ( `Customer_ID` varchar(256) NOT NULL, `Full_Name` varchar(256) NOT NULL, `Email` varchar(256) NOT NULL, `Password` varchar(256) NOT NULL, `Address` varchar(256) NOT NULL, `PhoneNum` varchar(11) NOT NULL, PRIMARY KEY (`Customer_ID`), UNIQUE KEY `Email` (`Email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `customer` -- INSERT INTO `customer` (`Customer_ID`, `Full_Name`, `Email`, `Password`, `Address`, `PhoneNum`) VALUES ('8c10dca2-2373-45f8-ba90-9ab3fa8a4fb4', '<NAME>', '<EMAIL>', 'Abdo022012$', 'Al Amal,Faisal,Cairo', '01146631026'); -- -------------------------------------------------------- -- -- Table structure for table `orders` -- DROP TABLE IF EXISTS `orders`; CREATE TABLE IF NOT EXISTS `orders` ( `Order_ID` varchar(256) NOT NULL, `Customer_ID` varchar(256) NOT NULL, `Full_Price` double NOT NULL, `Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `Shipping_Address` varchar(256) NOT NULL, `Product_List_ID` varchar(256) NOT NULL, `Payment_Method` varchar(256) NOT NULL, `Customer_Feedback` text, PRIMARY KEY (`Order_ID`), UNIQUE KEY `Product_List_ID` (`Product_List_ID`), KEY `Customer_ID` (`Customer_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `orders` -- INSERT INTO `orders` (`Order_ID`, `Customer_ID`, `Full_Price`, `Date`, `Shipping_Address`, `Product_List_ID`, `Payment_Method`, `Customer_Feedback`) VALUES ('015c7a11-5d6c-4699-a164-c0d8b6e37084', '8c10dca2-2373-45f8-ba90-9ab3fa8a4fb4', 676.5, '2021-07-14 01:36:32', 'Al Amal,Faisal,Cairo', '77373dd3-4ff2-4e56-ac84-19ac565f1cce', 'Cash, 676.5 L.E', 'Thanks'), ('261782a2-5b4b-48eb-8982-84442d0f4196', '8c10dca2-2373-45f8-ba90-9ab3fa8a4fb4', 1725.5, '2021-07-14 01:29:31', 'Al Amal,Faisal,Cairo', '17926fca-7dd6-414e-b7fc-41900ac56378', 'Cash, 1725.5 L.E', 'It was pleasant'), ('d71fe611-3466-4ea3-9137-d4bc8e7a69fc', '8c10dca2-2373-45f8-ba90-9ab3fa8a4fb4', 225.5, '2021-07-14 11:24:13', 'Al Amal,Faisal,Cairo', '7a2235f9-c189-425c-9e07-133befacd5dd', 'Cash, 225.5 L.E', NULL); -- -------------------------------------------------------- -- -- Table structure for table `product` -- DROP TABLE IF EXISTS `product`; CREATE TABLE IF NOT EXISTS `product` ( `Product_ID` varchar(256) NOT NULL, `Product_Name` varchar(256) NOT NULL, `Price` double NOT NULL, `Category` varchar(256) NOT NULL, `Company` varchar(256) NOT NULL, `Description` mediumtext NOT NULL, `Admin_ID` varchar(256) DEFAULT NULL, `ImagePath` varchar(256) DEFAULT NULL, PRIMARY KEY (`Product_ID`), KEY `Admin_ID` (`Admin_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `product` -- INSERT INTO `product` (`Product_ID`, `Product_Name`, `Price`, `Category`, `Company`, `Description`, `Admin_ID`, `ImagePath`) VALUES ('0da3fe43-657f-44b5-91bd-1f49b3e837fd', 'Monitor_1', 1500, 'Monitors', 'Apple', '14-inch Screen, 4K resolution', '180f969a-18f0-40d6-8d16-0bf7e26bce51', 'monitor_1.jpg'), ('25e66fc4-cf67-4ec8-9f06-5cc1f096c35e', 'Intel core-i7', 225.5, 'CPUs', 'Intel', 'Sate-of-the-art Cpu That is capable of speed processing', '180f969a-18f0-40d6-8d16-0bf7e26bce51', 'C:\\images\\CPU_INTEL.jpg'); -- -------------------------------------------------------- -- -- Table structure for table `product_list` -- DROP TABLE IF EXISTS `product_list`; CREATE TABLE IF NOT EXISTS `product_list` ( `Product_List_ID` varchar(256) NOT NULL, `Product_ID` varchar(256) NOT NULL, `Quantity` int(11) NOT NULL, KEY `Product_ID` (`Product_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `product_list` -- INSERT INTO `product_list` (`Product_List_ID`, `Product_ID`, `Quantity`) VALUES ('17926fca-7dd6-414e-b7fc-41900ac56378', '0da3fe43-657f-44b5-91bd-1f49b3e837fd', 1), ('17926fca-7dd6-414e-b7fc-41900ac56378', '25e66fc4-cf67-4ec8-9f06-5cc1f096c35e', 1), ('77373dd3-4ff2-4e56-ac84-19ac565f1cce', '25e66fc4-cf67-4ec8-9f06-5cc1f096c35e', 3), ('7a2235f9-c189-425c-9e07-133befacd5dd', '25e66fc4-cf67-4ec8-9f06-5cc1f096c35e', 1); -- -- Constraints for dumped tables -- -- -- Constraints for table `orders` -- ALTER TABLE `orders` ADD CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`Customer_ID`) REFERENCES `customer` (`Customer_ID`); -- -- Constraints for table `product` -- ALTER TABLE `product` ADD CONSTRAINT `product_ibfk_1` FOREIGN KEY (`Admin_ID`) REFERENCES `admin` (`Admin_ID`); -- -- Constraints for table `product_list` -- ALTER TABLE `product_list` ADD CONSTRAINT `product_list_ibfk_2` FOREIGN KEY (`Product_ID`) REFERENCES `product` (`Product_ID`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/src/AdminPage.java import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import java.awt.Color; import javax.swing.JButton; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.awt.event.ActionEvent; public class AdminPage { JFrame frame; private static Admin ADMIN; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { AdminPage window = new AdminPage(ADMIN); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public AdminPage(Admin ad) { ADMIN = ad; initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 800, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel lblNewLabel = new JLabel("Welcome, "+ADMIN.getName()); lblNewLabel.setForeground(new Color(0, 0, 128)); lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 14)); lblNewLabel.setBounds(171, 81, 333, 33); frame.getContentPane().add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("CHS"); lblNewLabel_1.setForeground(new Color(0, 128, 128)); lblNewLabel_1.setFont(new Font("Viner Hand ITC", Font.BOLD, 32)); lblNewLabel_1.setBounds(21, 10, 74, 52); frame.getContentPane().add(lblNewLabel_1); JButton btnNewButton = new JButton("Add A product"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { AddProdcutPage APwindow = new AddProdcutPage(ADMIN); APwindow.frame.setVisible(true); frame.setVisible(false); } catch (Exception R) { R.printStackTrace(); } } }); btnNewButton.setForeground(new Color(0, 128, 0)); btnNewButton.setFont(new Font("Times New Roman", Font.BOLD, 14)); btnNewButton.setBounds(41, 312, 183, 38); frame.getContentPane().add(btnNewButton); JButton btnRemoveAProduct = new JButton("Remove A product"); btnRemoveAProduct.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String ID = JOptionPane.showInputDialog(null, "Enter Product ID :"); try { Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3308/chs","root",""); String sql = "DELETE FROM product WHERE Product_ID = '"+ID+"'"; PreparedStatement posted = con.prepareStatement(sql); posted.executeUpdate(); JOptionPane.showMessageDialog(null, "Deleted Successfully!!"); con.close(); } catch(Exception R) { R.printStackTrace(); } } }); btnRemoveAProduct.setForeground(new Color(255, 0, 0)); btnRemoveAProduct.setFont(new Font("Times New Roman", Font.BOLD, 14)); btnRemoveAProduct.setBounds(529, 312, 183, 38); frame.getContentPane().add(btnRemoveAProduct); JButton btnModifyAProduct = new JButton("Modify A product"); btnModifyAProduct.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ModifyProductPage MPwindow = new ModifyProductPage(ADMIN); MPwindow.frame.setVisible(true); frame.setVisible(false); } catch (Exception R) { R.printStackTrace(); } } }); btnModifyAProduct.setForeground(new Color(0, 0, 128)); btnModifyAProduct.setFont(new Font("Times New Roman", Font.BOLD, 14)); btnModifyAProduct.setBounds(293, 312, 183, 38); frame.getContentPane().add(btnModifyAProduct); } } <file_sep>/src/User.java import java.util.UUID; public class User { protected String USER_ID; protected String full_name; protected String password; protected String Email; public void setPass(String Pass) { this.password = Pass; } public String getPass() { return this.password; } public void setMail(String mail) { this.Email = mail; } public String getMail() { return this.Email; } public void setName(String fn) { this.full_name = fn; } public String getName() { return this.full_name; } public void generate_ID() { this.USER_ID = UUID.randomUUID().toString(); } public void setID(String id) { this.USER_ID = id; } public String getID() { return this.USER_ID; } } <file_sep>/src/ShoppingCart.java import java.util.ArrayList; import java.util.UUID; import javax.swing.JOptionPane; public class ShoppingCart { private String Cart_ID; private ArrayList<Product> product_list; private Double Total_price = 0.0; ShoppingCart() { this.generateID(); this.product_list = new ArrayList<>(); } private void generateID() { // TODO Auto-generated method stub this.Cart_ID = UUID.randomUUID().toString(); } public String getID() { return this.Cart_ID; } public void AddItem(Product pr) { product_list.add(pr); JOptionPane.showMessageDialog(null, "Product Added!"); } public void removeItem(Product pr) { for(int i = 0; i < product_list.size(); i++) { if(product_list.get(i).getID().equals(pr.getID())) { product_list.remove(product_list.get(i)); break; } } JOptionPane.showMessageDialog(null, "Product removed!"); } public void UpdateQuantity(Product pr, int q) { for(int i = 0; i < product_list.size(); i++) { if(product_list.get(i).getID().equals(pr.getID())) { product_list.get(i).setQuan(q); break; } } JOptionPane.showMessageDialog(null, "Quantity Updated!"); } public int getLength() { int length = product_list.size(); return length; } public String printItems() { // TODO Auto-generated method stub String items = ""; for(int i = 0; i < product_list.size(); i++) { items += "Product_name: "+ product_list.get(i).getName() + "\tQuantity: " + product_list.get(i).getQuan() + "\tPrise: " + product_list.get(i).getPrice() + "\n"; } return items; } public Double getTotal_price() { this.Total_price = 0.0; for(int i = 0; i < product_list.size(); i++) { Total_price += product_list.get(i).getPrice() * product_list.get(i).getQuan(); } return this.Total_price; } public boolean SearchProduct(Product pr) { for(int i = 0; i < product_list.size(); i++) { if(product_list.get(i).getID().equals(pr.getID())) { return true; } } return false; } public ArrayList<Product> getProduct_list() { return this.product_list; } } <file_sep>/src/AdminSignUpPage.java import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import java.awt.Font; import java.awt.Color; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JPasswordField; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.awt.event.ActionEvent; public class AdminSignUpPage { JFrame frame; private JTextField textField; private JTextField textField_1; private JPasswordField passwordField; private JPasswordField passwordField_1; private JTextField textField_2; static Admin ADMIN; private String Email; private String password; private String full_name; private JPanel panel; private JLabel lblNewLabel_1; private JLabel lblPassword; private JLabel lblRetypePassword; private JLabel lblEmail; private JButton btnNewButton_1; private JButton btnNewButton; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { AdminSignUpPage window = new AdminSignUpPage(ADMIN); window.getFrame().setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public AdminSignUpPage(Admin ad) { ADMIN = ad; System.out.print(ADMIN.getID()); initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { setFrame(new JFrame()); getFrame().setBounds(100, 100, 800, 500); getFrame().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getFrame().getContentPane().setLayout(null); JLabel lblNewLabel = new JLabel("Enter Admin Code :"); lblNewLabel.setForeground(new Color(0, 0, 128)); lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 14)); lblNewLabel.setBounds(107, 73, 126, 24); getFrame().getContentPane().add(lblNewLabel); textField = new JTextField(); textField.setBounds(278, 77, 220, 19); getFrame().getContentPane().add(textField); textField.setColumns(10); Display_Info(); } public void Display_Info() { panel = new JPanel(); panel.setBounds(10, 114, 766, 339); getFrame().getContentPane().add(panel); panel.setLayout(null); lblNewLabel_1 = new JLabel("Full Name :"); lblNewLabel_1.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblNewLabel_1.setBounds(59, 39, 67, 17); panel.add(lblNewLabel_1); lblPassword = new JLabel("Password :"); lblPassword.setToolTipText("Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character:"); lblPassword.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblPassword.setBounds(59, 155, 63, 17); panel.add(lblPassword); lblRetypePassword = new JLabel("Re-type password :"); lblRetypePassword.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblRetypePassword.setBounds(400, 155, 111, 17); panel.add(lblRetypePassword); textField_1 = new JTextField(); textField_1.setColumns(10); textField_1.setBounds(164, 39, 95, 20); panel.add(textField_1); passwordField = new JPasswordField(); passwordField.setBounds(164, 155, 95, 20); panel.add(passwordField); passwordField_1 = new JPasswordField(); passwordField_1.setBounds(545, 155, 95, 20); panel.add(passwordField_1); lblEmail = new JLabel("E-mail :"); lblEmail.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblEmail.setBounds(400, 42, 45, 17); panel.add(lblEmail); textField_2 = new JTextField(); textField_2.setColumns(10); textField_2.setBounds(545, 39, 95, 20); panel.add(textField_2); btnNewButton_1 = new JButton("Sign Up"); btnNewButton_1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(check_info()) { try { Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3308/chs","root",""); String sql = "UPDATE admin SET Email = '"+Email+"', Password = '"+<PASSWORD>+"', Full_Name = '"+full_name +"' WHERE Admin_ID = '"+ADMIN.getID()+"'"; PreparedStatement posted = con.prepareStatement(sql); posted.executeUpdate(); try { LoginPage Lwindow = new LoginPage(); Lwindow.frame.setVisible(true); frame.setVisible(false); } catch (Exception R) { R.printStackTrace(); } con.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); btnNewButton_1.setForeground(new Color(0, 100, 0)); btnNewButton_1.setFont(new Font("Times New Roman", Font.BOLD, 14)); btnNewButton_1.setBounds(322, 270, 100, 25); panel.add(btnNewButton_1); } private boolean check_info() { if(!ADMIN.getID().equals(textField.getText())) { JOptionPane.showMessageDialog(getFrame(),"Code is Invalid!"); return false; } if(textField_1.getText().trim().equals("")) { textField_1.setText(""); JOptionPane.showMessageDialog(getFrame(),"Enter a valid name!"); return false; } else { full_name = textField_1.getText(); ADMIN.setName(full_name); } if(String.valueOf(passwordField.getPassword()).matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$#!%*?&])[A-Za-z\\d@$!%*?&]{8,}$")) { if(String.valueOf(passwordField.getPassword()).equals(String.valueOf(passwordField.getPassword()))) { password = String.valueOf(passwordField.getPassword()); ADMIN.setPass(password); } else { passwordField.setText(""); passwordField_1.setText(""); JOptionPane.showMessageDialog(null, "The two passwords don't equal each other!"); return false; } } else { passwordField.setText(""); passwordField_1.setText(""); JOptionPane.showMessageDialog(null,"Password must contain Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character:!!"); return false; } if(textField_2.getText().trim().equals("") || textField_2.getText().matches("^[\\\\w!#$%&’*+/=?`{|}~^-]+(?:\\\\.[\\\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\\\.)+[a-zA-Z]{2,6}$")) { textField_2.setText(""); JOptionPane.showMessageDialog(getFrame(),"Enter a valid email!"); return false; } else { Email = textField_2.getText(); ADMIN.setMail(Email); } return true; } public JFrame getFrame() { return frame; } public void setFrame(JFrame frame) { this.frame = frame; } } <file_sep>/src/Market.java import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JPanel; import javax.swing.ScrollPaneConstants; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import java.awt.Font; import java.awt.Color; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.SwingConstants; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Market { JFrame frame; static Market window; static ShoppingCart sC; static Customer cS; private Product pr; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { window = new Market(cS, sC); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Market(Customer cs, ShoppingCart sc) { sC = sc; cS = cs; pr = new Product(); initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.getContentPane().setBackground(Color.WHITE); frame.getContentPane().setForeground(Color.WHITE); frame.setBounds(100, 100, 950, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JScrollPane scrollPane = new JScrollPane(); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.setBounds(152, 49, 589, 374); frame.getContentPane().add(scrollPane); JPanel panel = new JPanel(); panel.setBackground(Color.WHITE); panel.setForeground(Color.WHITE); scrollPane.setViewportView(panel); panel.setLayout(null); JLabel lblNewLabel_2 = new JLabel("CPU_1"); lblNewLabel_2.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { /* Create Product Object */ pr.setID("25e66fc4-cf67-4ec8-9f06-5cc1f096c35e"); pr.setCat("CPUs"); pr.setCompany("Intel"); pr.setDes("Sate-of-the-art Cpu That is capable of speed processing"); pr.setName("Intel core-i7"); pr.setPrice(225.5); pr.setImagePath("C:\\أشيائي\\هرى\\Java-Workspace\\ProjectBeta\\src\\images\\CPU_INTEL.jpg"); try { ProductPage Pwindow = new ProductPage(cS, pr, sC); Pwindow.frame.setVisible(true); frame.setVisible(false); } catch (Exception R) { R.printStackTrace(); } } }); lblNewLabel_2.setIcon(new ImageIcon("C:\\\u0623\u0634\u064A\u0627\u0626\u064A\\\u0647\u0631\u0649\\Java-Workspace\\ProjectBeta\\src\\images\\CPU_INTEL.jpg")); lblNewLabel_2.setBounds(31, 10, 110, 90); panel.add(lblNewLabel_2); JLabel lblNewLabel_3 = new JLabel("CPU- Core-i7"); lblNewLabel_3.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_3.setForeground(new Color(0, 0, 128)); lblNewLabel_3.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblNewLabel_3.setBounds(31, 118, 109, 13); panel.add(lblNewLabel_3); JLabel lblNewLabel_2_1 = new JLabel("CPU_2"); lblNewLabel_2_1.setIcon(new ImageIcon("C:\\\u0623\u0634\u064A\u0627\u0626\u064A\\\u0647\u0631\u0649\\Java-Workspace\\ProjectBeta\\src\\images\\CPU-CORE-i9.jpg")); lblNewLabel_2_1.setBounds(214, 10, 110, 90); panel.add(lblNewLabel_2_1); JLabel lblNewLabel_2_2 = new JLabel("Keyboard_1"); lblNewLabel_2_2.setIcon(new ImageIcon("C:\\\u0623\u0634\u064A\u0627\u0626\u064A\\\u0647\u0631\u0649\\Java-Workspace\\ProjectBeta\\src\\images\\keyboard_1.jpg")); lblNewLabel_2_2.setBounds(389, 10, 110, 90); panel.add(lblNewLabel_2_2); JLabel lblNewLabel_2_3 = new JLabel("Mouse_1"); lblNewLabel_2_3.setIcon(new ImageIcon("C:\\\u0623\u0634\u064A\u0627\u0626\u064A\\\u0647\u0631\u0649\\Java-Workspace\\ProjectBeta\\src\\images\\mouse_1.jpg")); lblNewLabel_2_3.setBounds(31, 203, 110, 90); panel.add(lblNewLabel_2_3); JLabel lblNewLabel_2_4 = new JLabel("Monitor_2"); lblNewLabel_2_4.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { pr.setID("0da3fe43-657f-44b5-91bd-1f49b3e837fd"); pr.setCat("Monitors"); pr.setCompany("Apple"); pr.setDes("14-inch Screen, 4K resolution"); pr.setName("Monitor_1"); pr.setPrice(1500); pr.setImagePath("C:\\أشيائي\\هرى\\Java-Workspace\\ProjectBeta\\src\\images\\Monitor_2.jpg"); try { ProductPage Pwindow = new ProductPage(cS, pr, sC); Pwindow.frame.setVisible(true); frame.setVisible(false); } catch (Exception R) { R.printStackTrace(); } } }); lblNewLabel_2_4.setIcon(new ImageIcon("C:\\\u0623\u0634\u064A\u0627\u0626\u064A\\\u0647\u0631\u0649\\Java-Workspace\\ProjectBeta\\src\\images\\Monitor_2.jpg")); lblNewLabel_2_4.setBounds(214, 203, 110, 90); panel.add(lblNewLabel_2_4); JLabel lblNewLabel_2_5 = new JLabel("GPU_1"); lblNewLabel_2_5.setIcon(new ImageIcon("C:\\\u0623\u0634\u064A\u0627\u0626\u064A\\\u0647\u0631\u0649\\Java-Workspace\\ProjectBeta\\src\\images\\gpu_1.jpg")); lblNewLabel_2_5.setBounds(389, 203, 110, 90); panel.add(lblNewLabel_2_5); JLabel lblNewLabel_3_1 = new JLabel("CPU- Core-i9"); lblNewLabel_3_1.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_3_1.setForeground(new Color(0, 0, 128)); lblNewLabel_3_1.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblNewLabel_3_1.setBounds(214, 118, 109, 13); panel.add(lblNewLabel_3_1); JLabel lblNewLabel_3_2 = new JLabel("Keyboard_1"); lblNewLabel_3_2.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_3_2.setForeground(new Color(0, 0, 128)); lblNewLabel_3_2.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblNewLabel_3_2.setBounds(389, 118, 109, 13); panel.add(lblNewLabel_3_2); JLabel lblNewLabel_3_3 = new JLabel("Mouse_1"); lblNewLabel_3_3.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_3_3.setForeground(new Color(0, 0, 128)); lblNewLabel_3_3.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblNewLabel_3_3.setBounds(31, 319, 109, 13); panel.add(lblNewLabel_3_3); JLabel lblNewLabel_3_4 = new JLabel("Monitor_2"); lblNewLabel_3_4.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_3_4.setForeground(new Color(0, 0, 128)); lblNewLabel_3_4.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblNewLabel_3_4.setBounds(214, 319, 109, 13); panel.add(lblNewLabel_3_4); JLabel lblNewLabel_3_5 = new JLabel("GPU_1"); lblNewLabel_3_5.setLabelFor(lblNewLabel_2_5); lblNewLabel_3_5.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_3_5.setForeground(new Color(0, 0, 128)); lblNewLabel_3_5.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblNewLabel_3_5.setBounds(389, 319, 109, 13); panel.add(lblNewLabel_3_5); JComboBox comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel(new String[] {"--Select--", "CPUs", "Monitors", "Keyboards"})); comboBox.setBounds(34, 124, 95, 20); frame.getContentPane().add(comboBox); JComboBox comboBox_1 = new JComboBox(); comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"--Select--", "Dell", "HP", "Apple", "Intel"})); comboBox_1.setBounds(34, 330, 95, 20); frame.getContentPane().add(comboBox_1); JLabel lblNewLabel = new JLabel("Company :"); lblNewLabel.setForeground(new Color(0, 0, 128)); lblNewLabel.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblNewLabel.setBounds(34, 297, 63, 13); frame.getContentPane().add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("Categories :"); lblNewLabel_1.setForeground(new Color(0, 0, 128)); lblNewLabel_1.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblNewLabel_1.setBounds(34, 92, 85, 13); frame.getContentPane().add(lblNewLabel_1); JButton btnNewButton = new JButton("Profile"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Profile Pwindow = new Profile(cS, sC); Pwindow.frame.setVisible(true); frame.setVisible(false); } catch (Exception R) { R.printStackTrace(); } } }); btnNewButton.setForeground(new Color(0, 128, 0)); btnNewButton.setFont(new Font("Times New Roman", Font.PLAIN, 14)); btnNewButton.setBounds(802, 24, 100, 20); frame.getContentPane().add(btnNewButton); JLabel lblNewLabel_4 = new JLabel("ShoppingCart"); lblNewLabel_4.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { CartPage Cwindow = new CartPage(cS, sC); Cwindow.frame.setVisible(true); frame.setVisible(false); } catch (Exception R) { R.printStackTrace(); } } }); lblNewLabel_4.setIcon(new ImageIcon("C:\\أشيائي\\هرى\\Java-Workspace\\ProjectBeta\\src\\images\\shoppingcart.png")); lblNewLabel_4.setBounds(761, 139, 153, 120); frame.getContentPane().add(lblNewLabel_4); JLabel lblNewLabel_5 = new JLabel("+ "+Integer.valueOf(sC.getLength())); lblNewLabel_5.setLabelFor(lblNewLabel_4); lblNewLabel_5.setForeground(new Color(0, 0, 128)); lblNewLabel_5.setFont(new Font("Times New Roman", Font.BOLD, 24)); lblNewLabel_5.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_5.setBounds(761, 285, 153, 43); frame.getContentPane().add(lblNewLabel_5); } } <file_sep>/src/Tests/RegisterTest.java import static org.junit.Assert.*; import org.junit.Test; public class RegisterTest { @Test public void test() { RegisterPage instance = new RegisterPage(); boolean result = instance.TestHelp("Ahmed", "01146631026", "Ahme033019$", "Ahme033019$", "Alaml", "<EMAIL>"); assertTrue(result); } @Test public void test2() { RegisterPage instance = new RegisterPage(); boolean result = instance.TestHelp("", "01146631026", "Ahme033019$", "Ahme033019$", "Alaml", "<EMAIL>"); assertFalse(result); } @Test public void test3() { RegisterPage instance = new RegisterPage(); boolean result = instance.TestHelp("Ahmed", "01146631026", "Ahme033019$", "Ahme03301", "Alaml", "<EMAIL>"); assertFalse(result); } @Test public void test4() { RegisterPage instance = new RegisterPage(); boolean result = instance.TestHelp("Ahmed", "01146631026", "Ahme033019$", "Ahme033019$", "Alaml", "ahmed.98"); assertFalse(result); } } <file_sep>/src/CartPage.java import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import java.awt.Color; import javax.swing.SwingConstants; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JTextArea; import java.awt.SystemColor; public class CartPage { JFrame frame; static ShoppingCart sC; static Customer cS; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { CartPage window = new CartPage(cS, sC); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public CartPage(Customer cs, ShoppingCart sc) { sC = sc; cS = cs; initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 800, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel lblNewLabel = new JLabel("Items :"); lblNewLabel.setForeground(new Color(0, 0, 128)); lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 20)); lblNewLabel.setBounds(134, 84, 67, 13); frame.getContentPane().add(lblNewLabel); JLabel lblTotalPrise = new JLabel("Total Prise :"); lblTotalPrise.setForeground(new Color(0, 0, 128)); lblTotalPrise.setFont(new Font("Times New Roman", Font.BOLD, 20)); lblTotalPrise.setBounds(134, 381, 140, 24); frame.getContentPane().add(lblTotalPrise); JLabel lblNewLabel_2 = new JLabel(String.valueOf(sC.getTotal_price())+" L.E"); lblNewLabel_2.setFont(new Font("Times New Roman", Font.BOLD, 14)); lblNewLabel_2.setBounds(284, 386, 140, 16); frame.getContentPane().add(lblNewLabel_2); JButton btnCheckOut = new JButton("Check Out"); btnCheckOut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(sC.getLength() != 0) { try { OrderPage window = new OrderPage(cS, sC); window.frame.setVisible(true); frame.setVisible(false); } catch (Exception R) { R.printStackTrace(); } } else { JOptionPane.showMessageDialog(null, "Your cart is Empty!!"); } } }); btnCheckOut.setForeground(new Color(0, 128, 0)); btnCheckOut.setFont(new Font("Times New Roman", Font.BOLD, 16)); btnCheckOut.setBounds(585, 400, 138, 36); frame.getContentPane().add(btnCheckOut); JButton btnNewButton_1 = new JButton("BackToMarket"); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Market Mwindow = new Market(cS, sC); Mwindow.frame.setVisible(true); frame.setVisible(false); } catch (Exception R) { R.printStackTrace(); } } }); btnNewButton_1.setForeground(new Color(0, 128, 128)); btnNewButton_1.setFont(new Font("Times New Roman", Font.PLAIN, 14)); btnNewButton_1.setBounds(10, 20, 138, 36); frame.getContentPane().add(btnNewButton_1); JTextArea textArea = new JTextArea(sC.printItems()); textArea.setBackground(SystemColor.menu); textArea.setRows(10); textArea.setForeground(Color.BLACK); textArea.setFont(new Font("Times New Roman", Font.BOLD, 16)); textArea.setBounds(211, 79, 478, 257); frame.getContentPane().add(textArea); } } <file_sep>/src/Admin.java public class Admin extends User { private double Salary; public void setSalary(double S) { this.Salary = S; } public double getSalary() { return this.Salary; } } <file_sep>/README.md # Minimal-Computer-Hardware-Store A desktop application to sell computer hardware components <file_sep>/src/Profile.java import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.Font; import java.awt.Color; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Profile { JFrame frame; private static Profile window; private static Customer cs; private static ShoppingCart Sc; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { window = new Profile(cs, Sc); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Profile(Customer CS, ShoppingCart SC) { cs = CS; Sc = SC; initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 800, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel lblNewLabel_1 = new JLabel("CHS"); lblNewLabel_1.setForeground(new Color(0, 128, 128)); lblNewLabel_1.setFont(new Font("Viner Hand ITC", Font.BOLD, 32)); lblNewLabel_1.setBounds(30, 26, 74, 52); frame.getContentPane().add(lblNewLabel_1); JLabel lblNewLabel = new JLabel("Welcome, "+cs.getName()); lblNewLabel.setForeground(new Color(0, 0, 128)); lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 14)); lblNewLabel.setBounds(171, 81, 333, 33); frame.getContentPane().add(lblNewLabel); JLabel lblNewLabel_2 = new JLabel("Customer_ID :"); lblNewLabel_2.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblNewLabel_2.setBounds(74, 168, 119, 20); frame.getContentPane().add(lblNewLabel_2); JLabel lblNewLabel_2_1 = new JLabel("Address :"); lblNewLabel_2_1.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblNewLabel_2_1.setBounds(74, 265, 119, 20); frame.getContentPane().add(lblNewLabel_2_1); JLabel lblNewLabel_2_2 = new JLabel("E-mail :"); lblNewLabel_2_2.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblNewLabel_2_2.setBounds(410, 168, 119, 20); frame.getContentPane().add(lblNewLabel_2_2); JLabel lblNewLabel_2_3 = new JLabel("Phone no. :"); lblNewLabel_2_3.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblNewLabel_2_3.setBounds(410, 265, 119, 20); frame.getContentPane().add(lblNewLabel_2_3); JLabel lblNewLabel_2_4 = new JLabel(cs.getID()); lblNewLabel_2_4.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblNewLabel_2_4.setBounds(224, 168, 119, 20); frame.getContentPane().add(lblNewLabel_2_4); JLabel lblNewLabel_2_5 = new JLabel(cs.getAdd()); lblNewLabel_2_5.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblNewLabel_2_5.setBounds(224, 265, 119, 20); frame.getContentPane().add(lblNewLabel_2_5); JLabel lblNewLabel_2_6 = new JLabel(cs.getMail()); lblNewLabel_2_6.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblNewLabel_2_6.setBounds(559, 173, 119, 20); frame.getContentPane().add(lblNewLabel_2_6); JLabel lblNewLabel_2_7 = new JLabel(cs.getNo()); lblNewLabel_2_7.setFont(new Font("Times New Roman", Font.PLAIN, 14)); lblNewLabel_2_7.setBounds(559, 265, 119, 20); frame.getContentPane().add(lblNewLabel_2_7); JButton btnChangePassword = new JButton("Change Password"); btnChangePassword.setForeground(new Color(0, 128, 0)); btnChangePassword.setFont(new Font("Times New Roman", Font.BOLD, 14)); btnChangePassword.setBounds(93, 388, 160, 25); frame.getContentPane().add(btnChangePassword); JButton btnUpdateProfile = new JButton("Update Profile."); btnUpdateProfile.setForeground(Color.BLUE); btnUpdateProfile.setFont(new Font("Times New Roman", Font.BOLD, 14)); btnUpdateProfile.setBounds(443, 388, 160, 25); frame.getContentPane().add(btnUpdateProfile); JButton btnNewButton_1_1 = new JButton("BackToMarket"); btnNewButton_1_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Market Mwindow = new Market(cs, Sc); Mwindow.frame.setVisible(true); frame.setVisible(false); } catch (Exception R) { R.printStackTrace(); } } }); btnNewButton_1_1.setForeground(new Color(0, 128, 128)); btnNewButton_1_1.setFont(new Font("Times New Roman", Font.PLAIN, 14)); btnNewButton_1_1.setBounds(605, 26, 138, 36); frame.getContentPane().add(btnNewButton_1_1); } } <file_sep>/src/Customer.java public class Customer extends User { private String Address; private String PhoneNumber; public void setAdd(String add) { this.Address = add; } public String getAdd() { return this.Address; } public void setNo(String PN) { this.PhoneNumber = PN; } public String getNo() { return this.PhoneNumber; } }
12bb472fc875a328a000a02d13a3bae57758ea4e
[ "Markdown", "Java", "SQL" ]
13
Java
Abdulrahman-Adel/Minimal-Computer-Hardware-Store
f56ccfe75058f8cd101119e7bd08b0d1741abf3c
842bcc28740de08ce4ee933b09d73cef8c26062a
refs/heads/main
<repo_name>kiuyas/lifegame<file_sep>/LifeGame/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LifeGame { public partial class Form1 : Form { private Random random = null; private int[,] field = null; public Form1() { InitializeComponent(); random = new Random(); field = new int[10, 10]; } private void pictureBox1_Paint(object sender, PaintEventArgs e) { for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { if (field[x, y] == 1) { e.Graphics.FillRectangle(Brushes.Lime, x * 16, y * 16, 15, 15); } } } } private void btnRandom_Click(object sender, EventArgs e) { for(int i = 0; i < 20; i++) { int x = random.Next(10); int y = random.Next(10); while(field[x, y] == 1) { x = random.Next(10); y = random.Next(10); } field[x, y] = 1; } pictureBox1.Refresh(); } private void btnStart_Click(object sender, EventArgs e) { if (timer1.Enabled) { timer1.Stop(); } else { timer1.Start(); } } private int getFieldValue(int x, int y) { if (x < 0 || x >= 10 || y < 0 || y >= 10) { return 0; } return field[x, y]; } private void timer1_Tick(object sender, EventArgs e) { ShowNextGeneration(); } private void ShowNextGeneration() { int[,] nextField = new int[10, 10]; for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { int sum = getFieldValue(x - 1, y) + getFieldValue(x + 1, y) + getFieldValue(x, y - 1) + getFieldValue(x, y + 1) + getFieldValue(x - 1, y - 1) + getFieldValue(x - 1, y + 1) + getFieldValue(x + 1, y - 1) + getFieldValue(x + 1, y + 1); if (field[x, y] == 0 && sum == 3) { nextField[x, y] = 1; } else if (field[x, y] == 1 && (sum == 2 || sum == 3)) { nextField[x, y] = 1; } else if (field[x, y] == 1 && (sum == 1 || sum == 4)) { nextField[x, y] = 0; } } } field = nextField; pictureBox1.Refresh(); } private void btnPat1_Click(object sender, EventArgs e) { field = new int[10, 10]; field[5, 4] = 1; field[5, 5] = 1; field[5, 6] = 1; pictureBox1.Refresh(); } private void btnPat2_Click(object sender, EventArgs e) { field = new int[10, 10]; field[2, 0] = 1; field[2, 1] = 1; field[2, 2] = 1; field[5, 3] = 1; field[5, 4] = 1; field[5, 5] = 1; field[8, 6] = 1; field[8, 7] = 1; field[8, 8] = 1; pictureBox1.Refresh(); } private void btnPat9_Click(object sender, EventArgs e) { field = new int[10, 10]; field[2, 3] = 1; field[3, 3] = 1; field[4, 3] = 1; field[4, 2] = 1; field[3, 1] = 1; pictureBox1.Refresh(); } } } <file_sep>/README.md # lifegame simple life game
37e03442485ead9e5a92fd400298ffd5cf422bb9
[ "Markdown", "C#" ]
2
C#
kiuyas/lifegame
297f23a1b97575f8d1c9b73e6e5331f45a6c25fc
69e694699ec91a7fe8cd3b62625b6ab85b28620c
refs/heads/master
<repo_name>NanaEB/BA<file_sep>/omnetpp.fsm.editor.workspace/org.kermeta.fsm.gmf.diagram/src/fsm/diagram/providers/FsmParserProvider.java package fsm.diagram.providers; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.common.core.service.AbstractProvider; import org.eclipse.gmf.runtime.common.core.service.IOperation; import org.eclipse.gmf.runtime.common.ui.services.parser.GetParserOperation; import org.eclipse.gmf.runtime.common.ui.services.parser.IParser; import org.eclipse.gmf.runtime.common.ui.services.parser.IParserProvider; import org.eclipse.gmf.runtime.common.ui.services.parser.ParserService; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.ui.services.parser.ParserHintAdapter; import org.eclipse.gmf.runtime.notation.View; import fsm.FsmPackage; import fsm.diagram.edit.parts.ActionEntryLabel2EditPart; import fsm.diagram.edit.parts.ActionEntryLabelEditPart; import fsm.diagram.edit.parts.EActionExitLabel2EditPart; import fsm.diagram.edit.parts.EActionExitLabelEditPart; import fsm.diagram.edit.parts.SteadyStateNameEditPart; import fsm.diagram.edit.parts.TransientStateNameEditPart; import fsm.diagram.edit.parts.TransitionEffectGuardEditPart; import fsm.diagram.parsers.MessageFormatParser; import fsm.diagram.part.FsmVisualIDRegistry; /** * @generated */ public class FsmParserProvider extends AbstractProvider implements IParserProvider { /** * @generated */ private IParser steadyStateName_5004Parser; /** * @generated */ private IParser getSteadyStateName_5004Parser() { if (steadyStateName_5004Parser == null) { EAttribute[] features = new EAttribute[] { FsmPackage.eINSTANCE .getState_Name() }; MessageFormatParser parser = new MessageFormatParser(features); steadyStateName_5004Parser = parser; } return steadyStateName_5004Parser; } /** * @generated */ private IParser transientStateName_5005Parser; /** * @generated */ private IParser getTransientStateName_5005Parser() { if (transientStateName_5005Parser == null) { EAttribute[] features = new EAttribute[] { FsmPackage.eINSTANCE .getState_Name() }; MessageFormatParser parser = new MessageFormatParser(features); transientStateName_5005Parser = parser; } return transientStateName_5005Parser; } /** * @generated */ private IParser actionEntryLabel_5006Parser; /** * @generated */ private IParser getActionEntryLabel_5006Parser() { if (actionEntryLabel_5006Parser == null) { EAttribute[] features = new EAttribute[] { FsmPackage.eINSTANCE .getAction_EntryLabel() }; MessageFormatParser parser = new MessageFormatParser(features); parser.setViewPattern("entry/{0}"); //$NON-NLS-1$ parser.setEditorPattern("entry/{0}"); //$NON-NLS-1$ parser.setEditPattern("entry/{0}"); //$NON-NLS-1$ actionEntryLabel_5006Parser = parser; } return actionEntryLabel_5006Parser; } /** * @generated */ private IParser eActionExitLabel_5008Parser; /** * @generated */ private IParser getEActionExitLabel_5008Parser() { if (eActionExitLabel_5008Parser == null) { EAttribute[] features = new EAttribute[] { FsmPackage.eINSTANCE .geteAction_ExitLabel() }; MessageFormatParser parser = new MessageFormatParser(features); parser.setViewPattern("exit/{0}"); //$NON-NLS-1$ parser.setEditorPattern("exit/{0}"); //$NON-NLS-1$ parser.setEditPattern("exit/{0}"); //$NON-NLS-1$ eActionExitLabel_5008Parser = parser; } return eActionExitLabel_5008Parser; } /** * @generated */ private IParser actionEntryLabel_5007Parser; /** * @generated */ private IParser getActionEntryLabel_5007Parser() { if (actionEntryLabel_5007Parser == null) { EAttribute[] features = new EAttribute[] { FsmPackage.eINSTANCE .getAction_EntryLabel() }; MessageFormatParser parser = new MessageFormatParser(features); parser.setViewPattern("entry/{0}"); //$NON-NLS-1$ parser.setEditorPattern("entry/{0}"); //$NON-NLS-1$ parser.setEditPattern("entry/{0}"); //$NON-NLS-1$ actionEntryLabel_5007Parser = parser; } return actionEntryLabel_5007Parser; } /** * @generated */ private IParser eActionExitLabel_5009Parser; /** * @generated */ private IParser getEActionExitLabel_5009Parser() { if (eActionExitLabel_5009Parser == null) { EAttribute[] features = new EAttribute[] { FsmPackage.eINSTANCE .geteAction_ExitLabel() }; MessageFormatParser parser = new MessageFormatParser(features); parser.setViewPattern("exit/{0}"); //$NON-NLS-1$ parser.setEditorPattern("exit/{0}"); //$NON-NLS-1$ parser.setEditPattern("exit/{0}"); //$NON-NLS-1$ eActionExitLabel_5009Parser = parser; } return eActionExitLabel_5009Parser; } /** * @generated */ private IParser transitionEffectGuard_6001Parser; /** * @generated */ private IParser getTransitionEffectGuard_6001Parser() { if (transitionEffectGuard_6001Parser == null) { EAttribute[] features = new EAttribute[] { FsmPackage.eINSTANCE.getTransition_Effect(), FsmPackage.eINSTANCE.getTransition_Guard() }; EAttribute[] editableFeatures = new EAttribute[] { FsmPackage.eINSTANCE.getTransition_Effect(), FsmPackage.eINSTANCE.getTransition_Guard() }; MessageFormatParser parser = new MessageFormatParser(features, editableFeatures); parser.setViewPattern("[{1}] /{0}"); //$NON-NLS-1$ parser.setEditorPattern("[{1}] /{0}"); //$NON-NLS-1$ parser.setEditPattern("[{1}] /{0}"); //$NON-NLS-1$ transitionEffectGuard_6001Parser = parser; } return transitionEffectGuard_6001Parser; } /** * @generated */ protected IParser getParser(int visualID) { switch (visualID) { case SteadyStateNameEditPart.VISUAL_ID: return getSteadyStateName_5004Parser(); case TransientStateNameEditPart.VISUAL_ID: return getTransientStateName_5005Parser(); case ActionEntryLabelEditPart.VISUAL_ID: return getActionEntryLabel_5006Parser(); case EActionExitLabelEditPart.VISUAL_ID: return getEActionExitLabel_5008Parser(); case ActionEntryLabel2EditPart.VISUAL_ID: return getActionEntryLabel_5007Parser(); case EActionExitLabel2EditPart.VISUAL_ID: return getEActionExitLabel_5009Parser(); case TransitionEffectGuardEditPart.VISUAL_ID: return getTransitionEffectGuard_6001Parser(); } return null; } /** * Utility method that consults ParserService * @generated */ public static IParser getParser(IElementType type, EObject object, String parserHint) { return ParserService.getInstance().getParser( new HintAdapter(type, object, parserHint)); } /** * @generated */ public IParser getParser(IAdaptable hint) { String vid = (String) hint.getAdapter(String.class); if (vid != null) { return getParser(FsmVisualIDRegistry.getVisualID(vid)); } View view = (View) hint.getAdapter(View.class); if (view != null) { return getParser(FsmVisualIDRegistry.getVisualID(view)); } return null; } /** * @generated */ public boolean provides(IOperation operation) { if (operation instanceof GetParserOperation) { IAdaptable hint = ((GetParserOperation) operation).getHint(); if (FsmElementTypes.getElement(hint) == null) { return false; } return getParser(hint) != null; } return false; } /** * @generated */ private static class HintAdapter extends ParserHintAdapter { /** * @generated */ private final IElementType elementType; /** * @generated */ public HintAdapter(IElementType type, EObject object, String parserHint) { super(object, parserHint); assert type != null; elementType = type; } /** * @generated */ public Object getAdapter(Class adapter) { if (IElementType.class.equals(adapter)) { return elementType; } return super.getAdapter(adapter); } } } <file_sep>/omnetpp.fsm.editor.workspace/org.kermeta.fsm.gmf.diagram/src/fsm/diagram/providers/assistants/FsmModelingAssistantProviderOfSteadyStateEditPart.java package fsm.diagram.providers.assistants; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import fsm.diagram.edit.parts.SteadyStateEditPart; import fsm.diagram.edit.parts.TransientStateEditPart; import fsm.diagram.providers.FsmElementTypes; import fsm.diagram.providers.FsmModelingAssistantProvider; /** * @generated */ public class FsmModelingAssistantProviderOfSteadyStateEditPart extends FsmModelingAssistantProvider { /** * @generated */ @Override public List<IElementType> getTypesForPopupBar(IAdaptable host) { List<IElementType> types = new ArrayList<IElementType>(2); types.add(FsmElementTypes.Action_3001); types.add(FsmElementTypes.EAction_3003); return types; } /** * @generated */ @Override public List<IElementType> getRelTypesOnSource(IAdaptable source) { IGraphicalEditPart sourceEditPart = (IGraphicalEditPart) source .getAdapter(IGraphicalEditPart.class); return doGetRelTypesOnSource((SteadyStateEditPart) sourceEditPart); } /** * @generated */ public List<IElementType> doGetRelTypesOnSource(SteadyStateEditPart source) { List<IElementType> types = new ArrayList<IElementType>(1); types.add(FsmElementTypes.Transition_4001); return types; } /** * @generated */ @Override public List<IElementType> getRelTypesOnSourceAndTarget(IAdaptable source, IAdaptable target) { IGraphicalEditPart sourceEditPart = (IGraphicalEditPart) source .getAdapter(IGraphicalEditPart.class); IGraphicalEditPart targetEditPart = (IGraphicalEditPart) target .getAdapter(IGraphicalEditPart.class); return doGetRelTypesOnSourceAndTarget( (SteadyStateEditPart) sourceEditPart, targetEditPart); } /** * @generated */ public List<IElementType> doGetRelTypesOnSourceAndTarget( SteadyStateEditPart source, IGraphicalEditPart targetEditPart) { List<IElementType> types = new LinkedList<IElementType>(); if (targetEditPart instanceof SteadyStateEditPart) { types.add(FsmElementTypes.Transition_4001); } if (targetEditPart instanceof TransientStateEditPart) { types.add(FsmElementTypes.Transition_4001); } return types; } /** * @generated */ @Override public List<IElementType> getTypesForTarget(IAdaptable source, IElementType relationshipType) { IGraphicalEditPart sourceEditPart = (IGraphicalEditPart) source .getAdapter(IGraphicalEditPart.class); return doGetTypesForTarget((SteadyStateEditPart) sourceEditPart, relationshipType); } /** * @generated */ public List<IElementType> doGetTypesForTarget(SteadyStateEditPart source, IElementType relationshipType) { List<IElementType> types = new ArrayList<IElementType>(); if (relationshipType == FsmElementTypes.Transition_4001) { types.add(FsmElementTypes.SteadyState_2005); types.add(FsmElementTypes.TransientState_2006); } return types; } /** * @generated */ @Override public List<IElementType> getRelTypesOnTarget(IAdaptable target) { IGraphicalEditPart targetEditPart = (IGraphicalEditPart) target .getAdapter(IGraphicalEditPart.class); return doGetRelTypesOnTarget((SteadyStateEditPart) targetEditPart); } /** * @generated */ public List<IElementType> doGetRelTypesOnTarget(SteadyStateEditPart target) { List<IElementType> types = new ArrayList<IElementType>(1); types.add(FsmElementTypes.Transition_4001); return types; } /** * @generated */ @Override public List<IElementType> getTypesForSource(IAdaptable target, IElementType relationshipType) { IGraphicalEditPart targetEditPart = (IGraphicalEditPart) target .getAdapter(IGraphicalEditPart.class); return doGetTypesForSource((SteadyStateEditPart) targetEditPart, relationshipType); } /** * @generated */ public List<IElementType> doGetTypesForSource(SteadyStateEditPart target, IElementType relationshipType) { List<IElementType> types = new ArrayList<IElementType>(); if (relationshipType == FsmElementTypes.Transition_4001) { types.add(FsmElementTypes.SteadyState_2005); types.add(FsmElementTypes.TransientState_2006); types.add(FsmElementTypes.InitialState_2007); } return types; } } <file_sep>/not.combined.workspace/org.kermeta.fsm.gmf/src/fsm/impl/SteadyStateImpl.java /** */ package fsm.impl; import fsm.FsmPackage; import fsm.SteadyState; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Steady State</b></em>'. * <!-- end-user-doc --> * <p> * </p> * * @generated */ public class SteadyStateImpl extends StateImpl implements SteadyState { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SteadyStateImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return FsmPackage.Literals.STEADY_STATE; } } //SteadyStateImpl <file_sep>/OMNetpp/lazar_fsm/SC_fsm.cc /* * tic_fsm.cc * * Created on: 26.05.2015 * Author: Nana */ #define FSM_DEBUG #include <stdio.h> #include <string.h> #include <omnetpp.h> class SC: public cSimpleModule { // FSM and its states cFSM sc_fsm; enum { INIT = 0, PSEUDOSYNC = FSM_Steady(1), INTEGRATE = FSM_Steady(2), SYNC = FSM_Steady(3), STABLE = FSM_Steady(4), }; private: cMessage *handleMsgEvent; bool clique_Detection; int stable_cycle_counter; public: SC(); virtual ~SC(); protected: virtual void initialize(); virtual void handleMessage(cMessage *msg); }; Define_Module(SC); SC::SC() { // Set the pointer to NULL, so that the destructor won't crash // even if initialize() doesn't get called because of a runtime // error or user cancellation during the startup process. handleMsgEvent = NULL; } SC::~SC() { // Dispose of dynamically allocated the objects cancelAndDelete(handleMsgEvent); } void SC::initialize() { WATCH(stable_cycle_counter); sc_fsm.setName("sc_fsm"); stable_cycle_counter = 0; // Create the event object we'll use for timing handleMsgEvent = new cMessage("handleMsgEvent"); EV << "Scheduling first send to t=5.0s\n"; scheduleAt(5.0, handleMsgEvent); } void SC::handleMessage(cMessage *msg) { if (uniform(0, 1) < 0.5) { clique_Detection = false; } else { clique_Detection = true; } FSM_Switch(sc_fsm) { case FSM_Exit(INIT): if (par("read").boolValue() == true) { EV << "read == TRUE " << endl; FSM_Goto(sc_fsm, PSEUDOSYNC); } else { EV << "read == FALSE " << endl; FSM_Goto(sc_fsm, INTEGRATE); } break; case FSM_Enter(PSEUDOSYNC): break; case FSM_Enter(INTEGRATE): scheduleAt(simTime() + 5.0, handleMsgEvent); break; case FSM_Exit(INTEGRATE): if (clique_Detection == true) { EV << "clique_Detection == TRUE" << endl; FSM_Goto(sc_fsm, INTEGRATE); } else { EV << "clique_Detection == FALSE " << endl; FSM_Goto(sc_fsm, SYNC); } break; case FSM_Enter(SYNC): scheduleAt(simTime() + 5.0, handleMsgEvent); break; case FSM_Exit(SYNC): if (clique_Detection == true) { EV << "clique_Detection == TRUE" << endl; FSM_Goto(sc_fsm, INTEGRATE); stable_cycle_counter = 0; } else if ((clique_Detection == false) && (stable_cycle_counter >= par("num_stable_cycles").longValue())) { EV << "clique_Detection == FALSE && StablCounter erreicht! " << endl; stable_cycle_counter = 0; FSM_Goto(sc_fsm, STABLE); } else { EV << "clique_Detection == FALS" << endl; stable_cycle_counter++; FSM_Goto(sc_fsm, SYNC); } break; case FSM_Enter(STABLE): scheduleAt(simTime() + 5.0, handleMsgEvent); break; case FSM_Exit(STABLE): if (clique_Detection == true) { EV << "clique_Detection == TRUE" << endl; FSM_Goto(sc_fsm, INTEGRATE); } else { EV << "clique_Detection == FALSE " << endl; FSM_Goto(sc_fsm, STABLE); } break; } } <file_sep>/editors.not.combined.EclipseWorkspace/org.kermeta.fsm.gmf/src/fsm/SuperState.java /** */ package fsm; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Super State</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link fsm.SuperState#getOutTrans <em>Out Trans</em>}</li> * </ul> * </p> * * @see fsm.FsmPackage#getSuperState() * @model * @generated */ public interface SuperState extends EObject { /** * Returns the value of the '<em><b>Out Trans</b></em>' containment reference list. * The list contents are of type {@link fsm.Transition}. * It is bidirectional and its opposite is '{@link fsm.Transition#getSrc <em>Src</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Out Trans</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Out Trans</em>' containment reference list. * @see fsm.FsmPackage#getSuperState_OutTrans() * @see fsm.Transition#getSrc * @model opposite="src" containment="true" keys="Guard Effect" * @generated */ EList<Transition> getOutTrans(); } // SuperState <file_sep>/OMNetpp/lazar_fsm/omnetpp.ini [General] network = fsm_net<file_sep>/editors.not.combined.EclipseWorkspace/org.kermeta.fsm.gmf/src/fsm/impl/FSMImpl.java /** */ package fsm.impl; import fsm.FSM; import fsm.FsmPackage; import fsm.InitialState; import fsm.State; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>FSM</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link fsm.impl.FSMImpl#getState <em>State</em>}</li> * <li>{@link fsm.impl.FSMImpl#getIntialState <em>Intial State</em>}</li> * </ul> * </p> * * @generated */ public class FSMImpl extends MinimalEObjectImpl.Container implements FSM { /** * The cached value of the '{@link #getState() <em>State</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getState() * @generated * @ordered */ protected EList<State> state; /** * The cached value of the '{@link #getIntialState() <em>Intial State</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getIntialState() * @generated * @ordered */ protected InitialState intialState; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected FSMImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return FsmPackage.Literals.FSM; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<State> getState() { if (state == null) { state = new EObjectContainmentEList<State>(State.class, this, FsmPackage.FSM__STATE); } return state; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InitialState getIntialState() { return intialState; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetIntialState(InitialState newIntialState, NotificationChain msgs) { InitialState oldIntialState = intialState; intialState = newIntialState; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FsmPackage.FSM__INTIAL_STATE, oldIntialState, newIntialState); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setIntialState(InitialState newIntialState) { if (newIntialState != intialState) { NotificationChain msgs = null; if (intialState != null) msgs = ((InternalEObject)intialState).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FsmPackage.FSM__INTIAL_STATE, null, msgs); if (newIntialState != null) msgs = ((InternalEObject)newIntialState).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FsmPackage.FSM__INTIAL_STATE, null, msgs); msgs = basicSetIntialState(newIntialState, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FsmPackage.FSM__INTIAL_STATE, newIntialState, newIntialState)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case FsmPackage.FSM__STATE: return ((InternalEList<?>)getState()).basicRemove(otherEnd, msgs); case FsmPackage.FSM__INTIAL_STATE: return basicSetIntialState(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case FsmPackage.FSM__STATE: return getState(); case FsmPackage.FSM__INTIAL_STATE: return getIntialState(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case FsmPackage.FSM__STATE: getState().clear(); getState().addAll((Collection<? extends State>)newValue); return; case FsmPackage.FSM__INTIAL_STATE: setIntialState((InitialState)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case FsmPackage.FSM__STATE: getState().clear(); return; case FsmPackage.FSM__INTIAL_STATE: setIntialState((InitialState)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case FsmPackage.FSM__STATE: return state != null && !state.isEmpty(); case FsmPackage.FSM__INTIAL_STATE: return intialState != null; } return super.eIsSet(featureID); } } //FSMImpl <file_sep>/combined.workspace/org.kermeta.fsm.gmf.diagram/src/fsm/diagram/edit/policies/TransitionItemSemanticEditPolicy.java package fsm.diagram.edit.policies; import org.eclipse.gef.commands.Command; import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest; import fsm.diagram.providers.FsmElementTypes; /** * @generated */ public class TransitionItemSemanticEditPolicy extends FsmBaseItemSemanticEditPolicy { /** * @generated */ public TransitionItemSemanticEditPolicy() { super(FsmElementTypes.Transition_4001); } /** * @generated */ protected Command getDestroyElementCommand(DestroyElementRequest req) { return getGEFWrapper(new DestroyElementCommand(req)); } } <file_sep>/not.combined.workspace/org.kermeta.fsm.gmf/src/fsm/impl/ActionImpl.java /** */ package fsm.impl; import fsm.Action; import fsm.FsmPackage; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Action</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link fsm.impl.ActionImpl#getEntryLabel <em>Entry Label</em>}</li> * </ul> * </p> * * @generated */ public class ActionImpl extends MinimalEObjectImpl.Container implements Action { /** * The default value of the '{@link #getEntryLabel() <em>Entry Label</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEntryLabel() * @generated * @ordered */ protected static final String ENTRY_LABEL_EDEFAULT = null; /** * The cached value of the '{@link #getEntryLabel() <em>Entry Label</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEntryLabel() * @generated * @ordered */ protected String entryLabel = ENTRY_LABEL_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ActionImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return FsmPackage.Literals.ACTION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getEntryLabel() { return entryLabel; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setEntryLabel(String newEntryLabel) { String oldEntryLabel = entryLabel; entryLabel = newEntryLabel; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FsmPackage.ACTION__ENTRY_LABEL, oldEntryLabel, entryLabel)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case FsmPackage.ACTION__ENTRY_LABEL: return getEntryLabel(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case FsmPackage.ACTION__ENTRY_LABEL: setEntryLabel((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case FsmPackage.ACTION__ENTRY_LABEL: setEntryLabel(ENTRY_LABEL_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case FsmPackage.ACTION__ENTRY_LABEL: return ENTRY_LABEL_EDEFAULT == null ? entryLabel != null : !ENTRY_LABEL_EDEFAULT.equals(entryLabel); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (entryLabel: "); result.append(entryLabel); result.append(')'); return result.toString(); } } //ActionImpl <file_sep>/GMF.EMF.WS/org.kermeta.fsm.gmf/src/fsm/FSM.java /** */ package fsm; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>FSM</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link fsm.FSM#getState <em>State</em>}</li> * <li>{@link fsm.FSM#getIntialState <em>Intial State</em>}</li> * </ul> * </p> * * @see fsm.FsmPackage#getFSM() * @model * @generated */ public interface FSM extends EObject { /** * Returns the value of the '<em><b>State</b></em>' containment reference list. * The list contents are of type {@link fsm.State}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>State</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>State</em>' containment reference list. * @see fsm.FsmPackage#getFSM_State() * @model containment="true" keys="name" * @generated */ EList<State> getState(); /** * Returns the value of the '<em><b>Intial State</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Intial State</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Intial State</em>' containment reference. * @see #setIntialState(InitialState) * @see fsm.FsmPackage#getFSM_IntialState() * @model containment="true" keys="name" required="true" * @generated */ InitialState getIntialState(); /** * Sets the value of the '{@link fsm.FSM#getIntialState <em>Intial State</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Intial State</em>' containment reference. * @see #getIntialState() * @generated */ void setIntialState(InitialState value); } // FSM <file_sep>/EclipseWorkspace/org.kermeta.fsm.gmf.diagram/src/fsm/diagram/edit/helpers/ActionEditHelper.java package fsm.diagram.edit.helpers; /** * @generated */ public class ActionEditHelper extends FsmBaseEditHelper { } <file_sep>/OMNetpp/state_pattern/tic_fsm.cc #include <stdio.h> #include <string.h> #include <omnetpp.h> class cBaseState: public cObject { class Tic* p; public: virtual void handle(); cBaseState(Tic* machine); }; class Tic: public cSimpleModule { protected: void initialize(); void handleMessage(cMessage* msg){ } public: void setNewState (cBaseState* previousState); }; /*----------------------STATES OF TIC---------------------*/ class Tic_RECV: public cBaseState { void handle(); }; class Tic_SEND: public cBaseState { void handle(); }; class Tic_WAITTORECV: public cBaseState { void handle(); }; class Tic_WAITTOSEND: public cBaseState { void handle(); }; <file_sep>/XSLT-Kapitel-Tic-FSM/tic.fsm.switch.cc void Tic::handleMessage(cMessage *msg) { FSM_Switch(fsm) { case FSM_Exit(INIT): FSM_Goto(fsm, ModifyingMsg); break; case FSM_Enter(ModifyingMsg): //entry code scheduleAt(simTime() + 1.0, ticEvent); break; case FSM_Exit(ModifyingMsg): if (msg == ticEvent) { FSM_Goto(fsm, SendingMsg); } break; case FSM_Exit(ReceivingMsg): //exit code transferredMsg = msg; FSM_Goto(fsm, ModifyingMsg); break; case FSM_Exit(SendingMsg): //exit code send(transferredMsg, "out"); transferredMsg = NULL; FSM_Goto(fsm, WaitingForMsg); break; case FSM_Enter(WaitingForMsg): break; case FSM_Exit(WaitingForMsg): if (strcmp(msg->getName(), "transferredMsg") == 0) { EV << msg->getName() << endl; FSM_Goto(fsm, ReceivingMsg); } break; } }<file_sep>/EclipseWorkspace/org.kermeta.fsm.gmf.editor/src/fsm/presentation/TableEditorPart.java package fsm.presentation; import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider; import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; /** * This shows how a table view works. * A table can be used as a list with icons. * */ public class TableEditorPart extends FsmEditorPart { /** * The table viewer used by this editor part. */ protected TableViewer viewer; /** * Default constructor. * @param parent */ public TableEditorPart(FsmEditor parent) { super(parent); } /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ @Override public void createPartControl(Composite parent) { viewer = new TableViewer(parent, SWT.NONE); Table table = viewer.getTable(); TableLayout layout = new TableLayout(); table.setLayout(layout); table.setHeaderVisible(true); table.setLinesVisible(true); TableColumn objectColumn = new TableColumn(table, SWT.NONE); layout.addColumnData(new ColumnWeightData(3, 100, true)); objectColumn.setText(getString("_UI_ObjectColumn_label")); objectColumn.setResizable(true); TableColumn selfColumn = new TableColumn(table, SWT.NONE); layout.addColumnData(new ColumnWeightData(2, 100, true)); selfColumn.setText(getString("_UI_SelfColumn_label")); selfColumn.setResizable(true); viewer.setColumnProperties(new String [] {"a", "b"}); viewer.setContentProvider(new AdapterFactoryContentProvider(getAdapterFactory())); viewer.setLabelProvider(new AdapterFactoryLabelProvider(getAdapterFactory())); createContextMenuFor(viewer); getEditorSite().setSelectionProvider(viewer); } /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ @Override public void setFocus() { viewer.getTable().setFocus(); } /* (non-Javadoc) * @see org.example.emfgmf.topicmap.presentation.TopicmapEditorPart#setInput(java.lang.Object) */ @Override public void setInput(Object input) { viewer.setInput(input); } } <file_sep>/OMNetpp/tictoc_fsm/tic_fsm.cc /* * tic_fsm.cc * * Created on: 26.05.2015 * Author: Nana */ #define FSM_DEBUG #include <stdio.h> #include <string.h> #include <omnetpp.h> class Tic: public cSimpleModule { // FSM and its states cFSM tic_fsm; enum { g = 0, WAIT_SEND = FSM_Steady(1), WAIT_RECV = FSM_Steady(2), SEND = FSM_Transient(1), RECV = FSM_Transient(2), }; private: cMessage *ticEvent; // pointer to the event object which we'll use for timing cMessage *ticMsg; // variable to remember the message until we send it back public: Tic(); virtual ~Tic(); protected: virtual void initialize(); virtual void handleMessage(cMessage *msg); }; Define_Module(Tic); Tic::Tic() { // Set the pointer to NULL, so that the destructor won't crash // even if initialize() doesn't get called because of a runtime // error or user cancellation during the startup process. ticEvent = ticMsg = NULL; } Tic::~Tic() { // Dispose of dynamically allocated the objects cancelAndDelete(ticEvent); delete ticMsg; } void Tic::initialize() { tic_fsm.setName("tic_fsm"); // Create the event object we'll use for timing -- just any ordinary message. ticEvent = new cMessage("ticEvent"); // No tictoc message yet. ticMsg = NULL; if (strcmp("tic", getName()) == 0) { // We don't start right away, but instead send an message to ourselves // (a "self-message") -- we'll do the first sending when it arrives // back to us, at t=5.0s simulated time. EV << "Scheduling first send to t=5.0s\n"; ticMsg = new cMessage("ticMsg"); scheduleAt(5.0, ticEvent); } } void Tic::handleMessage(cMessage *msg) { FSM_Switch(tic_fsm) { case FSM_Exit(g): FSM_Goto(tic_fsm, WAIT_SEND); break; case FSM_Enter(WAIT_SEND): scheduleAt(simTime() + 1.0, ticEvent); EV << "Scheduling send to toc in t=1s " << endl; break; case FSM_Exit(WAIT_SEND): FSM_Goto(tic_fsm, SEND); break; case FSM_Enter(WAIT_RECV): EV << "Warten auf Toc Msg! " << endl; break; case FSM_Exit(WAIT_RECV): FSM_Goto(tic_fsm, RECV); break; case FSM_Exit(SEND): { send(ticMsg, "out"); ticMsg = NULL; FSM_Goto(tic_fsm, WAIT_RECV); break; } case FSM_Exit(RECV): { ticMsg = msg; FSM_Goto(tic_fsm, WAIT_SEND); break; } } //} } <file_sep>/OMNetpp/state_pattern/toc_fsm.cc #include <stdio.h> #include <string.h> #include <omnetpp.h> class cBaseState: public cObject { class Toc* p; public: virtual void handle(); cBaseState(Toc* machine); }; class Toc: public cSimpleModule { protected: void initialize(); void handleMessage(cMessage* msg); public: void setNewState (cBaseState* previousState); }; /*----------------------STATES OF TOC---------------------*/ class Toc_RECV: public cBaseState { void handle(); }; class Toc_SEND: public cBaseState { void handle(); }; class Toc_WAITTORECV: public cBaseState { void handle(); }; class Toc_WAITTOSEND: public cBaseState { void handle(); }; <file_sep>/code.generator.workspace/xslt/files/output.cc <?xml version="1.0" encoding="UTF-8"?> #define FSM_DEBUG #include <stdio.h> #include <string.h> #include <omnetpp.h> class FSM: public cSimpleModule{ cFSM fsm; enum { INIT = 0, tic = FSM_Steady(1), toe = FSM_Steady(2), toc = FSM_Transient(1), }; public: FSM(); virtual ~FSM(); protected: virtual void initialize(); virtual void handleMessage(cMessage *msg); }; Define_Module(FSM); FSM::FSM() {} FSM::~FSM() {} void Tic::initialize() { fsm.setName("fsm"); } void FSM::handleMessage(cMessage *msg) { FSM_Switch(fsm){ case FSM_Exit(INIT): if(start ==true){ //actions hallo(); FSM_Goto(fsm, tic); } break; } } <file_sep>/combined.workspace/org.kermeta.fsm.gmf.editor/src/fsm/presentation/ReverseAdapterFactoryContentProvider.java package fsm.presentation; import java.util.Collections; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class ReverseAdapterFactoryContentProvider extends AdapterFactoryContentProvider { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ReverseAdapterFactoryContentProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object [] getElements(Object object) { Object parent = super.getParent(object); return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object [] getChildren(Object object) { Object parent = super.getParent(object); return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean hasChildren(Object object) { Object parent = super.getParent(object); return parent != null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getParent(Object object) { return null; } }<file_sep>/EclipseWorkspace/org.kermeta.fsm.gmf.editor/src/fsm/presentation/TableTreeEditorPart.java package fsm.presentation; import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider; import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; /** * This shows how a tree view with columns works. * */ public class TableTreeEditorPart extends FsmEditorPart { /** * The tree viewer used by this editor part. */ protected TreeViewer viewer; /** * Default constructor. * @param parent */ public TableTreeEditorPart(FsmEditor parent) { super(parent); } /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ @Override public void createPartControl(Composite parent) { viewer = new TreeViewer(parent, SWT.NONE); Tree tree = viewer.getTree(); tree.setLayoutData(new FillLayout()); tree.setHeaderVisible(true); tree.setLinesVisible(true); TreeColumn objectColumn = new TreeColumn(tree, SWT.NONE); objectColumn.setText(getString("_UI_ObjectColumn_label")); objectColumn.setResizable(true); objectColumn.setWidth(250); TreeColumn selfColumn = new TreeColumn(tree, SWT.NONE); selfColumn.setText(getString("_UI_SelfColumn_label")); selfColumn.setResizable(true); selfColumn.setWidth(200); viewer.setColumnProperties(new String [] {"a", "b"}); viewer.setContentProvider(new AdapterFactoryContentProvider(getAdapterFactory())); viewer.setLabelProvider(new AdapterFactoryLabelProvider(getAdapterFactory())); createContextMenuFor(viewer); getEditorSite().setSelectionProvider(viewer); } /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ @Override public void setFocus() { viewer.getTree().setFocus(); } /* (non-Javadoc) * @see org.example.emfgmf.topicmap.presentation.TopicmapEditorPart#setInput(java.lang.Object) */ @Override public void setInput(Object input) { viewer.setInput(input); } } <file_sep>/editors.not.combined.EclipseWorkspace/org.kermeta.fsm.gmf/src/fsm/Transition.java /** */ package fsm; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Transition</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link fsm.Transition#getGuard <em>Guard</em>}</li> * <li>{@link fsm.Transition#getEffect <em>Effect</em>}</li> * <li>{@link fsm.Transition#getTarget <em>Target</em>}</li> * <li>{@link fsm.Transition#getSource <em>Source</em>}</li> * <li>{@link fsm.Transition#getSrc <em>Src</em>}</li> * </ul> * </p> * * @see fsm.FsmPackage#getTransition() * @model * @generated */ public interface Transition extends EObject { /** * Returns the value of the '<em><b>Guard</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Guard</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Guard</em>' attribute. * @see #setGuard(String) * @see fsm.FsmPackage#getTransition_Guard() * @model * @generated */ String getGuard(); /** * Sets the value of the '{@link fsm.Transition#getGuard <em>Guard</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Guard</em>' attribute. * @see #getGuard() * @generated */ void setGuard(String value); /** * Returns the value of the '<em><b>Effect</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Effect</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Effect</em>' attribute. * @see #setEffect(String) * @see fsm.FsmPackage#getTransition_Effect() * @model * @generated */ String getEffect(); /** * Sets the value of the '{@link fsm.Transition#getEffect <em>Effect</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Effect</em>' attribute. * @see #getEffect() * @generated */ void setEffect(String value); /** * Returns the value of the '<em><b>Target</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Target</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Target</em>' reference. * @see #setTarget(State) * @see fsm.FsmPackage#getTransition_Target() * @model keys="name" required="true" * @generated */ State getTarget(); /** * Sets the value of the '{@link fsm.Transition#getTarget <em>Target</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Target</em>' reference. * @see #getTarget() * @generated */ void setTarget(State value); /** * Returns the value of the '<em><b>Source</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Source</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Source</em>' reference. * @see #setSource(SuperState) * @see fsm.FsmPackage#getTransition_Source() * @model required="true" * @generated */ SuperState getSource(); /** * Sets the value of the '{@link fsm.Transition#getSource <em>Source</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Source</em>' reference. * @see #getSource() * @generated */ void setSource(SuperState value); /** * Returns the value of the '<em><b>Src</b></em>' container reference. * It is bidirectional and its opposite is '{@link fsm.SuperState#getOutTrans <em>Out Trans</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Src</em>' container reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Src</em>' container reference. * @see #setSrc(SuperState) * @see fsm.FsmPackage#getTransition_Src() * @see fsm.SuperState#getOutTrans * @model opposite="outTrans" transient="false" * @generated */ SuperState getSrc(); /** * Sets the value of the '{@link fsm.Transition#getSrc <em>Src</em>}' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Src</em>' container reference. * @see #getSrc() * @generated */ void setSrc(SuperState value); } // Transition <file_sep>/not.combined.workspace/org.kermeta.fsm.gmf.diagram/src/fsm/diagram/edit/policies/SteadyStateSteady_entry_exit_actionsItemSemanticEditPolicy.java package fsm.diagram.edit.policies; import org.eclipse.gef.commands.Command; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest; import fsm.diagram.edit.commands.ActionCreateCommand; import fsm.diagram.edit.commands.EActionCreateCommand; import fsm.diagram.providers.FsmElementTypes; /** * @generated */ public class SteadyStateSteady_entry_exit_actionsItemSemanticEditPolicy extends FsmBaseItemSemanticEditPolicy { /** * @generated */ public SteadyStateSteady_entry_exit_actionsItemSemanticEditPolicy() { super(FsmElementTypes.SteadyState_2005); } /** * @generated */ protected Command getCreateCommand(CreateElementRequest req) { if (FsmElementTypes.Action_3001 == req.getElementType()) { return getGEFWrapper(new ActionCreateCommand(req)); } if (FsmElementTypes.EAction_3003 == req.getElementType()) { return getGEFWrapper(new EActionCreateCommand(req)); } return super.getCreateCommand(req); } } <file_sep>/omnetpp.fsm.editor.workspace/org.kermeta.fsm.gmf.diagram/src/fsm/diagram/navigator/FsmNavigatorLabelProvider.java package fsm.diagram.navigator; import org.eclipse.gmf.runtime.common.ui.services.parser.IParser; import org.eclipse.gmf.runtime.common.ui.services.parser.ParserOptions; import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.viewers.ITreePathLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.ViewerLabel; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.IMemento; import org.eclipse.ui.navigator.ICommonContentExtensionSite; import org.eclipse.ui.navigator.ICommonLabelProvider; import fsm.diagram.edit.parts.Action2EditPart; import fsm.diagram.edit.parts.ActionEditPart; import fsm.diagram.edit.parts.ActionEntryLabel2EditPart; import fsm.diagram.edit.parts.ActionEntryLabelEditPart; import fsm.diagram.edit.parts.EAction2EditPart; import fsm.diagram.edit.parts.EActionEditPart; import fsm.diagram.edit.parts.EActionExitLabel2EditPart; import fsm.diagram.edit.parts.EActionExitLabelEditPart; import fsm.diagram.edit.parts.FSMEditPart; import fsm.diagram.edit.parts.InitialStateEditPart; import fsm.diagram.edit.parts.SteadyStateEditPart; import fsm.diagram.edit.parts.SteadyStateNameEditPart; import fsm.diagram.edit.parts.TransientStateEditPart; import fsm.diagram.edit.parts.TransientStateNameEditPart; import fsm.diagram.edit.parts.TransitionEditPart; import fsm.diagram.edit.parts.TransitionEffectGuardEditPart; import fsm.diagram.part.FsmDiagramEditorPlugin; import fsm.diagram.part.FsmVisualIDRegistry; import fsm.diagram.providers.FsmElementTypes; import fsm.diagram.providers.FsmParserProvider; /** * @generated */ public class FsmNavigatorLabelProvider extends LabelProvider implements ICommonLabelProvider, ITreePathLabelProvider { /** * @generated */ static { FsmDiagramEditorPlugin .getInstance() .getImageRegistry() .put("Navigator?UnknownElement", ImageDescriptor.getMissingImageDescriptor()); //$NON-NLS-1$ FsmDiagramEditorPlugin .getInstance() .getImageRegistry() .put("Navigator?ImageNotFound", ImageDescriptor.getMissingImageDescriptor()); //$NON-NLS-1$ } /** * @generated */ public void updateLabel(ViewerLabel label, TreePath elementPath) { Object element = elementPath.getLastSegment(); if (element instanceof FsmNavigatorItem && !isOwnView(((FsmNavigatorItem) element).getView())) { return; } label.setText(getText(element)); label.setImage(getImage(element)); } /** * @generated */ public Image getImage(Object element) { if (element instanceof FsmNavigatorGroup) { FsmNavigatorGroup group = (FsmNavigatorGroup) element; return FsmDiagramEditorPlugin.getInstance().getBundledImage( group.getIcon()); } if (element instanceof FsmNavigatorItem) { FsmNavigatorItem navigatorItem = (FsmNavigatorItem) element; if (!isOwnView(navigatorItem.getView())) { return super.getImage(element); } return getImage(navigatorItem.getView()); } return super.getImage(element); } /** * @generated */ public Image getImage(View view) { switch (FsmVisualIDRegistry.getVisualID(view)) { case FSMEditPart.VISUAL_ID: return getImage( "Navigator?Diagram?http://www.kermeta.org/fsm?FSM", FsmElementTypes.FSM_1000); //$NON-NLS-1$ case SteadyStateEditPart.VISUAL_ID: return getImage( "Navigator?TopLevelNode?http://www.kermeta.org/fsm?SteadyState", FsmElementTypes.SteadyState_2005); //$NON-NLS-1$ case TransientStateEditPart.VISUAL_ID: return getImage( "Navigator?TopLevelNode?http://www.kermeta.org/fsm?TransientState", FsmElementTypes.TransientState_2006); //$NON-NLS-1$ case InitialStateEditPart.VISUAL_ID: return getImage( "Navigator?TopLevelNode?http://www.kermeta.org/fsm?InitialState", FsmElementTypes.InitialState_2007); //$NON-NLS-1$ case ActionEditPart.VISUAL_ID: return getImage( "Navigator?Node?http://www.kermeta.org/fsm?Action", FsmElementTypes.Action_3001); //$NON-NLS-1$ case Action2EditPart.VISUAL_ID: return getImage( "Navigator?Node?http://www.kermeta.org/fsm?Action", FsmElementTypes.Action_3002); //$NON-NLS-1$ case EActionEditPart.VISUAL_ID: return getImage( "Navigator?Node?http://www.kermeta.org/fsm?eAction", FsmElementTypes.EAction_3003); //$NON-NLS-1$ case EAction2EditPart.VISUAL_ID: return getImage( "Navigator?Node?http://www.kermeta.org/fsm?eAction", FsmElementTypes.EAction_3004); //$NON-NLS-1$ case TransitionEditPart.VISUAL_ID: return getImage( "Navigator?Link?http://www.kermeta.org/fsm?Transition", FsmElementTypes.Transition_4001); //$NON-NLS-1$ } return getImage("Navigator?UnknownElement", null); //$NON-NLS-1$ } /** * @generated */ private Image getImage(String key, IElementType elementType) { ImageRegistry imageRegistry = FsmDiagramEditorPlugin.getInstance() .getImageRegistry(); Image image = imageRegistry.get(key); if (image == null && elementType != null && FsmElementTypes.isKnownElementType(elementType)) { image = FsmElementTypes.getImage(elementType); imageRegistry.put(key, image); } if (image == null) { image = imageRegistry.get("Navigator?ImageNotFound"); //$NON-NLS-1$ imageRegistry.put(key, image); } return image; } /** * @generated */ public String getText(Object element) { if (element instanceof FsmNavigatorGroup) { FsmNavigatorGroup group = (FsmNavigatorGroup) element; return group.getGroupName(); } if (element instanceof FsmNavigatorItem) { FsmNavigatorItem navigatorItem = (FsmNavigatorItem) element; if (!isOwnView(navigatorItem.getView())) { return null; } return getText(navigatorItem.getView()); } return super.getText(element); } /** * @generated */ public String getText(View view) { if (view.getElement() != null && view.getElement().eIsProxy()) { return getUnresolvedDomainElementProxyText(view); } switch (FsmVisualIDRegistry.getVisualID(view)) { case FSMEditPart.VISUAL_ID: return getFSM_1000Text(view); case SteadyStateEditPart.VISUAL_ID: return getSteadyState_2005Text(view); case TransientStateEditPart.VISUAL_ID: return getTransientState_2006Text(view); case InitialStateEditPart.VISUAL_ID: return getInitialState_2007Text(view); case ActionEditPart.VISUAL_ID: return getAction_3001Text(view); case Action2EditPart.VISUAL_ID: return getAction_3002Text(view); case EActionEditPart.VISUAL_ID: return getEAction_3003Text(view); case EAction2EditPart.VISUAL_ID: return getEAction_3004Text(view); case TransitionEditPart.VISUAL_ID: return getTransition_4001Text(view); } return getUnknownElementText(view); } /** * @generated */ private String getFSM_1000Text(View view) { return ""; //$NON-NLS-1$ } /** * @generated */ private String getSteadyState_2005Text(View view) { IParser parser = FsmParserProvider.getParser( FsmElementTypes.SteadyState_2005, view.getElement() != null ? view.getElement() : view, FsmVisualIDRegistry.getType(SteadyStateNameEditPart.VISUAL_ID)); if (parser != null) { return parser.getPrintString(new EObjectAdapter( view.getElement() != null ? view.getElement() : view), ParserOptions.NONE.intValue()); } else { FsmDiagramEditorPlugin.getInstance().logError( "Parser was not found for label " + 5004); //$NON-NLS-1$ return ""; //$NON-NLS-1$ } } /** * @generated */ private String getTransientState_2006Text(View view) { IParser parser = FsmParserProvider.getParser( FsmElementTypes.TransientState_2006, view.getElement() != null ? view.getElement() : view, FsmVisualIDRegistry .getType(TransientStateNameEditPart.VISUAL_ID)); if (parser != null) { return parser.getPrintString(new EObjectAdapter( view.getElement() != null ? view.getElement() : view), ParserOptions.NONE.intValue()); } else { FsmDiagramEditorPlugin.getInstance().logError( "Parser was not found for label " + 5005); //$NON-NLS-1$ return ""; //$NON-NLS-1$ } } /** * @generated */ private String getInitialState_2007Text(View view) { return ""; //$NON-NLS-1$ } /** * @generated */ private String getAction_3001Text(View view) { IParser parser = FsmParserProvider .getParser(FsmElementTypes.Action_3001, view.getElement() != null ? view.getElement() : view, FsmVisualIDRegistry .getType(ActionEntryLabelEditPart.VISUAL_ID)); if (parser != null) { return parser.getPrintString(new EObjectAdapter( view.getElement() != null ? view.getElement() : view), ParserOptions.NONE.intValue()); } else { FsmDiagramEditorPlugin.getInstance().logError( "Parser was not found for label " + 5006); //$NON-NLS-1$ return ""; //$NON-NLS-1$ } } /** * @generated */ private String getAction_3002Text(View view) { IParser parser = FsmParserProvider.getParser( FsmElementTypes.Action_3002, view.getElement() != null ? view.getElement() : view, FsmVisualIDRegistry .getType(ActionEntryLabel2EditPart.VISUAL_ID)); if (parser != null) { return parser.getPrintString(new EObjectAdapter( view.getElement() != null ? view.getElement() : view), ParserOptions.NONE.intValue()); } else { FsmDiagramEditorPlugin.getInstance().logError( "Parser was not found for label " + 5007); //$NON-NLS-1$ return ""; //$NON-NLS-1$ } } /** * @generated */ private String getEAction_3003Text(View view) { IParser parser = FsmParserProvider .getParser(FsmElementTypes.EAction_3003, view.getElement() != null ? view.getElement() : view, FsmVisualIDRegistry .getType(EActionExitLabelEditPart.VISUAL_ID)); if (parser != null) { return parser.getPrintString(new EObjectAdapter( view.getElement() != null ? view.getElement() : view), ParserOptions.NONE.intValue()); } else { FsmDiagramEditorPlugin.getInstance().logError( "Parser was not found for label " + 5008); //$NON-NLS-1$ return ""; //$NON-NLS-1$ } } /** * @generated */ private String getEAction_3004Text(View view) { IParser parser = FsmParserProvider.getParser( FsmElementTypes.EAction_3004, view.getElement() != null ? view.getElement() : view, FsmVisualIDRegistry .getType(EActionExitLabel2EditPart.VISUAL_ID)); if (parser != null) { return parser.getPrintString(new EObjectAdapter( view.getElement() != null ? view.getElement() : view), ParserOptions.NONE.intValue()); } else { FsmDiagramEditorPlugin.getInstance().logError( "Parser was not found for label " + 5009); //$NON-NLS-1$ return ""; //$NON-NLS-1$ } } /** * @generated */ private String getTransition_4001Text(View view) { IParser parser = FsmParserProvider.getParser( FsmElementTypes.Transition_4001, view.getElement() != null ? view.getElement() : view, FsmVisualIDRegistry .getType(TransitionEffectGuardEditPart.VISUAL_ID)); if (parser != null) { return parser.getPrintString(new EObjectAdapter( view.getElement() != null ? view.getElement() : view), ParserOptions.NONE.intValue()); } else { FsmDiagramEditorPlugin.getInstance().logError( "Parser was not found for label " + 6001); //$NON-NLS-1$ return ""; //$NON-NLS-1$ } } /** * @generated */ private String getUnknownElementText(View view) { return "<UnknownElement Visual_ID = " + view.getType() + ">"; //$NON-NLS-1$ //$NON-NLS-2$ } /** * @generated */ private String getUnresolvedDomainElementProxyText(View view) { return "<Unresolved domain element Visual_ID = " + view.getType() + ">"; //$NON-NLS-1$ //$NON-NLS-2$ } /** * @generated */ public void init(ICommonContentExtensionSite aConfig) { } /** * @generated */ public void restoreState(IMemento aMemento) { } /** * @generated */ public void saveState(IMemento aMemento) { } /** * @generated */ public String getDescription(Object anElement) { return null; } /** * @generated */ private boolean isOwnView(View view) { return FSMEditPart.MODEL_ID .equals(FsmVisualIDRegistry.getModelID(view)); } } <file_sep>/OMNetpp/tictoc_fsm/toc_fsm.cc /* * toc_code.cc * * Created on: 26.05.2015 * Author: Nana */ #define FSM_DEBUG #include <stdio.h> #include <string.h> #include <omnetpp.h> class Toc: public cSimpleModule { // FSM and its states cFSM toc_fsm; enum { INIT = 0, WAIT_SEND = FSM_Steady(1), WAIT_RECV = FSM_Steady(2), SEND = FSM_Transient(1), RECV = FSM_Transient(2), }; private: cMessage *tocEvent; // pointer to the event object which we'll use for timing cMessage *tocMsg; // variable to remember the message until we send it back public: Toc(); virtual ~Toc(); protected: virtual void initialize(); virtual void handleMessage(cMessage *msg); }; Define_Module(Toc); Toc::Toc() { // Set the pointer to NULL, so that the destructor won't crash // even if initialize() doesn't get called because of a runtime // error or user cancellation during the startup process. tocEvent = tocMsg = NULL; } Toc::~Toc() { // Dispose of dynamically allocated the objects cancelAndDelete(tocEvent); delete tocMsg; } void Toc::initialize() { toc_fsm.setName("toc_fsm"); // Create the event object we'll use for timing -- just any ordinary message. tocEvent = new cMessage("tocEvent"); // No tictoc message yet. tocMsg = NULL; EV << "Enter the FSM in t=4.0s" << endl; scheduleAt(5.0, tocEvent); } void Toc::handleMessage(cMessage *msg) { FSM_Switch(toc_fsm) { case FSM_Exit(INIT): FSM_Goto(toc_fsm, WAIT_RECV); break; case FSM_Enter(WAIT_SEND): scheduleAt(simTime() + 1.0, tocEvent); EV << "Scheduling send to tic in t=1s\n " << endl; break; case FSM_Exit(WAIT_SEND): FSM_Goto(toc_fsm, SEND); break; case FSM_Enter(WAIT_RECV): EV << "Warten auf Tic Msg! " << endl; break; case FSM_Exit(WAIT_RECV): FSM_Goto(toc_fsm, RECV); break; case FSM_Exit(SEND): { send(tocMsg, "out"); tocMsg = NULL; FSM_Goto(toc_fsm, WAIT_RECV); break; } case FSM_Exit(RECV): { tocMsg = msg; FSM_Goto(toc_fsm, WAIT_SEND); break; } } //} } <file_sep>/OMNetpp/lazar_fsm_x/SC_fsm_x.cc /* * tic_fsm.cc * * Created on: 26.05.2015 * Author: Nana */ #define FSM_DEBUG #include <stdio.h> #include <string.h> #include <omnetpp.h> class SC: public cSimpleModule { // FSM and its states cFSM sc_fsm; enum { INIT = 0, PSEUDOSYNC = FSM_Steady(1), INTEGRATE = FSM_Steady(2), SYNC = FSM_Steady(3), STABLE = FSM_Steady(4), }; private: cMessage *handleMsgEvent; bool clique_Detection; int stable_cycle_counter; public: //_______________________________________________________________________________________________________________SC_State cOutVector *outVector; SC *sc; vector<int> *knownCMs; const char * CMs; cStringTokenizer *tokenizer; FILE *fp; vector<int> *values; int counter; int dummy; int data; bool local_timer; bool flood_receive; bool closed_window; bool round_completed; bool powerUp; bool first_sync_cycle; bool timeOutExpierd; uint32_t MembershipAcceptanceRange; uint32_t syncDomainId; uint32_t local_current_sync_priority; uint32_t local_clock; uint32_t local_sync_membership; uint32_t local_async_membership; uint32_t local_async_membership_f; uint32_t local_async_membership_r; uint64_t local_integration_cycle; int64_t clock_corr; uint64_t stable_cycle_counter; uint64_t duration; uint64_t max_transmission_delay; TTEScheduler *tteScheduler; SchedulerTimerEvent *event; SchedulerActionTimeEvent *event1; SchedulerActionTimeEvent *event2; SchedulerActionTimeEvent *event3; SchedulerActionTimeEvent *event4; SchedulerActionTimeEvent *event5; //template< const std::pair< unsigned int , PCFrame* > > //clock readings stack multimap<uint32_t, uint64_t> *container; std::map<uint32_t, pair<uint32_t, uint64_t> > *clock_stack; //multimap<unsigned int, PCFrame *> *f_container; //multimap<unsigned int, PCFrame *> *sync_container; //multimap<unsigned int,PCFrame*, const Compare& = Comp() > *f_container; //multimap<unsigned int, PCFrame *> *f_container; multimap<uint64_t, FrameEvent *> *e_container; SC(); virtual ~SC(); protected: virtual void initialize(); virtual void handleMessage(cMessage *msg); }; Define_Module(SC); SC::SC() { // Set the pointer to NULL, so that the destructor won't crash // even if initialize() doesn't get called because of a runtime // error or user cancellation during the startup process. handleMsgEvent = NULL; } SC::~SC() { // Dispose of dynamically allocated the objects cancelAndDelete(handleMsgEvent); } void SC::initialize() { sc_fsm.setName("sc_fsm"); //_______________________________________________________________________________________________________________SC //in/aus Datei schreiben/lesen path = "client"; //path = "/home/pcman/from_thinkpad/TTEthernetModel/examples/SICM_TEST_AS6802_sync/results/client"; ss << this->par("id").longValue(); path += ss.str(); if (this->par("read").boolValue()) { fp = fopen(path.c_str(), "r"); } else { fp = fopen(path.c_str(), "w+"); } } void SC::handleMessage(cMessage *msg) { //_______________________________________________________________________________________________________________INIT_CONST case FSM_Exit(INIT): //fp=fopen("/home/pcman/from_thinkpad/TTEthernetModel/examples/SICM_TEST_AS6802_sync/results/client.txt","w+"); if (sc->par("read").boolValue()) { values = new vector<int>(1200000); if (NULL != fp) { while (!feof(fp)) { fscanf(fp, "%d %d", &dummy, &data); values->at(counter++) = data; } //while } else { perror("Error opening file"); } counter = 0; } //read outVector = new cOutVector("client"); syncDomainId = sc->par("syncDomain").longValue(); local_current_sync_priority = sc->par("syncPriority").longValue(); MembershipAcceptanceRange = sc->par("MembershipAcceptanceRange").longValue(); local_timer = false; flood_receive = false; closed_window = false; round_completed = false; first_sync_cycle = false; local_clock = false; local_sync_membership = 0; local_async_membership = 0; //The monitoring intervals are longer than the integration_cycle_duration, requiring two variables local_async_membership_f, local_async_membership_r local_async_membership_f = 0; local_async_membership_r = 0; local_integration_cycle = 0; clock_corr = 0; stable_cycle_counter = 0; duration = 0; powerUp = true; max_transmission_delay = sc->par("max_transmission_delay").longValue(); event = new SchedulerTimerEvent("ASYNCHRON", TIMER_EVENT); event->setSchedulingPriority(3); container = new multimap<uint32_t, uint64_t>; clock_stack = new map<uint32, pair<uint32, uint64> >; //NOTE: A Time-Triggered Ethernet synchronization master makes all PCFs permanent before usage. //container for event's used to signal the "permanence pit" per frame e_container = new multimap<uint64_t, FrameEvent *>; //container for container for PCF frames delayed for permanence pit in SYNC/STABLE state; key = membership_new, value = PCFrame * //sync_container = new multimap<unsigned int, PCFrame* >; tteScheduler = (TTEScheduler*) sc->getParentModule()->getSubmodule( "tteScheduler"); //register the event's for the current/next cycle, they are used to signal a point's in time in the current/next integration cycle if (sc->par("read").boolValue()) { event3 = new SchedulerActionTimeEvent("smc_clock_corr_pit", ACTION_TIME_EVENT); event3->setAction_time( (unsigned int) sc->par("smc_clock_corr_pit").longValue()); event3->setDestinationGate(sc->gate("schedulerIn")); event3->setSchedulingPriority(4); //event4 is used to update/increment/ the "local_integration_cycle" value event4 = new SchedulerActionTimeEvent("smc_inc_pit", ACTION_TIME_EVENT); event4->setAction_time( sc->par("smc_scheduled_receive_pit").longValue() - sc->par("precision").longValue()); event4->setDestinationGate(sc->gate("schedulerIn")); event4->setSchedulingPriority(3); tteScheduler->registerEvent(event4); tteScheduler->registerEvent(event3); FSM_Goto(sc_fsm, PSEUDOSYNC); } else { FSM_Goto(sc_fsm, INTEGRATE); } break; //_______________________________________________________________________________________________________________PSEUDOSYNC case FSM_Enter(PSEUDOSYNC): if (string(message->getName()).compare("smc_inc_pit") == 0) { ev << "DEBUG SC_PSEUDOSYNC: local_integration_cycle before " << local_integration_cycle << endl; local_integration_cycle = (local_integration_cycle + 1) % (sc->par("max_integration_cycles").longValue()); ev << "DEBUG SC_PSEUDOSYNC: local_integration_cycle after " << local_integration_cycle << endl; tteScheduler->registerEvent(event4, true); } if (string(message->getName()).compare("smc_clock_corr_pit") == 0) { ev << "SC_PSEUDOSYNC clock correction" << endl; tteScheduler->clockCorrection(values->at(counter++)); tteScheduler->registerEvent(event3, true); } break; //_______________________________________________________________________________________________________________INTEGRATE case FSM_Enter(INTEGRATE): ev << "SC_INTEGRATE" << endl; sc->getDisplayString().setTagArg("i", 1, "red"); sc->bubble("INTEGRATE"); if (powerUp) { event->setTimer( (unsigned int) sc->par("sm_listen_timeout").longValue()); event->setDestinationGate(sc->gate("schedulerIn")); event->setSchedulingPriority(3); powerUp = false; } timeOutExpierd = false; tteScheduler->registerEvent(event); //timer start //ev << " DEBUG: SC_INTEGRATE::event->getTimer "<< event->getTimer() << endl; //local_timer=false; //TW(sm_listen_timeout); //local_timer=true; break; case FSM_Exit(INTEGRATE): if (message->arrivedOn("RCin")) { //ack to the buffer RCBuffer *rcBuffer = dynamic_cast<RCBuffer*>(message->getSenderModule()); if (rcBuffer) rcBuffer->resetBag(); //SM/SC makes all PCF frames permanent before usage PCFrame *pf = dynamic_cast<PCFrame *>(message); if ((pf->getSync_domain() == syncDomainId) && (pf->getSync_priority() == local_current_sync_priority)) { if ((transparentClockToTicks(pf->getTransparent_clock(), tteScheduler->par("tick").doubleValue()) + (tteScheduler->getTotalTicks() - pf->par("received_total").longValue()) > max_transmission_delay)) { ev << "WARNING: INTEGRATE: pkt->getTransparent_clock() > max_transmission_delay " << endl; } if (pf->getType() == IN) { ev << "DEBUG:SC INTEGRATE membership new value" << pf->getMembership_new() << endl; ev << "DEBUG:SC INTEGRATE membership new number of SM" << getValue(pf->getMembership_new(), 32) << endl; uint64_t permanence_delay = max_transmission_delay - (transparentClockToTicks( pf->getTransparent_clock(), tteScheduler->par("tick").doubleValue()) + (tteScheduler->getTotalTicks() - pf->par("received_total").longValue())); uint64_t permanence_pit = tteScheduler->getTotalTicks() + permanence_delay; if (e_container->find(permanence_pit) != e_container->end()) { if (getValue(pf->getMembership_new(), 32) > (getValue( e_container->find(permanence_pit)->second->getMember(), 32))) { ev << "DEBUG:SC INTEGRATE REPLACE membership new value" << pf->getMembership_new() << endl; ev << "DEBUG:SC INTEGRATE membership new number of SM " << getValue(pf->getMembership_new(), 32) << endl; tteScheduler->unregisterEvent( e_container->find(permanence_pit)->second); sc->cancelAndDelete( e_container->find(permanence_pit)->second); e_container->erase(permanence_pit); FrameEvent *f_event = new FrameEvent("IN_FRAME", TIMER_EVENT); f_event->setReceivedPort( pf->par("received_port").longValue()); f_event->setPcfType(IN); f_event->setIntegrationCycle( pf->getIntegration_cycle()); f_event->setMember(pf->getMembership_new()); f_event->setTimer(permanence_delay); f_event->setDestinationGate(sc->gate("schedulerIn")); f_event->setSchedulingPriority(2); tteScheduler->registerEvent(f_event); //save the event /we have to cancel and delete the events later/ e_container->insert(make_pair(permanence_pit, f_event)); } else if (getValue(pf->getMembership_new(), 32) == (getValue( e_container->find(permanence_pit)->second->getMember(), 32))) { if (pf->getIntegration_cycle() > e_container->find(permanence_pit)->second->getIntegrationCycle()) { ev << "DEBUG:SC INTEGRATE REPLACE int_cycle new value" << pf->getIntegration_cycle() << endl; tteScheduler->unregisterEvent( e_container->find(permanence_pit)->second); sc->cancelAndDelete( e_container->find(permanence_pit)->second); e_container->erase(permanence_pit); FrameEvent *f_event = new FrameEvent("IN_FRAME", TIMER_EVENT); f_event->setReceivedPort( pf->par("received_port").longValue()); f_event->setPcfType(IN); f_event->setIntegrationCycle( pf->getIntegration_cycle()); f_event->setMember(pf->getMembership_new()); f_event->setTimer(permanence_delay); f_event->setDestinationGate( sc->gate("schedulerIn")); f_event->setSchedulingPriority(2); tteScheduler->registerEvent(f_event); //save the event /we have to cancel and delete the events later/ e_container->insert( make_pair(permanence_pit, f_event)); } //int cycle } else { } } else { FrameEvent *f_event = new FrameEvent("IN_FRAME", TIMER_EVENT); f_event->setReceivedPort( pf->par("received_port").longValue()); f_event->setPcfType(IN); f_event->setMember(pf->getMembership_new()); f_event->setIntegrationCycle(pf->getIntegration_cycle()); //f_event->setAction_time(permanence_pit); f_event->setTimer(permanence_delay); f_event->setDestinationGate(sc->gate("schedulerIn")); f_event->setSchedulingPriority(2); tteScheduler->registerEvent(f_event); //save the event /we have to cancel and delete the events later/ e_container->insert(make_pair(permanence_pit, f_event)); // } delete pf; return; } //IN Frame ev << "SC DROP PCFrame " << pf->getName() << endl; delete pf; return; } //wrong sync domain or priority } //RCin if (message->arrivedOn("schedulerIn")) { if (string(message->getName()).compare("ASYNCHRON") == 0) { timeOutExpierd = true; return; } if (string(message->getName()).compare("IN_FRAME") == 0) { if (e_container->empty()) { ev << "SC_INTEGRATE Container is empty" << endl; return; } FrameEvent *frame_ = dynamic_cast<FrameEvent *>(message); int64_t ppt = tteScheduler->getTotalTicks(); //IN Frame? if (frame_->getPcfType() == IN) { int64_t temp = (int64_t) (tteScheduler->getTicks() - sc->par("smc_scheduled_receive_pit").longValue()); //local_clock=smc_scheduled_receive_pit; tteScheduler->clockCorrection(temp); local_integration_cycle = frame_->getIntegrationCycle(); local_sync_membership = getValue(frame_->getMember(), 32); local_async_membership = 0; if (local_sync_membership >= sc->par("sc_integrate_to_sync_thrld").longValue()) { //the synchronous clique detection return false and the device has synchronized to the current set of devices // if (!timeOutExpierd) { tteScheduler->unregisterEvent(event); } uint32_t tempKey = local_sync_membership; //container->insert(pair<uint32_t,uint64_t>(tempKey,tteScheduler->getTicks())); clock_stack->insert( pair<uint32, pair<uint32, uint64> >( frame_->getReceivedPort(), pair<uint32, uint64>(tempKey, tteScheduler->getTicks()))); ev << "DEBUG INTEGRATE: inserted value local_sync_membership" << local_sync_membership << endl; //register the event's for the current/next cycle, they are used to signal a point's in time in the current/next integration cycle event1 = new SchedulerActionTimeEvent("smc_async_eval_pit", ACTION_TIME_EVENT); //sm_dispatch_pit=smc_async_eval_pit // event1->setAction_time(sc->par("smc_async_eval_pit").longValue() - sc->par("smc_async_eval_pit").longValue()); event1->setAction_time(0); event1->setDestinationGate(sc->gate("schedulerIn")); event1->setSchedulingPriority(4); event2 = new SchedulerActionTimeEvent("smc_sync_eval_pit", ACTION_TIME_EVENT); event2->setAction_time( sc->par("smc_sync_eval_pit").longValue()); event2->setDestinationGate(sc->gate("schedulerIn")); event2->setSchedulingPriority(4); event3 = new SchedulerActionTimeEvent("smc_clock_corr_pit", ACTION_TIME_EVENT); event3->setAction_time( (unsigned int) sc->par("smc_clock_corr_pit").longValue()); event3->setDestinationGate(sc->gate("schedulerIn")); event3->setSchedulingPriority(4); //event4 is used to update/increment/ the "local_integration_cycle" value event4 = new SchedulerActionTimeEvent("smc_inc_pit", ACTION_TIME_EVENT); event4->setAction_time( sc->par("smc_scheduled_receive_pit").longValue() - sc->par("precision").longValue()); event4->setDestinationGate(sc->gate("schedulerIn")); event4->setSchedulingPriority(3); event5 = new SchedulerActionTimeEvent("smc_async_up", ACTION_TIME_EVENT); event5->setAction_time( (unsigned int) (sc->par("int_cycle_duration").longValue() - sc->par("acceptance_window").longValue())); event5->setDestinationGate(sc->gate("schedulerIn")); event5->setSchedulingPriority(4); tteScheduler->registerEvent(event1, true); tteScheduler->registerEvent(event2); tteScheduler->registerEvent(event4); tteScheduler->registerEvent(event5); delete frame_; if (e_container->find(ppt) != e_container->end()) { e_container->erase(ppt); } FSM_Goto(sc_fsm, SYNC); return; } delete frame_; if (e_container->find(ppt) != e_container->end()) { e_container->erase(ppt); return; } delete frame_; if (e_container->find(ppt) != e_container->end()) { e_container->erase(ppt); return; } //IN FRAME } } //schedulerIn } break; case FSM_Exit(SYNC): ev << "SC_SYNC::handleMessage" << endl; if (message->arrivedOn("schedulerIn")) { if (string(message->getName()).compare("IN_FRAME") == 0) { FrameEvent *evt = dynamic_cast<FrameEvent *>(message); uint32_t received_port = evt->getReceivedPort(); uint64_t int_cycle = evt->getIntegrationCycle(); uint32_t member = evt->getMember(); uint64_t permanence_pit = tteScheduler->getTicks(); if (int_cycle == local_integration_cycle) { if (inSchedule(permanence_pit, sc->par("smc_scheduled_receive_pit").longValue(), sc->par("precision").longValue())) { if (getValue(member, 32) >= (sc->par("max_pcf_membership").longValue() - MembershipAcceptanceRange) && (getValue(member, 32) <= (sc->par("max_pcf_membership").longValue()))) { uint32_t key_ = getValue(member, 32); //container->insert(pair<uint32_t, uint64_t>(key_, permanence_pit)); map<uint32_t, pair<uint32_t, uint64_t> >::iterator itr = clock_stack->find(received_port); if (itr == clock_stack->end()) { clock_stack->insert( pair<uint32_t, pair<uint32_t, uint64_t> >( received_port, pair<uint32_t, uint64_t>(key_, permanence_pit))); } else { if (key_ > itr->second.first) { itr->second.first = key_; itr->second.second = permanence_pit; } else if (key_ == itr->second.first) { if (permanence_pit > itr->second.second) { itr->second.second = permanence_pit; } } //membership equal } //found ev << "SC SYNC:in schedule key" << key_ << endl; ev << "SC SYNC: size container" << container->size() << endl; } //faulty sync master to be tolerated } else { //out of Schedule -> permanence pit out of bounds //update local_async_membership local_async_membership_f = local_async_membership_f | (member); local_async_membership_r = local_async_membership_r | (member); sc->bubble( "out of Schedule -> permanence pit out of bounds"); //write to log ev << "DEBUG: SC SYNC: permanence point in time(out of schedule)->" << permanence_pit << endl; } //inSchedule } else { //out of Schedule -> wrong integration cycle //update local_async_membership //local_async_membership = local_async_membership | (pcf->getMembership_new()); local_async_membership_f = local_async_membership_f | (member); local_async_membership_r = local_async_membership_r | (member); sc->bubble("out of Schedule -> wrong integration cycle"); ev << "DEBUG:SC SYNC: out of Schedule -> wrong integration cycle: " << int_cycle << endl; ev << "DEBUG: SC SYNC: out of Schedule local_integration_cycle->" << local_integration_cycle << endl; ev << "DEBUG: SC SYNC: out of Schedule FRAME integration_cycle->" << int_cycle << endl; } //local_integration_cycle uint64_t ppt = tteScheduler->getTotalTicks(); delete evt; if (e_container->find(ppt) != e_container->end()) { e_container->erase(ppt); } return; } //IN_FRAME if (string(message->getName()).compare("smc_async_eval_pit") == 0) { //update local_async_membership if ((local_integration_cycle % 2) == 0) { local_async_membership = local_async_membership_r; } else { local_async_membership = local_async_membership_f; } ev << "DEBUG SYNC: LOCAL_CLOCK smc_async_eval_pit" << tteScheduler->getTicks() * 80 << endl; if ((getValue(local_async_membership, 32) >= sc->par("sm_sync_threshold_async").longValue())) { ev << "DEBUG: SYNC: ASYNCHRONUS CLIQUE DETECTION -> TRUE" << endl; ev << "DEBUG: SYNC: NEXT STATE INTEGRATE" << endl; //event = new SchedulerTimerEvent("ASYNCHRON", TIMER_EVENT); event->setTimer( sc->par("sm_restart_timeout_async").longValue()); event->setDestinationGate(sc->gate("schedulerIn")); event->setSchedulingPriority(3); //duration=sm_restart_timeout_async; //local_clock=0; tteScheduler->clockCorrection(tteScheduler->getTicks()); local_integration_cycle = 0; local_sync_membership = 0; local_async_membership = 0; stable_cycle_counter = 0; //cancel the events for the synchronus state before enter the INTEGRATE state //tteScheduler->cancelAndDelete(event1); tteScheduler->unregisterEvent(event4); tteScheduler->unregisterEvent(event2); tteScheduler->unregisterEvent(event1); tteScheduler->unregisterEvent(event5); tteScheduler->unregisterEvent(event3); tteScheduler->cancelAndDelete(event1); tteScheduler->cancelAndDelete(event2); tteScheduler->cancelAndDelete(event3); tteScheduler->cancelAndDelete(event4); tteScheduler->cancelAndDelete(event5); //container->clear(); clock_stack->clear(); local_async_membership_r = 0; local_async_membership_f = 0; FSM_Goto(sc_fsm, INTEGRATE); return; } if ((!(getValue(local_async_membership, 32) >= sc->par("sm_sync_threshold_async").longValue()))) { //sm_dispatch_pit=smc_async_eval_pit //update local_integration_cycle, must be down before acceptance window ev << "DEBUG: SYNC: local_integration_cycle->" << local_integration_cycle << endl; tteScheduler->registerEvent(event1, true); } } //smc_async_eval_pit if (string(message->getName()).compare("smc_inc_pit") == 0) { local_integration_cycle = (local_integration_cycle + 1) % (sc->par("max_integration_cycles").longValue()); tteScheduler->registerEvent(event4, true); } if (string(message->getName()).compare("smc_sync_eval_pit") == 0) { tteScheduler->registerEvent(event3); /*Upon reaching the smc_sync_eval_pit or cm_sync_eval_pit, each device will update local_sync_membership. The device will set local_sync_membership (i.e., it will select the pcf_membership_new with the highest number of bits set from the set of in-schedule PCFs received during the acceptance window).*/ if (!clock_stack->empty()) { map<uint32_t, pair<uint32_t, uint64_t> >::iterator iter = clock_stack->begin(); if (clock_stack->size() == 1) { local_sync_membership = iter->second.first; } else { local_sync_membership = iter->second.first; while (iter != clock_stack->end()) { if (iter->second.first > local_sync_membership) { local_sync_membership = iter->second.first; } iter++; } //while } ev << "DEBUG STABLE clock_stack not empty: local_sync_membership" << local_sync_membership << endl; } else { //no "in Schedule" frame has been received during the acceptance window ev << "DEBUG: STABLE: clock_stack is empty" << endl; local_sync_membership = 0; } int dummy = sc->par("sc_sync_threshold_sync").longValue(); ev << "DEBUG SYNC smc_sync_eval_pit local_sync_membership" << local_sync_membership << endl; ev << "DEBUG SYNC smc_sync_eval_pit sc_sync_threshold_sync" << dummy << endl; ev << "DEBUG: SYNC: local_integration_cycle->" << local_integration_cycle << endl; if (local_sync_membership < (sc->par("sc_sync_threshold_sync").longValue())) { event->setTimer(sc->par("sm_restart_timeout_sync").longValue()); event->setDestinationGate(sc->gate("schedulerIn")); event->setSchedulingPriority(3); //local_clock=0; tteScheduler->clockCorrection(tteScheduler->getTicks()); local_integration_cycle = 0; local_sync_membership = 0; local_async_membership = 0; stable_cycle_counter = 0; //cancel the events for the synchronous state before enter the INTEGRATE State tteScheduler->unregisterEvent(event1); tteScheduler->unregisterEvent(event2); tteScheduler->unregisterEvent(event4); tteScheduler->unregisterEvent(event3); tteScheduler->unregisterEvent(event5); tteScheduler->cancelAndDelete(event1); tteScheduler->cancelAndDelete(event2); tteScheduler->cancelAndDelete(event3); tteScheduler->cancelAndDelete(event4); tteScheduler->cancelAndDelete(event5); clock_stack->clear(); local_async_membership_r = 0; local_async_membership_f = 0; FSM_Goto(sc_fsm, INTEGRATE); return; } if ((local_sync_membership >= sc->par("sc_sync_threshold_sync").longValue()) && (!sc->par("sc_sync_to_stable_enabled").boolValue())) { stable_cycle_counter++; tteScheduler->registerEvent(event2, true); return; } if ((local_sync_membership >= sc->par("sc_sync_threshold_sync").longValue()) && (sc->par("sc_sync_to_stable_enabled").boolValue()) && (stable_cycle_counter < sc->par("num_stable_cycles").longValue())) { stable_cycle_counter++; tteScheduler->registerEvent(event2, true); return; } if ((local_sync_membership >= sc->par("sc_sync_threshold_sync").longValue()) && (sc->par("sc_sync_to_stable_enabled").boolValue()) && (stable_cycle_counter >= sc->par("num_stable_cycles").longValue())) { tteScheduler->registerEvent(event2, true); stable_cycle_counter = 0; FSM_Goto(sc_fsm, STABLE); return; } } if (string(message->getName()).compare("smc_clock_corr_pit") == 0) { ev << "DEBUG SYNC: LOCAL_CLOCK smc_clock_corr_pit" << tteScheduler->getTicks() * 80 << endl; if (clock_stack->empty()) { sc->bubble("SC_SYNC clock_stack->empty"); } else if (clock_stack->size() == 1) { map<uint32_t, pair<uint32_t, uint64_t> >::iterator iter = clock_stack->begin(); clock_corr = iter->second.second - sc->par("smc_scheduled_receive_pit").longValue(); tteScheduler->clockCorrection(clock_corr); //outVector->recordWithTimestamp(simTime(),(double)clock_corr); if (!sc->par("read").boolValue()) { fprintf(fp, "%d ", tteScheduler->getCycles()); fprintf(fp, " %d \n", clock_corr); } //clear for the next cycle clock_stack->clear(); return; } else { //average method int64_t temp = 0; map<uint32_t, pair<uint32_t, uint64_t> >::iterator iter = clock_stack->begin(); while (iter != clock_stack->end()) { temp = temp + (iter->second.second - sc->par( "smc_scheduled_receive_pit").longValue()); iter++; } clock_corr = (double) (temp) / (double) (clock_stack->size()); ev << "DEBUG: SYNC:clock_corr_pit /more than one/ clock correction: " << clock_corr << endl; tteScheduler->clockCorrection(clock_corr); //for the next cycle clock_stack->clear(); return; } } if (string(message->getName()).compare("smc_async_up") == 0) { if ((local_integration_cycle % 2) == 0) { local_async_membership_f = 0; } else { local_async_membership_r = 0; } ev << "DEBUG:SYNC smc_async_up local_async_membership_r " << local_async_membership_r << endl; ev << "DEBUG:SYNC smc_async_up local_async_membership_f " << local_async_membership_f << endl; tteScheduler->registerEvent(event5, true); } } //message->arrivedOn("schedulerIn") if (message->arrivedOn("RCin")) { //send ack to the buffer RCBuffer *rcBuffer = dynamic_cast<RCBuffer*>(message->getSenderModule()); if (rcBuffer) rcBuffer->resetBag(); PCFrame *copy_ = dynamic_cast<PCFrame *>(message); if ((copy_->getSync_domain() == syncDomainId) && (copy_->getSync_priority() == local_current_sync_priority)) { if ((transparentClockToTicks(copy_->getTransparent_clock(), tteScheduler->par("tick").doubleValue()) + (tteScheduler->getTotalTicks() - copy_->par("received_total").longValue()) > max_transmission_delay)) { ev << "WARNING: SC SYNC: pkt->getTransparent_clock() > max_transmission_delay " << endl; } if (copy_->getType() == IN) { //calculate permanence pit uint64_t permanence_delay = max_transmission_delay - (transparentClockToTicks( copy_->getTransparent_clock(), tteScheduler->par("tick").doubleValue()) + (tteScheduler->getTotalTicks() - copy_->par("received_total").longValue())); uint64_t permanence_pit = tteScheduler->getTotalTicks() + permanence_delay; FrameEvent *f_event = new FrameEvent("IN_FRAME", TIMER_EVENT); f_event->setReceivedPort( copy_->par("received_port").longValue()); f_event->setPcfType(IN); f_event->setIntegrationCycle(copy_->getIntegration_cycle()); f_event->setMember(copy_->getMembership_new()); f_event->setTimer(permanence_delay); f_event->setDestinationGate(sc->gate("schedulerIn")); f_event->setSchedulingPriority(2); tteScheduler->registerEvent(f_event); e_container->insert( pair<uint64_t, FrameEvent *>(permanence_pit, f_event)); delete copy_; return; } else { ev << "ERROR::ONLY IN FRAMES ARE ACCEPTED BY SC " << copy_->getType() << endl; ev << "ERROR::UNKNOWN PCF TYPE " << copy_->getType() << endl; delete copy_; return; } //IN_FRAME } else { sc->bubble("wrong sync domain or sync priority"); delete copy_; return; } //sync_domain delete (copy_); } //RCin break; case FSM_Exit(STABLE): ev << "SC_STABLE::handleMessage" << endl; if (message->arrivedOn("schedulerIn")) { if (string(message->getName()).compare("IN_FRAME") == 0) { FrameEvent *evt = dynamic_cast<FrameEvent *>(message); uint32_t received_port = evt->getReceivedPort(); uint64_t int_cycle = evt->getIntegrationCycle(); uint32_t member = evt->getMember(); uint64_t permanence_pit = tteScheduler->getTicks(); if (int_cycle == local_integration_cycle) { if (inSchedule(permanence_pit, sc->par("smc_scheduled_receive_pit").longValue(), sc->par("precision").longValue())) { if (getValue(member, 32) >= (sc->par("max_pcf_membership").longValue() - MembershipAcceptanceRange) && (getValue(member, 32) <= (sc->par("max_pcf_membership").longValue()))) { uint32_t key_ = getValue(member, 32); map<uint32_t, pair<uint32_t, uint64_t> >::iterator itr = clock_stack->find(received_port); if (itr == clock_stack->end()) { clock_stack->insert( pair<uint32_t, pair<uint32_t, uint64_t> >( received_port, pair<uint32_t, uint64_t>(key_, permanence_pit))); } else { if (key_ > itr->second.first) { itr->second.first = key_; itr->second.second = permanence_pit; } else if (key_ == itr->second.first) { if (permanence_pit > itr->second.second) { itr->second.second = permanence_pit; } } //membership equal } //found ev << "SC_STABLE:in schedule key" << key_ << endl; ev << "SC_STABLE: size container" << container->size() << endl; } //faulty sync master to be tolerated } else { //out of Schedule -> permanence pit out of bounds //update local_async_membership //local_async_membership = local_async_membership | (pcf->getMembership_new()); local_async_membership_f = local_async_membership_f | (member); local_async_membership_r = local_async_membership_r | (member); sc->bubble( "out of Schedule -> permanence pit out of bounds"); //write to log ev << "DEBUG: SC_STABLE: permanence point in time(out of schedule)->" << permanence_pit << endl; } //inSchedule } else { //out of Schedule -> wrong integration cycle //update local_async_membership //local_async_membership = local_async_membership | (pcf->getMembership_new()); local_async_membership_f = local_async_membership_f | (member); local_async_membership_r = local_async_membership_r | (member); sc->bubble("out of Schedule -> wrong integration cycle"); ev << "DEBUG: SC_STABLE: out of Schedule -> wrong integration cycle: " << int_cycle << endl; ev << "DEBUG: SC_STABLE: out of Schedule local_integration_cycle->" << local_integration_cycle << endl; ev << "DEBUG: SC_STABLE: out of Schedule FRAME integration_cycle->" << int_cycle << endl; } //local_integration_cycle uint64_t ppt = tteScheduler->getTotalTicks(); if (e_container->find(ppt) != e_container->end()) { //delete e_container->find(ppt)->second; e_container->erase(ppt); ev << "CLIENT STABLE FRAME EVENT DELETED" << endl; } delete evt; ev << "CLIENT STABLE FRAME EVENT NOT DELETED" << endl; ev << "E_CONTAINER size" << e_container->size() << endl; return; } //IN_FRAME if (string(message->getName()).compare("smc_async_eval_pit") == 0) { //update local_async_membership if ((local_integration_cycle % 2) == 0) { local_async_membership = local_async_membership_r; } else { local_async_membership = local_async_membership_f; } tteScheduler->registerEvent(event1, true); if (getValue(local_async_membership, 32) >= sc->par("sc_stable_threshold_async").longValue()) { ev << "DEBUG STABLE smc_async_eval_pit local_sync_membership" << local_sync_membership << endl; ev << "DEBUG STABLE smc_async_eval_pit local_async_membership" << local_async_membership << endl; ev << "DEBUG STABLE: LOCAL_CLOCK smc_async_eval_pit" << tteScheduler->getTicks() * 80 << endl; ev << "SC_STABLE:: ASYNCHRONUS CLIQUE DETECTION TRUE" << endl; //event = new SchedulerTimerEvent("ASYNCHRON", TIMER_EVENT); //duration=sm_restart_timeout_async; event->setTimer( sc->par("sm_restart_timeout_async").longValue()); event->setDestinationGate(sc->gate("schedulerIn")); //local clock=0 tteScheduler->clockCorrection(tteScheduler->getTicks()); local_integration_cycle = 0; local_sync_membership = 0; local_async_membership = 0; local_async_membership_r = 0; local_async_membership_f = 0; stable_cycle_counter = 0; //cancel the events for the synchronus state before enter the INTEGRATE State tteScheduler->unregisterEvent(event4); tteScheduler->unregisterEvent(event1); tteScheduler->unregisterEvent(event2); tteScheduler->unregisterEvent(event5); //sp tteScheduler->unregisterEvent(event3); tteScheduler->cancelAndDelete(event1); tteScheduler->cancelAndDelete(event2); tteScheduler->cancelAndDelete(event3); tteScheduler->cancelAndDelete(event4); tteScheduler->cancelAndDelete(event5); clock_stack->clear(); //container->clear(); FSM_Goto(sc_fsm, INTEGRATE); return; } //asynchronus detection } //smc_async_eval_pit if (string(message->getName()).compare("smc_inc_pit") == 0) { local_integration_cycle = (local_integration_cycle + 1) % (sc->par("max_integration_cycles").longValue()); tteScheduler->registerEvent(event4, true); } if (string(message->getName()).compare("smc_sync_eval_pit") == 0) { tteScheduler->registerEvent(event3); /*Upon reaching the smc_sync_eval_pit or cm_sync_eval_pit, each device will update local_sync_membership. The device will set local_sync_membership S(i.e., it will select the pcf_membership_new with the highest number of bits set from the set of in-schedule PCFs received during the acceptance window).*/ if (!clock_stack->empty()) { map<uint32_t, pair<uint32_t, uint64_t> >::iterator iter = clock_stack->begin(); if (clock_stack->size() == 1) { local_sync_membership = iter->second.first; } else { local_sync_membership = iter->second.first; while (iter != clock_stack->end()) { if (iter->second.first > local_sync_membership) { local_sync_membership = iter->second.first; } iter++; } //while } ev << "DEBUG STABLE clock_stack not empty: local_sync_membership" << local_sync_membership << endl; } else { //no "in Schedule" frame has been received during the acceptance window ev << "DEBUG: STABLE: clock_stack is empty" << endl; local_sync_membership = 0; } if ((local_sync_membership < sc->par("sc_stable_threshold_sync").longValue()) && (stable_cycle_counter < sc->par("num_unstable_cycles").longValue())) { stable_cycle_counter++; tteScheduler->registerEvent(event2, true); return; } if ((local_sync_membership < sc->par("sc_stable_threshold_sync").longValue()) && (stable_cycle_counter >= sc->par("num_unstable_cycles").longValue())) { ev << "SC_STABLE:: SYNCHRONUS CLIQUE DETECTION TRUE" << endl; event->setSchedulingPriority(3); event->setTimer(sc->par("sm_restart_timeout_sync").longValue()); event->setDestinationGate(sc->gate("schedulerIn")); //local_clock=0; tteScheduler->clockCorrection(tteScheduler->getTicks()); local_integration_cycle = 0; local_sync_membership = 0; local_async_membership = 0; stable_cycle_counter = 0; //cancel the events for the synchronus state's before enter the INTEGRATE State tteScheduler->unregisterEvent(event4); tteScheduler->unregisterEvent(event1); tteScheduler->unregisterEvent(event2); tteScheduler->unregisterEvent(event3); tteScheduler->unregisterEvent(event5); tteScheduler->cancelAndDelete(event1); tteScheduler->cancelAndDelete(event2); tteScheduler->cancelAndDelete(event3); tteScheduler->cancelAndDelete(event4); tteScheduler->cancelAndDelete(event5); clock_stack->clear(); local_async_membership_r = 0; local_async_membership_f = 0; FSM_Goto(sc_fsm, INTEGRATE); return; } if (local_sync_membership >= sc->par("sc_stable_threshold_sync").longValue()) { stable_cycle_counter = 0; tteScheduler->registerEvent(event2, true); return; } } //smc_sync_eval_pit if (string(message->getName()).compare("smc_clock_corr_pit") == 0) { ev << "DEBUG STABLE: LOCAL_CLOCK smc_clock_corr_pit" << tteScheduler->getTicks() * 80 << endl; if (clock_stack->empty()) { sc->bubble("SC_STABLE clock_stack->empty"); } else if (clock_stack->size() == 1) { map<uint32_t, pair<uint32_t, uint64_t> >::iterator iter = clock_stack->begin(); clock_corr = iter->second.second - sc->par("smc_scheduled_receive_pit").longValue(); tteScheduler->clockCorrection(clock_corr); // outVector->recordWithTimestamp(simTime(),(double)clock_corr); if (!sc->par("read").boolValue()) { fprintf(fp, "%d ", tteScheduler->getCycles()); fprintf(fp, " %ld \n", clock_corr); } //clear for the next cycle clock_stack->clear(); return; } else { //average method int64_t temp = 0; map<uint32_t, pair<uint32_t, uint64_t> >::iterator iter = clock_stack->begin(); while (iter != clock_stack->end()) { temp = temp + (iter->second.second - sc->par( "smc_scheduled_receive_pit").longValue()); iter++; } clock_corr = (double) (temp) / (double) (clock_stack->size()); if (!sc->par("read").boolValue()) { fprintf(fp, "%d", tteScheduler->getCycles()); fprintf(fp, "%ld \n", clock_corr); } tteScheduler->clockCorrection(clock_corr); ev << "DEBUG: SC STABLE: clock correction " << clock_corr << endl; ev << "DEBUG: SC STABLE: Container size more than 1" << endl; //for the next cycle clock_stack->clear(); return; } } if (string(message->getName()).compare("smc_async_up") == 0) { if ((local_integration_cycle % 2) == 0) { local_async_membership_f = 0; } else { local_async_membership_r = 0; } ev << "DEBUG:STABLE smc_async_up local_async_membership_r " << local_async_membership_r << endl; ev << "DEBUG:STABLE smc_async_up local_async_membership_f " << local_async_membership_f << endl; tteScheduler->registerEvent(event5, true); } } //SchedulerIn if (message->arrivedOn("RCin")) { //send ack to the buffer RCBuffer *rcBuffer = dynamic_cast<RCBuffer*>(message->getSenderModule()); if (rcBuffer) rcBuffer->resetBag(); PCFrame *copy_ = dynamic_cast<PCFrame *>(message); if ((copy_->getSync_domain() == syncDomainId) && (copy_->getSync_priority() == local_current_sync_priority)) { if ((transparentClockToTicks(copy_->getTransparent_clock(), tteScheduler->par("tick").doubleValue()) + (tteScheduler->getTotalTicks() - copy_->par("received_total").longValue()) > max_transmission_delay)) { ev << "WARNING: SC STABLE: pkt->getTransparent_clock() > max_transmission_delay " << endl; } //calculate permanence pit uint64_t permanence_delay = max_transmission_delay - (transparentClockToTicks( copy_->getTransparent_clock(), tteScheduler->par("tick").doubleValue()) + (tteScheduler->getTotalTicks() - copy_->par("received_total").longValue())); uint64_t permanence_pit = tteScheduler->getTotalTicks() + permanence_delay; if (copy_->getType() == IN) { FrameEvent *f_event = new FrameEvent("IN_FRAME", TIMER_EVENT); f_event->setReceivedPort( copy_->par("received_port").longValue()); f_event->setPcfType(IN); f_event->setIntegrationCycle(copy_->getIntegration_cycle()); f_event->setMember(copy_->getMembership_new()); f_event->setTimer(permanence_delay); f_event->setDestinationGate(sc->gate("schedulerIn")); f_event->setSchedulingPriority(2); tteScheduler->registerEvent(f_event); e_container->insert( pair<uint64_t, FrameEvent *>(permanence_pit, f_event)); } else { ev << "ONLY IN FRAMES ARE ACCEPTED BY SYNC CLIENT " << copy_->getType() << endl; } //IN_FRAME } else { sc->bubble("wrong sync domain or priority"); } //sync_domain delete (copy_); } //RCin break; } } <file_sep>/combined.workspace/org.kermeta.fsm.gmf.diagram/src/fsm/diagram/providers/assistants/FsmModelingAssistantProviderOfEAction2EditPart.java package fsm.diagram.providers.assistants; import fsm.diagram.providers.FsmModelingAssistantProvider; /** * @generated */ public class FsmModelingAssistantProviderOfEAction2EditPart extends FsmModelingAssistantProvider { } <file_sep>/combined.workspace/org.kermeta.fsm.gmf/src/fsm/impl/SuperStateImpl.java /** */ package fsm.impl; import fsm.FsmPackage; import fsm.SuperState; import fsm.Transition; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Super State</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link fsm.impl.SuperStateImpl#getOutTrans <em>Out Trans</em>}</li> * </ul> * </p> * * @generated */ public class SuperStateImpl extends MinimalEObjectImpl.Container implements SuperState { /** * The cached value of the '{@link #getOutTrans() <em>Out Trans</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOutTrans() * @generated * @ordered */ protected EList<Transition> outTrans; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SuperStateImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return FsmPackage.Literals.SUPER_STATE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Transition> getOutTrans() { if (outTrans == null) { outTrans = new EObjectContainmentWithInverseEList<Transition>(Transition.class, this, FsmPackage.SUPER_STATE__OUT_TRANS, FsmPackage.TRANSITION__SRC); } return outTrans; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case FsmPackage.SUPER_STATE__OUT_TRANS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getOutTrans()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case FsmPackage.SUPER_STATE__OUT_TRANS: return ((InternalEList<?>)getOutTrans()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case FsmPackage.SUPER_STATE__OUT_TRANS: return getOutTrans(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case FsmPackage.SUPER_STATE__OUT_TRANS: getOutTrans().clear(); getOutTrans().addAll((Collection<? extends Transition>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case FsmPackage.SUPER_STATE__OUT_TRANS: getOutTrans().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case FsmPackage.SUPER_STATE__OUT_TRANS: return outTrans != null && !outTrans.isEmpty(); } return super.eIsSet(featureID); } } //SuperStateImpl <file_sep>/GMF.EMF.WS/org.kermeta.fsm.gmf/src/fsm/impl/TransitionImpl.java /** */ package fsm.impl; import fsm.FsmPackage; import fsm.State; import fsm.SuperState; import fsm.Transition; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EcoreUtil; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Transition</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link fsm.impl.TransitionImpl#getGuard <em>Guard</em>}</li> * <li>{@link fsm.impl.TransitionImpl#getEffect <em>Effect</em>}</li> * <li>{@link fsm.impl.TransitionImpl#getTarget <em>Target</em>}</li> * <li>{@link fsm.impl.TransitionImpl#getSource <em>Source</em>}</li> * <li>{@link fsm.impl.TransitionImpl#getSrc <em>Src</em>}</li> * </ul> * </p> * * @generated */ public class TransitionImpl extends MinimalEObjectImpl.Container implements Transition { /** * The default value of the '{@link #getGuard() <em>Guard</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getGuard() * @generated * @ordered */ protected static final String GUARD_EDEFAULT = null; /** * The cached value of the '{@link #getGuard() <em>Guard</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getGuard() * @generated * @ordered */ protected String guard = GUARD_EDEFAULT; /** * The default value of the '{@link #getEffect() <em>Effect</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEffect() * @generated * @ordered */ protected static final String EFFECT_EDEFAULT = null; /** * The cached value of the '{@link #getEffect() <em>Effect</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEffect() * @generated * @ordered */ protected String effect = EFFECT_EDEFAULT; /** * The cached value of the '{@link #getTarget() <em>Target</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTarget() * @generated * @ordered */ protected State target; /** * The cached value of the '{@link #getSource() <em>Source</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSource() * @generated * @ordered */ protected SuperState source; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TransitionImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return FsmPackage.Literals.TRANSITION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getGuard() { return guard; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setGuard(String newGuard) { String oldGuard = guard; guard = newGuard; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FsmPackage.TRANSITION__GUARD, oldGuard, guard)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getEffect() { return effect; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setEffect(String newEffect) { String oldEffect = effect; effect = newEffect; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FsmPackage.TRANSITION__EFFECT, oldEffect, effect)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public State getTarget() { if (target != null && target.eIsProxy()) { InternalEObject oldTarget = (InternalEObject)target; target = (State)eResolveProxy(oldTarget); if (target != oldTarget) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, FsmPackage.TRANSITION__TARGET, oldTarget, target)); } } return target; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public State basicGetTarget() { return target; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTarget(State newTarget) { State oldTarget = target; target = newTarget; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FsmPackage.TRANSITION__TARGET, oldTarget, target)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SuperState getSource() { if (source != null && source.eIsProxy()) { InternalEObject oldSource = (InternalEObject)source; source = (SuperState)eResolveProxy(oldSource); if (source != oldSource) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, FsmPackage.TRANSITION__SOURCE, oldSource, source)); } } return source; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SuperState basicGetSource() { return source; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSource(SuperState newSource) { SuperState oldSource = source; source = newSource; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FsmPackage.TRANSITION__SOURCE, oldSource, source)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SuperState getSrc() { if (eContainerFeatureID() != FsmPackage.TRANSITION__SRC) return null; return (SuperState)eInternalContainer(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetSrc(SuperState newSrc, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newSrc, FsmPackage.TRANSITION__SRC, msgs); return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSrc(SuperState newSrc) { if (newSrc != eInternalContainer() || (eContainerFeatureID() != FsmPackage.TRANSITION__SRC && newSrc != null)) { if (EcoreUtil.isAncestor(this, newSrc)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newSrc != null) msgs = ((InternalEObject)newSrc).eInverseAdd(this, FsmPackage.SUPER_STATE__OUT_TRANS, SuperState.class, msgs); msgs = basicSetSrc(newSrc, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FsmPackage.TRANSITION__SRC, newSrc, newSrc)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case FsmPackage.TRANSITION__SRC: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetSrc((SuperState)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case FsmPackage.TRANSITION__SRC: return basicSetSrc(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) { switch (eContainerFeatureID()) { case FsmPackage.TRANSITION__SRC: return eInternalContainer().eInverseRemove(this, FsmPackage.SUPER_STATE__OUT_TRANS, SuperState.class, msgs); } return super.eBasicRemoveFromContainerFeature(msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case FsmPackage.TRANSITION__GUARD: return getGuard(); case FsmPackage.TRANSITION__EFFECT: return getEffect(); case FsmPackage.TRANSITION__TARGET: if (resolve) return getTarget(); return basicGetTarget(); case FsmPackage.TRANSITION__SOURCE: if (resolve) return getSource(); return basicGetSource(); case FsmPackage.TRANSITION__SRC: return getSrc(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case FsmPackage.TRANSITION__GUARD: setGuard((String)newValue); return; case FsmPackage.TRANSITION__EFFECT: setEffect((String)newValue); return; case FsmPackage.TRANSITION__TARGET: setTarget((State)newValue); return; case FsmPackage.TRANSITION__SOURCE: setSource((SuperState)newValue); return; case FsmPackage.TRANSITION__SRC: setSrc((SuperState)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case FsmPackage.TRANSITION__GUARD: setGuard(GUARD_EDEFAULT); return; case FsmPackage.TRANSITION__EFFECT: setEffect(EFFECT_EDEFAULT); return; case FsmPackage.TRANSITION__TARGET: setTarget((State)null); return; case FsmPackage.TRANSITION__SOURCE: setSource((SuperState)null); return; case FsmPackage.TRANSITION__SRC: setSrc((SuperState)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case FsmPackage.TRANSITION__GUARD: return GUARD_EDEFAULT == null ? guard != null : !GUARD_EDEFAULT.equals(guard); case FsmPackage.TRANSITION__EFFECT: return EFFECT_EDEFAULT == null ? effect != null : !EFFECT_EDEFAULT.equals(effect); case FsmPackage.TRANSITION__TARGET: return target != null; case FsmPackage.TRANSITION__SOURCE: return source != null; case FsmPackage.TRANSITION__SRC: return getSrc() != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (Guard: "); result.append(guard); result.append(", Effect: "); result.append(effect); result.append(')'); return result.toString(); } } //TransitionImpl <file_sep>/omnetpp.fsm.editor.workspace/org.kermeta.fsm.gmf/src/fsm/impl/StateImpl.java /** */ package fsm.impl; import fsm.Action; import fsm.FsmPackage; import fsm.State; import fsm.eAction; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>State</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link fsm.impl.StateImpl#getName <em>Name</em>}</li> * <li>{@link fsm.impl.StateImpl#getEntry <em>Entry</em>}</li> * <li>{@link fsm.impl.StateImpl#getExit <em>Exit</em>}</li> * </ul> * </p> * * @generated */ public class StateImpl extends SuperStateImpl implements State { /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getEntry() <em>Entry</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEntry() * @generated * @ordered */ protected Action entry; /** * The cached value of the '{@link #getExit() <em>Exit</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExit() * @generated * @ordered */ protected eAction exit; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected StateImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return FsmPackage.Literals.STATE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FsmPackage.STATE__NAME, oldName, name)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Action getEntry() { return entry; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetEntry(Action newEntry, NotificationChain msgs) { Action oldEntry = entry; entry = newEntry; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FsmPackage.STATE__ENTRY, oldEntry, newEntry); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setEntry(Action newEntry) { if (newEntry != entry) { NotificationChain msgs = null; if (entry != null) msgs = ((InternalEObject)entry).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FsmPackage.STATE__ENTRY, null, msgs); if (newEntry != null) msgs = ((InternalEObject)newEntry).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FsmPackage.STATE__ENTRY, null, msgs); msgs = basicSetEntry(newEntry, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FsmPackage.STATE__ENTRY, newEntry, newEntry)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public eAction getExit() { return exit; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetExit(eAction newExit, NotificationChain msgs) { eAction oldExit = exit; exit = newExit; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FsmPackage.STATE__EXIT, oldExit, newExit); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setExit(eAction newExit) { if (newExit != exit) { NotificationChain msgs = null; if (exit != null) msgs = ((InternalEObject)exit).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FsmPackage.STATE__EXIT, null, msgs); if (newExit != null) msgs = ((InternalEObject)newExit).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FsmPackage.STATE__EXIT, null, msgs); msgs = basicSetExit(newExit, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FsmPackage.STATE__EXIT, newExit, newExit)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case FsmPackage.STATE__ENTRY: return basicSetEntry(null, msgs); case FsmPackage.STATE__EXIT: return basicSetExit(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case FsmPackage.STATE__NAME: return getName(); case FsmPackage.STATE__ENTRY: return getEntry(); case FsmPackage.STATE__EXIT: return getExit(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case FsmPackage.STATE__NAME: setName((String)newValue); return; case FsmPackage.STATE__ENTRY: setEntry((Action)newValue); return; case FsmPackage.STATE__EXIT: setExit((eAction)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case FsmPackage.STATE__NAME: setName(NAME_EDEFAULT); return; case FsmPackage.STATE__ENTRY: setEntry((Action)null); return; case FsmPackage.STATE__EXIT: setExit((eAction)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case FsmPackage.STATE__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case FsmPackage.STATE__ENTRY: return entry != null; case FsmPackage.STATE__EXIT: return exit != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (name: "); result.append(name); result.append(')'); return result.toString(); } } //StateImpl <file_sep>/OMNetpp/tictoc_fsm/tictoc_fsm.ini [General] network = tictoc_fsm_net <file_sep>/combined.workspace/org.kermeta.fsm.gmf.diagram/src/fsm/diagram/edit/helpers/TransientStateEditHelper.java package fsm.diagram.edit.helpers; /** * @generated */ public class TransientStateEditHelper extends FsmBaseEditHelper { } <file_sep>/EclipseWorkspace/org.kermeta.fsm.gmf.diagram/src/fsm/diagram/providers/assistants/FsmModelingAssistantProviderOfFSMEditPart.java package fsm.diagram.providers.assistants; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import fsm.diagram.providers.FsmElementTypes; import fsm.diagram.providers.FsmModelingAssistantProvider; /** * @generated */ public class FsmModelingAssistantProviderOfFSMEditPart extends FsmModelingAssistantProvider { /** * @generated */ @Override public List<IElementType> getTypesForPopupBar(IAdaptable host) { List<IElementType> types = new ArrayList<IElementType>(3); types.add(FsmElementTypes.SteadyState_2005); types.add(FsmElementTypes.TransientState_2006); types.add(FsmElementTypes.InitialState_2007); return types; } } <file_sep>/not.combined.workspace/org.kermeta.fsm.gmf/src/fsm/impl/eActionImpl.java /** */ package fsm.impl; import fsm.FsmPackage; import fsm.eAction; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>eAction</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link fsm.impl.eActionImpl#getExitLabel <em>Exit Label</em>}</li> * </ul> * </p> * * @generated */ public class eActionImpl extends MinimalEObjectImpl.Container implements eAction { /** * The default value of the '{@link #getExitLabel() <em>Exit Label</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExitLabel() * @generated * @ordered */ protected static final String EXIT_LABEL_EDEFAULT = null; /** * The cached value of the '{@link #getExitLabel() <em>Exit Label</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExitLabel() * @generated * @ordered */ protected String exitLabel = EXIT_LABEL_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected eActionImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return FsmPackage.Literals.EACTION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getExitLabel() { return exitLabel; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setExitLabel(String newExitLabel) { String oldExitLabel = exitLabel; exitLabel = newExitLabel; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FsmPackage.EACTION__EXIT_LABEL, oldExitLabel, exitLabel)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case FsmPackage.EACTION__EXIT_LABEL: return getExitLabel(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case FsmPackage.EACTION__EXIT_LABEL: setExitLabel((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case FsmPackage.EACTION__EXIT_LABEL: setExitLabel(EXIT_LABEL_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case FsmPackage.EACTION__EXIT_LABEL: return EXIT_LABEL_EDEFAULT == null ? exitLabel != null : !EXIT_LABEL_EDEFAULT.equals(exitLabel); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (exitLabel: "); result.append(exitLabel); result.append(')'); return result.toString(); } } //eActionImpl <file_sep>/EclipseWorkspace/org.kermeta.fsm.gmf/src/fsm/impl/FsmFactoryImpl.java /** */ package fsm.impl; import fsm.*; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class FsmFactoryImpl extends EFactoryImpl implements FsmFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static FsmFactory init() { try { FsmFactory theFsmFactory = (FsmFactory)EPackage.Registry.INSTANCE.getEFactory(FsmPackage.eNS_URI); if (theFsmFactory != null) { return theFsmFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new FsmFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FsmFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case FsmPackage.FSM: return createFSM(); case FsmPackage.STATE: return createState(); case FsmPackage.STEADY_STATE: return createSteadyState(); case FsmPackage.TRANSIENT_STATE: return createTransientState(); case FsmPackage.TRANSITION: return createTransition(); case FsmPackage.INITIAL_STATE: return createInitialState(); case FsmPackage.SUPER_STATE: return createSuperState(); case FsmPackage.ACTION: return createAction(); case FsmPackage.EACTION: return createeAction(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case FsmPackage.STRING: return createStringFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case FsmPackage.STRING: return convertStringToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FSM createFSM() { FSMImpl fsm = new FSMImpl(); return fsm; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public State createState() { StateImpl state = new StateImpl(); return state; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SteadyState createSteadyState() { SteadyStateImpl steadyState = new SteadyStateImpl(); return steadyState; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TransientState createTransientState() { TransientStateImpl transientState = new TransientStateImpl(); return transientState; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Transition createTransition() { TransitionImpl transition = new TransitionImpl(); return transition; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InitialState createInitialState() { InitialStateImpl initialState = new InitialStateImpl(); return initialState; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SuperState createSuperState() { SuperStateImpl superState = new SuperStateImpl(); return superState; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Action createAction() { ActionImpl action = new ActionImpl(); return action; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public eAction createeAction() { eActionImpl eAction = new eActionImpl(); return eAction; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String createStringFromString(EDataType eDataType, String initialValue) { return (String)super.createFromString(eDataType, initialValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertStringToString(EDataType eDataType, Object instanceValue) { return super.convertToString(eDataType, instanceValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FsmPackage getFsmPackage() { return (FsmPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static FsmPackage getPackage() { return FsmPackage.eINSTANCE; } } //FsmFactoryImpl
cc205620a42a2e5efcb68707e2a751c82965b6f6
[ "Java", "C++", "INI" ]
33
Java
NanaEB/BA
20bff57199604cfe5be1268d5835920be1604d71
e4fe80feabc3579fc59bf747bb3a0c4cf9eb9bf9
refs/heads/main
<file_sep>var PLAY = 1; var END = 0; var gameState = PLAY; var path1,jack,sun,ground var cloudsGroup,hurdlesGroup var score=0 function preload(){ path=loadImage("backgroundImg.png") running = loadAnimation("leg1.png","leg2.png","leg3.png","leg4.png","leg5.png","leg6.png","leg7.png","leg8.png"); hurdleimg=loadImage("hurdle.png"); sunAnimation = loadImage("sun.png"); groundImg=loadImage("ground.png") cloudImage = loadImage("cloud.png"); jumpsound = loadSound("jump.wav") gameOverImg = loadImage("gameOver.png"); restartImg = loadImage("restart.png"); sideImg=loadImage("side.png"); } function setup(){ createCanvas(600,400); path1=createSprite(300,200) path1.addImage("way", path) path1.scale=5 jack=createSprite(100,260,50,50) jack.addAnimation("runner", running) jack.scale=0.6 jack.setCollider("rectangle",0,0,40,225) sun = createSprite(width-50,75,10,10); sun.addAnimation("sun", sunAnimation); sun.scale = 0.1 invisibleGround = createSprite(width/2,385,width,125); invisibleGround.shapeColor ="#f4cbaa" ground=createSprite(300,400,600,100); ground.addImage("groun",groundImg) gameOver = createSprite(width/2,height/2- 50); gameOver.addImage(gameOverImg); restart = createSprite(width/2,height/2); restart.addImage(restartImg); restart.scale=0.1 gameOver.visible = false; restart.visible = false; cloudsGroup = new Group(); hurdlesGroup = new Group(); score=0 } function draw (){ background(0); if(gameState===PLAY){ score = score + Math.round(getFrameRate()/60); ground.velocityX=path1.velocityX path1.velocityX=-(5+5*score/10) if (path1.x < 0){ path1.x = path1.width/2; } if (ground.x < 0){ ground.x = ground.width/2; } if(keyDown("SPACE")){ jack.velocityY=-10 jumpsound.play() } jack.velocityY = jack.velocityY + 0.8 jack.collide(invisibleGround); spawnHurdle() spawnClouds() if(hurdlesGroup.isTouching(jack)){ gameState=END } } if(gameState===END){ gameOver.visible=true gameOver.depth-1 restart.visible=true restart.depth+1 path1.velocityX=0 ground.velocityX = 0; jack.velocityY = 0 jack.y=240 cloudsGroup.depth+2 hurdlesGroup.destroyEach() cloudsGroup.destroyEach() hurdlesGroup.setVelocityXEach(0); cloudsGroup.setVelocityXEach(0); hurdlesGroup.setLifetimeEach(-1); cloudsGroup.setLifetimeEach(-1); jack.addAnimation("runner",sideImg) if(mousePressedOver(restart)){ reset() } } drawSprites() textSize(20); fill("black") text("Score: "+ score,30,50); } function reset(){ gameState = PLAY; gameOver.visible = false; restart.visible = false; hurdlesGroup.destroyEach(); cloudsGroup.destroyEach(); jack.addAnimation("runner",running) score = 0; } function spawnHurdle(){ if(frameCount % 60===0){ hurdle=createSprite(600,300,50,50) hurdle.scale=0.3 hurdle.x=Math.round(random(600,500)) hurdle.addImage("hud",hurdleimg) hurdle.velocityX=-(5*score/10) hurdle.lifetime=300 hurdlesGroup.add(hurdle) } } function spawnClouds() { //write code here to spawn the clouds if (frameCount % 60 === 0) { var cloud = createSprite(width+20,height-320,40,10); cloud.y = Math.round(random(100,220)); cloud.addImage(cloudImage); cloud.scale = 0.5; cloud.velocityX = -3; //assign lifetime to the variable cloud.lifetime = 300; //adjust the depth cloud.depth = jack.depth; jack.depth = jack.depth+1; cloudsGroup.add(cloud); } }
9979399d0e90292c13b9f5b9e80cd723d77f1077
[ "JavaScript" ]
1
JavaScript
ragav5042/YOUR-OWN-INFINITE-RUNNER-GAME
073ee97db4228ec1726a8a44a2b76809b6aa2610
3109a4f7baf2d443bfb03baf2ecd2f0bd5706b0b
refs/heads/main
<file_sep>var nav = document.createElement('ul') nav.setAttribute('class','nav') var l1 = document.createElement('a') l1.setAttribute('href','index.html') l1.innerHTML = " Random Number Generator " l1.setAttribute('class','l1') nav.appendChild(l1) var l2 = document.createElement('a') l2.setAttribute('href','index2.html') l2.innerHTML = " DOB Manipulator " l2.setAttribute('class','l2') nav.appendChild(l2) document.body.appendChild(nav) var div = document.createElement('div') div.setAttribute('class','div1') document.body.appendChild(div) var label1 = document.createElement('label') label1.setAttribute('for','label1') label1.innerHTML='Unique 8 Digit Number is: ' label1.setAttribute('class','label1') div.append(label1) var text1 = document.createElement('label') text1.setAttribute('class','text1') text1.setAttribute('id','text1') div.appendChild(text1) var button1 = document.createElement('input') button1.setAttribute('type','button') button1.value = 'Click Here' button1.setAttribute('id','button1') button1.setAttribute('class','button1') button1.setAttribute('onclick','getnum(min,max)') document.body.appendChild(button1) function getnum(min,max){ var min = 10000000; var max = 99999999; var value = Math.floor(Math.random() * (max-min)+ min ) var value2 = value.toString().split(''); var result = new Set(value2) if(result.size != value2.length){ getnum(min,max) } else { document.getElementById('text1').innerHTML = value } console.log(result) } <file_sep># Frontend-Projects Few Projects made by using HTMLS,CSS and Javascript
312c0867904da90d939607fa0059f38f9a083252
[ "JavaScript", "Markdown" ]
2
JavaScript
nitishmohan8/Frontend-Projects
aba235982c5511d9f259e4c036e2bd4bfc7ec13a
69dced5b5943b8d3936305c645cd853aed7a5e8f
refs/heads/master
<repo_name>rokap0127/roguelike<file_sep>/Assets/Script/Item/Key.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Key : MonoBehaviour { public GameObject[] shutter; public GameObject[] bridge; private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "Knight") { bridge[0].SetActive(true); bridge[1].SetActive(true); shutter[0].SetActive(false); shutter[1].SetActive(false); shutter[2].SetActive(false); shutter[3].SetActive(false); } if (collision.gameObject.tag == "Archer") { bridge[0].SetActive(true); bridge[1].SetActive(true); shutter[0].SetActive(false); shutter[1].SetActive(false); shutter[2].SetActive(false); shutter[3].SetActive(false); } if (collision.gameObject.tag == "Mage") { bridge[0].SetActive(true); bridge[1].SetActive(true); shutter[0].SetActive(false); shutter[1].SetActive(false); shutter[2].SetActive(false); shutter[3].SetActive(false); } } } <file_sep>/Assets/Script/Map/MainMenu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MainMenu : MonoBehaviour { public GameObject[] menu; public Button[] button; public GameObject mapCamera; public bool menuflag = false; public bool cameraFlag=false; public bool itemFlag = false; public bool endFlag = false; // Start is called before the first frame update void Start() { ButtonDown(); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.LeftControl) && !menuflag|| Input.GetKeyDown(KeyCode.RightControl) && !menuflag) { menu[0].SetActive(true); Time.timeScale = 0f; menuflag = true; } else if (Input.GetKeyDown(KeyCode.LeftControl) && menuflag&&!cameraFlag&&!itemFlag&&!endFlag || Input.GetKeyDown(KeyCode.RightControl) && menuflag && !cameraFlag && !itemFlag && !endFlag || Input.GetMouseButtonDown(1) && menuflag && !cameraFlag && !itemFlag && !endFlag) { menu[0].SetActive(false); Time.timeScale = 1f; menuflag = false; } if(Input.GetKeyDown(KeyCode.LeftControl) && cameraFlag || Input.GetKeyDown(KeyCode.RightControl) && cameraFlag || Input.GetMouseButtonDown(1) && cameraFlag) { mapCamera.SetActive(false); menu[0].SetActive(true); cameraFlag = false; } if (Input.GetKeyDown(KeyCode.LeftControl) && itemFlag || Input.GetKeyDown(KeyCode.RightControl) && itemFlag || Input.GetMouseButtonDown(1) && itemFlag) { menu[1].SetActive(false); menu[0].SetActive(true); itemFlag = false; } if (Input.GetKeyDown(KeyCode.LeftControl) && endFlag || Input.GetKeyDown(KeyCode.RightControl) && endFlag || Input.GetMouseButtonDown(1) && endFlag) { menu[2].SetActive(false); endFlag = false; } } void ButtonDown() { button[0].onClick.AddListener(StartItem); button[1].onClick.AddListener(StartMap); button[2].onClick.AddListener(End); button[3].onClick.AddListener(Return); } void StartItem() { menu[1].SetActive(true); menu[0].SetActive(false); itemFlag = true; menuflag = false; } void StartMap() { mapCamera.SetActive(true); cameraFlag = true; menu[0].SetActive(false); } void End() { menu[2].SetActive(true); endFlag = true; } void Return() { menu[0].SetActive(false); menuflag = false; Time.timeScale = 1f; } }<file_sep>/Assets/Script/test.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class test : MonoBehaviour { public float floatHeight; public float leftForce; public float damping; public Rigidbody2D rb2D; // Start is called before the first frame update void Start() { rb2D = GetComponent<Rigidbody2D>(); } private void FixedUpdate() { RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up); if(hit.collider != null) { float distance = Mathf.Abs(hit.point.y - transform.position.y); float heightError = floatHeight - distance; float force = leftForce * heightError - rb2D.velocity.y * damping; rb2D.AddForce(Vector3.up * force); } } // Update is called once per frame void Update() { } } <file_sep>/Assets/Script/Character/PlayerGuard.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerGuard : MonoBehaviour { public Transform playerPosition; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void FixedUpdate() { ////プレイヤーよりxが1大きい //if (playerPosition.position.x > playerPosition.position.x + 1) //{ // transform.position = new Vector2(playerPosition.position.x + 2, playerPosition.position.y); //} ////プレイヤーよりxが1小さい //if (playerPosition.position.x < playerPosition.position.x - 1) //{ // transform.position = new Vector2(playerPosition.position.x - 2, playerPosition.position.y); //} ////プレイヤーよりyが1大きい //if (playerPosition.position.y > playerPosition.position.y + 1) //{ // transform.position = new Vector2(playerPosition.position.x, playerPosition.position.y + 2); //} ////プレイヤーよりyが1小さい //if (playerPosition.position.y < playerPosition.position.y - 1) //{ // transform.position = new Vector2(playerPosition.position.x, playerPosition.position.y - 2); //} } } <file_sep>/Assets/Script/Map/Switcher3.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Switcher3 : MonoBehaviour { public GameObject swich; public GameObject swich2; public GameObject bridge; public GameObject hole; public GameObject wall; public GameObject lever; public GameObject lever2; SwitchOn so; // Start is called before the first frame update void Start() { so = GetComponent<SwitchOn>(); } // Update is called once per frame void Update() { if(Input.GetKeyDown(KeyCode.E) && so.OnFlag) { swich.SetActive(false); swich2.SetActive(false); bridge.SetActive(true); hole.SetActive(false); wall.SetActive(true); lever.SetActive(true); lever2.SetActive(true); } } //private void OnCollisionEnter2D(Collision2D collision) //{ // if (collision.gameObject.tag == "Knight" // || collision.gameObject.tag == "Archer" // || collision.gameObject.tag == "Mage") // { // swich.SetActive(false); // bridge.SetActive(true); // hole.SetActive(false); // wall.SetActive(true); // lever.SetActive(true); // } //} } <file_sep>/Assets/Script/Scene/GameOverFlag.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameOverFlag : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if(Operation.knightDead && Operation.archerDead && Operation.mageDead) { SceneManager.LoadScene("GameOver"); } } } <file_sep>/Assets/Script/Enemy/EnemyManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyManager : MonoBehaviour { public Enemy[] m_enemyPrefabs; //敵のプレハブを管理する配列 public float m_interval; //出現時間(秒) private float m_timer; //出現タイミングを管理するタイマー // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { //出現タイミングを管理するタイマーを更新する m_timer += Time.deltaTime; //まだ敵が出現するタイミングではない場合、 //このフレームの処理はここで終える if(m_timer < m_interval) { return; } //出現するタイマーを管理するタイマーをリセットする m_timer = 0; //出現する敵をランダムに決定する var enemyIndex = Random.Range(0, m_enemyPrefabs.Length); //出現する敵のプレハブを配列から取得する var enemyPrefab = m_enemyPrefabs[enemyIndex]; //敵をオブジェクトを生成する var enemy = Instantiate(enemyPrefab); //敵を画面外のど位置に出現させるかランダムに決定する var respawnType = (RESPAWN_TYPE)Random.Range( 0, (int)RESPAWN_TYPE.SIZEOF); //敵を初期化する enemy.Init(respawnType); } } <file_sep>/Assets/Script/Camera/CameraController2.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class CameraController2 : MonoBehaviour { public GameObject[] sceneCamera; public GameObject[] entrance; public GameObject[] enemy; GameObject operation; Operation op; GameObject knight; GameObject archer; GameObject mage; Vector2 pos; // Start is called before the first frame update void Start() { operation = GameObject.FindGameObjectWithTag("Operation"); op = operation.GetComponent<Operation>(); sceneCamera[1].SetActive(true); } // Update is called once per frame void Update() { if(Operation.knightFlag) { knight = GameObject.FindGameObjectWithTag("Knight"); pos = knight.transform.position; } if(Operation.archerFlag) { archer = GameObject.FindGameObjectWithTag("Archer"); pos = archer.transform.position; } if(Operation.mageFlag) { mage = GameObject.FindGameObjectWithTag("Mage"); pos = mage.transform.position; } if (pos.x < entrance[0].transform.position.x) { sceneCamera[1].SetActive(true); sceneCamera[2].SetActive(false); sceneCamera[3].SetActive(false); sceneCamera[4].SetActive(false); sceneCamera[5].SetActive(false); sceneCamera[6].SetActive(false); sceneCamera[7].SetActive(false); sceneCamera[8].SetActive(false); enemy[1].SetActive(true); enemy[2].SetActive(false); enemy[3].SetActive(false); enemy[4].SetActive(false); enemy[5].SetActive(false); enemy[6].SetActive(false); enemy[7].SetActive(false); } if (pos.x > entrance[0].transform.position.x&& pos.y < entrance[1].transform.position.y) { sceneCamera[1].SetActive(false); sceneCamera[2].SetActive(true); sceneCamera[3].SetActive(false); sceneCamera[4].SetActive(false); sceneCamera[5].SetActive(false); sceneCamera[6].SetActive(false); sceneCamera[7].SetActive(false); sceneCamera[8].SetActive(false); enemy[1].SetActive(false); enemy[2].SetActive(true); enemy[3].SetActive(false); enemy[4].SetActive(false); enemy[5].SetActive(false); enemy[6].SetActive(false); enemy[7].SetActive(false); } if (pos.y > entrance[1].transform.position.y && pos.x > entrance[0].transform.position.x&&pos.x< entrance[2].transform.position.x) { sceneCamera[1].SetActive(false); sceneCamera[2].SetActive(false); sceneCamera[3].SetActive(true); sceneCamera[4].SetActive(false); sceneCamera[5].SetActive(false); sceneCamera[6].SetActive(false); sceneCamera[7].SetActive(false); sceneCamera[8].SetActive(false); enemy[1].SetActive(false); enemy[2].SetActive(false); enemy[3].SetActive(true); enemy[4].SetActive(false); enemy[5].SetActive(false); enemy[6].SetActive(false); enemy[7].SetActive(false); } if (pos.x > entrance[2].transform.position.x) { sceneCamera[1].SetActive(false); sceneCamera[2].SetActive(false); sceneCamera[3].SetActive(false); sceneCamera[4].SetActive(true); sceneCamera[5].SetActive(false); sceneCamera[6].SetActive(false); sceneCamera[7].SetActive(false); sceneCamera[8].SetActive(false); enemy[1].SetActive(false); enemy[2].SetActive(false); enemy[3].SetActive(false); enemy[4].SetActive(true); enemy[5].SetActive(false); enemy[6].SetActive(false); enemy[7].SetActive(false); } if (pos.x > entrance[2].transform.position.x && pos.y > entrance[3].transform.position.y) { sceneCamera[1].SetActive(false); sceneCamera[2].SetActive(false); sceneCamera[3].SetActive(false); sceneCamera[4].SetActive(false); sceneCamera[5].SetActive(true); sceneCamera[6].SetActive(false); sceneCamera[7].SetActive(false); sceneCamera[8].SetActive(false); enemy[1].SetActive(false); enemy[2].SetActive(false); enemy[3].SetActive(false); enemy[4].SetActive(false); enemy[5].SetActive(true); enemy[6].SetActive(false); enemy[7].SetActive(false); } if (pos.y > entrance[1].transform.position.y && pos.x < entrance[0].transform.position.x) { sceneCamera[1].SetActive(false); sceneCamera[2].SetActive(false); sceneCamera[3].SetActive(false); sceneCamera[4].SetActive(false); sceneCamera[5].SetActive(false); sceneCamera[6].SetActive(true); sceneCamera[7].SetActive(false); sceneCamera[8].SetActive(false); enemy[1].SetActive(false); enemy[2].SetActive(false); enemy[3].SetActive(false); enemy[4].SetActive(false); enemy[5].SetActive(false); enemy[6].SetActive(true); enemy[7].SetActive(false); } if (pos.y > entrance[4].transform.position.y && pos.x < entrance[1].transform.position.x) { sceneCamera[1].SetActive(false); sceneCamera[2].SetActive(false); sceneCamera[3].SetActive(false); sceneCamera[4].SetActive(false); sceneCamera[5].SetActive(false); sceneCamera[6].SetActive(false); sceneCamera[7].SetActive(true); sceneCamera[8].SetActive(false); enemy[1].SetActive(false); enemy[2].SetActive(false); enemy[3].SetActive(false); enemy[4].SetActive(false); enemy[5].SetActive(false); enemy[6].SetActive(false); enemy[7].SetActive(true); } if (pos.x < entrance[7].transform.position.x ) { sceneCamera[1].SetActive(false); sceneCamera[2].SetActive(false); sceneCamera[3].SetActive(false); sceneCamera[4].SetActive(false); sceneCamera[5].SetActive(false); sceneCamera[6].SetActive(false); sceneCamera[7].SetActive(false); sceneCamera[8].SetActive(true); enemy[1].SetActive(false); enemy[2].SetActive(false); enemy[3].SetActive(false); enemy[4].SetActive(false); enemy[5].SetActive(false); enemy[6].SetActive(false); enemy[7].SetActive(false); } //if (Input.GetKey(KeyCode.RightControl) || Input.GetKey(KeyCode.LeftControl)) //{ // sceneCamera[0].SetActive(true); // sceneCamera[1].SetActive(false); // sceneCamera[2].SetActive(false); // sceneCamera[3].SetActive(false); // sceneCamera[4].SetActive(false); // sceneCamera[5].SetActive(false); // sceneCamera[6].SetActive(false); // sceneCamera[7].SetActive(false); //} //if (Input.GetKeyUp(KeyCode.RightControl) || Input.GetKeyUp(KeyCode.LeftControl)) //{ // sceneCamera[0].SetActive(false); //} if (pos.y > entrance[5].transform.position.y) { if(!Operation.knightDead) { knight = GameObject.FindGameObjectWithTag("Knight"); Knight kt = knight.GetComponent<Knight>(); DataShare.knightHp = kt.playerHp; DataShare.knightMp = kt.playerMp; } if (!Operation.archerDead) { archer = GameObject.FindGameObjectWithTag("Archer"); Archer ac = archer.GetComponent<Archer>(); DataShare.archerHp = ac.playerHp; DataShare.archerMp = ac.playerMp; } if (!Operation.mageDead) { mage = GameObject.FindGameObjectWithTag("Mage"); Mage mg = mage.GetComponent<Mage>(); DataShare.mageHp = mg.playerHp; DataShare.mageMp = mg.playerMp; } SceneManager.LoadScene("Stage02"); } if (pos.x > entrance[6].transform.position.x) { if (!Operation.knightDead) { knight = GameObject.FindGameObjectWithTag("Knight"); Knight kt = knight.GetComponent<Knight>(); DataShare.knightHp = kt.playerHp; DataShare.knightMp = kt.playerMp; } if (!Operation.archerDead) { archer = GameObject.FindGameObjectWithTag("Archer"); Archer ac = archer.GetComponent<Archer>(); DataShare.archerHp = ac.playerHp; DataShare.archerMp = ac.playerMp; } if (!Operation.mageDead) { mage = GameObject.FindGameObjectWithTag("Mage"); Mage mg = mage.GetComponent<Mage>(); DataShare.mageHp = mg.playerHp; DataShare.mageMp = mg.playerMp; } SceneManager.LoadScene("Stage02"); } } }<file_sep>/Assets/Script/Map/MapManager3.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MapManager3 : MonoBehaviour { public GameObject shutter; public GameObject knight; public GameObject archer; public GameObject mage; // Start is called before the first frame update void Start() { Setting(); Invoke("Shut", 0.5f); } // Update is called once per frame void Update() { } void Shut() { shutter.SetActive(true); } void Setting() { if (!Operation.knightDead) { knight = GameObject.FindGameObjectWithTag("Knight"); Knight kt = knight.GetComponent<Knight>(); kt.playerHp = DataShare.knightHp; kt.playerMp = DataShare.knightMp; } else if (Operation.knightDead) { knight = GameObject.FindGameObjectWithTag("Knight"); Knight kt = knight.GetComponent<Knight>(); kt.playerHp = DataShare.knightHp; kt.playerMp = DataShare.knightMp; knight.SetActive(false); } if (!Operation.archerDead) { archer = GameObject.FindGameObjectWithTag("Archer"); Archer ac = archer.GetComponent<Archer>(); ac.playerHp = DataShare.archerHp; ac.playerMp = DataShare.archerMp; } else if(Operation.archerDead) { archer = GameObject.FindGameObjectWithTag("Archer"); Archer ac = archer.GetComponent<Archer>(); ac.playerHp = DataShare.archerHp; ac.playerMp = DataShare.archerMp; archer.SetActive(false); } if (!Operation.mageDead) { mage = GameObject.FindGameObjectWithTag("Mage"); Mage mg = mage.GetComponent<Mage>(); mg.playerHp = DataShare.mageHp; mg.playerMp = DataShare.mageMp; } else if(Operation.mageDead) { mage = GameObject.FindGameObjectWithTag("Mage"); Mage mg = mage.GetComponent<Mage>(); mg.playerHp = DataShare.mageHp; mg.playerMp = DataShare.mageMp; mage.SetActive(false); } } }<file_sep>/Assets/Script/Item/ItemChecker.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ItemChecker : MonoBehaviour { GameObject knight; GameObject archer; GameObject mage; Knight kt; Archer ac; Mage mg; public int HpPortion = 0; public int MpPortion = 0; public int SpeedUP = 0; public int DamageUP = 0; public int RevivalPendant = 0; public int Armor = 0; public int Bomb = 0; public bool DamageFlag = false; public bool SpeedFlag = false; public bool ArmorFlag = false; public bool RevivalFlag = false; public bool BombFlag = false; public bool KeyFlag = false; public GameObject bombActive; private void Awake() { //シーンが変わっても削除されない DontDestroyOnLoad(gameObject); } // Start is called before the first frame update void Start() { knight = GameObject.FindGameObjectWithTag("Knight"); archer = GameObject.FindGameObjectWithTag("Archer"); mage = GameObject.FindGameObjectWithTag("Mage"); kt = knight.GetComponent<Knight>(); ac = archer.GetComponent<Archer>(); mg = mage.GetComponent<Mage>(); } // Update is called once per frame void Update() { } private void FixedUpdate() { if(ArmorFlag &&Time.timeScale == 1f) { Invoke("AFlagOff", 10.0f); } if(DamageFlag && Time.timeScale == 1f) { Invoke("DFlagOff", 10.0f); } if(SpeedFlag && Time.timeScale == 1f) { Invoke("SFlagOff", 10.0f); } SetBomb(); } void AFlagOff() { ArmorFlag = false; } void DFlagOff() { DamageFlag = false; } void SFlagOff() { SpeedFlag = false; } void SetBomb() { if(BombFlag) { if(Input.GetKeyDown(KeyCode.LeftShift)|| Input.GetKeyDown(KeyCode.RightShift)) { if(Operation.knightFlag) { knight = GameObject.FindGameObjectWithTag("Knight"); Instantiate(bombActive, new Vector3(knight.transform.position.x, knight.transform.position.y + 0.3f, 0), transform.rotation); BombFlag = false; } if (Operation.archerFlag) { archer = GameObject.FindGameObjectWithTag("Archer"); Instantiate(bombActive, new Vector3(archer.transform.position.x, archer.transform.position.y + 0.3f, 0), transform.rotation); BombFlag = false; } if (Operation.mageFlag) { mage = GameObject.FindGameObjectWithTag("Mage"); Instantiate(bombActive, new Vector3(mage.transform.position.x, mage.transform.position.y + 0.3f, 0), transform.rotation); BombFlag = false; } } } } } <file_sep>/Assets/Script/Character/Operation.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Operation : MonoBehaviour { //コントロール中か public static bool knightFlag; //ナイト public static bool archerFlag; //アーチャー public static bool mageFlag; //メイジ //生きているか? public static bool knightDead; //ナイト public static bool archerDead; //アーチャー public static bool mageDead; //メイジ // Start is called before the first frame update void Start() { knightFlag = true; //オン archerFlag = false; //オフ mageFlag = false; //オフ knightDead = false; //オフ archerDead = false; //オフ mageDead = false; //オフ } private void Awake() { //シーンが変わっても削除されない DontDestroyOnLoad(gameObject); } // Update is called once per frame void Update() { //1ボタンを押したとき if(!knightDead && !knightFlag && Input.GetKeyDown(KeyCode.Alpha1)) { //ナイト オン KnightFlagOn(); } //2ボタンを押したとき if(!archerDead&& !archerFlag && Input.GetKeyDown(KeyCode.Alpha2)) { //アーチャー オン ArcherFlagOn(); } //3ボタンを押したとき if (!mageDead&& !mageFlag && Input.GetKeyDown(KeyCode.Alpha3)) { //メイジ オン MageFlagOn(); } } public static void KnightFlagOn() { //ナイト オン knightFlag = true; archerFlag = false; mageFlag = false; } public static void ArcherFlagOn() { //アーチャー オン knightFlag = false; archerFlag = true; mageFlag = false; } public static void MageFlagOn() { //メイジ オン knightFlag = false; archerFlag = false; mageFlag = true; } } <file_sep>/Assets/SwitchOn.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SwitchOn : MonoBehaviour { public bool OnFlag = false; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void OnTriggerEnter2D(Collider2D col) { if (col.gameObject.tag == "Knight" || col.gameObject.tag == "Archer" || col.gameObject.tag == "Mage") { OnFlag = true; } } } <file_sep>/Assets/MageEnemy.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MageEnemy : MonoBehaviour { public float moveSpeed; public int damage; public int enemyHp; public int enemyMaxHp; public Shot shotPrefab; //弾のプレハブ public float shotSpeed; //弾の移動の速さ public float shotAngleRange; //複数の弾を発射する時の角度 public float shotTimer; //弾の発射タイミングを管理するタイマー public int shotCount; //弾の発射数 public float shotInterval; //弾の発射間隔(秒) public Explotion explosionPrefab; //爆発エフェクト public Explotion magicPrefab; //メイジスキルエフェクト public List<Sprite> sprites;//スプライトリスト public float attackDistance; //近づく距離 public Image hpGauge; //HPゲージ public int knightAttack = 80; //ナイトからの攻撃 public int archerArow = 50; //アローからの攻撃 public int archerTrap = 30; //トラップからの攻撃 public int mageShot = 25; //メイジの通常攻撃 public int mageSkill = 40; //メイジのスキル攻撃 Direction direciton = Direction.DOWN; //向き SpriteRenderer spriteRenderer; //スプライトレンダラー Rigidbody2D enemyRigid; float distance = 0; float angle = 0; Vector3 _direction = Vector3.zero; float trapCount = 0; bool guardFlag = false; bool trapFlag = false; // Start is called before the first frame update void Start() { //Hpを最大にする enemyHp = enemyMaxHp; spriteRenderer = GetComponent<SpriteRenderer>(); enemyRigid = GetComponent<Rigidbody2D>(); } public void Update() { //Hpがを表示 hpGauge.fillAmount = (float)enemyHp / enemyMaxHp; } private void FixedUpdate() { //プレイヤーの位置へ向かうベクトルを生成する //ナイト if (Operation.knightFlag) { angle = Utils.GetAngle( transform.localPosition, Knight.instance.transform.localPosition); _direction = Utils.GetDirection(angle); //プレイヤーとの距離の絶対値 distance = Mathf.Abs(Vector2.Distance(transform.localPosition, Knight.instance.transform.localPosition)); } //アーチャー if (Operation.archerFlag) { angle = Utils.GetAngle( transform.localPosition, Archer.instance.transform.localPosition); //プレイヤーとの距離の絶対値 distance = Mathf.Abs(Vector2.Distance(transform.localPosition, Archer.instance.transform.localPosition)); _direction = Utils.GetDirection(angle); } //メイジ if (Operation.mageFlag) { angle = Utils.GetAngle( transform.localPosition, Mage.instance.transform.localPosition); _direction = Utils.GetDirection(angle); //プレイヤーとの距離の絶対値 distance = Mathf.Abs(Vector2.Distance(transform.localPosition, Mage.instance.transform.localPosition)); } if (/*!guardFlag &&*/ !trapFlag) { if (distance > attackDistance) { //プレイヤーが存在する方向へ移動する Vector3 movement = Vector2.zero; movement = _direction * moveSpeed; enemyRigid.MovePosition(transform.localPosition + movement); } else if (distance < attackDistance - 0.01f) { //プレイヤーが存在する方向の逆へ移動する Vector3 movement = Vector2.zero; movement = _direction * moveSpeed * -1; enemyRigid.MovePosition(transform.localPosition + movement); } PlayerRote(angle); //弾の発射を管理するタイマーを更新する shotTimer += Time.deltaTime; //まだ弾を発射するタイミングではない場合ここで処理を終える if (shotTimer < shotInterval) return; //弾を発射するタイマーをリセットする shotTimer = 0; //弾を発射する ShootNWay(angle, shotAngleRange, shotSpeed, shotCount); } if (trapFlag) { trapCount++; if (trapCount == 240) { trapFlag = false; trapCount = 0; } } } void PlayerRote(float angle) { //上を向く if (68 <= angle && angle < 113) { direciton = Direction.UP; spriteRenderer.sprite = sprites[(int)direciton]; } //右上を向く if (23 <= angle && angle < 68) { direciton = Direction.UPRIGHT; spriteRenderer.sprite = sprites[(int)direciton]; } //右を向く if (-23 <= angle && angle < 23) { direciton = Direction.RIGHT; spriteRenderer.sprite = sprites[(int)direciton]; } //右下を向く if (-68 <= angle && angle < -23) { direciton = Direction.DOWNRIGHT; spriteRenderer.sprite = sprites[(int)direciton]; } //下を向く if (-113 <= angle && angle < -68) { direciton = Direction.DOWN; spriteRenderer.sprite = sprites[(int)direciton]; } //左下を向く if (-158 <= angle && angle < -113) { direciton = Direction.DOWNLEFT; spriteRenderer.sprite = sprites[(int)direciton]; } //左を向く if (-158 > angle || angle >= 158) { direciton = Direction.LEFT; spriteRenderer.sprite = sprites[(int)direciton]; } //左上を向く if (113 <= angle && angle < 158) { direciton = Direction.UPLEFT; spriteRenderer.sprite = sprites[(int)direciton]; } } private void ShootNWay( float angleBase, float angleRange, float speed, int count) { var pos = transform.localPosition; //プレイヤーの位置 transform.localEulerAngles = _direction; var rot = transform.localRotation; //弾を複数発射する場合 if (1 < count) { //発射する回数分ループする for (int i = 0; i < count; i++) { //弾の発射角度を計算する var angle = angleBase + angleRange * ((float)i / (count - 1) - 0.5f); //発射する弾を生成する var shot = Instantiate(shotPrefab, pos, Quaternion.identity); //弾を発射する方向と速さを設定する shot.Init(angle, speed); } } else if (count == 1) { //発射する弾を生成する var shot = Instantiate(shotPrefab, pos, Quaternion.identity); //弾を発射する方向と速さを設定する shot.Init(angleBase, speed); } } private void OnTriggerEnter2D(Collider2D collision) { //ナイト if (collision.gameObject.tag == "PlayerAttack") { transform.position = Vector3.MoveTowards(transform.position, transform.position + _direction * -0.22f, 1.0f); Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす enemyHp -= knightAttack; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } //アーチャ if (collision.name.Contains("Arrow")) { Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす enemyHp -= archerArow; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } //トラップ if (collision.name.Contains("Trap")) { trapFlag = true; // 敵のHPを減らす enemyHp -= archerTrap; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } //メイジ if (collision.name.Contains("Shot_M")) { Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす enemyHp -= archerTrap; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } if (collision.name.Contains("Magic")) { Instantiate(magicPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす enemyHp -= mageSkill; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } //Playerにダメージ //if (collision.name.Contains("Knight")) //{ // //プレイヤーにダメージを与える // var knight = collision.GetComponent<Knight>(); // if (knight == null) return; // knight.Damage(damage); //} //if (collision.name.Contains("Archer")) //{ // //プレイヤーにダメージを与える // var archer = collision.GetComponent<Archer>(); // if (archer == null) return; // archer.Damage(damage); //} //if (collision.name.Contains("Mage")) //{ // //プレイヤーにダメージを与える // var mage = collision.GetComponent<Mage>(); // if (mage == null) return; // mage.Damage(damage); //} //if (collision.name.Contains("Guard")) //{ // moveSpeed = 0; //} } //private void OnTriggerStay2D(Collider2D collision) //{ // //moveSpeed = 0.01f; // if (collision.name.Contains("Guard")) // { // guardFlag = true; // } //} //private void OnCollisionExit2D(Collision2D collision) //{ // if (collision.gameObject.tag == "Guard") // { // guardFlag = false; // } //} } <file_sep>/Assets/Script/Gimmick/BlastBarrel.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BlastBarrel : MonoBehaviour { public Explotion explosionPrefab; //爆発エフェクト public int damage; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "Knight" || collision.gameObject.tag == "Archer" || collision.gameObject.tag == "Mage") { Instantiate( explosionPrefab, collision.transform.position, Quaternion.identity); Destroy(gameObject); } } } <file_sep>/Assets/Script/Item/LegendaryTreasure.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LegendaryTreasure : MonoBehaviour { GameObject checker; GameObject operation; GameObject data; bool OpenFlag=false; // Start is called before the first frame update void Start() { checker = GameObject.FindGameObjectWithTag("ItemChecker"); operation = GameObject.FindGameObjectWithTag("Operation"); data = GameObject.FindGameObjectWithTag("Data"); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.E) && OpenFlag) { Destroy(operation); Destroy(checker); Destroy(data); SceneManager.LoadScene("GameClear"); } } private void OnTriggerEnter2D(Collider2D col) { if (col.gameObject.tag == "Knight" || col.gameObject.tag == "Archer" || col.gameObject.tag == "Mage") { OpenFlag = true; } } private void OnTriggerExit2D(Collider2D collision) { if (collision.gameObject.tag == "Knight" || collision.gameObject.tag == "Archer" || collision.gameObject.tag == "Mage") { OpenFlag = false; } } } <file_sep>/Assets/Script/Enemy/Enemy.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public enum RESPAWN_TYPE { UP, //上 RIGHT, //右 DOWN, //下 LEFT, //左 SIZEOF, //敵の出現位置の数 } public class Enemy : MonoBehaviour { public Vector2 m_respawnPosInside; //敵の出現位置(内側) public Vector2 m_respawnPosOutside; //敵の出現位置(外側) public float m_speed; //移動する速さ public int m_hpMax; //HPの最大値 public int m_exp; //この敵を倒したときに獲得できる経験値 public int m_damage; //この敵がプレイヤーに与えるダメージ public Explotion explosionPrefab; //爆発エフェクト private int m_hp; //HP private Vector3 m_direction; //進行方向 //敵が生成したときに呼び出される関数 void Start() { //HPを初期化する m_hp = m_hpMax; } // Update is called once per frame void Update() { //まっすぐ移動する transform.localPosition += m_direction * m_speed; } //敵が出現するときに初期化する関数 public void Init(RESPAWN_TYPE respwanType) { var pos = Vector3.zero; //指定された出現位置の種類に応じて //出現位置と進行方向を決定する switch (respwanType) { //出現位置が上の場合 case RESPAWN_TYPE.UP: pos.x = Random.Range( -m_respawnPosInside.x, m_respawnPosInside.x); pos.y = m_respawnPosOutside.y; m_direction = Vector2.down; break; //出現位置が右の場合 case RESPAWN_TYPE.RIGHT: pos.x = m_respawnPosOutside.x; pos.y = Random.Range( -m_respawnPosInside.y, m_respawnPosInside.y); m_direction = Vector2.left; break; //出現位置が下の場合 case RESPAWN_TYPE.DOWN: pos.x = Random.Range( -m_respawnPosInside.x, m_respawnPosInside.x); pos.y = -m_respawnPosOutside.y; m_direction = Vector2.up; break; //出現位置が左の場合 case RESPAWN_TYPE.LEFT: pos.x = -m_respawnPosOutside.x; pos.y = Random.Range( -m_respawnPosInside.y, m_respawnPosInside.y); m_direction = Vector2.right; break; } //位置を反映する transform.localPosition = pos; } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "PlayerAttack") { //エフェクト生成 Instantiate( explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす m_hp--; //敵のHPがまだ残っている場合はここで処理を終える if(0 < m_hp) { return; } //敵を削除する Destroy(gameObject); } } } <file_sep>/Assets/Script/Map/Switcher2.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Switcher2: MonoBehaviour { public GameObject swich1; public GameObject swich2; public GameObject bridge; public GameObject hole; public GameObject wall; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "Knight" || collision.gameObject.tag == "Archer" || collision.gameObject.tag == "Mage") { swich1.SetActive(false); swich2.SetActive(true); bridge.SetActive(true); hole.SetActive(false); wall.SetActive(true); } } } <file_sep>/Assets/Script/Quit.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Quit : MonoBehaviour { public GameObject menuUI; bool menuflag = false; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Escape) && !menuflag) { menuUI.SetActive(true); menuflag = !menuflag; Time.timeScale = 0f; } else if (Input.GetKeyDown(KeyCode.Escape) && menuflag) { menuUI.SetActive(false); menuflag = !menuflag; Time.timeScale = 1f; } //if (Input.GetKey(KeyCode.Space)) // GameEnd(); //if (Input.GetKeyDown(KeyCode.Escape)) // GameEnd(); } public void GameEnd() { Debug.Log("ゲーム終了"); #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #elif UNITY_STANDALONE UnityEngine.Application.Quit(); #endif } } <file_sep>/Assets/Script/Enemy/Shot.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Shot : MonoBehaviour { public int damage; //プレイヤーに与えるダメージ public float _angle; private Vector3 velocity; // Start is called before the first frame update void Start() { } // Update is called once per frame void FixedUpdate() { transform.localPosition += velocity; } public void Init(float angle, float speed) { //弾の発射角度をベクトルに変換する var direction = Utils.GetDirection(angle); //発射角度と速さから速度を求める velocity = direction * speed; //弾が進行方向を向くようにする var angles = transform.localEulerAngles; angles.z = angle + _angle; transform.localEulerAngles = angles; //10秒後削除する Destroy(gameObject, 10); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.name.Contains("Guard")) Destroy(gameObject); //Playerにダメージ if (collision.name.Contains("Knight")) { //プレイヤーにダメージを与える var knight = collision.GetComponent<Knight>(); if (knight == null) return; knight.Damage(damage); } if (collision.name.Contains("Archer")) { //プレイヤーにダメージを与える var archer = collision.GetComponent<Archer>(); if (archer == null) return; archer.Damage(damage); } if (collision.name.Contains("Mage")) { //プレイヤーにダメージを与える var mage = collision.GetComponent<Mage>(); if (mage == null) return; mage.Damage(damage); } if (collision.name.Contains("Wall")) { Destroy(gameObject); } } } <file_sep>/Assets/Script/Character/Archer.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Archer : MonoBehaviour { public static Archer instance; //アーチャーのインスタンス public float moveSpeed; //移動の速さ public Arrow arrow; //矢のプレハブ public float arrowSpeed; //矢の移動の速さ public Trap trap; public int playerHp; //現在のHP public int playerMaxHp; //最大のHP public int playerMp; //現在のMP public int playerMaxMp; //最大のMP public int shootMp; //shootのMp public int trapMp; public float attackInterval; //攻撃間隔 public float attackCount; //攻撃カウント Direction direciton = Direction.DOWN; //現在の向き Animator anim; //アニメーター Rigidbody2D playerRigidbody; //プレイヤーRigidbody bool isAttack = false; //攻撃中か? float playerAngle; //プレイヤーの方向 new CapsuleCollider2D collider2D; float mpCount; //Mp回復スピード GameObject iChecker; ItemChecker ic; float defaultMoveSpeed; void Awake() { instance = this; } // Start is called before the first frame update void Start() { playerRigidbody = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); collider2D = GetComponent<CapsuleCollider2D>(); playerHp = playerMaxHp; //Hpを最大に設定 playerMp = playerMaxMp; //Mpを最大に設定する defaultMoveSpeed = moveSpeed; attackCount = attackInterval; //すぐ打てる状態に } int count; // Update is called once per frame void Update() { iChecker = GameObject.FindGameObjectWithTag("ItemChecker"); ic = iChecker.GetComponent<ItemChecker>(); //操作モード if (Operation.archerFlag) { //当たり判定 オン collider2D.enabled = true; //マウスのほうへ向く //プレイヤーのスクリーン座標を計算する var screenPos = Camera.main.WorldToScreenPoint(transform.position); //プレイヤーから見たマウスカーソルの方向を計算する var direction = Input.mousePosition - screenPos; playerAngle = Utils.GetAngle(Vector3.zero, direction); var angles = transform.localEulerAngles; angles.z = playerAngle; //方向決定 PlayerRote(playerAngle); attackCount += Time.deltaTime; //メニューが閉じているなら if (Time.timeScale > 0) { //攻撃カウントが足りているなら if (attackInterval <= attackCount) { //攻撃する Attack(); } } if (!ic.SpeedFlag) { moveSpeed = defaultMoveSpeed; } } //追尾モード else { //Mp回復 mpCount += Time.deltaTime; if (mpCount >= 1 && playerMaxMp > playerMp) { playerMp += 5; mpCount = 0; } collider2D.enabled = false; var direction = Knight.instance.transform.position - transform.position; var angle = Utils.GetAngle(Vector3.zero, direction); PlayerRote(angle); Tracking(); } } private void FixedUpdate() { if (Operation.archerFlag) { //*移動* //攻撃してない時 if (isAttack == false) { //Playerの移動 // 右・左 float x = Input.GetAxisRaw("Horizontal"); // 上・下 float y = Input.GetAxisRaw("Vertical"); //移動する Move(x, y); } } } void Tracking() { playerRigidbody.velocity = Vector2.zero; float _range = 0.25f; float _speed = 0.033f; if (!Operation.knightDead) { if (Knight.instance.transform.position.x > transform.position.x + _range) { transform.localPosition = Vector3.MoveTowards(transform.position, new Vector3(Knight.instance.transform.position.x - _range, Knight.instance.transform.position.y), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x - _range, Archer.archerInstance.transform.position.y); } if (Knight.instance.transform.position.x < transform.position.x - _range) { transform.localPosition = Vector3.MoveTowards(transform.localPosition, new Vector3(Knight.instance.transform.position.x + _range, Knight.instance.transform.position.y), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x + _range, Archer.archerInstance.transform.position.y); } if (Knight.instance.transform.position.y > transform.position.y + _range) { transform.localPosition = Vector3.MoveTowards(transform.position, new Vector3(Knight.instance.transform.position.x, Knight.instance.transform.position.y - _range), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x, Archer.archerInstance.transform.position.y - _range); } if (Knight.instance.transform.position.y < transform.position.y - _range) { transform.position = Vector3.MoveTowards(transform.localPosition, new Vector3(Knight.instance.transform.position.x, Knight.instance.transform.position.y + _range), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x, Archer.archerInstance.transform.position.y + _range); } } if (Operation.mageFlag && Operation.knightDead) { if (Mage.instance.transform.position.x > transform.position.x + _range) { transform.localPosition = Vector3.MoveTowards(transform.position, new Vector3(Mage.instance.transform.position.x - _range, Mage.instance.transform.position.y), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x - _range, Archer.archerInstance.transform.position.y); } if (Mage.instance.transform.position.x < transform.position.x - _range) { transform.localPosition = Vector3.MoveTowards(transform.localPosition, new Vector3(Mage.instance.transform.position.x + _range, Mage.instance.transform.position.y), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x + _range, Archer.archerInstance.transform.position.y); } if (Mage.instance.transform.position.y > transform.position.y + _range) { transform.localPosition = Vector3.MoveTowards(transform.position, new Vector3(Mage.instance.transform.position.x, Mage.instance.transform.position.y - _range), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x, Archer.archerInstance.transform.position.y - _range); } if (Mage.instance.transform.position.y < transform.position.y - _range) { transform.position = Vector3.MoveTowards(transform.localPosition, new Vector3(Mage.instance.transform.position.x, Mage.instance.transform.position.y + _range), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x, Archer.archerInstance.transform.position.y + _range); } } } //移動 private void Move(float h, float v) { Vector2 movement = Vector2.zero; movement.Set(h, v); movement = movement.normalized * moveSpeed * Time.deltaTime; playerRigidbody.MovePosition(playerRigidbody.position + movement); } void HomingMove() { Vector2 magePosition = transform.position; Vector2 playerPosition = Player.instance.transform.position; float vx = playerPosition.x - magePosition.x; float vy = playerPosition.y - magePosition.y; float dx, dy, radius; radius = Mathf.Atan2(vy, vx); dx = Mathf.Cos(radius) * moveSpeed; dy = Mathf.Sin(radius) * moveSpeed; if (Mathf.Abs(vx) < 0.1f) { dx = 0; } if (Mathf.Abs(vy) < 0.1f) { dy = 0; } magePosition.x += dx; magePosition.y += dy; gameObject.transform.localPosition = magePosition; } //マウスのほうへ向く void PlayerRote(float playerAngle) { //上を向く if (68 <= playerAngle && playerAngle < 113) { direciton = Direction.UP; anim.SetBool("Move@Up", true); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //右上を向く if (23 <= playerAngle && playerAngle < 68) { direciton = Direction.UPRIGHT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", true); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //右を向く if (-23 <= playerAngle && playerAngle < 23) { direciton = Direction.RIGHT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", true); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //右下を向く if (-68 <= playerAngle && playerAngle < -23) { direciton = Direction.DOWNRIGHT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", true); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //下を向く if (-113 <= playerAngle && playerAngle < -68) { direciton = Direction.DOWN; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", true); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //左下を向く if (-158 <= playerAngle && playerAngle < -113) { direciton = Direction.DOWNLEFT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", true); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //左を向く if (-158 > playerAngle || playerAngle >= 158) { direciton = Direction.LEFT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", true); anim.SetBool("Move@UpLeft", false); } //左上を向く if (113 <= playerAngle && playerAngle < 158) { direciton = Direction.UPLEFT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", true); } } void Attack() { if (Input.GetKeyDown(KeyCode.Mouse0)) { if (playerMp >= shootMp) { //矢を発射する ShootNWay(playerAngle, 0, arrowSpeed, 1); //Mpを減らす playerMp -= shootMp; attackCount = 0; } } if (Input.GetKeyDown(KeyCode.Mouse1)) { if(playerMp >= trapMp) { playerMp -= trapMp; Instantiate(trap, transform.localPosition, Quaternion.identity); } } } //弾を発射する private void ShootNWay( float angleBase, float angleRange, float speed, int count) { var pos = transform.localPosition; //プレイヤーの位置 if(1 < count) { for(int i = 0; i < count; i++) { //弾の発射角を計算する var angle = angleBase + angleRange * ((float)i / (count - 1) - 0.5f); //発射する弾を生成する var shot = Instantiate(arrow, pos, Quaternion.identity); shot.Init(angle, speed); } } else if( count == 1) { var shot = Instantiate(arrow, pos, Quaternion.identity); shot.Init(angleBase, speed); } } IEnumerator AttackInterval() { //停止 yield return new WaitForSeconds(attackInterval); } public void Damage(int damage) { playerHp -= damage; //HPがまだある場合、ここで処理を終える if (0 < playerHp) { return; } //アーチャー非表示 gameObject.SetActive(false); //アーチャーデスフラッグオン Operation.archerDead = true; Operation.archerFlag = false; //メイジが生きているなら if (!Operation.mageDead) { Operation.MageFlagOn(); } //ナイトが生きているなら else { Operation.KnightFlagOn(); } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "BlastBarrel") { playerHp -= 30; //HPがまだある場合、ここで処理を終える if (0 < playerHp) { return; } //アーチャー非表示 gameObject.SetActive(false); //アーチャーデスフラッグオン Operation.archerDead = true; Operation.archerFlag = false; //ナイトが生きているなら if (!Operation.knightDead) { Operation.KnightFlagOn(); } //メイジが生きているなら else { Operation.MageFlagOn(); } } } } <file_sep>/Assets/Script/Character/Knight.cs using System.Collections; using System.Collections.Generic; using UnityEngine.SceneManagement; using UnityEngine; //向き enum Direction { UP, //上 UPRIGHT, //右上 RIGHT, //右 DOWNRIGHT, //右下 DOWN, //下 DOWNLEFT, //左下 LEFT, //左 UPLEFT, //左上 }; //Knight専用Script public class Knight : MonoBehaviour { public static Knight instance; //ナイトのインスタンス public float moveSpeed;    //移動速度 public float guard_MoveSpeed; //ガード中の移動速度 public int playerHp; //現在のHP public int playerMaxHp; //最大のHP public int playerMp; //現在のMP public int playerMaxMp; //最大のMP public int shootMp; //消費Mp public int guardMp; //ガードMp float mpCount; //Mp回復スピード float guardMpCount; //Mp消費間隔 public GameObject playerAttack; //攻撃オブジェクト public GameObject guard; //ガードオブジェクト public float attackInterval; //攻撃間隔 public float attackCount; //攻撃カウント public int str; new CapsuleCollider2D collider2D; float speed; //スピードを一時的に保存する GameObject guard_Prefab; //ガードのプレハブ Direction direction = Direction.DOWN; //現在の向き Rigidbody2D playerRigidbody; //プレイヤーRigidbody Animator anim; //アニメーター SpriteRenderer spriteRenderer; //スプライトレンダラー bool isAttack = false; //攻撃中か? bool isGuard = false; //ガード中か GameObject iChecker; ItemChecker ic; float defaultMoveSpeed; void Awake() { instance = this; } // Start is called before the first frame update void Start() { playerRigidbody = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); spriteRenderer = GetComponent<SpriteRenderer>(); //最大Hpに設定 playerHp = playerMaxHp; //最大Mpに設定する playerMp = playerMaxMp; collider2D = GetComponent<CapsuleCollider2D>(); defaultMoveSpeed = moveSpeed; attackCount = attackInterval; //すぐ打てる状態に } // Update is called once per frame void Update() { iChecker = GameObject.FindGameObjectWithTag("ItemChecker"); ic = iChecker.GetComponent<ItemChecker>(); //操作モード if (Operation.knightFlag) { //当たり判定 オン collider2D.enabled = true; //マウスを向けた方向を向く //プレイヤーのスクリーン座標を計算する var screenPos = Camera.main.WorldToScreenPoint(transform.position); //プレイヤーから見たマウスカーソルの方向を計算する var direction = Input.mousePosition - screenPos; var angle = Utils.GetAngle(Vector3.zero, direction); var angles = transform.localEulerAngles; angles.z = angle; PlayerRote(angle); //Mpが足りているなら if (playerMp >= guardMp) { //ガードする Guard(); } else { isGuard = false; //速さをもとに戻す moveSpeed = speed; //オブジェクトを削除する Destroy(guard_Prefab); //アニメーションオフ anim.SetBool("Guard@Down", false); anim.SetBool("Guard@DownRight", false); anim.SetBool("Guard@DownLeft", false); anim.SetBool("Guard@UpRight", false); anim.SetBool("Guard@UpLeft", false); anim.SetBool("Guard@Up", false); anim.SetBool("Guard@Right", false); anim.SetBool("Guard@Left", false); } attackCount += Time.deltaTime; //メニューが閉じているなら if (Time.timeScale>0) { //ガードしていない時 if (!isGuard) { //Mpがあるなら if(playerMp > shootMp) { //攻撃カウントが足りているなら if (attackInterval <= attackCount) { //攻撃する Attack(); } } } } //ガード中なら if (isGuard) { //Mpカウントプラス guardMpCount += Time.deltaTime; if(guardMpCount > 0.5) { //Mp消費 playerMp -= guardMp; guardMpCount = 0; } } //プレイヤーHpがMaxを超えたらMaxまで戻す if (playerHp >= playerMaxHp) { playerHp = playerMaxHp; } if (playerHp <= 0 && !ic.RevivalFlag) { gameObject.SetActive(false); Invoke("Death", 0.51f); } if (!ic.SpeedFlag) { moveSpeed = defaultMoveSpeed; } } //追尾モード else { //Mp回復 mpCount += Time.deltaTime; if(mpCount >= 1 && playerMaxMp > playerMp) { playerMp+=10; mpCount = 0; } //当たり判定オフ collider2D.enabled = false; //追尾モード Tracking(); var direction = Mage.instance.transform.position - transform.position; var angle = Utils.GetAngle(Vector3.zero, direction); //向き指定 PlayerRote(angle); } } private void FixedUpdate() { //*移動* if (Operation.knightFlag) { //攻撃してない時 if (isAttack == false) { //Playerの移動 // 右・左 float x = Input.GetAxisRaw("Horizontal"); // 上・下 float y = Input.GetAxisRaw("Vertical"); //移動する Move(x, y); } } } void Tracking() { playerRigidbody.velocity = Vector2.zero; float _range = 0.25f; //追尾の幅 float _speed = 0.033f; //追尾の時のスピード if (!Operation.mageDead) { if (Mage.instance.transform.position.x > transform.position.x + _range) { transform.localPosition = Vector3.MoveTowards(transform.position, new Vector3(Mage.instance.transform.position.x - _range, Mage.instance.transform.position.y), _speed); } if (Mage.instance.transform.position.x < transform.position.x - _range) { transform.localPosition = Vector3.MoveTowards(transform.localPosition, new Vector3(Mage.instance.transform.position.x + _range, Mage.instance.transform.position.y), _speed); } if (Mage.instance.transform.position.y > transform.position.y + _range) { transform.localPosition = Vector3.MoveTowards(transform.position, new Vector3(Mage.instance.transform.position.x, Mage.instance.transform.position.y - _range), _speed); } if (Mage.instance.transform.position.y < transform.position.y - _range) { transform.position = Vector3.MoveTowards(transform.localPosition, new Vector3(Mage.instance.transform.position.x, Mage.instance.transform.position.y + _range), _speed); } } if (Operation.archerFlag && Operation.mageDead) { if (Archer.instance.transform.position.x > transform.position.x + _range) { transform.localPosition = Vector3.MoveTowards(transform.position, new Vector3(Archer.instance.transform.position.x - _range, Archer.instance.transform.position.y), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x - _range, Archer.archerInstance.transform.position.y); } if (Archer.instance.transform.position.x < transform.position.x - _range) { transform.localPosition = Vector3.MoveTowards(transform.localPosition, new Vector3(Archer.instance.transform.position.x + _range, Archer.instance.transform.position.y), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x + _range, Archer.archerInstance.transform.position.y); } if (Archer.instance.transform.position.y > transform.position.y + _range) { transform.localPosition = Vector3.MoveTowards(transform.position, new Vector3(Archer.instance.transform.position.x, Archer.instance.transform.position.y - _range), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x, Archer.archerInstance.transform.position.y - _range); } if (Archer.instance.transform.position.y < transform.position.y - _range) { transform.position = Vector3.MoveTowards(transform.localPosition, new Vector3(Archer.instance.transform.position.x, Archer.instance.transform.position.y + _range), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x, Archer.archerInstance.transform.position.y + _range); } } } //移動 private void Move(float h, float v) { Vector2 movement = Vector2.zero; movement.Set(h, v); //ガードしてるとき if (isGuard) { movement = movement.normalized * guard_MoveSpeed * Time.deltaTime; } //ガードしていない時 else if (!isGuard) { movement = movement.normalized * moveSpeed * Time.deltaTime; } playerRigidbody.MovePosition(playerRigidbody.position + movement); } void PlayerRote(float angle) { //上を向く if (68 <= angle && angle < 113) { direction = Direction.UP; anim.SetBool("Move@Up", true); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //右上を向く if (23 <= angle && angle < 68) { direction = Direction.UPRIGHT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", true); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //右を向く if (-23 <= angle && angle < 23) { direction = Direction.RIGHT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", true); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //右下を向く if (-68 <= angle && angle < -23) { direction = Direction.DOWNRIGHT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", true); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //下を向く if (-113 <= angle && angle < -68) { direction = Direction.DOWN; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", true); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //左下を向く if (-158 <= angle && angle < -113) { direction = Direction.DOWNLEFT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", true); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //左を向く if (-158 > angle || angle >= 158) { direction = Direction.LEFT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", true); anim.SetBool("Move@UpLeft", false); } //左上を向く if (113 <= angle && angle < 158) { direction = Direction.UPLEFT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", true); } } void Attack() { //攻撃 if (Input.GetKeyDown(KeyCode.Mouse0)) { //Mpを減らす playerMp -= shootMp; attackCount = 0; //上 if (direction == Direction.UP) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(0, 0.2f), Quaternion.Euler(0, 0, 180)); attack_object.transform.parent = transform; anim.SetBool("Attack@Up", true); isAttack = true; StartCoroutine("WaitForAttack"); } //右上 if (direction == Direction.UPRIGHT) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(0.1f, 0.1f), Quaternion.Euler(0, 0, 135)); attack_object.transform.parent = transform; anim.SetBool("Attack@UpRight", true); isAttack = true; StartCoroutine("WaitForAttack"); } //右 if (direction == Direction.RIGHT) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(0.2f, 0), Quaternion.Euler(0, 0, 90)); attack_object.transform.parent = transform; anim.SetBool("Attack@Right", true); isAttack = true; StartCoroutine("WaitForAttack"); } //右下 if (direction == Direction.DOWNRIGHT) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(0.1f, -0.1f), Quaternion.Euler(0, 0, 45)); attack_object.transform.parent = transform; anim.SetBool("Attack@DownRight", true); isAttack = true; StartCoroutine("WaitForAttack"); } //下 if (direction == Direction.DOWN) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(0, -0.3f), Quaternion.identity); attack_object.transform.parent = transform; anim.SetBool("Attack@Down", true); isAttack = true; StartCoroutine("WaitForAttack"); } //左下 if (direction == Direction.DOWNLEFT) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(-0.1f, -0.1f), Quaternion.Euler(0, 0, -45)); attack_object.transform.parent = transform; anim.SetBool("Attack@DownLeft", true); isAttack = true; StartCoroutine("WaitForAttack"); } //左 if (direction == Direction.LEFT) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(-0.2f, 0), Quaternion.Euler(0, 0, -90)); attack_object.transform.parent = transform; anim.SetBool("Attack@Left", true); isAttack = true; StartCoroutine("WaitForAttack"); } //左上 if (direction == Direction.UPLEFT) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(-0.1f, 0.1f), Quaternion.Euler(0, 0, 225)); attack_object.transform.parent = transform; anim.SetBool("Attack@UpLeft", true); isAttack = true; StartCoroutine("WaitForAttack"); } } } //ガード void Guard() { //スペース押したとき if (Input.GetKeyDown(KeyCode.Mouse1)) { isGuard = true; //数値を取っておく speed = moveSpeed; //ガード中のスピードにする moveSpeed = guard_MoveSpeed; //上 if (direction == Direction.UP) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(0, 0.1f), Quaternion.identity); guard_Prefab.transform.parent = transform; anim.SetBool("Guard@Up", true); } //右上 if (direction == Direction.UPRIGHT) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(0.1f, 0.1f), Quaternion.Euler(0, 0, -45)); guard_Prefab.transform.parent = transform; anim.SetBool("Guard@UpRight", true); } //右 if (direction == Direction.RIGHT) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(0.2f, 0), Quaternion.Euler(0, 0, 90)); guard_Prefab.transform.parent = transform; anim.SetBool("Guard@Right", true); } //右下 if (direction == Direction.DOWNRIGHT) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(0.1f, -0.1f), Quaternion.Euler(0, 0, 45)); guard_Prefab.transform.parent = transform; anim.SetBool("Guard@DownRight", true); } //下 if (direction == Direction.DOWN) { //ガード生成 guard_Prefab = Instantiate(guard, transform. localPosition + new Vector3(0, -0.2f), Quaternion.identity); guard_Prefab.transform.parent = transform; anim.SetBool("Guard@Down", true); } //左下 if (direction == Direction.DOWNLEFT) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(-0.1f, -0.1f), Quaternion.Euler(0, 0, -45)); guard_Prefab.transform.parent = transform; anim.SetBool("Guard@DownLeft", true); } //左 if (direction == Direction.LEFT) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(-0.2f, 0), Quaternion.Euler(0, 0, 90)); guard_Prefab.transform.parent = transform; anim.SetBool("Guard@Left", true); } //左上 if (direction == Direction.UPLEFT) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(-0.1f, 0.1f), Quaternion.Euler(0, 0, 45)); guard_Prefab.transform.parent = transform; anim.SetBool("Guard@UpLeft", true); } } //キーを離したとき if (Input.GetKeyUp(KeyCode.Mouse1)) { isGuard = false; //速さをもとに戻す moveSpeed = speed; //オブジェクトを削除する Destroy(guard_Prefab); //アニメーションオフ anim.SetBool("Guard@Down", false); anim.SetBool("Guard@DownRight", false); anim.SetBool("Guard@DownLeft", false); anim.SetBool("Guard@UpRight", false); anim.SetBool("Guard@UpLeft", false); anim.SetBool("Guard@Up", false); anim.SetBool("Guard@Right", false); anim.SetBool("Guard@Left", false); } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "BlastBarrel") { playerHp -= 30; //HPがまだある場合、ここで処理を終える if (0 < playerHp) { return; } //ナイト非表示 gameObject.SetActive(false); //ナイトデスフラッグオン Operation.knightDead = true; Operation.knightFlag = false; //アーチャーが生きているなら if (!Operation.archerDead) { Operation.ArcherFlagOn(); } //メイジが生きているなら else { Operation.MageFlagOn(); } } } //攻撃してるとき1時停止する IEnumerator WaitForAttack() { yield return new WaitForSeconds(0.5f); isAttack = false; anim.SetBool("Attack@Up", false); anim.SetBool("Attack@Left", false); anim.SetBool("Attack@Right", false); anim.SetBool("Attack@Down", false); anim.SetBool("Attack@UpRight", false); anim.SetBool("Attack@UpLeft", false); anim.SetBool("Attack@DownRight", false); anim.SetBool("Attack@DownLeft", false); } //点滅 IEnumerator Blinl() { var renderComponent = GetComponent<Renderer>(); renderComponent.enabled = !renderComponent.enabled; //yield return new WaitForSeconds(0.2f); yield return null; renderComponent.enabled = !renderComponent.enabled; } //ダメージを与える public void Damage(int damage) { playerHp -= damage; //HPがまだある場合、ここで処理を終える if (0 < playerHp) { return; } //ナイト非表示 gameObject.SetActive(false); //ナイトデスフラッグオン Operation.knightDead = true; Operation.knightFlag = false; //アーチャーが生きているなら if (!Operation.archerDead) { Operation.ArcherFlagOn(); } //メイジが生きているなら else { Operation.MageFlagOn(); } } void ChangeScene() { SceneManager.LoadScene("TitleScene"); } void Death() { Destroy(gameObject); } } <file_sep>/Assets/Script/Boss/MiniSlime.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MiniSlime : MonoBehaviour { public float moveSpeed; public int damage; public int enemyMaxHp; //最大Hp public int enemyHp; //現在のHp public Explotion explosionPrefab; bool guardFlag; bool trapFlag; float angle; Vector3 direction; float trapCount; // Start is called before the first frame update void Start() { enemyHp = enemyMaxHp; //最大Hpにする guardFlag = false; trapFlag = false; } private void FixedUpdate() { //プレイヤーの位置へ向かうベクトルを生成する //ナイト if (Operation.knightFlag) { angle = Utils.GetAngle( transform.localPosition, Knight.instance.transform.localPosition); direction = Utils.GetDirection(angle); } //アーチャー if (Operation.archerFlag) { angle = Utils.GetAngle( transform.localPosition, Archer.instance.transform.localPosition); direction = Utils.GetDirection(angle); } //メイジ if (Operation.mageFlag) { angle = Utils.GetAngle( transform.localPosition, Mage.instance.transform.localPosition); direction = Utils.GetDirection(angle); } if (!guardFlag && !trapFlag) { //プレイヤーが存在する方向へ移動する transform.localPosition += direction * moveSpeed; } if (trapFlag) { trapCount++; if (trapCount == 240) { trapFlag = false; trapCount = 0; } } } private void OnTriggerEnter2D(Collider2D collision) { //ナイト int knightAttack = 80; if (collision.gameObject.tag == "PlayerAttack") { transform.position = Vector3.MoveTowards(transform.position, transform.position + direction * -1 * 0.5f, 1.0f); Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす enemyHp -= knightAttack; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } //アーチャー int arrow = 50; if (collision.name.Contains("Arrow")) { Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす enemyHp -= arrow; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } //メイジ int m_shot = 25; if (collision.name.Contains("Shot_M")) { Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす enemyHp -= m_shot; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } int magic = 100; if (collision.name.Contains("Magic")) { Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす enemyHp -= magic; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } //Playerにダメージ if (collision.name.Contains("Knight")) { //プレイヤーにダメージを与える var knight = collision.GetComponent<Knight>(); if (knight == null) return; knight.Damage(damage); } if (collision.name.Contains("Archer")) { //プレイヤーにダメージを与える var archer = collision.GetComponent<Archer>(); if (archer == null) return; archer.Damage(damage); } if (collision.name.Contains("Mage")) { //プレイヤーにダメージを与える var mage = collision.GetComponent<Mage>(); if (mage == null) return; mage.Damage(damage); } int trap = 30; //トラップ if (collision.name.Contains("Trap")) { trapFlag = true; // 敵のHPを減らす enemyHp -= trap; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } } private void OnTriggerStay2D(Collider2D collision) { if (collision.name.Contains("Guard")) { //moveSpeed = 0; guardFlag = true; } } private void OnCollisionExit2D(Collision2D collision) { if (collision.gameObject.tag == "Guard") { //moveSpeed = 0.01f; guardFlag = false; } } } <file_sep>/Assets/Script/Character/Mage.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Mage : MonoBehaviour { public static Mage instance; //メイジのインスタンス public float moveSpeed; //移動の速さ public Magic magic; //魔法のプレハブ public Magic n_Magic; //ノーマルマジック public float magicSpeed; //魔法の速度 public float teleportRange; //テレポートの距離 public float slopeRange; //テレオート時間 public int playerHp; //現在のHP public int playerMaxHp; //最大のHP public int playerMp; //現在のMP public int playerMaxMp; //最大のMP public int shootMp; //通常攻撃 public int skillMp; //スキル攻撃 public float attackInterval; //攻撃間隔 public float attackCount; //攻撃カウント Direction direciton = Direction.DOWN; //現在の向き Animator anim; //アニメーター Rigidbody2D playerRigidbody; //プレイヤーRigidbody bool isAttack = false; //攻撃中か? float magicAngle; //魔法の角度 new CapsuleCollider2D collider2D; float mpCount; //Mp回復スピード GameObject iChecker; ItemChecker ic; float defaultMoveSpeed; // Start is called before the first frame update void Start() { playerRigidbody = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); collider2D = GetComponent<CapsuleCollider2D>(); playerHp = playerMaxHp; //Hpを最大に設定する playerMp = playerMaxMp; //Mpを最大に設定する defaultMoveSpeed = moveSpeed; attackCount = attackInterval; //すぐ打てる状態に } void Awake() { instance = this; } // Update is called once per frame void Update() { iChecker = GameObject.FindGameObjectWithTag("ItemChecker"); ic = iChecker.GetComponent<ItemChecker>(); if (Operation.mageFlag) { //当たり判定 オン collider2D.enabled = true; //マウスのほうへ向く //プレイヤーのスクリーン座標を計算する var screenPos = Camera.main.WorldToScreenPoint(transform.position); //プレイヤーから見たマウスカーソルの方向を計算する var direction = Input.mousePosition - screenPos; magicAngle = Utils.GetAngle(Vector3.zero, direction); var angles = transform.localEulerAngles; angles.z = magicAngle; //方向指定 PlayerRote(magicAngle); attackCount += Time.deltaTime; //メニューが閉じているなら if (Time.timeScale > 0) { //攻撃カウントが足りているなら if (attackInterval <= attackCount) { //攻撃する Attack(); } } //Teleport(teleportRange, slopeRange); if (!ic.SpeedFlag) { moveSpeed = defaultMoveSpeed; } } else { //Mp回復 mpCount += Time.deltaTime; if (mpCount >= 1 && playerMaxMp > playerMp) { playerMp += 5; mpCount = 0; } collider2D.enabled = false; var direction = Archer.instance.transform.position - transform.position; var angle = Utils.GetAngle(Vector3.zero, direction); //向き指定 PlayerRote(angle); Tracking(); } } private void FixedUpdate() { if (Operation.mageFlag) { //*移動* //攻撃してない時 if (isAttack == false) { //Playerの移動 // 右・左 float x = Input.GetAxisRaw("Horizontal"); // 上・下 float y = Input.GetAxisRaw("Vertical"); //移動する Move(x, y); } } } //追尾する void Tracking() { playerRigidbody.velocity = Vector2.zero; float _range = 0.25f; float _speed = 0.033f; if (!Operation.archerDead) { if (Archer.instance.transform.position.x > transform.position.x + _range) { transform.localPosition = Vector3.MoveTowards(transform.position, new Vector3(Archer.instance.transform.position.x - _range, Archer.instance.transform.position.y), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x - _range, Archer.archerInstance.transform.position.y); } if (Archer.instance.transform.position.x < transform.position.x - _range) { transform.localPosition = Vector3.MoveTowards(transform.localPosition, new Vector3(Archer.instance.transform.position.x + _range, Archer.instance.transform.position.y), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x + _range, Archer.archerInstance.transform.position.y); } if (Archer.instance.transform.position.y > transform.position.y + _range) { transform.localPosition = Vector3.MoveTowards(transform.position, new Vector3(Archer.instance.transform.position.x, Archer.instance.transform.position.y - _range), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x, Archer.archerInstance.transform.position.y - _range); } if (Archer.instance.transform.position.y < transform.position.y - _range) { transform.position = Vector3.MoveTowards(transform.localPosition, new Vector3(Archer.instance.transform.position.x, Archer.instance.transform.position.y + _range), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x, Archer.archerInstance.transform.position.y + _range); } } if (Operation.knightFlag && Operation.archerDead) { if (Knight.instance.transform.position.x > transform.position.x + _range) { transform.localPosition = Vector3.MoveTowards(transform.position, new Vector3(Knight.instance.transform.position.x - _range, Knight.instance.transform.position.y), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x - _range, Archer.archerInstance.transform.position.y); } if (Knight.instance.transform.position.x < transform.position.x - _range) { transform.localPosition = Vector3.MoveTowards(transform.localPosition, new Vector3(Knight.instance.transform.position.x + _range, Knight.instance.transform.position.y), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x + _range, Archer.archerInstance.transform.position.y); } if (Knight.instance.transform.position.y > transform.position.y + _range) { transform.localPosition = Vector3.MoveTowards(transform.position, new Vector3(Knight.instance.transform.position.x, Knight.instance.transform.position.y - _range), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x, Archer.archerInstance.transform.position.y - _range); } if (Knight.instance.transform.position.y < transform.position.y - _range) { transform.position = Vector3.MoveTowards(transform.localPosition, new Vector3(Knight.instance.transform.position.x, Knight.instance.transform.position.y + _range), _speed); //transform.position = new Vector2(Archer.archerInstance.transform.position.x, Archer.archerInstance.transform.position.y + _range); } } } /// <summary> /// 移動 /// </summary> /// <param name="h">x方向</param> /// <param name="v">y方向</param> private void Move(float h, float v) { Vector2 movement = Vector2.zero; movement.Set(h, v); movement = movement.normalized * moveSpeed * Time.deltaTime; playerRigidbody.MovePosition(playerRigidbody.position + movement); } void HomingMove() { Vector2 magePosition = transform.position; Vector2 playerPosition = Player.instance.transform.position; float vx = playerPosition.x - magePosition.x; float vy = playerPosition.y - magePosition.y; float dx, dy, radius; radius = Mathf.Atan2(vy, vx); dx = Mathf.Cos(radius) * moveSpeed; dy = Mathf.Sin(radius) * moveSpeed; if(Mathf.Abs(vx) < 0.1f) { dx = 0; } if(Mathf.Abs(vy) < 0.1f) { dy = 0; } magePosition.x += dx; magePosition.y += dy; gameObject.transform.localPosition = magePosition; } //マウスのほうへ向く void PlayerRote(float magicAngle) { //上を向く if (68 <= magicAngle && magicAngle < 113) { direciton = Direction.UP; anim.SetBool("Move@Up", true); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //右上を向く if (23 <= magicAngle && magicAngle < 68) { direciton = Direction.UPRIGHT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", true); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //右を向く if (-23 <= magicAngle && magicAngle < 23) { direciton = Direction.RIGHT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", true); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //右下を向く if (-68 <= magicAngle && magicAngle < -23) { direciton = Direction.DOWNRIGHT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", true); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //下を向く if (-113 <= magicAngle && magicAngle < -68) { direciton = Direction.DOWN; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", true); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //左下を向く if (-158 <= magicAngle && magicAngle < -113) { direciton = Direction.DOWNLEFT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", true); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //左を向く if (-158 > magicAngle || magicAngle >= 158) { direciton = Direction.LEFT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", true); anim.SetBool("Move@UpLeft", false); } //左上を向く if (113 <= magicAngle && magicAngle < 158) { direciton = Direction.UPLEFT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", true); } } void Attack() { if (Input.GetKeyDown(KeyCode.Mouse0)) { if(playerMp >= shootMp) { ShootNWay2(magicAngle, 0, magicSpeed, 1); playerMp -= shootMp; attackCount = 0; } } if (Input.GetKeyDown(KeyCode.Mouse1)) { if(playerMp > skillMp) { //1発撃つ ShootNWay(magicAngle, 0, magicSpeed, 1); playerMp -= skillMp; } } } /// <summary> /// 弾を発射する /// </summary> /// <param name="angleBase">発射角</param> /// <param name="angleRange">複数発射する時の角度</param> /// <param name="speed">速さ</param> /// <param name="count">発射数</param> private void ShootNWay( float angleBase, float angleRange, float speed, int count) { var pos = transform.localPosition; //プレイヤーの位置 if (1 < count) { for (int i = 0; i < count; i++) { //弾の発射角を計算する var angle = angleBase + angleRange * ((float)i / (count - 1) - 0.5f); //発射する弾を生成する var shot = Instantiate(magic, pos, Quaternion.identity); shot.Init(angle, speed); } } else if (count == 1) { var shot = Instantiate(magic, pos, Quaternion.identity); shot.Init(angleBase, speed); } } private void ShootNWay2( float angleBase, float angleRange, float speed, int count) { var pos = transform.localPosition; //プレイヤーの位置 if (1 < count) { for (int i = 0; i < count; i++) { //弾の発射角を計算する var angle = angleBase + angleRange * ((float)i / (count - 1) - 0.5f); //発射する弾を生成する var shot = Instantiate(n_Magic, pos, Quaternion.identity); shot.Init(angle, speed); } } else if (count == 1) { var shot = Instantiate(n_Magic, pos, Quaternion.identity); shot.Init(angleBase, speed); } } private void Teleport(float range, float slopeRange) { if (Input.GetKeyDown(KeyCode.Space)) { //上 if (direciton == Direction.UP) { transform.position += new Vector3(0, range); } //右上 if (direciton == Direction.UPRIGHT) { transform.position += new Vector3(slopeRange, slopeRange); } //右 if (direciton == Direction.RIGHT) { transform.position += new Vector3(range, 0); } //右下 if (direciton == Direction.DOWNRIGHT) { transform.position += new Vector3(slopeRange, -slopeRange); } //下 if (direciton == Direction.DOWN) { transform.position += new Vector3(0, -range); } //左下 if (direciton == Direction.DOWNLEFT) { transform.position += new Vector3(-slopeRange, -slopeRange); } //左 if (direciton == Direction.LEFT) { transform.position += new Vector3(-range, 0); } //左上 if (direciton == Direction.UPLEFT) { transform.position += new Vector3(-slopeRange, slopeRange); } } } public void Damage(int damage) { playerHp -= damage; //HPがまだある場合、ここで処理を終える if (0 < playerHp) { return; } //メイジ非表示 gameObject.SetActive(false); //メイジデスフラッグオン Operation.mageDead = true; Operation.mageFlag = false; //ナイトが生きているなら if (!Operation.knightDead) { Operation.knightFlag = true; } //アーチャーが生きているなら else { Operation.archerFlag = true; } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "BlastBarrel") { playerHp -= 30; //HPがまだある場合、ここで処理を終える if (0 < playerHp) { return; } //メイジ非表示 gameObject.SetActive(false); //メイジデスフラッグオン Operation.mageDead = true; Operation.mageFlag = false; //アーチャーが生きているなら if (!Operation.archerDead) { Operation.ArcherFlagOn(); } //メイジが生きているなら else { Operation.KnightFlagOn(); } } } } <file_sep>/Assets/Script/Enemy/Skeleton.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Skeleton : MonoBehaviour { public float moveSpeed; //移動速度 public int damage; //攻撃力 public int enemyHp; //現在のHp public int enemyMaxHp; //最大のHp public Explotion explosionPrefab; //爆発エフェクト public Explotion magicPrefab; //メイジスキルエフェクト public List<Sprite> sprites; //スプライトリスト public float attackDistance; //近づく距離 public GameObject skeletonAttack; //攻撃オブジェクト public float attackInterval; //攻撃間隔 public Image hpGauge; //HPゲージ public int knightAttack = 80; //ナイトからの攻撃 public int archerArow = 50; //アローからの攻撃 public int archerTrap = 30; //トラップからの攻撃 public int mageShot = 25; //メイジの通常攻撃 public int mageSkill = 40; //メイジのスキル攻撃 //ガードに触れているか bool guardFlag = false; //トラップにかかったか? bool trapFlag = false; Direction direction = Direction.DOWN; //向き //Animator anim; //アニメーション SpriteRenderer spriteRenderer; //スプライトレンダラー Rigidbody2D enemyRigid; float distance; float angle; Vector3 _direction; float trapCount; float attackCount; // Start is called before the first frame update void Start() { //最大Hpにする enemyHp = enemyMaxHp; //anim = GetComponent<Animator>(); spriteRenderer = GetComponent<SpriteRenderer>(); enemyRigid = GetComponent<Rigidbody2D>(); } public void Update() { //Hpがを表示 hpGauge.fillAmount = (float)enemyHp / enemyMaxHp; } // Update is called once per frame void FixedUpdate() { //プレイヤーの位置へ向かうベクトルを生成する //ナイト if (Operation.knightFlag) { angle = Utils.GetAngle( transform.localPosition, Knight.instance.transform.localPosition); _direction = Utils.GetDirection(angle); //プレイヤーとの距離の絶対値 distance = Mathf.Abs(Vector2.Distance(transform.localPosition, Knight.instance.transform.localPosition)); } //アーチャー if (Operation.archerFlag) { angle = Utils.GetAngle( transform.localPosition, Archer.instance.transform.localPosition); _direction = Utils.GetDirection(angle); //プレイヤーとの距離の絶対値 distance = Mathf.Abs(Vector2.Distance(transform.localPosition, Archer.instance.transform.localPosition)); } //メイジ if (Operation.mageFlag) { angle = Utils.GetAngle( transform.localPosition, Mage.instance.transform.localPosition); _direction = Utils.GetDirection(angle); //プレイヤーとの距離の絶対値 distance = Mathf.Abs(Vector2.Distance(transform.localPosition, Mage.instance.transform.localPosition)); } if(!trapFlag) { //プレイヤーとの距離が if(distance >= attackDistance) { //プレイヤーが存在する方向へ移動する transform.localPosition += _direction * moveSpeed; attackCount = attackInterval; } else { attackCount += Time.deltaTime; if(attackCount >= attackInterval) { if (!guardFlag) { //攻撃生成 Attack(); attackCount = 0; } } if (distance < attackDistance-0.01) { //プレイヤーが存在する方向へ移動する transform.localPosition += _direction * moveSpeed * -1; } } } if (trapFlag) { trapCount++; if (trapCount == 240) { trapFlag = false; trapCount = 0; } } //向き PlayerRote(angle); } void Attack() { //上 if(direction == Direction.UP) { GameObject attackObject = Instantiate(skeletonAttack, transform.localPosition + new Vector3(0, 0.2f), Quaternion.Euler(0, 0, 180)); attackObject.transform.parent = transform; } //右上 if (direction == Direction.UPRIGHT) { GameObject attackObject = Instantiate(skeletonAttack, transform.localPosition + new Vector3(0.15f, 0.15f), Quaternion.Euler(0, 0, 135)); attackObject.transform.parent = transform; } //右 if (direction == Direction.RIGHT) { GameObject attackObject = Instantiate(skeletonAttack, transform.localPosition + new Vector3(0.2f, 0), Quaternion.Euler(0, 0, 90)); attackObject.transform.parent = transform; } //右下 if (direction == Direction.DOWNRIGHT) { GameObject attackObject = Instantiate(skeletonAttack, transform.localPosition + new Vector3(0.1f, -0.1f), Quaternion.Euler(0, 0, 45)); attackObject.transform.parent = transform; } //下 if(direction == Direction.DOWN) { GameObject attackObject = Instantiate(skeletonAttack, transform.localPosition + new Vector3(0, -0.3f), Quaternion.Euler(0, 0, 0)); attackObject.transform.parent = transform; } //左下 if(direction == Direction.DOWNLEFT) { GameObject attackObject = Instantiate(skeletonAttack, transform.localPosition + new Vector3(-0.1f, -0.1f), Quaternion.Euler(0, 0, -45)); attackObject.transform.parent = transform; } //左 if (direction == Direction.LEFT) { GameObject attackObject = Instantiate(skeletonAttack, transform.localPosition + new Vector3(-0.2f, 0), Quaternion.Euler(0, 0, -90)); attackObject.transform.parent = transform; } //左上 if (direction == Direction.UPLEFT) { GameObject attackObject = Instantiate(skeletonAttack, transform.localPosition + new Vector3(-0.1f, 0.1f), Quaternion.Euler(0, 0, 225)); attackObject.transform.parent = transform; } } void PlayerRote(float angle) { //上を向く if (68 <= angle && angle < 113) { direction = Direction.UP; spriteRenderer.sprite = sprites[(int)direction]; } //右上を向く if (23 <= angle && angle < 68) { direction = Direction.UPRIGHT; spriteRenderer.sprite = sprites[(int)direction]; } //右を向く if (-23 <= angle && angle < 23) { direction = Direction.RIGHT; spriteRenderer.sprite = sprites[(int)direction]; } //右下を向く if (-68 <= angle && angle < -23) { direction = Direction.DOWNRIGHT; spriteRenderer.sprite = sprites[(int)direction]; } //下を向く if (-113 <= angle && angle < -68) { direction = Direction.DOWN; spriteRenderer.sprite = sprites[(int)direction]; } //左下を向く if (-158 <= angle && angle < -113) { direction = Direction.DOWNLEFT; spriteRenderer.sprite = sprites[(int)direction]; } //左を向く if (-158 > angle || angle >= 158) { direction = Direction.LEFT; spriteRenderer.sprite = sprites[(int)direction]; } //左上を向く if (113 <= angle && angle < 158) { direction = Direction.UPLEFT; spriteRenderer.sprite = sprites[(int)direction]; } } private void OnTriggerEnter2D(Collider2D collision) { //ナイト if (collision.gameObject.tag == "PlayerAttack") { transform.position = Vector3.MoveTowards(transform.position, transform.position + _direction * -0.22f, 1.0f); Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす enemyHp -= knightAttack; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } //アーチャー if (collision.name.Contains("Arrow")) { Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす enemyHp -= archerArow; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } //トラップ if (collision.name.Contains("Trap")) { trapFlag = true; // 敵のHPを減らす enemyHp -= archerTrap; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } //メイジ if (collision.name.Contains("Shot_M")) { Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす enemyHp -= mageShot; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } int magic = 40; if (collision.name.Contains("Magic")) { Instantiate(magicPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす enemyHp -= magic; //敵のHPがまだ残っている場合はここで処理を終える if (0 < enemyHp) { return; } //敵を削除する Destroy(gameObject); } //Playerにダメージ //if (collision.name.Contains("Knight")) //{ // //プレイヤーにダメージを与える // var knight = collision.GetComponent<Knight>(); // if (knight == null) return; // knight.Damage(damage); //} //if (collision.name.Contains("Archer")) //{ // //プレイヤーにダメージを与える // var archer = collision.GetComponent<Archer>(); // if (archer == null) return; // archer.Damage(damage); //} //if (collision.name.Contains("Mage")) //{ // //プレイヤーにダメージを与える // var mage = collision.GetComponent<Mage>(); // if (mage == null) return; // mage.Damage(damage); //} } private void OnTriggerStay2D(Collider2D collision) { if (collision.name.Contains("Guard")) { //moveSpeed = 0; guardFlag = true; } } private void OnCollisionExit2D(Collision2D collision) { if (collision.gameObject.tag == "Guard") { //moveSpeed = 0.01f; guardFlag = false; } } } <file_sep>/Assets/Script/Character/Trap.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Trap : MonoBehaviour { SpriteRenderer spriteRenderer; public Sprite trapOpen; public Sprite trapClose; public float breakTime; new BoxCollider2D collider2D; // Start is called before the first frame update void Start() { spriteRenderer = gameObject.GetComponent<SpriteRenderer>(); collider2D = GetComponent<BoxCollider2D>(); } // Update is called once per frame void Update() { } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "Enemy") { spriteRenderer.sprite = trapClose; collider2D.enabled = false; Destroy(gameObject, breakTime); } } } <file_sep>/Assets/Script/Utils.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Utils : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } //指定された、2つの位置から角度を求めて返す public static float GetAngle(Vector2 from, Vector2 to) { var dx = to.x - from.x; var dy = to.y - from.y; var rad = Mathf.Atan2(dy, dx); return rad * Mathf.Rad2Deg; } public static Vector3 GetDirection(float angle) { return new Vector3( Mathf.Cos(angle * Mathf.Deg2Rad), Mathf.Sin(angle * Mathf.Deg2Rad), 0 ); } } <file_sep>/Assets/Script/Boss/SuperSlime.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SuperSlime : MonoBehaviour { public float moveSpeed; //移動速度 public float shotSpeed; //ショットスピード public int damage; public int bossHp; //現在のHp public int bossMaxHp; //最大のHp public SlimeShot slimeShot; //スライムショット public GameObject treasure; public GameObject map; public GameObject shutter; public float shotInterval; //ショットの間隔 float shotCount; //shotカウント bool guardFlag; bool trapFlag; public Explotion explosionPrefab; //爆発エフェクト // Start is called before the first frame update void Start() { bossHp = bossMaxHp; //Hpを最大にする } private void FixedUpdate() { //プレイヤーの位置へ向かうベクトルを生成する var angle = Utils.GetAngle( transform.localPosition, Knight.instance.transform.localPosition); var direction = Utils.GetDirection(angle); //プレイヤーが存在する方向へ移動する transform.localPosition += direction * moveSpeed; shotCount ++; if (shotCount == shotInterval) { shotCount = 0; SlimeShot(direction); } } //スライムショット void SlimeShot(Vector3 direction) { var slime = Instantiate(slimeShot, transform.position, Quaternion.identity); var rb = slime.GetComponent<Rigidbody2D>(); rb.AddForce(direction * shotSpeed); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "PlayerAttack") { //エフェクト生成 Instantiate( explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす bossHp--; //敵のHPがまだ残っている場合はここで処理を終える if (0 < bossHp) { return; } //Instantiate(treasure, transform.position, Quaternion.identity); map.SetActive(true); shutter.SetActive(false); //敵を削除する Destroy(gameObject); } //ナイト int knightAttack = 80; if (collision.gameObject.tag == "PlayerAttack") { Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす bossHp -= knightAttack; //敵のHPがまだ残っている場合はここで処理を終える if (0 < bossHp) { return; } //Instantiate(treasure, transform.position, Quaternion.identity); map.SetActive(true); shutter.SetActive(false); //敵を削除する Destroy(gameObject); } //アーチャー int arrow = 50; if (collision.name.Contains("Arrow")) { Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす bossHp -= arrow; //敵のHPがまだ残っている場合はここで処理を終える if (0 < bossHp) { return; } //Instantiate(treasure, transform.position, Quaternion.identity); map.SetActive(true); shutter.SetActive(false); //敵を削除する Destroy(gameObject); } //メイジ int m_shot = 25; if (collision.name.Contains("Shot_M")) { Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす bossHp -= m_shot; //敵のHPがまだ残っている場合はここで処理を終える if (0 < bossHp) { return; } //Instantiate(treasure, transform.position, Quaternion.identity); map.SetActive(true); shutter.SetActive(false); //敵を削除する Destroy(gameObject); } int magic = 100; if (collision.name.Contains("Magic")) { Instantiate(explosionPrefab, collision.transform.position, Quaternion.identity); //敵のHPを減らす bossHp -= magic; //敵のHPがまだ残っている場合はここで処理を終える if (0 < bossHp) { return; } //Instantiate(treasure, transform.position, Quaternion.identity); map.SetActive(true); shutter.SetActive(false); //敵を削除する Destroy(gameObject); } int trap = 30; //トラップ if (collision.name.Contains("Trap")) { trapFlag = true; // 敵のHPを減らす bossHp -= trap; //敵のHPがまだ残っている場合はここで処理を終える if (0 < bossHp) { return; } //Instantiate(treasure, transform.position, Quaternion.identity); map.SetActive(true); shutter.SetActive(false); //敵を削除する Destroy(gameObject); } //Playerにダメージ if (collision.name.Contains("Knight")) { //プレイヤーにダメージを与える var knight = collision.GetComponent<Knight>(); if (knight == null) return; knight.Damage(damage); } if (collision.name.Contains("Archer")) { //プレイヤーにダメージを与える var archer = collision.GetComponent<Archer>(); if (archer == null) return; archer.Damage(damage); } if (collision.name.Contains("Mage")) { //プレイヤーにダメージを与える var mage = collision.GetComponent<Mage>(); if (mage == null) return; mage.Damage(damage); } } } <file_sep>/Assets/Open2.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Open2 : MonoBehaviour { GameObject iChecker; ItemChecker ic; public bool OpenFlag = false; public GameObject[] shutter; public GameObject[] bridge; public GameObject map; public Text TextHud; // Start is called before the first frame update void Start() { iChecker = GameObject.FindGameObjectWithTag("ItemChecker"); ic = iChecker.GetComponent<ItemChecker>(); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.E) && OpenFlag && ic.KeyFlag) { bridge[0].SetActive(true); map.SetActive(true); shutter[0].SetActive(false); shutter[1].SetActive(false); TextHud.text = "扉を開けた!"; Invoke("text", 5f); } } private void OnTriggerEnter2D(Collider2D col) { if (col.gameObject.tag == "Knight"|| col.gameObject.tag == "Archer"|| col.gameObject.tag == "Mage") { if(Operation.archerDead && Operation.mageDead|| Operation.knightDead && Operation.mageDead|| Operation.knightDead && Operation.mageDead) { OpenFlag = true; } } } private void OnTriggerExit2D(Collider2D collision) { if (collision.gameObject.tag == "Knight" || collision.gameObject.tag == "Archer" || collision.gameObject.tag == "Mage") { OpenFlag = false; } } void text() { TextHud.text = " "; } } <file_sep>/Assets/DamageUI.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DamageUI : MonoBehaviour { private float fadeOutSpeed = 1.0f; private float moveSpeed = 0.4f; Text damageText; // Start is called before the first frame update void Start() { damageText = GetComponent<Text>(); } // Update is called once per frame void LateUpdate() { transform.rotation = Camera.main.transform.rotation; transform.position += Vector3.up * moveSpeed * Time.deltaTime; damageText.color = Color.Lerp(damageText.color, new Color(1.0f, 0f, 0f, 0f), fadeOutSpeed * Time.deltaTime); if (damageText.color.a <= 0.1f) { Destroy(gameObject); } } } <file_sep>/Assets/Script/Map/MapManager2.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MapManager2 : MonoBehaviour { public GameObject knight; public GameObject mage; public GameObject archer; public GameObject shutter; // Start is called before the first frame update void Awake() { } void Start() { Invoke("Shut", 0.5f); } // Update is called once per frame void Update() { } void Shut() { shutter.SetActive(true); } } <file_sep>/Assets/Script/Item/Bomb.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bomb : MonoBehaviour { public Explotion explosionPrefab; //爆発エフェクト // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void FixedUpdate() { Invoke("Blast", 5.0f); } private void OnCollisionEnter2D(Collision2D collision) { Instantiate( explosionPrefab, collision.transform.position, Quaternion.identity); GameObject[] enemys = GameObject.FindGameObjectsWithTag("Enemy"); foreach (GameObject enemy in enemys) { float pos = (transform.position - enemy.transform.position).magnitude; if (pos < 0.5f && pos > -0.5f) { Destroy(enemy); } } Destroy(gameObject); } void Blast() { Instantiate( explosionPrefab, transform.position, Quaternion.identity); GameObject[] enemys = GameObject.FindGameObjectsWithTag("Enemy"); foreach (GameObject enemy in enemys) { float pos = (transform.position - enemy.transform.position).magnitude; if (pos < 1.0f && pos > -1.0f) { Destroy(enemy); } } Destroy(gameObject); } } <file_sep>/Assets/Script/Map/Switcher1.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Switcher1 : MonoBehaviour { public GameObject swich1; public GameObject swich3; public GameObject bridge1; public GameObject bridge2; public GameObject hole1; public GameObject hole2; public GameObject wall; public GameObject lever; SwitchOn so; // Start is called before the first frame update void Start() { so = GetComponent<SwitchOn>(); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.E) && so.OnFlag) { swich1.SetActive(false); swich3.SetActive(true); bridge1.SetActive(true); bridge2.SetActive(true); hole1.SetActive(false); hole2.SetActive(false); wall.SetActive(true); lever.SetActive(true); } } } <file_sep>/Assets/Script/Item/ItemManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ItemManager : MonoBehaviour { GameObject iChecker; ItemChecker ic; public int THpPortion; public int TMpPortion; public int TSpeedUP; public int TDamageUP; public int TRevivalPendant; public int TArmor; public int TBomb; // Start is called before the first frame update void Start() { iChecker = GameObject.FindGameObjectWithTag("ItemChecker"); ic = iChecker.GetComponent<ItemChecker>(); } // Update is called once per frame void Update() { } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "Knight" || collision.gameObject.tag == "Archer" || collision.gameObject.tag == "Mage") { if (this.tag == "HPportion") { ic.HpPortion += 1; Destroy(gameObject); } if (this.tag == "MPportion") { ic.MpPortion += 1; Destroy(gameObject); } if (this.tag == "SpeedUP") { ic.SpeedUP += 1; Destroy(gameObject); } if (this.tag == "DamageUP") { ic.DamageUP += 1; Destroy(gameObject); } if (this.tag == "RevivalPendant") { ic.RevivalPendant += 1; Destroy(gameObject); } if (this.tag == "Armor") { ic.Armor += 1; Destroy(gameObject); } if (this.tag == "Bomb") { ic.Bomb += 1; Destroy(gameObject); } if (this.tag == "Key") { ic.KeyFlag = true; Destroy(gameObject); } if (this.tag == "Treasure") { ic.HpPortion += THpPortion; ic.MpPortion += TMpPortion; ic.SpeedUP += TSpeedUP; ic.DamageUP += TDamageUP; ic.RevivalPendant += TRevivalPendant; ic.Armor += TArmor; ic.Bomb += TBomb; Destroy(gameObject); } if (this.tag == "Untagged") { Destroy(gameObject); } } } } <file_sep>/Assets/Script/Gimmick/Spin.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spin : MonoBehaviour { public int damage; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { gameObject.transform.Rotate(new Vector3(0,0,3)); } private void OnTriggerStay2D(Collider2D collision) { //Playerにダメージ if (collision.name.Contains("Knight")) { //プレイヤーにダメージを与える var knight = collision.GetComponent<Knight>(); if (knight == null) return; knight.Damage(damage); } if (collision.name.Contains("Archer")) { //プレイヤーにダメージを与える var archer = collision.GetComponent<Archer>(); if (archer == null) return; archer.Damage(damage); } if (collision.name.Contains("Mage")) { //プレイヤーにダメージを与える var mage = collision.GetComponent<Mage>(); if (mage == null) return; mage.Damage(damage); } } } <file_sep>/Assets/Script/Spown.cs  using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spown : MonoBehaviour { public GameObject player; //プレイヤー public List<GameObject> enemys; //エネミーリスト public Transform player_Spown_Position; //プレイヤーの登場位置 public List<Transform> enemy_Spown_Position; //エネミーの登場位置 public Explotion spwanEffectPrefab; //登場エフェクト public float spwanInterval; //敵を生成する間隔 public float time; //時間 Vector3 pos = Vector3.zero; // Start is called before the first frame update void Start() { Instantiate(player, player_Spown_Position.position, Quaternion.identity); //Instantiate(enemys[0], enemy_Spown_Position.position, Quaternion.identity); } // Update is called once per frame void Update() { time += Time.deltaTime; if (spwanInterval > time) return; time = 0; StartCoroutine("EnemySpawn"); } IEnumerator EnemySpawn() { pos = enemy_Spown_Position [Random.Range(0, enemy_Spown_Position.Count)]. position; Instantiate(spwanEffectPrefab, pos, Quaternion.identity); yield return new WaitForSeconds(0.5f); Instantiate(enemys[0], pos, Quaternion.identity); } } <file_sep>/Assets/Script/Character/Player.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Player : MonoBehaviour { public float moveSpeed; //移動速度 public float guard_MoveSpeed; //ガード中の移動速度 public int playerHp = 100; //HP public GameObject playerAttack; //攻撃オブジェクト public GameObject guard; //ガードオブジェクト public static Player instance; public int MaxHp; Direction direciton = Direction.DOWN; //現在の向き Rigidbody2D playerRigidbody; //プレイヤーRigidbody Animator anim; //アニメーター SpriteRenderer spriteRenderer; //スプライトレンダラー bool isAttack = false; //攻撃中か? ItemChecker ic; float defaultMoveSpeed; //向き private enum Direction { UP, UPRIGHT, RIGHT, DOWNRIGHT, DOWN, DOWNLEFT, LEFT, UPLEFT, }; void Awake() { instance = this; //シーンが変わっても削除されない DontDestroyOnLoad(gameObject); } // Start is called before the first frame update void Start() { playerRigidbody = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); spriteRenderer = GetComponent<SpriteRenderer>(); defaultMoveSpeed = moveSpeed; ic = GetComponent<ItemChecker>(); } // Update is called once per frame void Update() { //マウスを向けた方向を向く PlayerRote(); //ガードする Guard(); if (playerHp >= MaxHp) { playerHp = MaxHp; } if (playerHp<=0&&!ic.RevivalFlag) { gameObject.SetActive(false); Invoke("ChangeScene", 0.5f); Invoke("Death", 0.51f); } if(!ic.SpeedFlag) { moveSpeed = defaultMoveSpeed; } } private void FixedUpdate() { //攻撃する Attack(); if (Input.GetKeyDown(KeyCode.F)) { Debug.Log(guard.tag); } //*移動* //攻撃してない時 if(isAttack == false) { //Playerの移動 // 右・左 float x = Input.GetAxisRaw("Horizontal"); // 上・下 float y = Input.GetAxisRaw("Vertical"); //移動する Move(x, y); } } //移動 private void Move(float h, float v) { Vector2 movement = Vector2.zero; movement.Set(h, v); movement = movement.normalized * moveSpeed * Time.deltaTime; playerRigidbody.MovePosition(playerRigidbody.position + movement); } void PlayerRote() { //プレイヤーのスクリーン座標を計算する var screenPos = Camera.main.WorldToScreenPoint(transform.position); //プレイヤーから見たマウスカーソルの方向を計算する var direction = Input.mousePosition - screenPos; var angle = Utils.GetAngle(Vector3.zero, direction); var angles = transform.localEulerAngles; angles.z = angle; //上を向く if(68 <= angle && angle < 113) { direciton = Direction.UP; anim.SetBool("Move@Up", true); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //右上を向く if (23 <= angle && angle < 68) { direciton = Direction.UPRIGHT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", true); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //右を向く if(-23 <= angle && angle < 23) { direciton = Direction.RIGHT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", true); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //右下を向く if(-68 <= angle && angle < -23) { direciton = Direction.DOWNRIGHT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", true); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //下を向く if(-113 <= angle && angle < -68) { direciton = Direction.DOWN; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", true); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //左下を向く if(-158 <= angle && angle < -113) { direciton = Direction.DOWNLEFT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", true); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", false); } //左を向く if (-158 > angle || angle >= 158) { direciton = Direction.LEFT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", true); anim.SetBool("Move@UpLeft", false); } //左上を向く if(113 <= angle && angle < 158) { direciton = Direction.UPLEFT; anim.SetBool("Move@Up", false); anim.SetBool("Move@UpRight", false); anim.SetBool("Move@Right", false); anim.SetBool("Move@DownRight", false); anim.SetBool("Move@Down", false); anim.SetBool("Move@DownLeft", false); anim.SetBool("Move@Left", false); anim.SetBool("Move@UpLeft", true); } } //void Turning() //{ // var position = Camera.main.WorldToScreenPoint(transform.localPosition); // var rotation = Quaternion.LookRotation(Vector3.forward, Input.mousePosition - position); // //Debug.Log(rotation); // if(rotation.w >= 0.9 && rotation.z < 0.5 && rotation.z > -0.5) // { // anim.SetBool("Move@Up", true); // anim.SetBool("Move@Down", false); // anim.SetBool("Move@Left", false); // anim.SetBool("Move@Right", false); // up++; // } // if(rotation.z >= 0.9 && rotation.w < 0.5 && rotation.w > -0.5) // { // anim.SetBool("Move@Down", true); // anim.SetBool("Move@Up", false); // anim.SetBool("Move@Left", false); // anim.SetBool("Move@Right", false); // //anim.Play("Move_Down"); // down++; // } // if(rotation.z >= 0.5 && rotation.w >= 0.5) // { // anim.SetBool("Move@Up", false); // anim.SetBool("Move@Down", false); // anim.SetBool("Move@Left", true); // anim.SetBool("Move@Right", false); // //anim.Play("Move_Left"); // left++; // } // if(rotation.z <= -0.5 && rotation.w >= 0.5) // { // anim.SetBool("Move@Up", false); // anim.SetBool("Move@Down", false); // anim.SetBool("Move@Left", false); // anim.SetBool("Move@Right", true); // //anim.Play("Move_Right"); // right++; // } //} void Attack() { //攻撃 if (Input.GetKeyDown(KeyCode.Mouse0)) { //上 if (direciton == Direction.UP) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(0, 0.2f), Quaternion.identity); attack_object.transform.parent = transform; //anim.Play("Attack_Up"); isAttack = true; StartCoroutine("WaitForAttack"); //up_Attack.SetActive(true); } //右上 if(direciton == Direction.UPRIGHT) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(0.1f, 0.1f), Quaternion.Euler(0, 0, -45)); attack_object.transform.parent = transform; isAttack = true; StartCoroutine("WaitForAttack"); } //右 if (direciton == Direction.RIGHT) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(0.2f, 0) , Quaternion.Euler(0, 0, 90)); attack_object.transform.parent = transform; //anim.Play("Attack_Right"); isAttack = true; StartCoroutine("WaitForAttack"); //right_Attack.SetActive(true); } //右下 if(direciton == Direction.DOWNRIGHT) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(0.1f, -0.1f), Quaternion.Euler(0, 0, 45)); attack_object.transform.parent = transform; isAttack = true; StartCoroutine("WaitForAttack"); } //下 if (direciton == Direction.DOWN) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(0, -0.2f), Quaternion.identity); attack_object.transform.parent = transform; //anim.Play("Attack_Down"); isAttack = true; StartCoroutine("WaitForAttack"); //down_Attack.SetActive(true); } //左下 if(direciton == Direction.DOWNLEFT) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(-0.1f, -0.1f), Quaternion.Euler(0, 0, -45)); attack_object.transform.parent = transform; isAttack = true; StartCoroutine("WaitForAttack"); } //左 if (direciton == Direction.LEFT) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(-0.2f, 0), Quaternion.Euler(0, 0, 90)); attack_object.transform.parent = transform; //anim.Play("Attack_Left"); isAttack = true; StartCoroutine("WaitForAttack"); //left_Attack.SetActive(true); } //左上 if(direciton == Direction.UPLEFT) { //攻撃オブジェクトを生成する GameObject attack_object = Instantiate(playerAttack, transform.localPosition + new Vector3(-0.1f, 0.1f), Quaternion.Euler(0, 0, 45)); attack_object.transform.parent = transform; isAttack = true; StartCoroutine("WaitForAttack"); } } } float speed; //スピードを一時的に保存する GameObject guard_Prefab; //ガードのプレハブ //ガード void Guard() { //スペース押したとき if (Input.GetMouseButtonDown(1)) { //数値を取っておく speed = moveSpeed; //ガード中のスピードにする moveSpeed = guard_MoveSpeed; //上 if (direciton == Direction.UP) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(0, 0.2f), Quaternion.identity); guard_Prefab.transform.parent = transform; anim.SetBool("Guard@Up", true); } //右上 if(direciton == Direction.UPRIGHT) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(0.1f, 0.1f), Quaternion.Euler(0, 0, -45)); guard_Prefab.transform.parent = transform; } //右 if (direciton == Direction.RIGHT) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(0.2f, 0), Quaternion.Euler(0, 0, 90)); guard_Prefab.transform.parent = transform; anim.SetBool("Guard@Right", true); } //右下 if(direciton == Direction.DOWNRIGHT) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(0.1f, -0.1f), Quaternion.Euler(0, 0, 45)); guard_Prefab.transform.parent = transform; } //下 if (direciton == Direction.DOWN) { //ガード生成 guard_Prefab = Instantiate(guard, transform. localPosition + new Vector3(0, -0.2f), Quaternion.identity); guard_Prefab.transform.parent = transform; anim.SetBool("Guard@Down", true); } //左下 if(direciton == Direction.DOWNLEFT) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(-0.1f, -0.1f), Quaternion.Euler(0, 0, -45)); guard_Prefab.transform.parent = transform; } //左 if (direciton == Direction.LEFT) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(-0.2f, 0), Quaternion.Euler(0, 0, 90)); guard_Prefab.transform.parent = transform; anim.SetBool("Guard@Left", true); } //左上 if(direciton == Direction.UPLEFT) { //ガード生成 guard_Prefab = Instantiate(guard, transform.localPosition + new Vector3(-0.1f, 0.1f), Quaternion.Euler(0, 0, 45)); guard_Prefab.transform.parent = transform; } } //キーを離したとき if (Input.GetMouseButtonUp(1)) { //速さをもとに戻す moveSpeed = speed; //オブジェクトを削除する Destroy(guard_Prefab); //アニメーションオフ anim.SetBool("Guard@Down", false); anim.SetBool("Guard@Up", false); anim.SetBool("Guard@Right", false); anim.SetBool("Guard@Left", false); } } private void OnCollisionEnter2D(Collision2D collision) { // if(collision.gameObject.tag == "Enemy" && // gameObject.tag != "Guard") // { // StartCoroutine(Blinl()); // playerHp -= 10; // } if (collision.gameObject.tag == "BlastBarrel") { playerHp -= 30; } if (collision.gameObject.tag == "Bomb") { playerHp -= 10; } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "Needle") { playerHp -= 20; } } //private void OnCollisionEnter2D(Collision2D collision) //{ // if (collision.gameObject.tag == "Enemy" && // gameObject.tag != "Guard") // { // StartCoroutine(Blinl()); // playerHp -= 10; // } //} //攻撃してるとき1時停止する IEnumerator WaitForAttack() { yield return new WaitForSeconds(0.5f); isAttack = false; } //点滅 IEnumerator Blinl() { var renderComponent = GetComponent<Renderer>(); renderComponent.enabled = !renderComponent.enabled; //yield return new WaitForSeconds(0.2f); yield return null; renderComponent.enabled = !renderComponent.enabled; } //ダメージを与える public void Damage(int damage) { ic = GetComponent<ItemChecker>(); if(ic.ArmorFlag) { playerHp -= damage/4; } else if(!ic.ArmorFlag) { playerHp -= damage; } //HPがまだある場合、ここで処理を終える if(0 < playerHp) { return; } //gameObject.SetActive(false); } void ChangeScene() { SceneManager.LoadScene("TitleScene"); } void Death() { Destroy(gameObject); } } <file_sep>/Assets/Script/Camera/CameraController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class CameraController : MonoBehaviour { public GameObject[] sceneCamera; public GameObject[] entrance; public GameObject enemy; GameObject operation; Operation op; GameObject knight; GameObject archer; GameObject mage; Vector2 pos; // Start is called before the first frame update void Start() { operation = GameObject.FindGameObjectWithTag("Operation"); op = operation.GetComponent<Operation>(); sceneCamera[1].SetActive(true); } // Update is called once per frame void Update() { if (Operation.knightFlag) { knight = GameObject.FindGameObjectWithTag("Knight"); pos = knight.transform.position; } if (Operation.archerFlag) { archer = GameObject.FindGameObjectWithTag("Archer"); pos = archer.transform.position; } if (Operation.mageFlag) { mage = GameObject.FindGameObjectWithTag("Mage"); pos = mage.transform.position; } if (pos.y < entrance[0].transform.position.y) { sceneCamera[1].SetActive(true); sceneCamera[2].SetActive(false); sceneCamera[3].SetActive(false); enemy.SetActive(false); } if (pos.y > entrance[0].transform.position.y&& pos.y < entrance[1].transform.position.y) { sceneCamera[1].SetActive(false); sceneCamera[2].SetActive(true); sceneCamera[3].SetActive(false); enemy.SetActive(true); } if (pos.y > entrance[1].transform.position.y) { sceneCamera[1].SetActive(false); sceneCamera[2].SetActive(false); sceneCamera[3].SetActive(true); enemy.SetActive(false); } } }<file_sep>/Assets/Script/Boss/Slime.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Slime : MonoBehaviour { public GameObject bullet; public int SlimeHp = 10; public float moveSpeed; public float bulletSpeed; public float attenuation; public Transform player_position; public Player player; Rigidbody2D enemyRigi; Vector2 diff; float time; Vector3 verocity; // Start is called before the first frame update void Start() { player = GetComponent<Player>(); enemyRigi = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update() { if(SlimeHp == 0) { Destroy(gameObject); } time += Time.deltaTime; Attack(); //追尾移動 verocity += (player_position.position - transform.position); verocity *= attenuation; transform.position += verocity *= Time.deltaTime; } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "PlayerAttack") { StartCoroutine(Blinl()); SlimeHp -= 5; } } void Attack() { time += Time.deltaTime; float timeOut = 1; if (time > timeOut) { GameObject bulletScript = Instantiate(bullet, transform.position, Quaternion.identity); Rigidbody2D bulletRigi = bulletScript.GetComponent<Rigidbody2D>(); bulletRigi.AddForce(verocity.normalized * bulletSpeed); time = 0; } } //点滅 IEnumerator Blinl() { var renderComponent = GetComponent<Renderer>(); renderComponent.enabled = !renderComponent.enabled; //yield return new WaitForSeconds(0.2f); yield return null; renderComponent.enabled = !renderComponent.enabled; } private void OnTriggrtEnter2D(Collision2D collision) { if(collision.gameObject.tag == "Player") { player.Damage(10); } } } <file_sep>/Assets/Script/UI.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UI : MonoBehaviour { public Image knightHpGauge; public Image archerHpGauge; public Image mageHpGauge; public Image knightMpGauge; public Image archerMpGauge; public Image mageMpGauge; public Image knightPlayFlag; public Image archerPlayFlag; public Image magePlayFlag; // Start is called before the first frame update void Start() { knightPlayFlag.fillAmount = 0; archerPlayFlag.fillAmount = 0; magePlayFlag.fillAmount = 0; } // Update is called once per frame void Update() { KnightHpGauge(); ArcherHpGauge(); MageHpGauge(); KnightMpGauge(); ArcherMpGauge(); MageMpGauge(); if (Operation.knightFlag) { knightPlayFlag.fillAmount = 1; archerPlayFlag.fillAmount = 0; magePlayFlag.fillAmount = 0; } if (Operation.archerFlag) { knightPlayFlag.fillAmount = 0; archerPlayFlag.fillAmount = 1; magePlayFlag.fillAmount = 0; } if (Operation.mageFlag) { knightPlayFlag.fillAmount = 0; archerPlayFlag.fillAmount = 0; magePlayFlag.fillAmount = 1; } } void KnightHpGauge() { var player = Knight.instance; var hp = player.playerHp; var hpMax = player.playerMaxHp; knightHpGauge.fillAmount = (float)hp / hpMax; } void ArcherHpGauge() { var player = Archer.instance; var hp = player.playerHp; var hpMax = player.playerMaxHp; archerHpGauge.fillAmount = (float)hp / hpMax; } void MageHpGauge() { var player = Mage.instance; var hp = player.playerHp; var hpMax = player.playerMaxHp; mageHpGauge.fillAmount = (float)hp / hpMax; } void KnightMpGauge() { var player = Knight.instance; var mp = player.playerMp; var mpMax = player.playerMaxMp; knightMpGauge.fillAmount = (float)mp / mpMax; } void ArcherMpGauge() { var player = Archer.instance; var mp = player.playerMp; var mpMax = player.playerMaxMp; archerMpGauge.fillAmount = (float)mp / mpMax; } void MageMpGauge() { var player = Mage.instance; var mp = player.playerMp; var mpMax = player.playerMaxMp; mageMpGauge.fillAmount = (float)mp / mpMax; } } <file_sep>/Assets/Script/Camera/CameraController3.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class CameraController3: MonoBehaviour { public GameObject camera0; public GameObject camera1; public GameObject camera2; public GameObject camera3; public GameObject camera4; public GameObject camera5; public GameObject camera6; public GameObject camera7; public GameObject entrance1; public GameObject entrance2; public GameObject entrance3; public GameObject entrance4; public GameObject entrance5; public GameObject entrance6; public GameObject entrance7; public GameObject[] enemy; public GameObject shutter; GameObject operation; Operation op; GameObject knight; GameObject archer; GameObject mage; Vector2 pos; public GameObject boss; public GameObject bossPosition; // Start is called before the first frame update void Start() { operation = GameObject.FindGameObjectWithTag("Operation"); op = operation.GetComponent<Operation>(); knight = GameObject.FindGameObjectWithTag("Knight"); archer = GameObject.FindGameObjectWithTag("Archer"); mage = GameObject.FindGameObjectWithTag("Mage"); camera1.SetActive(true); } // Update is called once per frame void Update() { if (Operation.knightFlag) { pos = knight.transform.position; } if (Operation.archerFlag) { pos = archer.transform.position; } if (Operation.mageFlag) { pos = mage.transform.position; } if (pos.y < entrance1.transform.position.y) { camera1.SetActive(true); camera2.SetActive(false); camera3.SetActive(false); camera4.SetActive(false); camera5.SetActive(false); camera6.SetActive(false); camera7.SetActive(false); enemy[1].SetActive(true); enemy[2].SetActive(false); enemy[3].SetActive(false); enemy[4].SetActive(false); enemy[5].SetActive(false); enemy[6].SetActive(false); enemy[7].SetActive(false); } if (pos.y > entrance1.transform.position.y) { camera1.SetActive(false); camera2.SetActive(true); camera3.SetActive(false); camera4.SetActive(false); camera5.SetActive(false); camera6.SetActive(false); camera7.SetActive(false); enemy[1].SetActive(false); enemy[2].SetActive(false); enemy[3].SetActive(false); enemy[4].SetActive(true); enemy[5].SetActive(false); enemy[6].SetActive(false); enemy[7].SetActive(false); } if (pos.x < entrance2.transform.position.x && pos.y < entrance1.transform.position.y) { camera1.SetActive(false); camera2.SetActive(false); camera3.SetActive(true); camera4.SetActive(false); camera5.SetActive(false); camera6.SetActive(false); camera7.SetActive(false); enemy[1].SetActive(false); enemy[2].SetActive(true); enemy[3].SetActive(false); enemy[4].SetActive(false); enemy[5].SetActive(false); enemy[6].SetActive(false); enemy[7].SetActive(false); } if (pos.x > entrance3.transform.position.x && pos.y < entrance1.transform.position.y) { camera1.SetActive(false); camera2.SetActive(false); camera3.SetActive(false); camera4.SetActive(true); camera5.SetActive(false); camera6.SetActive(false); camera7.SetActive(false); enemy[1].SetActive(false); enemy[2].SetActive(false); enemy[3].SetActive(true); enemy[4].SetActive(false); enemy[5].SetActive(false); enemy[6].SetActive(false); enemy[7].SetActive(false); } if (pos.x < entrance4.transform.position.x && pos.y > entrance1.transform.position.y && pos.y < entrance6.transform.position.y) { camera1.SetActive(false); camera2.SetActive(false); camera3.SetActive(false); camera4.SetActive(false); camera5.SetActive(true); camera6.SetActive(false); camera7.SetActive(false); enemy[1].SetActive(false); enemy[2].SetActive(false); enemy[3].SetActive(false); enemy[4].SetActive(false); enemy[5].SetActive(true); enemy[6].SetActive(false); enemy[7].SetActive(false); } if (pos.x > entrance5.transform.position.x && pos.y > entrance1.transform.position.y&& pos.y < entrance6.transform.position.y) { camera1.SetActive(false); camera2.SetActive(false); camera3.SetActive(false); camera4.SetActive(false); camera5.SetActive(false); camera6.SetActive(true); camera7.SetActive(false); enemy[1].SetActive(false); enemy[2].SetActive(false); enemy[3].SetActive(false); enemy[4].SetActive(false); enemy[5].SetActive(false); enemy[6].SetActive(true); enemy[7].SetActive(false); } if (pos.y > entrance6.transform.position.y) { camera1.SetActive(false); camera2.SetActive(false); camera3.SetActive(false); camera4.SetActive(false); camera5.SetActive(false); camera6.SetActive(false); camera7.SetActive(true); enemy[1].SetActive(false); enemy[2].SetActive(false); enemy[3].SetActive(false); enemy[4].SetActive(false); enemy[5].SetActive(false); enemy[6].SetActive(false); enemy[7].SetActive(true); //Invoke("Shut", 0.5f); } if (pos.y > entrance7.transform.position.y) { if (!Operation.knightDead) { knight = GameObject.FindGameObjectWithTag("Knight"); Knight kt = knight.GetComponent<Knight>(); DataShare.knightHp = kt.playerHp; DataShare.knightMp = kt.playerMp; } else if (Operation.knightDead) { DataShare.knightHp = 0; DataShare.knightMp = 0; } if (!Operation.archerDead) { archer = GameObject.FindGameObjectWithTag("Archer"); Archer ac = archer.GetComponent<Archer>(); DataShare.archerHp = ac.playerHp; DataShare.archerMp = ac.playerMp; } if (Operation.archerDead) { DataShare.archerHp = 0; DataShare.archerMp = 0; } if (!Operation.mageDead) { mage = GameObject.FindGameObjectWithTag("Mage"); Mage mg = mage.GetComponent<Mage>(); DataShare.mageHp = mg.playerHp; DataShare.mageMp = mg.playerMp; } if (Operation.mageDead) { DataShare.mageHp = 0; DataShare.mageMp = 0; } SceneManager.LoadScene("Stage03"); } } void Shut() { shutter.SetActive(true); } }<file_sep>/Assets/Script/Item/ItemMenu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ItemMenu : MonoBehaviour { GameObject knight; GameObject archer; GameObject mage; GameObject iChecker; Knight kt; Archer ac; Mage mg; ItemChecker ic; bool menuflag = false; public GameObject ItemUI; public Text[] text; public Button[] button; GameObject operation; Operation op; private void Awake() { } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { operation = GameObject.FindGameObjectWithTag("Operation"); op = operation.GetComponent<Operation>(); iChecker = GameObject.FindGameObjectWithTag("ItemChecker"); ic = iChecker.GetComponent<ItemChecker>(); operation = GameObject.FindGameObjectWithTag("Operation"); ItemDisplay(); } void ItemDisplay() { text[0].text = "HPポーション ×" + ic.HpPortion; text[1].text = "MPポーション ×" + ic.MpPortion; text[2].text = "スピードUP ×" + ic.SpeedUP; text[3].text = "ダメージUP ×" + ic.DamageUP; text[4].text = "復活ペンダント ×" + ic.RevivalPendant; text[5].text = "強化アーマー ×" + ic.Armor; text[6].text = "爆弾 ×" + ic.Bomb; } public void UseHpPortion() { if(Operation.knightFlag) { knight = GameObject.FindGameObjectWithTag("Knight"); kt = knight.GetComponent<Knight>(); if (ic.HpPortion > 0 && kt.playerHp < kt.playerMaxHp) { kt.playerHp += 20; ic.HpPortion -= 1; } } if(Operation.archerFlag) { archer = GameObject.FindGameObjectWithTag("Archer"); ac = archer.GetComponent<Archer>(); if (ic.HpPortion > 0 && ac.playerHp < ac.playerMaxHp) { ac.playerHp += 20; ic.HpPortion -= 1; } } if(Operation.mageFlag) { mage = GameObject.FindGameObjectWithTag("Mage"); mg = mage.GetComponent<Mage>(); if (ic.HpPortion > 0 && mg.playerHp < mg.playerMaxHp) { mg.playerHp += 20; ic.HpPortion -= 1; } } } public void UseMpPortion() { if(Operation.knightFlag) { knight = GameObject.FindGameObjectWithTag("Knight"); kt = knight.GetComponent<Knight>(); if (ic.MpPortion > 0 && kt.playerMp < kt.playerMaxMp) { kt.playerMp += 20; ic.MpPortion -= 1; } } if(Operation.archerFlag) { archer = GameObject.FindGameObjectWithTag("Archer"); ac = archer.GetComponent<Archer>(); if (ic.MpPortion > 0 && ac.playerMp < ac.playerMaxMp) { ac.playerMp += 20; ic.MpPortion -= 1; } } if(Operation.mageFlag) { mage = GameObject.FindGameObjectWithTag("Mage"); mg = mage.GetComponent<Mage>(); if (ic.MpPortion > 0 && mg.playerMp < mg.playerMaxMp) { mg.playerMp += 20; ic.MpPortion -= 1; } } } public void UseSpeedUP() { if (ic.SpeedUP > 0 && !ic.SpeedFlag) { ic.SpeedFlag = true; if(!Operation.knightDead) { knight = GameObject.FindGameObjectWithTag("Knight"); kt = knight.GetComponent<Knight>(); kt.moveSpeed = kt.moveSpeed * 3; } if(!Operation.archerDead) { archer = GameObject.FindGameObjectWithTag("Archer"); ac = archer.GetComponent<Archer>(); ac.moveSpeed = ac.moveSpeed * 3; } if(!Operation.mageDead) { mage = GameObject.FindGameObjectWithTag("Mage"); mg = mage.GetComponent<Mage>(); mg.moveSpeed = mg.moveSpeed * 3; } ic.SpeedUP -= 1; } } public void UseDamageUP() { if (ic.DamageUP > 0 && !ic.DamageFlag) { ic.DamageFlag = true; ic.DamageUP -= 1; } } public void UseRevivalPendant() { if (ic.RevivalPendant > 0 && !ic.RevivalFlag) { ic.RevivalFlag = true; ic.RevivalPendant -= 1; } } public void UseArmor() { if (ic.Armor > 0 && !ic.ArmorFlag) { ic.ArmorFlag = true; ic.Armor -= 1; } } public void UseBomb() { if (ic.Bomb > 0 && !ic.BombFlag) { ic.BombFlag = true; ic.Bomb -= 1; } } public void MenuFlag() { if (menuflag) { enabled = false; } else if (!menuflag) { enabled = true; } } }
be9192ce5204482e6244f28869533627ca1c176c
[ "C#" ]
41
C#
rokap0127/roguelike
1cecf6db5bf988ac2818f9f3ad113ff558840131
d4d0efd94b1d72d713eb7a92dcf8b1b601ab7f8c
refs/heads/master
<file_sep># Yummly API Credentials YUMMLY_ID=xxxxxxxx YUMMLY_API_KEY=<KEY> <file_sep>'use strict'; require('dotenv').config(); global.expect = require('expect.js'); global.yummly = require('../lib/yummly'); global.credentials = { id: process.env.YUMMLY_ID || '3cbb14d1', key: process.env.YUMMLY_API_KEY || '6eed2ccd0ec397588fa29dfbe3becd78' };
c11ebca64586f6d81056b5561170c21d248107c4
[ "JavaScript", "Shell" ]
2
Shell
mattkrick/node-yummly
30da259b1634e0eb396fcd7a0feff3f56323a164
6dcdffa8eda48bbfbdd25f2ce1d46565a3ed5a7e
refs/heads/master
<file_sep>import React from 'react'; import logo from '../../assets/images/logo.png'; export default function Logo() { return ( <div className="header__logo_box"> <div className="header__logo">ravraw.io</div> </div> ); } <file_sep>import React from 'react'; export default function Skills() { return ( <div className="skills"> <h1>Technologies Worked with</h1> <div className="skills__list"> <div className="skills__item"> <h3>front-end</h3> <ul> <li>Javascript</li> <li>html5</li> <li>css3</li> <li>sass/scss</li> <li>Bootstrap</li> <li>React</li> <li>React router</li> <li>Jest / Enzyme (testing)</li> <li>Webpack (Bundling)</li> <li>Babel (Compiler)</li> <li>GIT (version control)</li> </ul> </div> <div className="skills__item"> <h3>back end</h3> <ul> <li>NodeJs</li> <li>Express</li> <li>Ruby </li> <li>Ruby on Rails</li> <li>Restfull Api</li> <li>GraphQL</li> <li>PostgresQl</li> <li>MongoDB</li> <li>KnexJs</li> </ul> </div> </div> </div> ); } <file_sep>import React from 'react'; import reactLogo from '../../assets/images/react.png'; import reactRouterLogo from '../../assets/images/reactRouter.png'; import sassLogo from '../../assets/images/sass.png'; //import reactLogo from '../../assets/images/react.png'; export default function() { return ( <footer className="footer"> <p>Thank you for visiting , this site is work in progress :</p> <img src={sassLogo} alt="img" /> <img src={reactRouterLogo} alt="img" /> <img src={reactLogo} alt="img" /> </footer> ); } <file_sep>import React from 'react'; //import Link from './Link'; import { NavLink } from 'react-router-dom'; export default function LinkList() { return ( <ul className="link__list"> <NavLink className="link__item" activeClassName="selected" exact to="/"> Home </NavLink> <NavLink className="link__item" activeClassName="selected" to="/about"> About </NavLink> <NavLink className="link__item" activeClassName="selected" to="/skills"> Skills </NavLink> <NavLink className="link__item" activeClassName="selected" to="/projects"> Projects </NavLink> <NavLink className="link__item" activeClassName="selected" to="/contact"> Contact </NavLink> </ul> ); } <file_sep>import React from 'react'; export default function Link(props) { return ( <React.Fragment> <li className="link">{props.name}</li> </React.Fragment> ); } <file_sep>import React from 'react'; export default function About() { return ( <div className="about"> {/*<img src="https://avatars3.githubusercontent.com/u/32376706?s=460&v=4" alt="" width="200px" height="200px" />*/} <div className="about__bio"> <h1> Restaurant manager to Full-stack Web developer</h1> <p> It all started by managing a Facebook page for a previous employer, which lead me to research more about web development. More I learned, more fascinated I became with the power of coding, and how it is shaping the future. </p> <p> After self-learning the basics of front end development from online resources like Udemy and free code camp, I decided to join " <a href="https://lighthouselabs.ca/web-bootcamp" target="_blanck"> Lighthouse labs Full-stack web developer program </a> ". It was an amazing learning experience and helped to develop my skills as a professional. </p> <p> Currently, I am looking for an opportunity as a "Full-stack Web developer" and working on side projects to enhance my skills. </p> <p> "I am passionate about crafting great user experience while developing clean modular code. Keen to learn new web technologies to build better more efficient solutions." </p> </div> </div> ); } <file_sep>import React from 'react'; import { Route, Switch } from 'react-router-dom'; import Home from '../PageViews/Home'; import About from '../PageViews/About'; import Projects from '../PageViews/Projects'; import Contact from '../PageViews/Contact'; import Skills from '../PageViews/Skills'; import ProjectDetails from '../PageViews/ProjectDetails'; export default function() { return ( <main className="main"> <Switch> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> <Route path="/Skills" component={Skills} /> <Route path="/projects" component={Projects} /> <Route path="/contact" component={Contact} /> <Route path="/projectDetails" component={ProjectDetails} /> </Switch> </main> ); }
09d70f1e5b144a4b99993c680e412d5e9f9b1c01
[ "JavaScript" ]
7
JavaScript
ravraw/ravraw_porfolio
14d5b056905a9fea6cf149ea0665740372fcf8a0
5de6e5fd5e840ca2f0dd4b55b689f0dbd18bb7b3
refs/heads/master
<file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals import json from django import forms from django.conf import settings from django.forms import MultiWidget from django.utils.safestring import mark_safe from .utils import get_backend class MapWidget(MultiWidget): def __init__(self, attrs=None): self.map_backend = get_backend(settings.TREASURE_MAP) if self.map_backend.only_map: widgets = ( forms.HiddenInput(attrs=attrs), forms.HiddenInput(attrs=attrs), ) else: widgets = ( forms.NumberInput(attrs=attrs), forms.NumberInput(attrs=attrs), ) super(MapWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return [value.format_latitude, value.format_longitude] return [None, None] @property def is_hidden(self): return False def get_context_widgets(self): context = { "map_options": json.dumps(self.map_backend.get_map_options()), "width": self.map_backend.width, "height": self.map_backend.height, "only_map": self.map_backend.only_map, } return context def render(self, name, value, attrs=None, renderer=None): context = self.get_context(name, value, attrs) context.update(self.get_context_widgets()) return mark_safe(renderer.render(self.map_backend.get_widget_template(), context)) def _get_media(self): media = forms.Media() for w in self.widgets: media = media + w.media media += forms.Media(js=(self.map_backend.get_api_js(), self.map_backend.get_js())) return media media = property(_get_media) class AdminMapWidget(MapWidget): def get_context_widgets(self): context = super(AdminMapWidget, self).get_context_widgets() context["width"] = self.map_backend.admin_width context["height"] = self.map_backend.admin_height return context <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals import django __author__ = "<NAME>" __version__ = "0.3.4" if django.VERSION < (3, 2): default_app_config = "treasuremap.apps.TreasureMapConfig" VERSION = __version__ <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from collections import OrderedDict try: from urllib import urlencode except ImportError: from urllib.parse import urlencode from django.conf import settings from .base import BaseMapBackend class YandexMapBackend(BaseMapBackend): NAME = "yandex" API_URL = "//api-maps.yandex.ru/2.1/" def get_api_js(self): params = OrderedDict() params["lang"] = settings.LANGUAGE_CODE if self.API_KEY: params["apikey"] = self.API_KEY return "{js_lib}?{params}".format(js_lib=self.API_URL, params=urlencode(params)) <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from collections import OrderedDict from django.conf import settings from django.core.exceptions import ImproperlyConfigured class BaseMapBackend(object): """ Base map backend """ NAME = None API_URL = None def __init__(self): self.options = getattr(settings, "TREASURE_MAP", {}) self.API_KEY = self.options.get("API_KEY", None) try: self.width = int(self.options.get("SIZE", (400, 400))[0]) self.height = int(self.options.get("SIZE", (400, 400))[1]) except (IndexError, ValueError): raise ImproperlyConfigured( # pylint: disable=raise-missing-from "Invalid SIZE parameter, use: (width, height)." ) try: self.admin_width = int(self.options.get("ADMIN_SIZE", (400, 400))[0]) self.admin_height = int(self.options.get("ADMIN_SIZE", (400, 400))[1]) except (IndexError, ValueError): raise ImproperlyConfigured( # pylint: disable=raise-missing-from "Invalid ADMIN SIZE parameter, use: (width, height)." ) def get_js(self): """ Get jQuery plugin """ if self.NAME is None: raise ImproperlyConfigured("Your use abstract class.") return "treasuremap/default/js/jquery.treasuremap-{}.js".format(self.NAME) def get_api_js(self): """ Get javascript libraries """ raise NotImplementedError() def get_widget_template(self): return self.options.get("WIDGET_TEMPLATE", "treasuremap/widgets/map.html") @property def only_map(self): return self.options.get("ONLY_MAP", True) def get_map_options(self): map_options = self.options.get("MAP_OPTIONS", {}) map_options = OrderedDict(sorted(map_options.items(), key=lambda x: x[1], reverse=True)) if not map_options.get("latitude"): map_options["latitude"] = 51.562519 if not map_options.get("longitude"): map_options["longitude"] = -1.603156 if not map_options.get("zoom"): map_options["zoom"] = 5 return map_options <file_sep>Django>=4.1 black==22.3.0 isort==5.10.1 pylint==2.14.4 yamllint==1.26.3 <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from .widgets import MapWidget class LatLongField(forms.MultiValueField): widget = MapWidget default_error_messages = { "invalid_coordinates": _("Enter a valid coordinate."), } def __init__(self, *args, **kwargs): errors = self.default_error_messages.copy() if "error_messages" in kwargs: errors.update(kwargs["error_messages"]) fields = ( forms.DecimalField(label=_("latitude")), forms.DecimalField(label=_("longitude")), ) super(LatLongField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: if data_list[0] in self.empty_values: raise ValidationError(self.error_messages["invalid_coordinates"], code="invalid") if data_list[1] in self.empty_values: raise ValidationError(self.error_messages["invalid_coordinates"], code="invalid") return data_list return None <file_sep># Generated by Django 3.0.6 on 2020-06-04 09:00 from django.db import migrations, models import treasuremap.fields class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="MyModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID" ), ), ("empty_point", treasuremap.fields.LatLongField(max_length=24)), ( "null_point", treasuremap.fields.LatLongField(blank=True, max_length=24, null=True), ), ( "default_point", treasuremap.fields.LatLongField( default=treasuremap.fields.LatLong(33.000000, 44.000000), max_length=24 ), ), ], ), ] <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from decimal import Decimal from django.core.exceptions import ValidationError from django.db import models from django.utils.deconstruct import deconstructible from django.utils.translation import gettext_lazy as _ from .forms import LatLongField as FormLatLongField @deconstructible class LatLong(object): def __init__(self, latitude=0.0, longitude=0.0): self.latitude = Decimal(latitude) self.longitude = Decimal(longitude) @staticmethod def _equals_to_the_cent(a, b): return round(a, 6) == round(b, 6) @staticmethod def _no_equals_to_the_cent(a, b): return round(a, 6) != round(b, 6) @property def format_latitude(self): return "{:.6f}".format(self.latitude) @property def format_longitude(self): return "{:.6f}".format(self.longitude) def __repr__(self): return "{}({:.6f}, {:.6f})".format(self.__class__.__name__, self.latitude, self.longitude) def __str__(self): return "{:.6f};{:.6f}".format(self.latitude, self.longitude) def __eq__(self, other): return isinstance(other, LatLong) and ( self._equals_to_the_cent(self.latitude, other.latitude) and self._equals_to_the_cent(self.longitude, other.longitude) ) def __ne__(self, other): return isinstance(other, LatLong) and ( self._no_equals_to_the_cent(self.latitude, other.latitude) or self._no_equals_to_the_cent(self.longitude, other.longitude) ) class LatLongField(models.Field): description = _("Geographic coordinate system fields") default_error_messages = { "invalid": _("'%(value)s' both values must be a decimal number or integer."), "invalid_separator": _("As the separator value '%(value)s' must be ';'"), } def __init__(self, *args, **kwargs): kwargs["max_length"] = 24 super(LatLongField, self).__init__(*args, **kwargs) def get_internal_type(self): return "CharField" def to_python(self, value): if value is None: return None elif not value: return LatLong() elif isinstance(value, LatLong): return value else: if isinstance(value, (list, tuple, set)): args = value else: args = value.split(";") if len(args) != 2: raise ValidationError( self.error_messages["invalid_separator"], code="invalid", params={"value": value}, ) return LatLong(*args) def get_db_prep_value( self, value, connection, prepared=False # pylint: disable=unused-argument ): value = super(LatLongField, self).get_prep_value(value) if value is None: return None value = self.to_python(value) return str(value) def from_db_value( self, value, expression, connection, *args, **kwargs ): # pylint: disable=unused-argument return self.to_python(value) def formfield(self, _form_class=None, choices_form_class=None, **kwargs): return super(LatLongField, self).formfield( form_class=FormLatLongField, choices_form_class=choices_form_class, **kwargs ) <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from treasuremap import fields class MyModel(models.Model): empty_point = fields.LatLongField() null_point = fields.LatLongField(blank=True, null=True) default_point = fields.LatLongField(default=fields.LatLong(33, 44)) <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals import importlib from django.core.exceptions import ImproperlyConfigured from .backends.base import BaseMapBackend def import_class(path): path_bits = path.split(".") class_name = path_bits.pop() module_path = ".".join(path_bits) module_itself = importlib.import_module(module_path) if not hasattr(module_itself, class_name): raise ImportError("The Python module {} has no {} class.".format(module_path, class_name)) return getattr(module_itself, class_name) def get_backend(map_config): if not map_config.get("BACKEND"): map_config["BACKEND"] = "treasuremap.backends.google.GoogleMapBackend" backend = import_class(map_config["BACKEND"]) if not issubclass(backend, BaseMapBackend): raise ImproperlyConfigured("Is backend {} is not instance BaseMapBackend.".format(backend)) return backend() <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from decimal import Decimal, InvalidOperation from django.core.exceptions import ImproperlyConfigured, ValidationError from django.forms.renderers import get_default_renderer from django.test import TestCase from django.test.utils import override_settings from treasuremap.backends.base import BaseMapBackend from treasuremap.backends.google import GoogleMapBackend from treasuremap.backends.yandex import YandexMapBackend from treasuremap.fields import LatLong, LatLongField from treasuremap.forms import LatLongField as FormLatLongField from treasuremap.utils import get_backend, import_class from treasuremap.widgets import AdminMapWidget, MapWidget from .models import MyModel class LatLongObjectTestCase(TestCase): def test_create_empty_latlong(self): latlong = LatLong() self.assertEqual(latlong.latitude, 0.0) self.assertEqual(latlong.longitude, 0.0) def test_create_latlog_with_float(self): latlong = LatLong(latitude=33.300, longitude=44.440) self.assertEqual(latlong.latitude, Decimal(33.300)) self.assertEqual(latlong.longitude, Decimal(44.440)) def test_create_latlog_with_string(self): latlong = LatLong(latitude="33.300", longitude="44.440") self.assertEqual(latlong.latitude, Decimal("33.300")) self.assertEqual(latlong.longitude, Decimal("44.440")) def test_create_latlog_with_invalid_value(self): self.assertRaises(InvalidOperation, LatLong, "not int", 44.440) def test_latlog_object_str(self): latlong = LatLong(latitude=33.300, longitude=44.440) self.assertEqual(str(latlong), "33.300000;44.440000") def test_latlog_object_repr(self): latlong = LatLong(latitude=33.300, longitude=44.440) self.assertEqual(repr(latlong), "LatLong(33.300000, 44.440000)") def test_latlog_object_eq(self): self.assertEqual( LatLong(latitude=33.300, longitude=44.440), LatLong(latitude=33.300, longitude=44.440) ) def test_latlog_object_ne(self): self.assertNotEqual( LatLong(latitude=33.300, longitude=44.441), LatLong(latitude=22.300, longitude=44.441) ) class LatLongFieldTestCase(TestCase): def test_latlog_field_create(self): m = MyModel.objects.create() new_m = MyModel.objects.get(pk=m.pk) self.assertEqual(new_m.empty_point, LatLong()) self.assertEqual(new_m.null_point, None) self.assertEqual(new_m.default_point, LatLong(33, 44)) def test_latlog_field_change_with_latlog_obj(self): m = MyModel.objects.create(empty_point=LatLong(22.123456, 33.654321)) new_m = MyModel.objects.get(pk=m.pk) self.assertEqual(new_m.empty_point, LatLong(22.123456, 33.654321)) def test_latlog_field_change_with_string(self): m = MyModel.objects.create(empty_point="22.123456;33.654321") new_m = MyModel.objects.get(pk=m.pk) self.assertEqual(new_m.empty_point, LatLong(22.123456, 33.654321)) def test_latlog_field_change_invalid_value(self): self.assertRaises(ValidationError, MyModel.objects.create, empty_point="22.12345633.654321") def test_get_prep_value_convert(self): field = LatLongField() self.assertEqual(field.get_prep_value(""), "") self.assertEqual( field.get_prep_value(LatLong(22.123456, 33.654321)), LatLong(22.123456, 33.654321) ) self.assertIsNone(field.get_prep_value(None)) def test_get_formfield(self): field = LatLongField() form_field = field.formfield() self.assertIsInstance(form_field, FormLatLongField) def test_deconstruct(self): field = LatLongField() _, _, args, kwargs = field.deconstruct() new_instance = LatLongField(*args, **kwargs) self.assertEqual(field.max_length, new_instance.max_length) class LoadBackendTestCase(TestCase): def test_load_google(self): backend = get_backend({"BACKEND": "treasuremap.backends.google.GoogleMapBackend"}) self.assertEqual(backend.__class__.__name__, "GoogleMapBackend") def test_load_yandex(self): backend = get_backend({"BACKEND": "treasuremap.backends.yandex.YandexMapBackend"}) self.assertEqual(backend.__class__.__name__, "YandexMapBackend") def test_load_failed(self): self.assertRaises( ImportError, get_backend, {"BACKEND": "treasuremap.backends.unknown.UnknownMapBackend"} ) def test_load_without_backend(self): backend = get_backend({}) self.assertEqual(backend.__class__.__name__, "GoogleMapBackend") def test_load_not_subclass_mapbackend(self): self.assertRaises(ImproperlyConfigured, get_backend, {"BACKEND": "django.test.TestCase"}) class ImportClassTestCase(TestCase): def test_import_from_string(self): c = import_class("django.test.TestCase") self.assertEqual(c, TestCase) def test_import_from_string_none(self): with self.assertRaises(ImportError): import_class("django.test.NonModel") class BaseMapBackendTestCase(TestCase): def test_base_init(self): backend = BaseMapBackend() self.assertEqual(backend.NAME, None) self.assertEqual(backend.API_URL, None) def test_base_get_js(self): backend = BaseMapBackend() self.assertRaises(ImproperlyConfigured, backend.get_js) def test_base_get_js_with_name(self): backend = BaseMapBackend() backend.NAME = "test" self.assertEqual(backend.get_js(), "treasuremap/default/js/jquery.treasuremap-test.js") def test_base_get_api_js(self): backend = BaseMapBackend() self.assertRaises(NotImplementedError, backend.get_api_js) def test_base_widget_template_default(self): backend = BaseMapBackend() self.assertEqual(backend.get_widget_template(), "treasuremap/widgets/map.html") @override_settings(TREASURE_MAP={"WIDGET_TEMPLATE": "template/custom.html"}) def test_base_widget_template_custom(self): backend = BaseMapBackend() self.assertEqual(backend.get_widget_template(), "template/custom.html") def test_base_api_key_default(self): backend = BaseMapBackend() self.assertEqual(backend.API_KEY, None) @override_settings(TREASURE_MAP={"API_KEY": "random_string"}) def test_base_api_key_settings(self): backend = BaseMapBackend() self.assertEqual(backend.API_KEY, "random_string") def test_base_only_map_default(self): backend = BaseMapBackend() self.assertEqual(backend.only_map, True) @override_settings(TREASURE_MAP={"ONLY_MAP": False}) def test_base_only_map_settings(self): backend = BaseMapBackend() self.assertEqual(backend.only_map, False) def test_base_size_default(self): backend = BaseMapBackend() self.assertEqual(backend.width, 400) self.assertEqual(backend.height, 400) @override_settings(TREASURE_MAP={"SIZE": (500, 500)}) def test_base_size_settings(self): backend = BaseMapBackend() self.assertEqual(backend.width, 500) self.assertEqual(backend.height, 500) @override_settings(TREASURE_MAP={"SIZE": ("Invalid",)}) def test_base_size_invalid_settings(self): self.assertRaises(ImproperlyConfigured, BaseMapBackend) @override_settings(TREASURE_MAP={"ADMIN_SIZE": (500, 500)}) def test_base_admin_size_settings(self): backend = BaseMapBackend() self.assertEqual(backend.admin_width, 500) self.assertEqual(backend.admin_height, 500) @override_settings(TREASURE_MAP={"ADMIN_SIZE": ("Invalid",)}) def test_base_admin_size_invalid_settings(self): self.assertRaises(ImproperlyConfigured, BaseMapBackend) def test_base_map_options_default(self): backend = BaseMapBackend() self.assertDictEqual( backend.get_map_options(), {"latitude": 51.562519, "longitude": -1.603156, "zoom": 5} ) @override_settings( TREASURE_MAP={"MAP_OPTIONS": {"latitude": 44.1, "longitude": -55.1, "zoom": 1}} ) def test_base_map_options_settings(self): backend = BaseMapBackend() self.assertDictEqual( backend.get_map_options(), {"latitude": 44.1, "longitude": -55.1, "zoom": 1} ) class GoogleMapBackendTestCase(TestCase): def test_get_api_js_default(self): backend = GoogleMapBackend() self.assertEqual(backend.get_api_js(), "//maps.googleapis.com/maps/api/js?v=3.exp") @override_settings(TREASURE_MAP={"API_KEY": "random_string"}) def test_get_api_js_with_api_key(self): backend = GoogleMapBackend() self.assertEqual( backend.get_api_js(), "//maps.googleapis.com/maps/api/js?v=3.exp&key=random_string" ) class YandexMapBackendTestCase(TestCase): def test_get_api_js(self): backend = YandexMapBackend() self.assertEqual(backend.get_api_js(), "//api-maps.yandex.ru/2.1/?lang=en-us") @override_settings(TREASURE_MAP={"API_KEY": "random_string"}) def test_get_api_js_with_api_key(self): backend = YandexMapBackend() self.assertEqual( backend.get_api_js(), "//api-maps.yandex.ru/2.1/?lang=en-us&apikey=random_string" ) class FormTestCase(TestCase): def test_witget_render(self): witget = MapWidget() done_html = """ {"latitude": 51.562519, "longitude": -1.603156, "zoom": 5} """ out_html = witget.render( "name", LatLong(22.123456, 33.654321), renderer=get_default_renderer() ) self.assertTrue(out_html, done_html) def test_witget_render_js(self): witget = MapWidget() out_html = str(witget.media) self.assertIn("//maps.googleapis.com/maps/api/js?v=3.exp", out_html) self.assertIn("/static/treasuremap/default/js/jquery.treasuremap-google.js", out_html) def test_admin_witget_render(self): witget = AdminMapWidget() done_html = """ {"latitude": 51.562519, "longitude": -1.603156, "zoom": 5} """ out_html = witget.render( "name", LatLong(22.123456, 33.654321), renderer=get_default_renderer() ) self.assertTrue(out_html, done_html) def test_admin_witget_render_js(self): witget = AdminMapWidget() out_html = str(witget.media) self.assertIn("//maps.googleapis.com/maps/api/js?v=3.exp", out_html) self.assertIn("/static/treasuremap/default/js/jquery.treasuremap-google.js", out_html) <file_sep>.. image:: https://github.com/silentsokolov/django-treasuremap/workflows/build/badge.svg?branch=master :target: https://github.com/silentsokolov/django-treasuremap/actions?query=workflow%3Abuild+branch%3Amaster .. image:: https://codecov.io/gh/silentsokolov/django-treasuremap/branch/master/graph/badge.svg :target: https://codecov.io/gh/silentsokolov/django-treasuremap django-treasuremap ================== django-treasuremap app, makes it easy to store and display the location on the map using different providers (Google, Yandex, etc). Requirements ------------ * Python 2.7+ or Python 3.4+ * Django 1.11+ Installation ------------ Use your favorite Python package manager to install the app from PyPI, e.g. Example: ``pip install django-treasuremap`` Add ``treasuremap`` to ``INSTALLED_APPS``: Example: .. code:: python INSTALLED_APPS = ( ... 'treasuremap', ... ) Configuration ------------- Within your ``settings.py``, you’ll need to add a setting (which backend to use, etc). Example: .. code:: python TREASURE_MAP = { 'BACKEND': 'treasuremap.backends.google.GoogleMapBackend', 'API_KEY': 'Your API key', 'SIZE': (400, 600), 'MAP_OPTIONS': { 'zoom': 5 } } Example usage ------------- In models ~~~~~~~~~ .. code:: python from django.db import models from treasuremap.fields import LatLongField class Post(models.Model): name = models.CharField(max_length=100) point = LatLongField(blank=True) In admin ~~~~~~~~~ .. code:: python from django.contrib import admin from treasuremap.widgets import AdminMapWidget from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'point': kwargs['widget'] = AdminMapWidget() return super(PostAdmin,self).formfield_for_dbfield(db_field,**kwargs) In forms ~~~~~~~~ .. code:: python from django import forms from treasuremap.forms import LatLongField class PostForm(models.Model): point = LatLongField() .. code:: html <head> ... <!-- jQuery is required; include if need --> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> ... </head> <form method="POST" action="."> {{ form.media }} {% csrf_token %} {{ form.as_p }} </form> Depending on what backend you are using, the correct widget will be displayed with a marker at the currently position (jQuery is required). .. image:: https://raw.githubusercontent.com/silentsokolov/django-treasuremap/master/docs/images/screenshot.png Settings -------- Support map: ~~~~~~~~~~~~ - Google map ``treasuremap.backends.google.GoogleMapBackend`` - Yandex map ``treasuremap.backends.yandex.YandexMapBackend`` Other settings: ~~~~~~~~~~~~~~~ - ``API_KEY`` - if need, default ``None`` - ``SIZE`` - tuple with the size of the map, default ``(400, 400)`` - ``ADMIN_SIZE`` - tuple with the size of the map on the admin panel, default ``(400, 400)`` - ``ONLY_MAP`` - hide field lat/long, default ``True`` - ``MAP_OPTIONS`` - dict, used to initialize the map, default ``{'latitude': 51.562519, 'longitude': -1.603156, 'zoom': 5}``. ``latitude`` and ``longitude`` is required, do not use other "LatLong Object". <file_sep>(function($) { function addMarker(position, map, latinput, lnginput, markers) { // del markers deleteMarkers(map, markers); // create new placemark var placemark = new ymaps.Placemark(position, {}); // add placemark to map map.geoObjects.add(placemark); // update value latinput.val(placemark.geometry.getCoordinates()[0].toFixed(6)); lnginput.val(placemark.geometry.getCoordinates()[1].toFixed(6)); // save marker markers.push(placemark); // move map to new position in center map.panTo(position); } function deleteMarkers(map, markers) { for (var i = 0; i < markers.length; i++) { map.geoObjects.remove(markers[i]); } markers = []; } $(document).ready(function() { return ymaps.ready(function() { $('.treasure-map').each(function (index, element) { var map_element = $(element).children('.map').get(0); var latitude_input = $(element).children('input:eq(0)'); var longitude_input = $(element).children('input:eq(1)'); var options = $.parseJSON($(element).children('script').text()) || {}; var markers = []; var defaultMapOptions = {}; // init default map options defaultMapOptions.center = [ parseFloat(latitude_input.val()) || options.latitude, parseFloat(longitude_input.val()) || options.longitude ]; // merge user and default options var mapOptions = $.extend(defaultMapOptions, options); // create map var map = new ymaps.Map(map_element, mapOptions); // add default marker if (latitude_input.val() && longitude_input.val()) { addMarker(defaultMapOptions.center, map, latitude_input, longitude_input, markers); } // init listener return map.events.add("click", function(e) { addMarker(e.get('coords'), map, latitude_input, longitude_input, markers); } ); }); }); }); })((typeof window.jQuery == 'undefined' && typeof window.django != 'undefined') ? django.jQuery : jQuery); <file_sep>## [Unreleased] ## [0.3.4] - 2020-08-10 ### Added - Compatibility Django 3.2 ## [0.3.3] - 2020-08-10 ### Added - Compatibility Django 3.1 ## [0.3.2] - 2019-12-05 ### Added - Compatibility Django 3.0 ## [0.3.1] - 2019-08-20 ### Fixed - MANIFEST.in paths ## [0.3.0] - 2019-08-20 ### Added - Compatibility Django 2.2 ### Deleted - Support Django < 1.11 ## [0.2.7] - 2018-10-15 ### Fixed - Fix context from_db_value ## [0.2.6] - 2018-04-23 ### Added - Django 2.0 support ## [0.2.5] - 2017-05-30 ### Added - Django 1.11 support ## [0.2.4] - 2016-01-02 ### Added - Django 1.11 support ## [0.2.3] - 2015-11-12 ### Added - Test code ### Deleted - LatLong as list - Required settings [Unreleased]: https://github.com/silentsokolov/django-treasuremap/compare/v0.3.4...HEAD [0.3.4]: https://github.com/silentsokolov/django-treasuremap/compare/v0.3.3...v0.3.4 [0.3.3]: https://github.com/silentsokolov/django-treasuremap/compare/v0.3.2...v0.3.3 [0.3.2]: https://github.com/silentsokolov/django-treasuremap/compare/v0.3.1...v0.3.2 [0.3.1]: https://github.com/silentsokolov/django-treasuremap/compare/v0.3.0...v0.3.1 [0.3.0]: https://github.com/silentsokolov/django-treasuremap/compare/v0.2.7...v0.3.0 [0.2.7]: https://github.com/silentsokolov/django-treasuremap/compare/v0.2.6...v0.2.7 [0.2.6]: https://github.com/silentsokolov/django-treasuremap/compare/v0.2.5...v0.2.6 [0.2.5]: https://github.com/silentsokolov/django-treasuremap/compare/v0.2.4...v0.2.5 [0.2.4]: https://github.com/silentsokolov/django-treasuremap/compare/v0.2.3...v0.2.4 [0.2.3]: https://github.com/silentsokolov/django-treasuremap/compare/v0.2...v0.2.3 <file_sep>(function($) { function addMarker(position, map, latinput, lnginput, markers) { // del markers deleteMarkers(null, markers); // create new marker var marker = new google.maps.Marker({ position: position, map: map }); // update value latinput.val(marker.getPosition().lat().toFixed(6)); lnginput.val(marker.getPosition().lng().toFixed(6)); // save marker markers.push(marker); // move map to new position in center map.panTo(position); } function deleteMarkers(map, markers) { for (var i = 0; i < markers.length; i++) { markers[i].setMap(map); } markers = []; } $(document).ready(function() { $('.treasure-map').each(function (index, element) { var map_element = $(element).children('.map').get(0); var latitude_input = $(element).children('input:eq(0)'); var longitude_input = $(element).children('input:eq(1)'); var options = $.parseJSON($(element).children('script').text()) || {}; var markers = []; // var zoom = options.zoom || 4; var defaultMapOptions = {}; // init default map options defaultMapOptions.center = new google.maps.LatLng( parseFloat(latitude_input.val()) || options.latitude, parseFloat(longitude_input.val()) || options.longitude ); // merge user and default options var mapOptions = $.extend(defaultMapOptions, options); // create map var map = new google.maps.Map(map_element, mapOptions); // add default marker if (latitude_input.val() && longitude_input.val()) { addMarker(defaultMapOptions.center, map, latitude_input, longitude_input, markers); } // init listener google.maps.event.addListener(map, 'click', function (e) { addMarker(e.latLng, map, latitude_input, longitude_input, markers); }); }); }); })((typeof window.jQuery == 'undefined' && typeof window.django != 'undefined') ? django.jQuery : jQuery);
f6c26ffb12610e1fa6143c981909f9a484cc35f5
[ "reStructuredText", "JavaScript", "Markdown", "Python", "Text" ]
15
Python
silentsokolov/django-treasuremap
9f047a55860368393bdd86ef42e61fd8c0e1ee74
c4e8eaa52b7292681b5dd2fbb4c150763baedfe3
refs/heads/master
<file_sep>## 嘗試用最新版gradle 5.4.1 與 JDK12 去建構 Spring boot 微服務專案 ### build.gradle新增 plugins { id 'java' id 'org.springframework.boot' version '2.1.5.RELEASE' id 'io.spring.dependency-management' version '1.0.7.RELEASE' } dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' compile("org.springframework.boot:spring-boot-starter-web") //classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.10.RELEASE") } ### 其他就依循Spring Boot 啟動設計Java 的 @SpringBootApplication<file_sep>package com.idv.main.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HsiController { @GetMapping("/Hello") public String hello(){ return "Hello World"; } }
31aa2af93bb32c4aef9e68841242c0af4481adc4
[ "Markdown", "Java" ]
2
Markdown
seanjef/boot
c1f4ea15527ae866e809d5e7fe66bd214fae6bc6
bf524682042867d7656ffb6eb20f6724bd736727
refs/heads/master
<repo_name>schoolsplay/slimmemeter-rpi<file_sep>/start_server.sh #!/usr/bin/env bash cd /home/pi/slimmemeter-rpi/rspiWebServer || exit python3 app.py <file_sep>/P1uitlezen.py # DSMR P1 uitlezen import time versie = "1.0" import sys import serial ############################################################################## # Main program ############################################################################## print("DSMR P1 uitlezen (raw)", versie) print("Control-C om te stoppen") print("Pas eventueel de waarde ser.port aan in het python script") input("Hit any key to start") # Set COM port config (dsmr4.2) # ser = serial.Serial() # ser.baudrate = 9600 # ser.bytesize = serial.SEVENBITS # ser.parity = serial.PARITY_EVEN # ser.stopbits = serial.STOPBITS_ONE # ser.xonxoff = 0 # ser.rtscts = 0 # ser.timeout = 20 # Set COM port config (dsmr 5.0) ser = serial.Serial() ser.baudrate = 115200 ser.bytesize = serial.SEVENBITS ser.parity = serial.PARITY_EVEN ser.stopbits = serial.STOPBITS_ONE ser.xonxoff = 0 ser.rtscts = 0 ser.timeout = 20 ser.port = "/dev/ttyUSB0" # Open COM port try: ser.open() except Exception as e: print(f"Error opening COM: {e}") sys.exit("Fout bij het openen van %s. Aaaaarch." % ser.name) p1_lines = [] p1_teller = 0 runme = True while runme: p1_line = '' # Read 1 line try: p1 = ser.readline() except Exception as e: print(e) sys.exit("Error reading serial socket") else: p1 = p1.decode() print("raw", p1) if p1.startswith('1-3:0.2.8'): # start of telegram, we continue print("start of telegram found, continue") p1_lines.append(p1) runme = False else: print("No telegram start found, polling after 2 seconds") time.sleep(2) runme = True while runme: p1_line = '' # Read 1 line try: p1 = ser.readline() except Exception as e: print(e) sys.exit("Error reading serial socket") else: p1 = p1.decode() print("raw", p1) if p1[0].isdigit(): print(f"line {p1_teller} => {p1}") p1_lines.append(p1) elif p1.startswith("!"): # end of a telegram p1_lines.append(p1) break p1_teller = p1_teller + 1 with open('telegram-dsrm50.txt', 'w') as f: f.writelines(p1_lines) print("telegram written to telegram-dmsr50.txt") # Close port try: ser.close() except: sys.exit("Oops %s. Programma afgebroken. Kon de seriele poort niet sluiten." % ser.name) print('Done.')<file_sep>/P1Reader/P1_reader_dsmr50.py # Module to read, parse and store in a sqlite db telegrams from # from a dutch smart meter (slimme meter). # Meant as a single shot to be called from a cron script. # You need to check the exit code as this will exit on error with only a print statement. import os import sqlite3 import sys import time import serial from DSMR50 import obis, obis2dbcol # Set COM port config ser = serial.Serial() ser.baudrate = 115200 ser.bytesize = serial.SEVENBITS ser.parity = serial.PARITY_EVEN ser.stopbits = serial.STOPBITS_ONE ser.xonxoff = 0 ser.rtscts = 0 ser.timeout = 20 ser.port = "/dev/ttyUSB0" db_path = 'dsmr50.1.sqlite' # differences between old meter and the new one. # See email stedin 13-10-2022 old_1 = 10479 - 1517 old_2 = 13317 - 1508 old_t1 = 1944 - 152 old_t2 = 4337 - 388 def stop(v): try: ser.close() except Exception: pass sys.exit(v) def make_db(db_path): cmd1 = """ create table electric ( id INTEGER not null primary key autoincrement, created_at TEXT, delivered_1 REAL, delivered_2 REAL, returned_1 REAL, returned_2 REAL, actual_delivering REAL, actual_returning REAL ); """ cmd2 = """ create table gas ( id INTEGER not null constraint gas_pk primary key autoincrement, created_at TEXT, gas_delivered REAL ); """ conn = sqlite3.connect(db_path) cur = conn.cursor() try: cur.execute(cmd1) cur.execute(cmd2) conn.commit() except Exception as e: print(f"Failed to create dbase: {e}") stop(4) finally: conn.close() def read_com(): # Open COM port try: ser.open() except Exception as e: print(f"Error opening COM: {e}") stop(1) read_trys = 30 # we don't poll until the end of time while read_trys: # Read 1 line try: p1 = ser.readline() except Exception as e: print(e) print("Error reading serial socket, continuing") if not read_trys: print("No start of telegram found, read timeout, quitting") stop(1) else: read_trys = - 1 time.sleep(10) else: p1 = p1.decode() print("raw", p1) if p1.startswith('1-3:0.2.8'): # start of telegram, we continue print("start of telegram found, continue") read_trys = 0 else: print("No telegram start found, continuing polling") if not read_trys: print("No start of telegram found, read timeout, quitting") stop(2) else: read_trys = - 1 # If we come here we have a start of a telegram p1_lines = [] runme = True while runme: p1_line = '' # Read 1 line try: p1 = ser.readline() except Exception as e: print(e) # we don't try again as this error means trouble after the above read stop(3) else: try: p1 = p1.decode('ascii') except UnicodeError as e: print(f"Failed to decode: {p1} => {e}") stop(6) if p1[0].isdigit(): print(f"read => {p1}") p1_lines.append(p1) elif p1.startswith("!"): # end of a telegram print("end of telegram") ser.close() break return p1_lines def parse_telegram(telegram): for line in telegram: line = line.strip() if line[0].isdigit(): print(f"raw line => {line}") try: key, val = line.split('(', 1) except Exception as e: print(f"failed to parse line: {e}") stop(6) if key not in obis2dbcol.keys(): print(f"key {key} not found in obis, continuing") continue if '0-1:24.2.1' in key: # special case for gas, key value is different print(f"gas key, val: {key}, {val}") val = val.split(')(') val[1] = val[1][:-4] try: val[1] = float(val[1]) except Exception as e: print(f"Failed to floatify val: e") stop(6) else: val[0] = f"20{val[0][0:2]}-{val[0][2:4]}-{val[0][4:6]} {val[0][6:8]}:{val[0][8:10]}:{val[0][10:12]}" else: val = val[:-1] # loose last ) if key in ('1-0:1.8.1', '1-0:1.8.2', '1-0:2.8.1', '1-0:2.8.2', '1-0:1.7.0', '1-0:2.7.0'): # these are Kw values val = val[:-4] try: val = float(val) except Exception as e: print(f"Failed to floatify val: e") stop(6) if key == '1-0:1.7.0' or key == '1-0:2.7.0': # we convert into Watts iso KW for current usage val = val * 1000 # here we make some adjustments, the meter was a refurbished one with old values if key == '1-0:1.8.1': val = val + old_1 elif key == '1-0:1.8.2': val = val + old_2 elif key == '1-0:2.8.1': val = val + old_t1 elif key == '1-0:2.8.2': val = val + old_t2 if type(val) is str and val.endswith('S'): # it's a timestamp val = f"20{val[0:2]}-{val[2:4]}-{val[4:6]} {val[6:8]}:{val[8:10]}:{val[10:12]}" obis[key] = val return obis def validate(db_dict): #print(db_dict) if not db_dict['created_at'] or '-' not in db_dict['created_at'] or ':' not in db_dict['created_at']: return False if not db_dict['delivered_1'] or not db_dict['delivered_2'] or not db_dict['returned_1'] or not db_dict['returned_2']: return False if not db_dict['gas_delivered'] or '-' not in db_dict['gas_delivered'][0] or '-' not in db_dict['gas_delivered'][0]: return False return True def store(telegram): db_dict = {} for k, v in telegram.items(): if k in obis2dbcol.keys(): db_dict[obis2dbcol[k]] = v if not validate(db_dict): print("invalid values, skipping this one") stop(5) gas_date, m3 = db_dict['gas_delivered'] del db_dict['gas_delivered'] conn = sqlite3.connect(db_path) cur = conn.cursor() try: cur.execute("INSERT INTO electric VALUES (NULL, :created_at, :delivered_1, :delivered_2, " ":returned_1, :returned_2, :actual_delivering, :actual_returning)", db_dict) cur.execute("INSERT INTO gas (id, created_at, gas_delivered) VALUES(NULL, ?, ?)", (gas_date, m3)) conn.commit() except Exception as e: print(f"Failed to commit to dbase: {e}") conn.rollback() finally: conn.close() def main(): telegram = read_com() if len(telegram) != 34: print(f"Incomplete telegram, is {len(telegram)} lines iso 34") stop(3) obis_dict = parse_telegram(telegram) # here we fetch the values we interested in from the telegram to put into our dbase store(obis_dict) if __name__ == '__main__': if not os.path.exists(db_path): make_db(db_path) if len(sys.argv) > 1: # Testing purposes import pprint with open(sys.argv[1], 'r') as f: lines = f.readlines() obis_dict = parse_telegram(lines) pprint.pprint(obis_dict) store(obis_dict) else: main() <file_sep>/P1Reader/run_reader.sh #!/usr/bin/env bash # call this from crontab # we try a few times as the serial output can be crappy. for i in 1 2 3 4 5 6; do python3.9 P1_reader_dsmr50.py if [ $? -eq 0 ]; then break fi done <file_sep>/P1uitlezer-DSMR42-py3.py # # DSMR P1 uitlezer # (c) 10-2012 2016 - GJ - gratis te kopieren en te plakken PRODUCTION = True from datetime import datetime import sqlite3 from pprint import pprint versie = "1.2-py3" import sys import serial ################ # Error display # ################ def show_error(mesg=''): ft = sys.exc_info()[0] fv = sys.exc_info()[1] print("Fout in %s type: %s" % (mesg, ft)) print("Fout waarde: %s" % fv) return def halt(mesg="Clean exit", ret=0): print(mesg) # Close port and show status try: ser.close() except: show_error(ser.name) # in *nix you should pass 0 for succes or >0 when it fails as exitr value sys.exit(1) sys.exit(ret) ################################################## # Main program ################################################## print("DSMR 4.2 P1 uitlezer", versie) print("Control-C om te stoppen") # Set COM port config ser = serial.Serial() ser.baudrate = 115200 ser.bytesize = serial.SEVENBITS ser.parity = serial.PARITY_EVEN ser.stopbits = serial.STOPBITS_ONE ser.xonxoff = 0 ser.rtscts = 0 ser.timeout = 20 ser.port = "/dev/ttyUSB0" # Open COM port try: ser.open() except: show_error(ser.name) halt("Error opening serial socket", ret=1) # Initialize # stack is mijn list met de 36 regeltjes. p1_teller = 0 t_lines = {} db_t_lines = [None] # Test # with open('test-telegram.txt', 'r') as f: # lines = f.readlines() while p1_teller < 36: p1_line = '' # Read 1 line try: p1 = ser.readline() # if lines: # p1 = lines.pop(0) # else: # break except Exception as e: print(e) show_error(ser.name) halt("Error reading serial socket", ret=2) else: p1 = p1.decode() #print("raw output", p1) if p1[0].isdigit(): #print(p1) key, val = p1.strip().split('(', 1) db_t_lines.append(val.strip(")")) # strip the ) to get original value for dbase val = val[:-1] # loose last ) if "*kW" in val: val = val.split('*kW')[0] t_lines[key] = val elif p1.startswith("!"): # end of a telegram break p1_teller = p1_teller + 1 #print(len(t_lines), "total lines") if len(t_lines) != 30: halt("No valid telegram received?", ret=3) # strore the data into the dbase first #pprint(db_t_lines) t = datetime.now().astimezone().isoformat() db_t_lines.append(t) con = sqlite3.connect('dsmr42.sqlite') cur = con.cursor() placeholders = ', '.join('?' * len(db_t_lines)) sql = 'INSERT INTO telegrams VALUES ({})'.format(placeholders) #print(sql, db_t_lines) cur.execute(sql, db_t_lines) con.commit() if PRODUCTION: sys.exit(0) meter = 0 for key, val in t_lines.items(): #print(key, val) if key == "1-0:1.8.1": print("{:<30s} {:<10} KW".format("totaal laagtarief verbruik", val)) meter += int(float(val)) elif key == "1-0:1.8.2": print("{:<30s} {:<10} KW".format("totaal hoogtarief verbruik", val)) meter += int(float(val)) elif key == "1-0:2.8.1": print("{:<30s} {:<10} KW".format("totaal laagtarief retour", val)) meter -= int(float(val)) elif key == "1-0:2.8.2": print("{:<30s} {:<10} KW".format("totaal hoogtarief retour", val)) meter -= int(float(val)) elif key == "1-0:1.7.0": print("{:<30s} {:<10} W".format("huidig afgenomen vermogen", float(val) * 1000)) elif key == "1-0:2.7.0": print("{:<30s} {:<10} W".format("huidig teruggeleverd vermogen", float(val) * 1000)) print("{:<30s} {:<10} KW {:<10}".format("meter totaal", meter, "afgenomen/teruggeleverd van het net")) <file_sep>/README.md # Slimme meter info Code is forked from: https://github.com/gejanssen/slimmemeter-rpi Telegram codes and explanation: http://domoticx.com/p1-poort-slimme-meter-hardware/ en de NL netbeheerders pdf: Slimme_meter_15_a727fce1f1.pdf ## Korte uitleg over slimme meters (Taken from domotix) ### Wat is een P1 poort? De P1 poort is een seriele poort (is optioneel) op je digitale elektra meter waarin je een RJ-11 (Registered Jack) stekkertje kan steken (bekend van de telefoonaansluitingen) om zo de meterstanden en het verbruik uit te lezen. Het is niet mogelijk om gegevens naar de poort te sturen! Onderaan deze pagina heb ik de informatiebladen “Dutch Smart Meter Requirements” (DSMR) toegevoegd. ### Niet standaard (zie DSMR v4.04, Hfdst 4.6 “signals”) Deze seriele poort is echter niet standaard, ondanks dat hij op UART TTL niveau werkt, zijn de logische waarden omgedraaid: 1=0 en 0=1 ,dit is softwarematig op te lossen, maar geeft niet altijd het gewenste resultaat, oplossing is om dit hardwarematig te doen, bijvoorbeeld met een chip ertussen te plaatsen vaak wordt een MAX232 of 7404 gebruikt. Volgens de specificatie kan de poort max. 15v aan, dus een echt RS232 signaal (+12v) vanuit een “echte” com poort moet hij aan kunnen. De P1 poort stuurt alleen maar data als de RTS pin is voorzien van >+5v ten opzichte van de GND (-), zolang de spanning daarop blijft staan wordt er elke 10 seconden een “telegram” verzonden op de TxD ### Voorbeeld van een telegram, zie Dit voorbeeld is van een Landis 360 DSRM5.0 telegram-dsrm50.txt ## Connect to the meter To connect to the meter you need a serial2usb cable. Not a normal one but a special cable. You can make it yourself, search the internet if you fancy some soldering. I just buy it on aliexpress :-) Search for "Dutch Smart Meter" and you have a cable for 5 euros :-) Make sure to include your type of meter as there are differences between various meters. Also check the reviews for dutch reviewers to make sure you will get a working cable for your meter. ## Code dependencies: flask pyserial ## Pull the meter for a telegram We use a crontab to pull every 2 minutes a new telegram from the meter. (Uncomment the last part to get some output for testing) ```*/2 * * * * /home/pi/slimmemeter-rpi/pull.sh #>>/tmp/cronrun 2>&1``` ## Setup server as a systemd service To start the flask server use the systemd service. (make sure start_server.sh is chmod a+x) ``` cp appWebserver.service to /etc/systemd/system/ pi@raspberrypi:~ $ sudo systemctl start appWebserver pi@raspberrypi:~ $ sudo systemctl status appWebserver ● appWebserver.service - Flask Webserver Loaded: loaded (/etc/systemd/system/appWebserver.service; disabled; vendor preset: enabled) Active: active (running) since Wed 2019-10-30 15:10:18 CET; 8s ago Main PID: 11334 (bash) Memory: 18.8M CGroup: /system.slice/appWebserver.service ├─11334 bash /home/pi/slimmemeter-rpi/start_server.sh └─11335 python3 appWebserverHist.py okt 30 15:10:18 raspberrypi systemd[1]: Started Flask Webserver. pi@raspberrypi:~ $ And enable it so that systemd will make it part of the setup pi@raspberrypi:~ $ sudo systemctl enable appWebserver Created symlink /etc/systemd/system/multi-user.target.wants/appWebserver.service → /etc/systemd/system/appWebserver.service. pi@raspberrypi:~ $ ``` <file_sep>/sql2csv.py import datetime import re import sqlite3 dbpath = 'dsmr50.sqlite' numSamples = 0 # meaning all entries db_col = '1-0:1.7.0' csv_name = 'KW-usage.csv' def getDatetimeObject(iso_string): if iso_string.find('.') == -1: # when we don't have a decimal the datetime fails a, b = iso_string.split('+') iso_string = "{}.0+{}".format(a, b) timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', iso_string) return datetime.datetime.strptime(timestamp, "%Y%m%dT%H%M%S.%f%z") conn = sqlite3.connect(dbpath) curs = conn.cursor() if numSamples == 0: curs.execute("select COUNT(id) from telegrams") numSamples = curs.fetchall()[0][0] print("getting {} number of samples".format(numSamples)) curs.execute("SELECT `timestamp` FROM telegrams ORDER BY timestamp ASC LIMIT 1") timestamp_start = getDatetimeObject(curs.fetchone()[0]) curs.execute("SELECT `timestamp` FROM telegrams ORDER BY timestamp DESC LIMIT 1") timestamp_end = getDatetimeObject(curs.fetchone()[0]) curs.execute("SELECT `{}`, `timestamp` FROM telegrams ORDER BY timestamp ASC LIMIT ".format(db_col) + str(numSamples)) data = curs.fetchall() datalist = [(v.split('*')[0], getDatetimeObject(ts)) for v, ts in data if '*' in v] csvlist = "" for v, dt in datalist: csvlist += "{},{}_{}:{}\r\n ".format(v, dt.date(), dt.hour, dt.minute) with open(csv_name, 'w') as f: f.write(csvlist) print("Done, your list is in {}".format(csv_name)) <file_sep>/clean_db.py #!/usr/bin/env python3 # script for use in a crontab for cleaning dbase # it removes rows older than 21 days import sqlite3 import sys dbpath = sys.argv[1] sql = """DELETE FROM telegrams WHERE timestamp <= date('now','-21 day'); """ con = sqlite3.connect(dbpath) cur = con.cursor() cur.execute(sql) con.commit() <file_sep>/P1Reader/rspiWebServer/utils.py import datetime import sqlite3 db_path = '../dsmr50.1.sqlite' # f'{item[1]:.2f}' def get_returning(today=True): raw_d = {} data = [] conn = sqlite3.connect(db_path) cur = conn.cursor() if today: now = str(datetime.date.today()) cur.execute(f"SELECT created_at, actual_returning FROM electric WHERE created_at BETWEEN '{now} 00:00:00' AND '{now} 23:59:59'") else: cur.execute( f"SELECT created_at, actual_returning FROM electric") for k, v in cur.fetchall(): k = k.split(' ')[1][:2] # we only want the hour for our graph label if k not in raw_d.keys(): raw_d[k] = [(k, v)] else: raw_d[k].append(('.', v)) for k in sorted(raw_d): data += raw_d[k] return data if __name__ == '__main__': print(get_returning())
776a8d5a1e71777ca8cd1b4978acafaf48c63d27
[ "Markdown", "Python", "Shell" ]
9
Shell
schoolsplay/slimmemeter-rpi
6b8e30fed39b72d098e70203abcf9dc6287d45d4
701b698af4cb0d910a394e473ada016d1598fe57
refs/heads/master
<file_sep>class Fetch def get_words d = "" a = [] d = Nokogiri::HTML(open("http://cutup.heroku.com/thedocument")) document = d.css('div#container').each do |c| a << c a = a.to_s end a = a.gsub(/<\/?[^>]*>/, "") new = a.split(/ /) num = new.size one = rand(num) two = rand(num) three = rand(num) words = new[one] words << " " words << new[two] words << " " words << new[three] puts words words = URI.escape(words) doc = Nokogiri::HTML(open("http://www.google.com/search?q=#{words}")) new = [] #sorts thru google search results and creates array with each doc.css('h3.r a.l').each do |link| new << link end #this loops through search results, finds urls for each, and returns first one that contains ".html" result = [] new.each do |p| if p.values[0] =~ /\.html/ result << p.values[0] break p end end #if result is nil, run code again if result.empty? puts "result is empty" return nil else #this gives us a valid url to pass into nokogiri r = result.to_s #print url (for testing) puts r doc2 = Nokogiri::HTML(open(r)) new2 = [] doc2.css('p').each do |text| text = text.to_s.gsub(/<\/?[^>]*>/, "") #this assures that html markup is removed from result new2 << text end #OK - so this will find the <p> element with the most num of characters and store it in array "arr" char = 0 arr = [] new2.each do |c| d = c.to_s.count c if d > char char = d arr.clear arr << c end end #not long enough to return a useful response - 21 is an arbitrary length I chose if arr.inspect.length < 21 puts "less than 21" return nil else #This splits the arr into "sentence" elements and holds on to longest one, storing it in "final" arr = arr.to_s.split(".") p = 0 final = [] arr.each do |c| longest = c.to_s.count c if longest > p p = longest final.clear final << c end end final end end end end<file_sep>require 'fetch' require 'nokogiri' require 'open-uri' class Generate def call(env) request = Rack::Request.new(env) if request.post? val = Fetch.new final = val.get_words while final == nil ; final = val.get_words ; end #add final period unless punctuation already exists at end of string if final.slice(-1,1) =~ /\.|\?|\!/ final = final.to_s else final = final.to_s + "." end final = final.gsub(/<\/?[^>]*>/, "") final = final.squeeze(" ") else final = "" end header = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <title>Kill The Buddha!</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"/stylesheets/wild.css\" /> <script type=\"text/javaScript\" src=\"/js/jquery.js\"></script> <script type=\"text/javaScript\" src=\"/js/javascript.js\"></script> </head>" body = "<body> <div class=\"overlay\"> <div id=\"container\"> <p><img src=\"images/kill.jpg\"</p> <span class=\"box\"> <form name=\"process\" action=\"\" method=\"post\"> <span class=\"click\"><button id=\"process\"><img src=\"images/buddha.jpg\"</button></span> </form> </span> <div class=\"loading\">SEARCHING...</div> <div class=\"event\"></div> <div class=\"response\">#{final}</p></div> </div> <div class=\"header\"> <div class=\"header_bar\"><a class=\"whatClick\">What?</a></div> <div class=\"header_bar\"><a class=\"howClick\">How?</a></div> <div class=\"header_bar\"><a class=\"whyClick\">Why?</a></div> </div> <div class=\"what\"> <p><i>Kill the Buddha!</i> is a unique web experience. You can't post or share anything here, and nothing has been curated for you. This site doesn't store anything, doesn't connect you to anything, but responds to your requests in a surprising (and delightful) way. </p> </div> <div class=\"how\"> <p> Clicking on the Golden Buddha will execute a google search using 3 random words (pulled from <a href=\"http://cutup.heroku.com/thedocument\">here</a>). After processing for a few moments, a response will be displayed below. The responses range from the banal to the sublime. </p> </div> <div class=\"why\"> <p>Wrong question! </p> </div> </div> </body> </html>" [ 200, {"Content-Type" => "text/html"}, [header + body] ] end end <file_sep>require 'generate' gen = Generate.new builder = Rack::Builder.new do use Rack::ShowExceptions use Rack::Static, :urls => [ "/stylesheets", "/images", "/js" ] use Rack::Reloader map '/' do run gen end map '/*' do run gen end end run builder <file_sep> $(document).ready(function() { $('.loading').hide(); $('.loading').ajaxStart(function() { $('.response').hide(); $('.loading').fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn(); }); $('.click').click(function() { $('.response').load(''); }); $('.what').hide(); $('.how').hide(); $('.why').hide(); $('.whatClick').click(function() { $('.how').hide(); $('.why').hide(); $('.what').show('slow'); }); $('.howClick').click(function() { $('.what').hide(); $('.why').hide(); $('.how').show('slow'); }); $('.whyClick').click(function() { $('.how').hide(); $('.what').hide(); $('.why').show('slow'); }); $('.overlay').click(function() { $('.how').hide(); $('.what').hide(); $('.why').hide(); }) })
2a610f29bd733208490e713c59bbbd18ac00b736
[ "JavaScript", "Ruby" ]
4
Ruby
mkarges/kill_the_buddha
d68e6867fea06fdb8c74dbf2f247d026176e36f3
c9395c94f89e347087bd6ac893c5db2f3e845078
refs/heads/master
<repo_name>camargoguilherme/api-filmes-teste<file_sep>/src/models/episodio.js const mongoose = require('mongoose'); const EpisodioSchema = mongoose.Schema({ title: String, uri: String, uriVideo: [String], referer: String, dublado: Boolean }, { timestamps: true }); module.exports = mongoose.model('Episodio', EpisodioSchema);<file_sep>/src/controllers/temporadaController.js const Temporada = require('../models/temporadaModel'); class TemporadaController{ // Create and Save a new Temporada async create(req, res){ // Validate request console.log(req.body) if(!req.body.temporada && !req.body.serieId) { return res.status(400).send({ message: "As informacoes da temporada não pode ser vazio" }); } // Create a Temporada const temporada = new Temporada({ serieId: req.body.serieId, temporadas: req.body.temporadas }); // Save Temporada in the database temporada.save() .then(data => { res.send(data); }).catch(err => { res.status(500).send({ message: err.message || "Some error occurred while creating the Temporada." }); }); }; // Retrieve and return all temporadas from the database. async findAll(req, res){ Temporada.find({}, {_id:1, serieId:1, temporadas:1 }) .then(temporadas => { res.send(temporadas); }).catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving temporadas." }); }); }; // Find a single temporada with a temporadaId async findOne(req, res){ Temporada.find({serieId: req.params.serieId}, {_id:1, serieId:1, temporadas:1 }) .then(temporada => { if(!temporada) { return res.status(404).send({ message: "Temporada not found with id " + req.params.serieId }); } res.send(temporada); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "Temporada not found with id " + req.params.serieId }); } return res.status(500).send({ message: "Error retrieving temporada with id " + req.params.temporadaId }); }); }; // Update a temporada identified by the temporadaId in the request async update(req, res){ // Validate Request if(!req.body.content) { return res.status(400).send({ message: "Temporada content can not be empty" }); } // Find temporada and update it with the request body Temporada.findByIdAndUpdate(req.params.temporadaId, { title: req.body.title || "Untitled Temporada", content: req.body.content }, {new: true}) .then(temporada => { if(!temporada) { return res.status(404).send({ message: "Temporada not found with id " + req.params.temporadaId }); } res.send(temporada); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "Temporada not found with id " + req.params.temporadaId }); } return res.status(500).send({ message: "Error updating temporada with id " + req.params.temporadaId }); }); }; // Delete a temporada with the specified temporadaId in the request async delete(req, res){ Temporada.findByIdAndRemove(req.params.temporadaId) .then(temporada => { if(!temporada) { return res.status(404).send({ message: "Temporada not found with id " + req.params.temporadaId }); } res.send({message: "Temporada deleted successfully!"}); }).catch(err => { if(err.kind === 'ObjectId' || err.name === 'NotFound') { return res.status(404).send({ message: "Temporada not found with id " + req.params.temporadaId }); } return res.status(500).send({ message: "Could not delete temporada with id " + req.params.temporadaId }); }); }; } <file_sep>/src/controllers/userController.js const User = require('../models/userModel'); class UserController{ // Create and Save a new User async create(req, res){ let username = req.body.username; let fullname = req.body.fullname; let password = req.body.password; let email = req.body.email; console.log(req.body) if (username && password) { User.create({ username : username, fullname: fullname, email : email, password : <PASSWORD>, admin: false }, function (err, user) { if (err) return res.status(500).send({"error":err, "message":"There was a problem registering the user."}) // create a token /* var token = jwt.sign({ id: user._id }, process.env.JWT_WORD, { expiresIn: 86400 // expires in 24 hours }); */ res.status(200).send({ auth: true, token: token }); }); }else{ res.status(400).send({ "message": "campos obrigatorios" }); } }; // Retrieve and return all users from the database. async findAll(req, res){ User.find() .then(users => { res.send(users); }).catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving users." }); }); }; // Find a single user with a userId async findOne(req, res){ User.findById(req.params.userId) .then(user => { if(!user) { return res.status(404).send({ message: "User not found with id " + req.params.userId }); } res.send(user); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "User not found with id " + req.params.userId }); } return res.status(500).send({ message: "Error retrieving user with id " + req.params.userId }); }); }; // Update a user identified by the userId in the request async update(req, res){ console.log(req.body) // Find user and update it with the request body User.findOneAndUpdate({_id: req.params.userId}, req.body, {upsert: true}, function (err, user) { if (err) res.status(404).send({status: 'error', message: err}); res.send(user); } ) .then(/*user => { if(!user) { return res.status(404).send({ message: "User not found with id " + req.params.userId }); } res.send(user); }*/).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "User not found with id " + req.params.userId }); } return res.status(500).send({ message: "Error updating user with id " + req.params.userId }); }); }; // Delete a user with the specified userId in the request async delete(req, res){ User.findByIdAndRemove(req.params.userId) .then(user => { if(!user) { return res.status(404).send({ message: "User not found with id " + req.params.userId }); } res.send({message: "User deleted successfully!"}); }).catch(err => { if(err.kind === 'ObjectId' || err.name === 'NotFound') { return res.status(404).send({ message: "User not found with id " + req.params.userId }); } return res.status(500).send({ message: "Could not delete user with id " + req.params.userId }); }); }; } <file_sep>/src/controllers/filmeController.js const Filme = require('../models/filmeModel'); class FilmeController{ // Create and Save a new Movie async create(req, res){ // Validate request if(!req.body.filme) { return res.status(400).send({ message: "Informações do filmes nao podem estar vazias" }); } // Create a Movie const filme = new Filme({ titulo: '', posterStart: '', uriPage: '', uri: '', resumo: '', img: '', }); // Save Movie in the database filme.save() .then(data => { res.send(data); }).catch(err => { res.status(500).send({ message: err.message || "Ocorreu um erro ao gravar o filme" }); }); }; // Retrieve and return all movies from the database. async findAll(req, res){ Filme.find() .then(filmes => { res.send(filmes); }).catch(err => { res.status(500).send({ message: err.message || "Ocorreu um erro ao recuperar os filmes" }); }); }; // Find a single movie with a filmeId async findOne(req, res){ Filme.findById(req.params.filmeId) .then(filme => { if(!filme) { return res.status(404).send({ message: "Nenhum filme encontrada com id " + req.params.filmeId }); } res.send(filme); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: `Filme ${req.params.filmeId} não encontrado` }); } return res.status(500).send({ message: "Error retrieving movie with id " + req.params.filmeId }); }); }; // Update a note identified by the noteId in the request async update(req, res){ // Validate Request if(!req.body.content) { return res.status(400).send({ message: "Informações do filmes nao podem estar vazias" }); } // Find note and update it with the request body Filme.findByIdAndUpdate(req.params.filmeId, { title: req.body.title || "Untitled Movie", content: req.body.content }, {new: true}) .then(filme => { if(!filme) { return res.status(404).send({ message: `Filme ${req.params.filmeId} não encontrado` }); } res.send(filme); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: `Filme ${req.params.filmeId} não encontrado` }); } return res.status(500).send({ message: "Error updating movie with id " + req.params.filmeId }); }); }; // Delete a note with the specified noteId in the request async delete(req, res){ Filme.findByIdAndRemove(req.params.filmeId) .then(filme => { if(!filme) { return res.status(404).send({ message: `Filme ${req.params.filmeId} não encontrado` }); } res.send({message: "Filme Deletado com sucesso!"}); }).catch(err => { if(err.kind === 'ObjectId' || err.name === 'NotFound') { return res.status(404).send({ message: `Filme ${req.params.filmeId} não encontrado` }); } return res.status(500).send({ message: `Filme ${req.params.filmeId} não encontrado` }); }); }; } <file_sep>/README.md # api-filmes-teste<file_sep>/src/routes/index.js const { Router } = require('express'); const router = new Router(); var User = require('../models/user'); var jwt = require('jsonwebtoken'); var { isAuthenticate, authenticate } = require('../auth/authServices'); /** * @api {post} /login Login * @apiGroup Auth * * @apiParam {String} username Usuário. * @apiParam {String} password <PASSWORD>. * * @apiParamExample {json} Login exemplo: * { * "username": "username-example", * "password": "<PASSWORD>" * } * * @apiSuccessExample {json} Sucesso * HTTP/1.1 200 OK * { * auth: true, * _id: "5bd08c3304bf<PASSWORD>", * username: "teste", * token: "<KEY>" * } * * @apiErrorExample {json} Usuário ou senha inválidos * HTTP/1.1 401 OK * { * message: "usuário ou senha inválidos" * } * * @apiErrorExample {json} Usuário não encontrado * HTTP/1.1 401 OK * { * message: "usuário não encontrado" * } */ router.post('/login', authenticate); /** * @api {post} /signup Signup * @apiGroup Auth * * @apiParam {String} username Usuário. * @apiParam {String} password <PASSWORD>. * @apiParam {String} fullname Nome completo. * @apiParam {String} email Email. * * @apiParamExample {json} Signup exemplo: * { * "username": "teste", * "password": "<PASSWORD>", * "fullname": "Teste Teste", * "email": "<EMAIL>" * } * * @apiSuccessExample {json} Sucesso * HTTP/1.1 200 OK * { * auth: true, * _id: "5bd08c3304bf9a313bb9daf6", * username: "teste", * token: "<KEY>" * } */ router.post('/signup', function (req, res, next) { let username = req.body.username; let fullname = req.body.fullname; let password = req.body.password; let email = req.body.email; console.log(req.body) if (username && password) { User.create({ username : username, fullname: fullname, email : email, password : <PASSWORD>, admin: false }, function (err, user) { if (err) return res.status(500).send({"error":err, "message":"There was a problem registering the user."}) // create a token var token = jwt.sign({ id: user._id }, process.env.JWT_WORD, { expiresIn: 86400 // expires in 24 hours }); res.status(200).send({ auth: true, token: token }); }); }else{ res.status(400).send({ "message": "campos obrigatorios" }); } }) /** * @api {get} /logout Logout * @apiGroup Auth * * @apiSuccess {Object[]} profiles List of user profiles. * @apiSuccess {Number} profiles.age Users age. * @apiSuccess {String} profiles.image Avatar-Image. */ router.get('/logout', function (req, res, next) { if (req.session) { // delete session object req.session.destroy(function (err) { if (err) { return next(err); } else { return res.redirect('/'); } }); } }); /** * @api {post} /authenticated Authenticated * @apiGroup Auth * * @apiHeader {String} x-access-token Token. * * @apiHeaderExample {json} Header Exemplo * { * "x-access-token":"<KEY>" * } * * @apiErrorExample {json} Nenhum token fornecido * HTTP/1.1 401 OK * { * auth: false, * message: "Nenhum token fornecido" * } * * @apiErrorExample {json} Falha ao autenticar token * HTTP/1.1 500 OK * { * auth: false, * message: "Falha ao autenticar token" * } */ router.get('/authenticated', (req, res, next) =>{ var token = req.headers['x-access-token']; if (!token) return res.status(401).send({ auth: false, message: 'Nenhum token fornecido' }); jwt.verify(token, process.env.JWT_WORD, function(err, decoded) { if (err) return res.status(500).send({ auth: false, message: 'Falha ao autenticar token' }); //res.status(200).send(decoded); res.status(200).send({ auth: true, token: token }); }); }); module.exports = router;<file_sep>/src/app.js const express = require('express'); const app = express(); var cors = require('cors') const bodyParser = require('body-parser'); var session = require('express-session'); var MongoStore = require('connect-mongo')(session); var compression = require('compression'); const { isAuthenticate } = require('./auth/authServices'); // Configuring the database const mongoose = require('mongoose'); mongoose.Promise = global.Promise; // Connecting to the database mongoose.connect(process.env.URL_DEV || process.env.URL, { useNewUrlParser: true }).then(() => { console.log("Successfully connected to the database"); if(process.env.URL_DEV) console.log('Conetado a base de Desenvolvimento') else console.log('Conetado a base de Produção') }).catch(err => { console.log('Could not connect to the database. Exiting now...', err); process.exit(); }); var db = mongoose.connection; //handle mongo error db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function () { // we're connected! }); app.use(cors()); app.use(compression()); //Rotas // const index = require('./routes/index'); const parser = require('./routes/parser'); // const filme = require('./routes/filmes'); // const serie = require('./routes/series'); // const temporada = require('./routes/temporadas'); // const user = require('./routes/user'); app.use(bodyParser.json()); // support json encoded bodies app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies //prefix url const prefix = '/api/v1'; /** * @api {get} / Status * @apiGroup Status * @apiSuccess {String} status Mensagens de status da API * @apiSuccessExample {json} Sucesso * HTTP/1.1 200 OK * { * title: "Node Express API", * version: "0.0.1" * } */ app.get('/', function(req, res, next){ return res.redirect(prefix) }) app.get(prefix, function(req, res, next){ return res.redirect(prefix+'/apidoc') }) app.get(prefix+'/status', function (req, res, next) { res.status(200).send({ title: "Node Express API", version: "0.0.1" }); }); app.use(prefix, express.static("public")) // app.use(prefix, index); // app.use(isAuthenticate); app.use(prefix, parser); // app.use(prefix, filmes); // app.use(prefix, series ); // app.use(prefix, temporada); // app.use(prefix, user); /* //use sessions for tracking logins app.use(session({ secret: 'work hard', resave: true, saveUninitialized: false, store: new MongoStore({ mongooseConnection: db }) }));*/ module.exports = app;<file_sep>/src/routes/parser.js const express = require('express'); const router = express.Router(); const parserController = require('../controllers/parserController'); var { isAdmin } = require('../auth/authServices'); /** * @apiDefine admin Acesso permitido para admins * O acesso a esse endpoint é permitido apenas para usuários admin */ /** * @api {get} /parser/filmes Parsear Filmes * @apiGroup Parser * @apiPermission admin */ router.get('/parser/filmes', parserController.filmes); /** * @api {get} /parse/series Parsear Series * @apiGroup Parse * @apiPermission admin */ router.get('/parser/series', parserController.series); /** * @api {get} /parse/series Parsear Temporadas * @apiGroup Parse * @apiPermission admin */ router.get('/parser/temporadas', parserController.temporadas); /** * @api {get} /parse/series Parsear Episodios * @apiGroup Parse * @apiPermission admin */ router.get('/parser/episodios', parserController.episodios); /** * @api {get} /parse/preparar Teste do parse * @apiGroup Parse * @apiPermission admin */ router.get('/parser/preparar'); module.exports = router;<file_sep>/src/parsers/filmes.js const request = require('request'); const cheerio = require('cheerio') const jsdom = require("jsdom"); const { JSDOM } = jsdom; const fs = require('fs'); const Filme = require('../models/filmeModel') const urlFile = './filmes.json'; class ParserFilmes{ async getFilmes(link = 'http://gofilmes.me/'){ try { let filmes = new Array(); let index = 1 filme = { uri: null, uriPage:'http://gofilmes.me/arraste-me-para-o-inferno', referer: null, titulo:null, posterStart: null, categoria: null } getPropsFilme(filme) /*let time = setInterval(() => { let aux = getFilmes(link+'?p='+index); aux.map( filme =>{ filmes.push(filme) }) if(index > 60){ clearInterval(time) } index++ }, 15000); */ } catch (error) { console.error(error); } } getFilmes(link){ try { let filmes = new Array(); request(link, function (error, response, body) { console.log(link) if(response && response.statusCode == 200){ var $ = cheerio.load(body) $('.poster').each( function(i, elem) { let categoria = new Array() $(this).children().each( function(i, elem) { $(this).children('.t-gen').each( function(i, elem) { categoria.push($(this).text()) }) }) filme = { referer: null, uri: null, titulo: $(this).children('a').children('img').attr().alt, uriPage: $(this).children('a').attr().href, posterStart: $(this).children('a').children('img').attr().src.replace(/(w)\d+/g, 'w1280'), categoria: categoria } getPropsFilme(filme); }); } }); return filmes; } catch (error) { console.error(error); } } getPropsFilme(filme){ request(filme.uriPage, function (error, response, body) { if(response && response.statusCode == 200){ var $ = cheerio.load(body) $('body').each( function(i, elem) { let url = '' + $(this).children('.player').children('#player').children('script') ; try{ url = url.match(/(https?:\/\/.*\.(?:png|jpg))/g)[0]; }catch(err){ url = url.match(/(https?:\/\/.*\.(?:png|jpg))/g); } filme.referer = url filme.titulo = $(this).children('.dsk').children('.col-1').children('.capa').attr().alt; filme.resumo = $(this).children('.dsk').children('.col-2').children('.sinopse').text().replace('Sinopse:', '').trim(); filme.posterStart = $(this).children('.dsk').children('.col-1').children('.capa').attr().src.replace(/(w)\d+/g, 'w1280'); getUrlFilme(filme) }) } }) } getUrlFilme(filme){ request(filme.referer, function (error, response, body) { if(response && response.statusCode == 200){ var $ = cheerio.load(body) $('body').children('center').children('.align').each( function(i, elem) { let urls = urlify('' + $(this)); filme.uri = urls; //insertFilme(filme); if(urls.dublado.length>0){ console.log('urls.dublado') urls.dublado.map((url, index)=>{ getUrl(url, index, true, filme) }) } if(urls.legendado.length>0){ console.log('urls.legendado') urls.legendado.map((url, index)=>{ getUrl(url, index, false, filme) }) } //console.log('Filme salvo') //console.log(filme) }) } }) } getUrl(url, index, dublado, filme){ const options = { url, headers: { 'Referer': filme.referer } }; request(options, function (error, response, body) { if(response && response.statusCode == 200){ body = body .replace(/(%3A)/g,':') .replace(/(%2F)/g,'/') .replace(/(%3F)/g,'?') .replace(/(%3D)/g,'=') let urlFilme = imgUrlify(body); if(dublado && urlFilme){ filme.uri.dublado[index]=urlFilme; } if(!dublado && urlFilme){ filme.uri.legendado[index]=urlFilme; } console.log(filme) insertFilme(filme) } }) } insertFilme(filme){ Filme.findOneAndUpdate({titulo: filme.titulo}, filme, {upsert: true}, function (err, filme) { if (err) console.error(err) return filme; } ).then() }; async getFilme(url){ console.log('getFilme') /*try { let response = await fetch(url); let responseText = await response.text(); const dom = new JSDOM(responseText); let links = dom.window.document.querySelector('#player').innerHTML; let descricao = dom.window.document.querySelector('.dsk').innerHTML; let filme = { resumo: '', uri: '', img: '' } //links = parse(links); //links = urlify(links[1].children[0].content) links = urlify(links) filme.resumo = descricao[3].children[5].children[2].content; filme.uri = await getMovieURL( links ); filme.img = urlify(links[0].substring(5 , links[0].length), true); return filme; } catch (error) { console.error(error); }*/ } urlify(text) { var urlRegex = /(?:(?:https?|ftp):\/\/)(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/g; var urlImgRegex = /(((https:\/\/)|(www\.))[^\s]+[(.jpg)|(.png)|(.mp4)])/g; let dubRegex = /(DUBLADO)|(LEGENDADO)/g let url = text.match(urlRegex); let dub = text.match(dubRegex) let length = url.length; let links = { dublado: new Array(), legendado: new Array() } for(i=0; i<length; i++){ if(dub[i] == "DUBLADO") links.dublado.push(url[i]) else links.legendado.push(url[i]) } return links; } imgUrlify(text) { var urlRegex = /((https):\/\/streamguard.cc)(([^\s()<>]+|\((?:[^\s()<>]+|(\([^\s()<>]+\)))?\))+(?:\(([^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/g; let aux = text.match(urlRegex) if(aux) aux = aux[0] return aux; } writeFile(path, data){ fs.writeFileSync(path, data,function (err) { if (err) throw err; console.log('Saved!'); }); } readFile(path){ let data; if(fs.existsSync(path)){ data = fs.readFileSync(path, 'utf8', function (err,data) { if (err) { console.error(err); return err; } return data; }); } return data; } } <file_sep>/src/models/temporada.js const mongoose = require('mongoose'); const TemporadaSchema = mongoose.Schema({ title: String, episodios:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Episodio' }] }, { timestamps: true }); module.exports = mongoose.model('Temporada', TemporadaSchema);<file_sep>/src/controllers/parserController.js //const parseFilmes = require('../parsers/filmes') const pfHeadLess = require('../parsers/filmesHeadless') const parserSeries = require('../parsers/series') class ParserController{ async filmes(req, res, next){ console.log('Preparando Filmes') pfHeadLess.filmes(req, res, next); }; async series(req, res, next){ console.log('Preparando Series') parserSeries.series(req, res, next); }; async temporadas(req, res, next){ console.log('Preparando Temporadas') parserSeries.temporadas(req, res, next) }; async episodios(req, res, next){ console.log('Preparando Episodios') parserSeries.episodios(req, res, next) }; } module.exports = new ParserController();<file_sep>/src/routes/users.js const express = require('express'); const router = express.Router(); const user = require('../controllers/userController'); var { isAdmin } = require('../auth/authServices'); const prefix = '/user' // Create a new User router.post(prefix, user.create); // Retrieve all user router.get(prefix, user.findAll); // Retrieve a single User with userId router.get(prefix+'/:userId', user.findOne); // Update a User with userId router.put(prefix+'/:userId', user.update); // Delete a User with userId router.delete(prefix+'/:userId', user.delete); module.exports = router;<file_sep>/src/models/user.js var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); var jwt = require('jsonwebtoken'); var UserSchema = new mongoose.Schema({ email: { type: String, unique: true, required: true, trim: true }, username: { type: String, unique: true, required: true, trim: true }, password: { type: String, required: true, }, fullname:{ type: String, required: true, }, admin:{ type: Boolean, required: true }, token: String, fcm_token: String, favoritos: Array, avatar: JSON }); UserSchema.pre('save', function(next) { if (this.isModified('password')) { this.password = this._hashPassword(this.password); } return next(); }); UserSchema.methods = { _hashPassword(password) { return bcrypt.hashSync(password); }, authenticateUser(password) { return bcrypt.compareSync(password, this.password); }, createToken() { // create a token var token = jwt.sign({ id: this._id }, process.env.JWT_WORD || config.secret, { //expiresIn: 86400 // expires in 24 hours }); return token }, toJson() { return { auth: true, _id: this._id, username: this.username, email: this.email, fullname: this.fullname, token: this.createToken(), fcm_token: this.fcm_token, avatar: this.avatar, favoritos: this.favoritos } }, }; module.exports = mongoose.model('User', UserSchema);<file_sep>/src/auth/authServices.js var User = require('../models/user'); var jwt = require('jsonwebtoken'); //Verifica se usuario esta autenticado exports.authenticate = (req, res, done) => { let username = req.body.username; let password = req.body.password; console.log(req.body) User.findOne({ username: username }) .exec(function (err, user) { var error = new Error(); if (err) { error = err; error.status = 500; return done(error) } else if (!user) { error.message = { auth: false, message: 'Erro ao realizar login, usuário não encontrado'}; error.status = 401; return done(error); } if(!user.authenticateUser(password)){ error.message = { auth: false,message: 'Usuário ou senha inválidos'}; error.status = 401; return done(error); }else{ return res.status(200).send(user.toJson()); } }); } //Verifica se usuario esta autenticado exports.isAuthenticate = (req, res, next) => { var token = req.headers['x-access-token']; if (!token) return res.status(401).send({ auth: false, message: 'Nenhum token fornecido' }); jwt.verify(token, process.env.JWT_WORD || config.secret, function(err, decoded) { if (err) return res.status(500).send({ auth: false, message: 'Falha ao autenticar token' }); //res.status(200).send(decoded); return next(); }); } // Verifica se usuario é admin exports.isAdmin = (req, res, callback) => { var token = req.headers['x-access-token']; let userId; if (!token) return res.status(401).send({ auth: false, message: 'Nenhum token fornecido' }); jwt.verify(token, process.env.JWT_WORD , function(err, decoded) { console.log(decoded) if (err) return res.status(500).send({ auth: false, message: 'Falha ao autenticar token' }); User.findOne({ _id: decoded._id }) .exec(function (err, user) { if (err) { return callback(err) } else if (!user) { /*var err = new Error('Usuário não encontrado'); err.status = 401;*/ return callback(err); } if (user.admin) { return callback(null, user); } else { var err = new Error('Usuário não é admin'); err.status = 401; return callback(err); } }); }); }<file_sep>/public/apidoc/api_data.js define({ "api": [ { "type": "get", "url": "/logout", "title": "Logout", "group": "Auth", "success": { "fields": { "Success 200": [ { "group": "Success 200", "type": "Object[]", "optional": false, "field": "profiles", "description": "<p>List of user profiles.</p>" }, { "group": "Success 200", "type": "Number", "optional": false, "field": "profiles.age", "description": "<p>Users age.</p>" }, { "group": "Success 200", "type": "String", "optional": false, "field": "profiles.image", "description": "<p>Avatar-Image.</p>" } ] } }, "version": "0.0.0", "filename": "src/routes/index.js", "groupTitle": "Auth", "name": "GetLogout" }, { "type": "post", "url": "/authenticated", "title": "Authenticated", "group": "Auth", "header": { "fields": { "": [ { "group": "Header", "type": "String", "optional": false, "field": "x-access-token", "description": "<p>Token.</p>" } ] }, "examples": [ { "title": "Header Exemplo", "content": "{\n \"x-access-token\":\"<KEY>}", "type": "json" } ] }, "error": { "examples": [ { "title": "Nenhum token fornecido", "content": "HTTP/1.1 401 OK\n{\n auth: false, \n message: \"Nenhum token fornecido\"\n}", "type": "json" }, { "title": "Falha ao autenticar token", "content": "HTTP/1.1 500 OK\n{\n auth: false, \n message: \"Falha ao autenticar token\" \n}", "type": "json" } ] }, "version": "0.0.0", "filename": "src/routes/index.js", "groupTitle": "Auth", "name": "PostAuthenticated" }, { "type": "post", "url": "/login", "title": "Login", "group": "Auth", "parameter": { "fields": { "Parameter": [ { "group": "Parameter", "type": "String", "optional": false, "field": "username", "description": "<p>Usuário.</p>" }, { "group": "Parameter", "type": "String", "optional": false, "field": "password", "description": "<p>Senha.</p>" } ] }, "examples": [ { "title": "Login exemplo:", "content": "{\n \"username\": \"username-example\",\n \"password\": \"<PASSWORD>\"\n}", "type": "json" } ] }, "success": { "examples": [ { "title": "Sucesso", "content": "HTTP/1.1 200 OK\n{\n auth: true,\n _id: \"5bd08c3304bf9a313bb9daf6\",\n username: \"teste\",\n token: \"<KEY>.P<KEY>widzkS5MB_5Bqw0XhrCU4\" \n}", "type": "json" } ] }, "error": { "examples": [ { "title": "Usuário ou senha inválidos", "content": "HTTP/1.1 401 OK\n{\n message: \"usuário ou senha inválidos\"\n}", "type": "json" }, { "title": "Usuário não encontrado", "content": "HTTP/1.1 401 OK\n{\n message: \"usuário não encontrado\" \n}", "type": "json" } ] }, "version": "0.0.0", "filename": "src/routes/index.js", "groupTitle": "Auth", "name": "PostLogin" }, { "type": "post", "url": "/signup", "title": "Signup", "group": "Auth", "parameter": { "fields": { "Parameter": [ { "group": "Parameter", "type": "String", "optional": false, "field": "username", "description": "<p>Usuário.</p>" }, { "group": "Parameter", "type": "String", "optional": false, "field": "password", "description": "<p>Senha.</p>" }, { "group": "Parameter", "type": "String", "optional": false, "field": "fullname", "description": "<p>Nome completo.</p>" }, { "group": "Parameter", "type": "String", "optional": false, "field": "email", "description": "<p>Email.</p>" } ] }, "examples": [ { "title": "Signup exemplo:", "content": "{\n \"username\": \"teste\",\n \"password\": \"<PASSWORD>\",\n \"fullname\": \"Teste Teste\",\n \"email\": \"<EMAIL>\"\n}", "type": "json" } ] }, "success": { "examples": [ { "title": "Sucesso", "content": "HTTP/1.1 200 OK\n{\n auth: true,\n _id: \"5bd08c3304bf9a313bb9daf6\",\n username: \"teste\",\n token: \"<KEY> \n}", "type": "json" } ] }, "version": "0.0.0", "filename": "src/routes/index.js", "groupTitle": "Auth", "name": "PostSignup" }, { "type": "get", "url": "/parse/preparar", "title": "Teste do parse", "group": "Parse", "permission": [ { "name": "admin", "title": "Acesso permitido para admins", "description": "<p>O acesso a esse endpoint é permitido apenas para usuários admin</p>" } ], "version": "0.0.0", "filename": "src/routes/parser.js", "groupTitle": "Parse", "name": "GetParsePreparar" }, { "type": "get", "url": "/parse/series", "title": "Parsear Temporadas", "group": "Parse", "permission": [ { "name": "admin", "title": "Acesso permitido para admins", "description": "<p>O acesso a esse endpoint é permitido apenas para usuários admin</p>" } ], "version": "0.0.0", "filename": "src/routes/parser.js", "groupTitle": "Parse", "name": "GetParseSeries" }, { "type": "get", "url": "/parse/series", "title": "Parsear Series", "group": "Parse", "permission": [ { "name": "admin", "title": "Acesso permitido para admins", "description": "<p>O acesso a esse endpoint é permitido apenas para usuários admin</p>" } ], "version": "0.0.0", "filename": "src/routes/parser.js", "groupTitle": "Parse", "name": "GetParseSeries" }, { "type": "get", "url": "/parser/filmes", "title": "Parsear Filmes", "group": "Parser", "permission": [ { "name": "admin", "title": "Acesso permitido para admins", "description": "<p>O acesso a esse endpoint é permitido apenas para usuários admin</p>" } ], "version": "0.0.0", "filename": "src/routes/parser.js", "groupTitle": "Parser", "name": "GetParserFilmes" }, { "type": "delete", "url": "/series/:serieId", "title": "Deletar serie", "group": "Series", "permission": [ { "name": "admin", "title": "Acesso permitido para admins", "description": "<p>O acesso a esse endpoint é permitido apenas para usuários admin</p>" } ], "parameter": { "fields": { "Parameter": [ { "group": "Parameter", "type": "String", "optional": false, "field": "serieId", "description": "<p>Id da Serie</p>" } ] } }, "success": { "examples": [ { "title": "Sucesso", "content": "HTTP/1.1 200 OK\n{\n \n}", "type": "json" } ] }, "version": "0.0.0", "filename": "src/routes/series.js", "groupTitle": "Series", "name": "DeleteSeriesSerieid", "header": { "fields": { "": [ { "group": "Header", "type": "String", "optional": false, "field": "x-access-token", "description": "<p>Token.</p>" } ] }, "examples": [ { "title": "Header Exemplo ", "content": "{\n \"x-access-token\":\"<KEY>}", "type": "json" } ] }, "error": { "examples": [ { "title": "Nenhum token fornecido", "content": "HTTP/1.1 401 OK\n{\n auth: false, \n message: \"Nenhum token fornecido\"\n}", "type": "json" }, { "title": "Falha ao autenticar token", "content": "HTTP/1.1 500 OK\n{\n auth: false, \n message: \"Falha ao autenticar token\" \n}", "type": "json" } ] } }, { "type": "get", "url": "/series", "title": "Listar todas series", "group": "Series", "permission": [ { "name": "authenticated" } ], "success": { "examples": [ { "title": "Sucesso", "content": " HTTP/1.1 200 OK\n [\n { \n \"_id\": \"5bf00fc03846d0e8ea842ed7\", \n \"titulo\": \"Supernatural\", \n \"__v\": 0, \n \"createdAt\": \"2018-11-17T12:55:28.304Z\",\n \"path\": \"Supernatural\", \n \"posterStart\": \"https://image.tmdb.org/t/p/w300/3iFm6Kz7iYoFaEcj4fLyZHAmTQA.jpg\", \n \"updatedAt\": \"2018-11-17T13:34:11.220Z\", \n \"uriPage\": \"https://tuaserie.com/serie/assistir-serie-supernatural-online/\"\n },\n { \n \"_id\": \"5bf00fc43846d0e8ea842f1f\", \n \"titulo\": \"Chicago MED\", \n \"__v\": 0, \n \"createdAt\": \"2018-11-17T12:55:32.552Z\", \n \"path\": \"Chicago_MED\", \n \"posterStart\": \"https://image.tmdb.org/t/p/w300/jMvkqK2uQbghLgZUNEhYL1SHT7e.jpg\",\n \"updatedAt\": \"2018-11-17T12:58:45.876Z\", \n \"uriPage\": \"https://tuaserie.com/serie/assistir-chicago-med/\"\n },\n ...\n]", "type": "json" } ], "fields": { "Success 200": [ { "group": "Success 200", "type": "String", "optional": false, "field": "_id", "description": "<p>ID.</p>" }, { "group": "Success 200", "type": "String", "optional": false, "field": "titulo", "description": "<p>Titulo.</p>" }, { "group": "Success 200", "type": "Integer", "optional": false, "field": "__v", "description": "" }, { "group": "Success 200", "type": "String", "optional": false, "field": "path", "description": "" }, { "group": "Success 200", "type": "String", "optional": false, "field": "posterStart", "description": "<p>Link.</p>" }, { "group": "Success 200", "type": "updatedAt", "optional": false, "field": "series", "description": "<p>Series.</p>" }, { "group": "Success 200", "type": "String", "optional": false, "field": "uriPage", "description": "<p>Link.</p>" } ] } }, "version": "0.0.0", "filename": "src/routes/series.js", "groupTitle": "Series", "name": "GetSeries", "header": { "fields": { "": [ { "group": "Header", "type": "String", "optional": false, "field": "x-access-token", "description": "<p>Token.</p>" } ] }, "examples": [ { "title": "Header Exemplo ", "content": "{\n \"x-access-token\":\"<KEY>}", "type": "json" } ] }, "error": { "examples": [ { "title": "Nenhum token fornecido", "content": "HTTP/1.1 401 OK\n{\n auth: false, \n message: \"Nenhum token fornecido\"\n}", "type": "json" }, { "title": "Falha ao autenticar token", "content": "HTTP/1.1 500 OK\n{\n auth: false, \n message: \"Falha ao autenticar token\" \n}", "type": "json" } ] } }, { "type": "get", "url": "/series/:serieId", "title": "Encontrar série", "group": "Series", "permission": [ { "name": "authenticated" } ], "parameter": { "fields": { "Parameter": [ { "group": "Parameter", "type": "String", "optional": false, "field": "serieId", "description": "<p>Id da Serie</p>" } ] } }, "success": { "examples": [ { "title": "Sucesso", "content": "HTTP/1.1 200 OK\n{ \n \"_id\": \"5bf00fc03846d0e8ea842ed7\", \n \"titulo\": \"Supernatural\", \n \"__v\": 0, \n \"createdAt\": \"2018-11-17T12:55:28.304Z\",\n \"path\": \"Supernatural\", \n \"posterStart\": \"https://image.tmdb.org/t/p/w300/3iFm6Kz7iYoFaEcj4fLyZHAmTQA.jpg\", \n \"updatedAt\": \"2018-11-17T13:34:11.220Z\", \n \"uriPage\": \"https://tuaserie.com/serie/assistir-serie-supernatural-online/\"\n},", "type": "json" } ], "fields": { "Success 200": [ { "group": "Success 200", "type": "String", "optional": false, "field": "_id", "description": "<p>ID.</p>" }, { "group": "Success 200", "type": "String", "optional": false, "field": "titulo", "description": "<p>Titulo.</p>" }, { "group": "Success 200", "type": "Integer", "optional": false, "field": "__v", "description": "" }, { "group": "Success 200", "type": "String", "optional": false, "field": "path", "description": "" }, { "group": "Success 200", "type": "String", "optional": false, "field": "posterStart", "description": "<p>Link.</p>" }, { "group": "Success 200", "type": "updatedAt", "optional": false, "field": "series", "description": "<p>Series.</p>" }, { "group": "Success 200", "type": "String", "optional": false, "field": "uriPage", "description": "<p>Link.</p>" } ] } }, "version": "0.0.0", "filename": "src/routes/series.js", "groupTitle": "Series", "name": "GetSeriesSerieid", "header": { "fields": { "": [ { "group": "Header", "type": "String", "optional": false, "field": "x-access-token", "description": "<p>Token.</p>" } ] }, "examples": [ { "title": "Header Exemplo ", "content": "{\n \"x-access-token\":\"<KEY>.<KEY>_5Bqw0XhrCU4\"\n}", "type": "json" } ] }, "error": { "examples": [ { "title": "Nenhum token fornecido", "content": "HTTP/1.1 401 OK\n{\n auth: false, \n message: \"Nenhum token fornecido\"\n}", "type": "json" }, { "title": "Falha ao autenticar token", "content": "HTTP/1.1 500 OK\n{\n auth: false, \n message: \"Falha ao autenticar token\" \n}", "type": "json" } ] } }, { "type": "post", "url": "/series/", "title": "Criar serie", "group": "Series", "permission": [ { "name": "admin", "title": "Acesso permitido para admins", "description": "<p>O acesso a esse endpoint é permitido apenas para usuários admin</p>" } ], "parameter": { "fields": { "Parameter": [ { "group": "Parameter", "type": "String", "optional": false, "field": "titulo", "description": "<p>Titulo da Serie</p>" }, { "group": "Parameter", "type": "String", "optional": false, "field": "path", "description": "<p>Titulo da Serie</p>" }, { "group": "Parameter", "type": "String", "optional": false, "field": "posterStart", "description": "<p>Link do poster da Serie</p>" }, { "group": "Parameter", "type": "String", "optional": false, "field": "uriPage", "description": "<p>Link da Serie</p>" } ] }, "examples": [ { "title": "Exemplo de serie", "content": "{\n \"titulo\": \"Supernatural\", \n \"path\": \"Supernatural\", \n \"posterStart\": \"https://image.tmdb.org/t/p/w300/3iFm6Kz7iYoFaEcj4fLyZHAmTQA.jpg\", \n \"uriPage\": \"https://tuaserie.com/serie/assistir-serie-supernatural-online/\"\n}", "type": "json" } ] }, "success": { "examples": [ { "title": "Sucesso", "content": "HTTP/1.1 200 OK\n { \n \"_id\": \"5bf00fc03846d0e8ea842ed7\", \n \"titulo\": \"Supernatural\", \n \"__v\": 0, \n \"createdAt\": \"2018-11-17T12:55:28.304Z\",\n \"path\": \"Supernatural\", \n \"posterStart\": \"https://image.tmdb.org/t/p/w300/3iFm6Kz7iYoFaEcj4fLyZHAmTQA.jpg\", \n \"updatedAt\": \"2018-11-17T13:34:11.220Z\", \n \"uriPage\": \"https://tuaserie.com/serie/assistir-serie-supernatural-online/\"\n },", "type": "json" } ] }, "version": "0.0.0", "filename": "src/routes/series.js", "groupTitle": "Series", "name": "PostSeries", "header": { "fields": { "": [ { "group": "Header", "type": "String", "optional": false, "field": "x-access-token", "description": "<p>Token.</p>" } ] }, "examples": [ { "title": "Header Exemplo ", "content": "{\n \"x-access-token\":\"ey<PASSWORD> <KEY>}", "type": "json" } ] }, "error": { "examples": [ { "title": "Nenhum token fornecido", "content": "HTTP/1.1 401 OK\n{\n auth: false, \n message: \"Nenhum token fornecido\"\n}", "type": "json" }, { "title": "Falha ao autenticar token", "content": "HTTP/1.1 500 OK\n{\n auth: false, \n message: \"Falha ao autenticar token\" \n}", "type": "json" } ] } }, { "type": "put", "url": "/series/:serieId", "title": "Atualizar serie", "group": "Series", "permission": [ { "name": "admin", "title": "Acesso permitido para admins", "description": "<p>O acesso a esse endpoint é permitido apenas para usuários admin</p>" } ], "parameter": { "fields": { "Parameter": [ { "group": "Parameter", "type": "String", "optional": false, "field": "titulo", "description": "<p>Titulo.</p>" }, { "group": "Parameter", "type": "String", "optional": false, "field": "path", "description": "<p>.</p>" }, { "group": "Parameter", "type": "String", "optional": false, "field": "posterStart", "description": "<p>Link para imagem de poster da Série.</p>" }, { "group": "Parameter", "type": "String", "optional": false, "field": "uriPage", "description": "<p>Link da Série.</p>" } ] } }, "success": { "fields": { "Success 200": [ { "group": "Success 200", "type": "json", "optional": false, "field": "series", "description": "<p>Series.</p>" } ] }, "examples": [ { "title": "Sucesso", "content": "HTTP/1.1 200 OK\n{\n}", "type": "json" } ] }, "version": "0.0.0", "filename": "src/routes/series.js", "groupTitle": "Series", "name": "PutSeriesSerieid", "header": { "fields": { "": [ { "group": "Header", "type": "String", "optional": false, "field": "x-access-token", "description": "<p>Token.</p>" } ] }, "examples": [ { "title": "Header Exemplo ", "content": "{\n \"x-access-token\":\"<KEY>n}", "type": "json" } ] }, "error": { "examples": [ { "title": "Nenhum token fornecido", "content": "HTTP/1.1 401 OK\n{\n auth: false, \n message: \"Nenhum token fornecido\"\n}", "type": "json" }, { "title": "Falha ao autenticar token", "content": "HTTP/1.1 500 OK\n{\n auth: false, \n message: \"Falha ao autenticar token\" \n}", "type": "json" } ] } }, { "type": "get", "url": "/", "title": "Status", "group": "Status", "success": { "fields": { "Success 200": [ { "group": "Success 200", "type": "String", "optional": false, "field": "status", "description": "<p>Mensagens de status da API</p>" } ] }, "examples": [ { "title": "Sucesso", "content": "HTTP/1.1 200 OK\n{\n title: \"Node Express API\",\n version: \"0.0.1\"\n}", "type": "json" } ] }, "version": "0.0.0", "filename": "src/app.js", "groupTitle": "Status", "name": "Get" } ] }); <file_sep>/server.js if(process.env.NODE_ENV === 'DEVELOPMENT' ){ dotenv = require('dotenv'); dotenv.config(); } normalizaPort = (val) => { const port = parseInt(val, 10); if (isNaN(port)) { return val; } if (port >= 0) { return port; } return false; } const app = require('./src/app'); const port = normalizaPort(process.env.PORT || '3003'); /* // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Erro em realizar ação'); err.status = 404; next(err); });*/ // error handler // define as the last app.use callback app.use((err, req, res, next) => { res.status(err.status || 500); res.send(err.message); }); app.listen(port, () => { console.log(`API running on http://localhost:${port}`) })<file_sep>/src/models/filme.js const mongoose = require('mongoose'); const FilmeSchema = mongoose.Schema({ titulo: { type: String, unique: true, required: true, trim: true }, uri: Array, referer: String, uriPage: String, resumo: String, posterStart: String, category:[{ type: String }], new: { type: Boolean, default: true } }, { timestamps: true }); module.exports = mongoose.model('Filme', FilmeSchema);<file_sep>/src/routes/filmes.js const express = require('express'); const router = express.Router(); const filmes = require('../controllers/filmeController'); var { isAdmin } = require('../auth/authServices'); const prefix = '/filmes' // Retrieve all Movies router.get(prefix, filmes.findAll); // Retrieve a single Movie with filmeId router.get(prefix+'/:filmeId', filmes.findOne); // Create a new Movie //router.post(prefix, isAdmin, filmes.create); // Update a Movie with filmeId router.put(prefix+'/:filmeId', isAdmin, filmes.update); // Delete a Movie with filmeId router.delete(prefix+'/:filmeId', isAdmin, filmes.delete); module.exports = router;
2ad97fb2d1b757cecd5d1f6e47a43c6947a5ada3
[ "JavaScript", "Markdown" ]
18
JavaScript
camargoguilherme/api-filmes-teste
c07794458180e75ccc9c418c87db7ddd32ba0ebb
77db55ee4f8f4c65e095c3d14e93f73abba015ab
refs/heads/master
<repo_name>zhangzju/learnG2<file_sep>/README.md # learn g2 g2是蚂蚁金服发布的antv三件套中的用于数据可视化的类库,相比于echarts和D3,功能上不是特别强大,但是应该能满足基本的数据可视化需求。 关键的一点是,相比于独立的功能完备的类库,g2的优势在于背后有一整个家族的支撑,antd和antv作为出色的类库,能够让g2在适配方面做得更好。 这个repo是循序渐进了解g2这个类库的记录。 ## 文件说明 这个仓库使用vue.js来实现各种数据图表的绘制,同时附加文档说明~ 具体有用到的文件夹是src和document. 1. src:源代码目录 2. document: 学习总结目录 学习总结目录中的内容在具体的工程中也会有。 ## 使用方法 ```shell git clone <path_of_this_repo> ``` 这个仓库使用的是vue-init生成的webpack模板,不再在本项目中许多文件并不是必要的,因此只需要关注如何run就可以了!~ ```shell npm run dev ``` <file_sep>/src/main.js import Vue from 'vue' import App from './App' import VueRouter from 'vue-router' import LineG2 from './components/LineG2' import PlotG2 from './components/PlotG2' Vue.use(VueRouter) const routes = [ { path: '/LineG2', component: LineG2 }, { path: '/PlotG2', component: PlotG2 } ] const router = new VueRouter({ routes // (缩写)相当于 routes: routes }) /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<App/>', components: { App } })
7fb77abc8591a76fb576167d71ac95d19ec416b4
[ "Markdown", "JavaScript" ]
2
Markdown
zhangzju/learnG2
6e0eef1073c17b11a1bd4d442bf2f82057fb57d2
f696f278129e70bfcb5e215f60fefb6aaad52eba
refs/heads/master
<file_sep>module github.com/xdire/algrefresh go 1.12 <file_sep>package queues import ( "fmt" "github.com/xdire/algrefresh/lists" "testing" ) type testStruct struct { name string } func TestPriorityQueueList_AddStruct(t *testing.T) { sa := &PriorityQueueList{} sa.list = lists.NewLinkedListOrdered(lists.OrderedIntComparator) sa.Add(&testStruct{name: "three"}, 3) sa.Add(&testStruct{name: "two"}, 2) sa.Add(&testStruct{name: "one"}, 1) sa.Add(&testStruct{name: "three three"}, 3) sa.Add(&testStruct{name: "two two"}, 2) sa.Add(&testStruct{name: "one one"}, 1) size := sa.Size() fmt.Printf("\nstruct array size %d", size) one := &testStruct{} err := sa.PollValue(one) if err != nil { t.Error(err) t.Fail() } two := &testStruct{} err = sa.PollValue(two) if err != nil { t.Error(err) t.Fail() } three := &testStruct{} err = sa.PollValue(three) if err != nil { t.Error(err) t.Fail() } fmt.Printf("\nstruct values received [%+v] [%+v] [%+v]", one, two, three) one = &testStruct{} err = sa.PollValue(one) if err != nil { t.Error(err) t.Fail() } two = &testStruct{} err = sa.PollValue(two) if err != nil { t.Error(err) t.Fail() } three = &testStruct{} err = sa.PollValue(three) if err != nil { t.Error(err) t.Fail() } fmt.Printf("\nstruct values deleted [%+v] [%+v] [%+v]", one, two, three) size = sa.Size() fmt.Printf("\nstruct array size %d", size) } func TestPriorityQueueList_AddString(t *testing.T) { sa := &PriorityQueueList{} sa.list = lists.NewLinkedListOrdered(lists.OrderedIntComparator) sa.Add("one", 1) sa.Add("two", 2) sa.Add("three", 3) sa.Add("three three", 3) sa.Add("two two", 2) sa.Add("one one", 1) size := sa.Size() fmt.Printf("\nstring pq size %d", size) one := "" err := sa.PollValue(&one) if err != nil { t.Error(err) t.Fail() } two := "" err = sa.PollValue(&two) if err != nil { t.Error(err) t.Fail() } three := "" err = sa.PollValue(&three) if err != nil { t.Error(err) t.Fail() } fmt.Printf("\nstring values received [%+v] [%+v] [%+v]", one, two, three) one = "" err = sa.PollValue(&one) if err != nil { t.Error(err) t.Fail() } two = "" err = sa.PollValue(&two) if err != nil { t.Error(err) t.Fail() } three = "" err = sa.PollValue(&three) if err != nil { t.Error(err) t.Fail() } fmt.Printf("\nvalues deleted [%+v] [%+v] [%+v]", one, two, three) size = sa.Size() fmt.Printf("\nstring pq size %d", size) } func TestPriorityQueueList_Fill(t *testing.T) { sa := &PriorityQueueList{} sa.list = lists.NewLinkedListOrdered(lists.OrderedIntComparator) for i:=0; i<1000; i++ { sa.Add(i, i % 10) } fmt.Printf("\npq size after 1000 entries %d", sa.size) for i:=0; i<999; i++ { err := sa.PollValue(nil) if err != nil { t.Fail() } } err := sa.PollValue(nil) if err != nil { t.Fail() } fmt.Printf("\npq size after polling of 1000 entries %d", sa.size) } <file_sep>package hw01_06_shellsort import ( "github.com/xdire/algrefresh/sorts" "reflect" "testing" ) func Test_ShellSortGap2(t *testing.T) { t.Run("ShellSort Half Gap", func(t *testing.T) { data := []int64{1, 3, 7, 0, 12, 2, 5} sorts.ShellInt(data) if !reflect.DeepEqual(data, []int64{0, 1, 2, 3, 5, 7, 12}) { t.Error("ShellSort expected result not right") } }) }<file_sep>package lists import ( "errors" "fmt" "reflect" "unsafe" ) type ifRepresentation struct { Type, Data unsafe.Pointer typ uintptr word unsafe.Pointer } type emptyInterface interface {} type AbstractComparator func(a interface{}, b interface{}) (int8, error) type nodeComparable struct { cmpIndex interface{} next *nodeComparable data interface{} } func OrderedIntComparator(a interface{}, b interface{}) (int8, error) { aInt, ok := a.(int) bInt, ok1 := b.(int) if ok && ok1 { if aInt > bInt { return 1, nil } else if aInt < bInt { return -1, nil } return 0, nil } return 0, fmt.Errorf("non comparable values provided") } type LinkedListOrdered struct { head *nodeComparable tail *nodeComparable size uint32 genericType interface{} genericIsPointer bool comparator func(a interface{}, b interface{}) (int8, error) } func NewLinkedListOrdered(cmp AbstractComparator) *LinkedListOrdered { return &LinkedListOrdered{ head: nil, tail: nil, size: 0, genericType: nil, genericIsPointer: false, comparator: cmp, } } func (l *LinkedListOrdered) Once(item interface{}, order interface{}) interface{} { if l.genericType == nil { vt := reflect.ValueOf(item).Type().Kind() if vt == reflect.Ptr { l.genericType = reflect.ValueOf(item).Elem().Type() l.genericIsPointer = true } else { l.genericType = vt } l.genericType = item } return l.addComparable(item, order, true) } func (l *LinkedListOrdered) GetOrderValue(order interface{}, receiver interface{}) error { _, err := l.orderGetter(order, receiver) return err } func (l *LinkedListOrdered) SetComparator(cmp func(a interface{}, b interface{}) (int8, error)) { l.comparator = cmp } func (l *LinkedListOrdered) Size() uint32 { return l.size } func (l *LinkedListOrdered) Add(item interface{}, order interface{}) { if l.genericType == nil { vt := reflect.ValueOf(item).Type().Kind() if vt == reflect.Ptr { l.genericType = reflect.ValueOf(item).Elem().Type() l.genericIsPointer = true } else { l.genericType = vt } l.genericType = item } if l.comparator == nil { panic("no comparator presented for ordered list") } // Use method which can work with comparable l.addComparable(&item, order, false) } func (l *LinkedListOrdered) addComparable(item interface{}, order interface{}, once bool) interface{} { if l.head == nil { l.head = &nodeComparable{ cmpIndex: order, next: nil, data: item, } l.tail = l.head l.size++ return l.head.data } else { // Walk the list counter := 0 next := l.head prev := l.head for next != nil { // Compare order of values res, err := l.comparator(next.cmpIndex, order) if err != nil { panic(err) } // Check if value is equal to order // and return back the real value to interface if once && res == 0 { return next.data } // If comparable value lesser than current value then // switch values if res == 1 { // If at head then switch head if counter == 0 { l.head = &nodeComparable{ cmpIndex: order, next: prev, data: item, } l.size++ return l.head.data } else { // Switch prev next to new node and link next prev.next = &nodeComparable{ cmpIndex: order, next: next, data: item, } l.size++ return prev.next.data } } // iterate prev = next next = next.next counter++ } // If iteration didn't return any results // just add to the tail l.tail.next = &nodeComparable{ cmpIndex: order, next: nil, data: item, } l.tail = l.tail.next l.size++ return l.tail.data } } func (l *LinkedListOrdered) GetValue(index uint32, receiver interface{}) { _, err := l.getter(index, receiver) if err != nil { panic(err) } } func (l *LinkedListOrdered) Get(index uint32) (interface{}, error) { return l.getter(index, nil) } func (l *LinkedListOrdered) GetOrder(order interface{}) (interface{}, error) { return l.orderGetter(order, nil) } func (l *LinkedListOrdered) Remove(index uint32) (interface{}, error) { return l.remover(index, nil) } func (l *LinkedListOrdered) RemoveValue(index uint32, receiver interface{}) { _, err := l.remover(index, receiver) if err != nil { panic(err) } } func (l *LinkedListOrdered) remover(index uint32, receiver interface{}) (interface{}, error) { if l.head == nil || index > l.size - 1 { return nil, errors.New("index out of boundaries") } prev := l.head next := l.head // Check if index is zero, for that situation just replace // head with the next element from the head if index == 0 { next = l.head l.head = l.head.next } else { // If index is greater than zero we need to search until the index // and when found link previous element to the current next element counter := uint32(0) for counter != index { prev = next next = next.next counter++ } prev.next = next.next } // Provide the value back to requester if receiver != nil && l.genericIsPointer { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(next.data).Elem()) } else if receiver != nil { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(next.data)) } // If deleted value was actual tail then replace tail with // previous element (obviously tail was deleted) if next == l.tail { l.tail = prev } // Decrement size l.size-- // If size equals to 1 then Head will turn into Tail if l.size == 1 { l.head = l.tail } // If last element gone then reset the head and tail if l.size == 0 { l.head = nil l.tail = nil } return next.data, nil } func (l *LinkedListOrdered) getter(index uint32, receiver interface{}) (interface{}, error) { if l.head == nil || index > l.size - 1 { return nil, errors.New("index out of boundaries") } counter := uint32(0) next := l.head for counter != index { next = next.next counter++ } if receiver != nil && l.genericIsPointer { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(next.data).Elem()) } else if receiver != nil { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(next.data)) } return next.data, nil } func (l *LinkedListOrdered) orderGetter(order interface{}, receiver interface{}) (interface{}, error) { next := l.head for next != nil { if next.cmpIndex == order { if receiver != nil && l.genericIsPointer { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(next.data).Elem()) } else if receiver != nil { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(next.data)) } return next.data, nil } next = next.next } return nil, errors.New("not found") } func (l *LinkedListOrdered) Push(item interface{}) { l.Add(item, 0) } func (l *LinkedListOrdered) Poll() (interface{}, error) { if l.size == 0 { return nil, errors.New("empty") } return l.remover(0, nil) } func (l *LinkedListOrdered) Peek() (interface{}, error) { if l.size == 0 { return nil, errors.New("empty") } return l.getter(0, nil) } func (l *LinkedListOrdered) PollValue(receiver interface{}) error { if l.size == 0 { return errors.New("empty") } l.RemoveValue(0, receiver) return nil } func (l *LinkedListOrdered) PeekValue(receiver interface{}) error { if l.size == 0 { return errors.New("empty") } l.GetValue(0, receiver) return nil } <file_sep>package lists import ( "errors" "reflect" ) type node struct { next *node data interface{} } type LinkedList struct { head *node tail *node size uint32 genericType interface{} genericIsPointer bool } func (l *LinkedList) Size() uint32 { return l.size } func (l *LinkedList) Add(item interface{}) { if l.genericType == nil { vt := reflect.ValueOf(item).Type().Kind() if vt == reflect.Ptr { l.genericType = reflect.ValueOf(item).Elem().Type() l.genericIsPointer = true } else { l.genericType = vt } l.genericType = item } // If head is not defined then dedicate the separate procedure // to fulfill head and tail if l.head == nil { l.head = &node{ next: nil, data: item, } l.tail = l.head } else { // Add straight to tail if head is presented l.tail.next = &node{ next: nil, data: item, } l.tail = l.tail.next } // Increment size l.size++ } func (l *LinkedList) Get(index uint32) (interface{}, error) { return l.getter(index, nil) } func (l *LinkedList) Remove(index uint32) (interface{}, error) { return l.remover(index, nil) } func (l *LinkedList) GetValue(index uint32, receiver interface{}) { _, err := l.getter(index, receiver) if err != nil { panic(err) } } func (l *LinkedList) RemoveValue(index uint32, receiver interface{}) { _, err := l.remover(index, receiver) if err != nil { panic(err) } } func (l *LinkedList) AddAtIndex(index uint32, item interface{}) { if l.head == nil && index == 0 { l.Add(item) } if index > l.size { panic("cannot add index which out of size bounds") } counter := uint32(0) prev := l.head next := l.head for counter != index { prev = next next = next.next counter++ } prev.next = &node{ next: next, data: item, } l.size++ } func (l *LinkedList) getter(index uint32, receiver interface{}) (interface{}, error) { if l.head == nil || index > l.size - 1 { return nil, errors.New("index out of boundaries") } counter := uint32(0) next := l.head for counter != index { next = next.next counter++ } if receiver != nil && l.genericIsPointer { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(next.data).Elem()) } else if receiver != nil { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(next.data)) } return next.data, nil } func (l *LinkedList) remover(index uint32, receiver interface{}) (interface{}, error) { if l.head == nil || index > l.size - 1 { return nil, errors.New("index out of boundaries") } prev := l.head next := l.head // Check if index is zero, for that situation just replace // head with the next element from the head if index == 0 { next = l.head l.head = l.head.next } else { // If index is greater than zero we need to search until the index // and when found link previous element to the current next element counter := uint32(0) for counter != index { prev = next next = next.next counter++ } prev.next = next.next } // Provide the value back to requester if receiver != nil && l.genericIsPointer { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(next.data).Elem()) } else if receiver != nil { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(next.data)) } // If deleted value was actual tail then replace tail with // previous element (obviously tail was deleted) if next == l.tail { l.tail = prev } // Decrement size l.size-- // If size equals to 1 then Head will turn into Tail if l.size == 1 { l.head = l.tail } // If last element gone then reset the head and tail if l.size == 0 { l.head = nil l.tail = nil } return next.data, nil } <file_sep>package tests import ( "fmt" "github.com/xdire/algrefresh/util" "io/ioutil" "testing" ) type testExecutor func(t *testing.T, input string, compareTo string) error type testObject struct { name string dataIn string dataOut string fileIn util.File fileOut util.File err error } func testReader(t *testing.T, files []util.File, executor testExecutor) { pattern, err := util.CreatePrefixSuffixNamePattern([]string{"test."}, []string{".in",".out"}) if err != nil { t.Error(err) } testMap := make(map[string]*testObject) combs := util.CombinePattern(files, pattern) for k, v := range combs { if _, ok := testMap[k]; !ok { testMap[k] = &testObject{ name: k, } } testObj := testMap[k] for _, file := range v.Files { if testObj.err != nil { continue } if file.SuffixSelector == ".in" { testObj.fileIn = file.File data, err := ioutil.ReadFile(file.Path) if err != nil { testObj.err = err } testObj.dataIn = string(data) } if file.SuffixSelector == ".out" { testMap[k].fileOut = file.File data, err := ioutil.ReadFile(file.Path) if err != nil { testObj.err = err } testObj.dataOut = string(data) } } } for _, file := range testMap { t.Run(fmt.Sprintf("Test for input %s", file.name), func(t *testing.T) { err := executor(t, file.dataIn, file.dataOut) if err != nil { t.Fatalf("Test failed for input %s", file.name) } }) } } <file_sep>package hw01_09_avl_tree import ( "fmt" "github.com/xdire/algrefresh/trees" "testing" ) type data int16 func (d data) Compare(cmpTo trees.Comparable) int { if dd, ok := cmpTo.(data); ok { if d > dd { return 1 } else if d < dd { return -1 } } return 0 } func TestAVLTree_Add(t *testing.T) { tree := &trees.AVLTree{} type args struct { items []trees.Comparable } tests := []struct { name string args args }{ { "Testing the AVL tree addition", args{items: []trees.Comparable{ data(4), data(1), data(3), data(6), data(-1), data(15), data(123), }}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for _, v := range tt.args.items { tree.Add(v) } root, err := tree.Peek() if err != nil { t.Error(err) } fmt.Printf("%+v", root) }) } }<file_sep>package hw01_04_algebraic import "testing" func TestGCDMod(t *testing.T) { type args struct { a int64 b int64 } tests := []struct { name string args args want int64 }{ { name: "Finding GCD with modulo", args:args{ a: 32, b: 56, }, want: 8, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := GCDMod(tt.args.a, tt.args.b); got != tt.want { t.Errorf("GCDMod() = %v, want %v", got, tt.want) } }) } } func TestGCDSub(t *testing.T) { type args struct { a int64 b int64 } tests := []struct { name string args args want int64 }{ { name: "Finding GCD with subtraction", args:args{ a: 32, b: 56, }, want: 8, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := GCDSub(tt.args.a, tt.args.b); got != tt.want { t.Errorf("GCDSub() = %v, want %v", got, tt.want) } }) } }<file_sep>package lists import ( "fmt" "testing" ) func TestVectorArray_AddStruct(t *testing.T) { sa := &VectorArray{} sa.Add(&TestStruct{name: "one"}) sa.Add(&TestStruct{name: "two"}) sa.Add(&TestStruct{name: "three"}) size := sa.Size() fmt.Printf("\nstruct array size %d", size) one := &TestStruct{} sa.GetValue(0, one) two := &TestStruct{} sa.GetValue(1, two) three := &TestStruct{} sa.GetValue(2, three) fmt.Printf("\nstruct values received [%+v] [%+v] [%+v]", one, two, three) remOne := &TestStruct{} sa.Remove(0, remOne) remTwo := &TestStruct{} sa.Remove(1, remTwo) remThree := &TestStruct{} sa.Remove(0, remThree) fmt.Printf("\nstruct values deleted [%+v] [%+v] [%+v]", remOne, remTwo, remThree) size = sa.Size() fmt.Printf("\nstruct array size %d", size) } func TestVectorArray_AddString(t *testing.T) { sa := &VectorArray{} sa.Add("one") sa.Add("two") sa.Add("three") size := sa.Size() fmt.Printf("\nstring array size %d", size) one := "" sa.GetValue(0, &one) two := "" sa.GetValue(1, &two) three := "" sa.GetValue(2, &three) fmt.Printf("\nstring values received [%+v] [%+v] [%+v]", one, two, three) remOne := "" sa.Remove(0, &remOne) remTwo := "" sa.Remove(1, &remTwo) remThree := "" sa.Remove(0, &remThree) fmt.Printf("\nvalues deleted [%+v] [%+v] [%+v]", remOne, remTwo, remThree) size = sa.Size() fmt.Printf("\narray size %d", size) } func TestVectorArray_AddInt(t *testing.T) { sa := &VectorArray{} sa.Add(1) sa.Add(2) sa.Add(3) size := sa.Size() fmt.Printf("\nstring array size %d", size) one := 0 sa.GetValue(0, &one) two := 0 sa.GetValue(1, &two) three := 0 sa.GetValue(2, &three) fmt.Printf("\nstring values received [%+v] [%+v] [%+v]", one, two, three) remOne := 0 sa.Remove(0, &remOne) remTwo := 0 sa.Remove(1, &remTwo) remThree := 0 sa.Remove(0, &remThree) fmt.Printf("\nvalues deleted [%+v] [%+v] [%+v]", remOne, remTwo, remThree) size = sa.Size() fmt.Printf("\narray size %d", size) } <file_sep>package sorts import "fmt" func ShellInt(a []int64) { size := len(a) // Start step loop decreasing the steps in half for step := size / 2; step > 0; step = step / 2 { // Walk up all elements starting the steps start for i := step; i < size; i++ { // Save current result stor := a[i] j := i // While j is after beginning and (a[j - Step value]) greater than // current a[i] value do the swap for ; j >= step && a[j - step] > stor; j -= step { fmt.Printf("\n [j] going as %d with val [%d] with step %d with stor %d", j, a[j], step, stor) a[j] = a[j - step] } fmt.Printf("\n Placing a[j] going as %d with step %d with stor %d", j, step, stor) // Apply previous value to j-index a[j] = stor } } }<file_sep>package util import ( "fmt" "os" "path/filepath" "regexp" "strings" ) type File struct { Path string Info os.FileInfo } type FileCombination struct { File PrefixSelector string SuffixSelector string } type Combination struct { Files []FileCombination Matched string } type CompiledPattern interface { Pattern() *regexp.Regexp PrefixesSize() int SuffixesSize() int Prefixes() []string Suffixes() []string } type CommonCompiledPattern struct { p *regexp.Regexp prefixList []string suffixList []string } func (c CommonCompiledPattern) Prefixes() []string { return c.prefixList } func (c CommonCompiledPattern) Suffixes() []string { return c.suffixList } func (c CommonCompiledPattern) Pattern() *regexp.Regexp { return c.p } func (c CommonCompiledPattern) PrefixesSize() int { if c.prefixList != nil { return len(c.prefixList) } return 0 } func (c CommonCompiledPattern) SuffixesSize() int { if c.suffixList != nil { return len(c.suffixList) } return 0 } func GetDirectoryFiles(directory string) ([]File, error) { files := make([]File, 0) err := filepath.Walk(directory, func(path string, info os.FileInfo, err error) error { if err != nil { return err } files = append(files, File{ Path: path, Info: info, }) return nil }) if err != nil { return files, fmt.Errorf("cannot get directory files, %+v", err) } return files, nil } func CombinePattern(files []File, pattern CompiledPattern) map[string]*Combination { combs := make(map[string]*Combination) for _, v := range files { res := pattern.Pattern().FindStringSubmatch(v.Info.Name()) if res != nil { str := "" suffix := "" prefix := "" if len(res) == 4 { // Both suffixes and prefixes were defined, take all of those prefix = res[1] str = res[2] suffix = res[3] } else if len(res) == 3 && pattern.PrefixesSize() - 1 > 0 { // Situation when its either prefix or suffix, and if prefixes // are defined then we taking the prefix as a found param prefix = res[1] str = res[2] if pattern.SuffixesSize() == 1 { suffix = pattern.Suffixes()[0] } } else if len(res) == 3 && pattern.SuffixesSize() - 1 > 0 { // Situation when its either prefix or suffix, and if suffixes // are defined then we taking the suffix as a found param suffix = res[2] str = res[1] if pattern.PrefixesSize() == 1 { prefix = pattern.Prefixes()[0] } } else if len(res) == 2 { // No prefix and suffix were defined for the search str = res[1] } else { // Probably just skip this kind of variant, probably that // can be named as undefined behavior continue } // If found populate if comb, ok := combs[str]; ok { comb.Files = append(comb.Files, FileCombination{ File: v, PrefixSelector: prefix, SuffixSelector: suffix, }) continue } // Create if not found combs[str] = &Combination{ Files: []FileCombination{{ File: v, PrefixSelector: prefix, SuffixSelector: suffix, }}, Matched: str, } } } return combs } func CreatePrefixSuffixNamePattern(prefixes []string, suffixes []string) (CompiledPattern, error) { prefixesCombine := make([]string, len(prefixes)) for i, v := range prefixes { prefixesCombine[i] = fmt.Sprintf("(?:%s)", v) } suffixesCombine := make([]string, len(suffixes)) for i, v := range suffixes { suffixesCombine[i] = fmt.Sprintf("(?:%s)", v) } p := "" s := "" // Combine prefixes if len(prefixesCombine) > 1 { p = "(" + strings.Join(prefixesCombine, "|") + ")" } else if len(prefixesCombine) > 0 { p = prefixesCombine[0] } // Combine suffixes if len(suffixesCombine) > 1 { s = "(" + strings.Join(suffixesCombine, "|") + ")" } else if len(suffixesCombine) > 0 { s = suffixesCombine[0] } // Compile var r *regexp.Regexp var err error // Output if len(p) > 0 && len(s) > 0{ r, err = regexp.Compile("" + p + "(.*)" + s + "") } else if len(p) > 0 { r, err = regexp.Compile("" + p + "(.*)") } else if len(s) > 0 { r, err = regexp.Compile("(.*)" + s + "") } if err != nil { return nil, err } return CommonCompiledPattern{ p: r, prefixList: prefixes, suffixList: suffixes, }, nil } <file_sep>package tests import ( "github.com/xdire/algrefresh/homework/hw01_05_chess" "github.com/xdire/algrefresh/util" "strings" "testing" ) func Test_FENParse(t *testing.T) { files, err := util.GetDirectoryFiles("02_bits/1_Bitboard_FEN") if err != nil { t.Fatalf("Cannot get test files from: 01_strings_checks directory") } testReader(t, files, func(t *testing.T, input string, compareTo string) error { bitboard := &hw01_05_chess.BitBoard{} inputFormatted := strings.Trim(input," \n\r\t") compareFormatted := strings.TrimRight(compareTo, "\r\n") err := bitboard.ParseFEN(inputFormatted) if err != nil { t.Error(err) } output := bitboard.PrintLineNumberPositions() if output != compareFormatted { t.Errorf("Failed for input of %s with result of \n[%s] should be \n[%s]", inputFormatted, output, compareFormatted) } return nil }) }<file_sep>package trees import "fmt" type Comparable interface { Compare(c Comparable) int } type bstNode struct { left *bstNode right *bstNode parent *bstNode value Comparable level uint16 } func (bn *bstNode) calcLevel() { // Create local var l := uint16(0) if bn.left == nil && bn.right == nil { // Empty case just take zero } else if bn.left == nil { l = bn.right.level + 1 } else if bn.right == nil { l = bn.left.level + 1 } else { if bn.right.level >= bn.left.level { l = bn.right.level + 1 } else { l = bn.left.level + 1 } } // Replace in memory if changed if bn.level != l { bn.level = l } } type AVLTree struct { root *bstNode } func (a *AVLTree) Add(item Comparable) { // If root was empty if a.root == nil { a.root = &bstNode{ value: item, } return } // Full add var node *bstNode root := a.root for { cmp := item.Compare(root.value) if cmp < 0 { if root.left == nil { root.left = &bstNode{ value: item, } node = root.left break } root = root.left } else if cmp > 0 { if root.right == nil { root.right = &bstNode{ value: item, } node = root.right break } root = root.right } } a.rebalance(node) } func (a *AVLTree) Delete(item interface{}) { } func (a *AVLTree) Search(item interface{}) { } func (a *AVLTree) Peek() (Comparable, error) { if a.root != nil { return a.root.value, nil } return nil, fmt.Errorf("empty") } func (a *AVLTree) PrettyPrint() string { return "" } func (a *AVLTree) rebalance(node *bstNode) { for node != nil { node.calcLevel() lh := 0 rh := 0 if node.left != nil { lh = int(node.left.level) } if node.right != nil { rh = int(node.right.level) } sideCalc := lh - rh if sideCalc > 1 { a.rebalanceToRight(node) } else if sideCalc < -1 { a.rebalanceToLeft(node) } node = node.parent } } func (a *AVLTree) rebalanceToRight(node *bstNode) { var leftLeft int var leftRight int if node.left != nil && node.left.left != nil { leftLeft = int(node.left.left.level) } if node.right != nil && node.left.right != nil { leftRight = int(node.left.right.level) } if leftLeft >= leftRight { a.srr(node) } else { } } func (a *AVLTree) rebalanceToLeft(node *bstNode) { var rightRight int var rightLeft int if node.right != nil && node.right.right != nil { rightRight = int(node.right.right.level) } if node.right != nil && node.right.left != nil { rightLeft = int(node.right.left.level) } if rightRight >= rightLeft { a.slr(node) } else { } } func (a *AVLTree) blr(node *bstNode) { rotateChild := node.right a.slr(node) a.slr(node) a.srr(rotateChild) } func (a *AVLTree) brr(node *bstNode) { rotateChild := node.left a.srr(node) a.srr(node) a.slr(rotateChild) } func (a *AVLTree) slr(prevRoot *bstNode) { // Define rotation elements rotateCenter := prevRoot.right left := rotateCenter.left // Remap that previous root will be on the left of rotation center prevRoot.right = left rotateCenter.left = prevRoot rotateCenter.parent = prevRoot.parent prevRoot.parent = rotateCenter // Check if rotator left node did exist and switch it's parent if left != nil { left.parent = prevRoot } // Update the metadata on nodes prevRoot.calcLevel() rotateCenter.calcLevel() // Update tree root if prevRoot was actual tree root if prevRoot == a.root { a.root = rotateCenter return } // If prevRoot was not the tree root then update parent node // depending on which branch the prevRoot did reside if rotateCenter.parent.left == prevRoot { rotateCenter.parent.left = rotateCenter } else { rotateCenter.parent.right = rotateCenter } } func (a *AVLTree) srr(prevRoot *bstNode) { // Define rotation elements rotateCenter := prevRoot.left right := rotateCenter.right // Remap that previous root will be on the left of rotation center prevRoot.left = right rotateCenter.right = prevRoot rotateCenter.parent = prevRoot.parent prevRoot.parent = rotateCenter // Check if rotator left node did exist and switch it's parent if right != nil { right.parent = prevRoot } // Update the metadata on nodes prevRoot.calcLevel() rotateCenter.calcLevel() // Update tree root if prevRoot was actual tree root if prevRoot == a.root { a.root = rotateCenter return } // If prevRoot was not the tree root then update parent node // depending on which branch the prevRoot did reside if rotateCenter.parent.left == prevRoot { rotateCenter.parent.left = rotateCenter } else { rotateCenter.parent.right = rotateCenter } } <file_sep>package lists import ( "fmt" "testing" ) func TestLinkedList_AddStruct(t *testing.T) { sa := &LinkedList{} sa.Add(&TestStruct{name: "one"}) sa.Add(&TestStruct{name: "two"}) sa.Add(&TestStruct{name: "three"}) size := sa.Size() fmt.Printf("\nstruct array size %d", size) one := &TestStruct{} sa.GetValue(0, one) two := &TestStruct{} sa.GetValue(1, two) three := &TestStruct{} sa.GetValue(2, three) fmt.Printf("\nstruct values received [%+v] [%+v] [%+v]", one, two, three) remOne := &TestStruct{} sa.RemoveValue(0, remOne) remTwo := &TestStruct{} sa.RemoveValue(1, remTwo) remThree := &TestStruct{} sa.RemoveValue(0, remThree) fmt.Printf("\nstruct values deleted [%+v] [%+v] [%+v]", remOne, remTwo, remThree) size = sa.Size() fmt.Printf("\nstruct array size %d", size) } func TestLinkedList_AddString(t *testing.T) { sa := &LinkedList{} sa.Add("one") sa.Add("two") sa.Add("three") size := sa.Size() fmt.Printf("\nstring array size %d", size) one := "" sa.GetValue(0, &one) two := "" sa.GetValue(1, &two) three := "" sa.GetValue(2, &three) fmt.Printf("\nstring values received [%+v] [%+v] [%+v]", one, two, three) remOne := "" sa.RemoveValue(0, &remOne) remTwo := "" sa.RemoveValue(1, &remTwo) remThree := "" sa.RemoveValue(0, &remThree) fmt.Printf("\nvalues deleted [%+v] [%+v] [%+v]", remOne, remTwo, remThree) size = sa.Size() fmt.Printf("\narray size %d", size) } func TestLinkedList_AddInt(t *testing.T) { sa := &LinkedList{} sa.Add(1) sa.Add(2) sa.Add(3) size := sa.Size() fmt.Printf("\nstring array size %d", size) one := 0 sa.GetValue(0, &one) two := 0 sa.GetValue(1, &two) three := 0 sa.GetValue(2, &three) fmt.Printf("\nstring values received [%+v] [%+v] [%+v]", one, two, three) remOne := 0 sa.RemoveValue(0, &remOne) remTwo := 0 sa.RemoveValue(1, &remTwo) remThree := 0 sa.RemoveValue(0, &remThree) fmt.Printf("\nvalues deleted [%+v] [%+v] [%+v]", remOne, remTwo, remThree) size = sa.Size() fmt.Printf("\narray size %d", size) } func TestLinkedList_Fill(t *testing.T) { a := &LinkedList{} for i:=0; i<1000; i++ { a.Add(i) } fmt.Printf("\narray size after 1000 entries %d", a.size) for i:=0; i<999; i++ { a.Remove(1, nil) } a.Remove(0, nil) fmt.Printf("\narray size after deletion of 1000 entries %d", a.size) }<file_sep>package hw01_05_chess import ( "errors" "fmt" "strconv" "strings" ) const ( // Whites WPawn uint8 = iota WKnight WBishop WRook WQueen WKing // Blacks BPawn BKnight BBishop BRook BQueen BKing ) var resolveMap = map[rune]uint8 { // Whites 'P': WPawn, 'N': WKnight, 'B': WBishop, 'R': WRook, 'Q': WQueen, 'K': WKing, // Blacks 'p': BPawn, 'n': BKnight, 'b': BBishop, 'r': BRook, 'q': BQueen, 'k': BKing, } var resolveOrder = [12]rune{'P', 'N', 'B', 'R', 'Q', 'K', 'p', 'n', 'b', 'r', 'q', 'k'} type BitBoard struct { board [12]uint64 } //func NewBitBoard() *BitBoard { // return &BitBoard{board: [12]uint64{}} //} func (bb *BitBoard) DecodeFENCharacter(chr rune) (uint8, error) { if val, ok := resolveMap[chr]; ok { return val, nil } return 255, errors.New("not found") } func (bb *BitBoard) PlaceFENCharacter(chr rune) (uint8, error) { if val, ok := resolveMap[chr]; ok { return val, nil } return 255, errors.New("not found") } /** For FEN encoding following is true: - ROWS are coming top-down, meaning first row is 8, last is 1 - Every FIRST ROW POSITION is: ROW * 8 (Cells) */ func (bb *BitBoard) ParseFEN(str string) error { rows := strings.Split(str, "/") for row, chars := range rows { pos := uint8(0) for _, chr := range []rune(chars) { numVal, err := strconv.ParseUint(string(chr), 10, 0) if err == nil { pos += uint8(numVal) continue } figure, err := bb.DecodeFENCharacter(chr) if err != nil { return fmt.Errorf("wrong FEN format at row %d and character %c at pos %d", row, chr, pos) } // As the rows coming top-down we need to subtract first row from max row before // adding the array positional value bb.board[figure] |= 1 << uint64((7 - uint8(row)) * 8 + pos) pos++ } } return nil } func (bb *BitBoard) PrintLineNumberPositions() string { out := "" for i, _ := range resolveOrder { out += fmt.Sprintf("%d\r\n", bb.board[i]) } return strings.TrimRight(out, "\r\n") }<file_sep>package queues import ( "errors" "github.com/xdire/algrefresh/lists" ) type PriorityQueueList struct { list *lists.LinkedListOrdered size uint32 } func NewPriorityQueueList(comparator lists.AbstractComparator) *PriorityQueueList { return &PriorityQueueList{ list: lists.NewLinkedListOrdered(comparator), size: 0, } } func (p *PriorityQueueList) SetComparator(c func(a interface{}, b interface{}) (int8, error)) { p.list.SetComparator(c) } func (p *PriorityQueueList) Add(item interface{}, order interface{}) { ll := &lists.LinkedList{} llr := p.list.Once(ll, order).(*lists.LinkedList) llr.Add(item) p.size++ } func (p *PriorityQueueList) Poll() (interface{}, error) { return p.pPoll(nil) } func (p *PriorityQueueList) Peek() (interface{}, error) { return p.pPeek(nil) } func (p *PriorityQueueList) PollValue(receiver interface{}) error { _, err := p.pPoll(receiver) return err } func (p *PriorityQueueList) PeekValue(receiver interface{}) error { _, err := p.pPeek(receiver) return err } func (p *PriorityQueueList) Size() uint32 { return p.size } func (p *PriorityQueueList) pPoll(receiver interface{}) (interface{}, error) { llr, err := p.list.Peek() if err != nil { return nil, err } ll := llr.(*lists.LinkedList) // RemoveValue first index of sublist if size at least 2 if ll.Size() > 1 { p.size-- if receiver != nil { ll.RemoveValue(0, receiver) return nil, nil } return ll.Remove(0) } else if ll.Size() == 1 { // RemoveValue first index and remove the order // altogether if size is 1 if receiver != nil { ll.RemoveValue(0, receiver) _, err = p.list.Poll() p.size-- return nil, nil } v, err := ll.Remove(0) if err != nil { return nil, err } _, err = p.list.Poll() p.size-- return v, err } else { // If by somehow attached linked list was zeroed // in size, so we can't get any information from that // remove it and repeat _, err = p.list.Poll() return p.pPoll(receiver) } } func (p *PriorityQueueList) pPeek(receiver interface{}) (interface{}, error) { llr, err := p.list.Peek() if err != nil { return nil, err } ll := llr.(*lists.LinkedList) // If size is positive get first if ll.Size() > 0 { if receiver != nil { ll.GetValue(0, receiver) return nil, nil } return ll.Get(0) } // Should never happen due proper removal but covered return nil, errors.New("queue malfunction") } <file_sep>package lists import ( "fmt" "reflect" ) type SingleArray struct { arr []interface{} size uint32 genericType interface{} genericIsPointer bool } func NewSingleArray() *SingleArray { return &SingleArray{} } func (sa *SingleArray) Size() uint32 { return sa.size } func (sa *SingleArray) Add(item interface{}) { if sa.genericType == nil { vt := reflect.ValueOf(item).Type().Kind() if vt == reflect.Ptr { sa.genericType = reflect.ValueOf(item).Elem().Type() sa.genericIsPointer = true } else { sa.genericType = vt } fmt.Printf("\nType Kind: %+v\n", sa.genericType) sa.genericType = item } if sa.arr == nil { sa.size = 1 sa.arr = sa.allocate(sa.size) sa.arr[sa.size - 1] = item return } sa.resize(sa.size + 1) sa.arr[sa.size - 1] = item } func (sa *SingleArray) Get(index uint32) (interface{}, error) { panic("implement me") } func (sa *SingleArray) Remove(index uint32) (interface{}, error) { panic("implement me") } func (sa *SingleArray) GetValue(index uint32, receiver interface{}) { if index > sa.size - 1 { panic("out of bounds") } if sa.genericIsPointer { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(sa.arr[index]).Elem()) } else { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(sa.arr[index])) } } func (sa *SingleArray) RemoveValue(index uint32, receiver interface{}) { if index > sa.size { panic("out of bounds") } if sa.genericIsPointer { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(sa.arr[index]).Elem()) } else { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(sa.arr[index])) } // Shrink the slice by slicing original slice until the index // and appending everything what after index + 1 with spread if sa.size > 1 { sa.arr = append(sa.arr[:index], sa.arr[index+1:]...) } else { sa.arr = nil } sa.size-- } func (sa *SingleArray) AddAtIndex(index uint32, item interface{}) { if index > sa.size { panic("out of bounds") } sa.resize(sa.size + 1) sa.arr[sa.size - 1] = item } func (sa *SingleArray) allocate(size uint32) []interface{} { return make([]interface{}, size) } func (sa *SingleArray) resize(size uint32) { newArr := sa.allocate(size) copy(newArr, sa.arr) sa.arr = newArr sa.size = size } <file_sep>package lists import ( "reflect" ) type VectorArray struct { arr []interface{} size uint32 vector uint32 genericType interface{} genericIsPointer bool } func NewVectorArray(vector uint32) *VectorArray { return &VectorArray{vector:vector} } func (sa *VectorArray) Size() uint32 { return sa.size } func (sa *VectorArray) Add(item interface{}) { if sa.genericType == nil { vt := reflect.ValueOf(item).Type().Kind() if vt == reflect.Ptr { sa.genericType = reflect.ValueOf(item).Elem().Type() sa.genericIsPointer = true } else { sa.genericType = vt } sa.genericType = item } if sa.arr == nil { sa.resize() sa.arr[sa.size] = item sa.size++ return } if int(sa.size) == len(sa.arr) { sa.resize() } sa.arr[sa.size] = item sa.size++ } func (sa *VectorArray) Get(index uint32) (interface{}, error) { panic("implement me") } func (sa *VectorArray) Remove(index uint32) (interface{}, error) { panic("implement me") } func (sa *VectorArray) GetValue(index uint32, receiver interface{}) { if index > uint32(len(sa.arr) - 1) { panic("out of bounds") } if sa.genericIsPointer { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(sa.arr[index]).Elem()) } else { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(sa.arr[index])) } } func (sa *VectorArray) RemoveValue(index uint32, receiver interface{}) { if index > sa.size { panic("out of bounds") } if sa.genericIsPointer { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(sa.arr[index]).Elem()) } else { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(sa.arr[index])) } // Shrink the slice by slicing original slice until the index // and appending everything what after index + 1 with spread if sa.size > 1 { sa.arr = append(sa.arr[:index], sa.arr[index+1:]...) } else { sa.arr = nil } sa.size-- } func (sa *VectorArray) AddAtIndex(index uint32, item interface{}) { if index > sa.size + sa.vector { panic("out of bounds") } if index < uint32(len(sa.arr) - 1) { sa.arr[index] = item return } sa.resize() sa.arr[index] = item } func (sa *VectorArray) allocate(size uint32) []interface{} { return make([]interface{}, size) } func (sa *VectorArray) resize() { if sa.vector == 0 { sa.vector = 8 } newArr := sa.allocate(sa.size + sa.vector) if sa.arr != nil { copy(newArr, sa.arr) } sa.arr = newArr } <file_sep>package lists import ( "reflect" ) type FactorArray struct { arr []interface{} size uint32 factor uint32 cap uint32 initialCap uint32 genericType interface{} genericIsPointer bool } type FactorOptions struct { Factor uint32 InitialCap uint32 } func NewFactorArray(opt *FactorOptions) *FactorArray { f := uint32(50) c := uint32(8) if opt != nil { if opt.Factor != 0 { f = opt.Factor } if opt.InitialCap != 0 { c = opt.InitialCap } } return &FactorArray{factor: f, cap: c, initialCap: c} } func (sa *FactorArray) Size() uint32 { return sa.size } func (sa *FactorArray) Add(item interface{}) { if sa.genericType == nil { vt := reflect.ValueOf(item).Type().Kind() if vt == reflect.Ptr { sa.genericType = reflect.ValueOf(item).Elem().Type() sa.genericIsPointer = true } else { sa.genericType = vt } sa.genericType = item } if sa.arr == nil { sa.resize() sa.arr[sa.size] = item sa.size++ return } if sa.size == uint32(len(sa.arr)) { sa.resize() } sa.arr[sa.size] = item sa.size++ } func (sa *FactorArray) Get(index uint32) (interface{}, error) { panic("implement me") } func (sa *FactorArray) Remove(index uint32) (interface{}, error) { panic("implement me") } func (sa *FactorArray) GetValue(index uint32, receiver interface{}) { if index > uint32(len(sa.arr) - 1) { panic("out of bounds") } if sa.genericIsPointer { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(sa.arr[index]).Elem()) } else { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(sa.arr[index])) } } func (sa *FactorArray) RemoveValue(index uint32, receiver interface{}) { if index > sa.size { panic("out of bounds") } if receiver != nil && sa.genericIsPointer { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(sa.arr[index]).Elem()) } else if receiver != nil { reflect.ValueOf(receiver).Elem().Set(reflect.ValueOf(sa.arr[index])) } // Shrink the slice by slicing original slice until the index // and appending everything what after index + 1 with spread if sa.size > 1 { sa.arr = append(sa.arr[:index], sa.arr[index+1:]...) sa.cap-- } else { sa.arr = nil sa.cap = sa.initialCap } sa.size-- } func (sa *FactorArray) AddAtIndex(index uint32, item interface{}) { if index > sa.size + sa.factor { panic("out of bounds") } if index < uint32(len(sa.arr) - 1) { sa.arr[index] = item return } sa.resize() sa.arr[index] = item } func (sa *FactorArray) allocate(size uint32) []interface{} { return make([]interface{}, size) } func (sa *FactorArray) resize() { if sa.cap < sa.initialCap { sa.cap = sa.initialCap } newArr := sa.allocate(sa.size + sa.cap * sa.factor / 100) if sa.arr != nil { copy(newArr, sa.arr) } sa.arr = newArr } <file_sep>package lists type TestStruct struct { name string } <file_sep>package hw01_04_algebraic import "fmt" /* Power through iteration --- */ func PowIter(a float64, b uint32) float64 { res := float64(1) for i:=uint32(0); i < b; i++ { res *= a } return res } /* Power calculated through quadratic multiplication with addition --- */ func Pow2Mul(a float64, b int32) float64 { res := a pow := int32(1) // Until the power reaches half of desired power // double it, if reaches the half, then doubling // will not be possible anymore for pow < b / 2 { res *= res pow *= 2 fmt.Printf("\nPow 1/2: %d Result: %f", pow, res) } // Increase the rest in iterative mode for pow < b { res *= a pow++ fmt.Printf("\nPow 2/2: %d Result: %f", pow, res) } return res } /* Power calculated through counting power in binary disassemble fashion --- */ func Pow2Bin(a float64, b int64) float64 { res := float64(1) // Check until b reaches 0 or 1 for b > 1 { // If b is odd then multiply the result into the accumulator // - basically apply the single exponent each time the 1 is leftover of power if b % 2 == 1 { res *= a } // Power the value quadratically each cycle, meaning every // half-decreased power will be accounted and applied a *= a // Decrease the power in half b /= 2 } // Fulfill the rest accumulated values into result if b > 0 { res *= a } return res } <file_sep>package hw01_04_algebraic /* GCD by subtraction --- Example of 32 56 32 != 56 -> 56 - 32 -> 32 - 24 -> 24 - 8 -> 16 - 8 -> 8 = 8 */ func GCDSub(a int64, b int64) int64 { for a != b { if a > b { a -= b } else { b -= a } } return a } /* GCD by modulo --- Example of 32 56 32 != 0 && 56 != 0 -> 56 % 32 = 24 -> 32 % 24 = 8 -> 24 % 8 = 0 -> a > 0 ? return a(8) */ func GCDMod(a int64, b int64) int64 { for a != 0 && b != 0 { if a > b { a %= b } else { b %= a } } if a != 0 { return a } return b } <file_sep>package hw01_04_algebraic import "testing" func TestPow2Bin(t *testing.T) { type args struct { a float64 b int64 } tests := []struct { name string args args want float64 }{ { name: "Test power through binary", args:args{ a: 5, b: 9, }, want: 1953125, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := Pow2Bin(tt.args.a, tt.args.b); got != tt.want { t.Errorf("Pow2Bin() = %v, want %v", got, tt.want) } }) } } func TestPow2Mul(t *testing.T) { type args struct { a float64 b int32 } tests := []struct { name string args args want float64 }{ { name: "Test power through quadratic multiplications", args:args{ a: 5, b: 8, }, want: 390625, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := Pow2Mul(tt.args.a, tt.args.b); got != tt.want { t.Errorf("Pow2Mul() = %v, want %v", got, tt.want) } }) } } func TestPowIter(t *testing.T) { type args struct { a float64 b uint32 } tests := []struct { name string args args want float64 }{ { name: "Test power through iteration", args:args{ a: 5, b: 8, }, want: 390625, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := PowIter(tt.args.a, tt.args.b); got != tt.want { t.Errorf("PowIter() = %v, want %v", got, tt.want) } }) } } <file_sep>package tests import ( "github.com/xdire/algrefresh/util" "strconv" "strings" "testing" ) func Test_StringCounters(t *testing.T) { files, err := util.GetDirectoryFiles("01_strings_checks") if err != nil { t.Fatalf("Cannot get test files from: 01_strings_checks directory") } testReader(t, files, func(t *testing.T, input string, compareTo string) error { length := len(strings.Trim(input," \n\r\t")) desired, err := strconv.ParseInt(compareTo, 10, 0) if err != nil { t.Errorf("Parameter to compare is wrongly defined for " + "String Counters, should be integer, while it is: %+v, error: %+v", compareTo, err) } if int64(length) != desired{ t.Errorf("Failed for length of %d of input [%s] should be %d", length, input, desired) } return nil }) }<file_sep>package util import ( "os" "testing" "time" ) func TestCombinePattern(t *testing.T) { psPattern, err := CreatePrefixSuffixNamePattern([]string{"test."}, []string{".in", ".out"}) psPattern2, err := CreatePrefixSuffixNamePattern([]string{"quests.", "test."}, []string{".out"}) if err != nil { t.Error(err) } type args struct { files []File re CompiledPattern } tests := []struct { name string args args prefixEquals1 string prefixEquals2 string suffixEquals1 string suffixEquals2 string }{ { "Prefix Suffix pattern combination 1", args{ files: []File{ { Path: "here1", Info: FileInfoFake{FakeName: "test.idx1.in"}, }, { Path: "here2", Info: FileInfoFake{FakeName: "test.idx1.out"}, }, { Path: "here3", Info: FileInfoFake{FakeName: "test.idx2.out"}, }, { Path: "here4", Info: FileInfoFake{FakeName: "test.idx2.in"}, }, { Path: "nothere5", Info: FileInfoFake{FakeName: "test.idx2.an"}, }, { Path: "nothere6", Info: FileInfoFake{FakeName: "quests.idx2.in"}, }, }, re: psPattern, }, "test.", "", ".in", ".out", }, { "Prefix Suffix pattern combination 2", args{ files: []File{ { Path: "here1", Info: FileInfoFake{FakeName: "test.idx1.in"}, }, { Path: "here2", Info: FileInfoFake{FakeName: "test.idx1.out"}, }, { Path: "here3", Info: FileInfoFake{FakeName: "test.idx2.out"}, }, { Path: "here4", Info: FileInfoFake{FakeName: "test.idx2.in"}, }, { Path: "nothere5", Info: FileInfoFake{FakeName: "test.idx2.an"}, }, { Path: "nothere6", Info: FileInfoFake{FakeName: "quests.idx2.out"}, }, }, re: psPattern2, }, "test.", "quests.", ".in", ".out", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { res := CombinePattern(tt.args.files, tt.args.re) t.Logf("\n%+v\n%+v", res["idx1"], res["idx2"]) if len(res) != 2 { t.Errorf("Length should be equal 4 items for thest to pass") } for _, v := range res { for _, fileComb := range v.Files { if fileComb.PrefixSelector != tt.prefixEquals1 && fileComb.PrefixSelector != tt.prefixEquals2 { t.Errorf("Prefix should be propertly determined for test") } if fileComb.SuffixSelector != tt.suffixEquals1 && fileComb.SuffixSelector != tt.suffixEquals2 { t.Errorf("Suffix should be properly determined for test") } } } }) } } type FileInfoFake struct { FakeName string } func (f FileInfoFake) Name() string { return f.FakeName } func (f FileInfoFake) Size() int64 { panic("implement me") } func (f FileInfoFake) Mode() os.FileMode { panic("implement me") } func (f FileInfoFake) ModTime() time.Time { panic("implement me") } func (f FileInfoFake) IsDir() bool { panic("implement me") } func (f FileInfoFake) Sys() interface{} { panic("implement me") }<file_sep>package trees import "math" type IntervalSumTree struct { tree []float64 } func NewIntervalTreeFromSlice(from []float64) *IntervalSumTree { // Build the tree where newSize := 1 << uint64(math.Log(float64(len(from) - 1) + 1)) it := &IntervalSumTree{tree: make([]float64, newSize)} it.buildTree(from) return it } func (it *IntervalSumTree) buildTree(from []float64) { elements := len(from) for i := elements; i < len(it.tree); i++ { it.tree[i] = from[i - elements] } for i := elements - 1; i > 0; i-- { it.tree[i] = it.tree[i * 2] + it.tree[(i * 2) + 1] } } func (it *IntervalSumTree) SumAt(from, to int) { }<file_sep>package algrefresh type IList interface { Size() uint32 Add(item interface{}) Get(index uint32) (interface{}, error) Remove(index uint32) (interface{}, error) GetValue(index uint32, receiver interface{}) RemoveValue(index uint32, receiver interface{}) AddAtIndex(index uint32, item interface{}) } type IOrderedList interface { Size() uint32 SetComparator(c func(a interface{}, b interface{}) (int8, error)) Add(item interface{}, order interface{}) Once(item interface{}, order interface{}) interface{} Get(index uint32) (interface{}, error) GetOrder(order interface{}) (interface{}, error) GetValue(index uint32, receiver interface{}) GetOrderValue(order interface{}, receiver interface{}) error Remove(index uint32) (interface{}, error) RemoveValue(index uint32, receiver interface{}) } type IQueue interface { Push(item interface{}) Poll() (interface{}, error) Peek() (interface{}, error) PollValue(receiver interface{}) error PeekValue(receiver interface{}) error Size() uint32 } type IPriorityQueue interface { SetComparator(c func(a interface{}, b interface{}) (int8, error)) Add(item interface{}, order interface{}) Poll() (interface{}, error) Peek() (interface{}, error) PollValue(receiver interface{}) error PeekValue(receiver interface{}) error Size() uint32 } <file_sep>package lists import ( "fmt" "testing" ) func TestLinkedListOrdered_AddStruct(t *testing.T) { sa := &LinkedListOrdered{comparator:OrderedIntComparator} sa.Add(&TestStruct{name: "one"}, 3) sa.Add(&TestStruct{name: "two"}, 2) sa.Add(&TestStruct{name: "three"}, 1) size := sa.Size() fmt.Printf("\nstruct array size %d", size) one := &TestStruct{} sa.GetValue(0, one) two := &TestStruct{} sa.GetValue(1, two) three := &TestStruct{} sa.GetValue(2, three) fmt.Printf("\nstruct values received [%+v] [%+v] [%+v]", one, two, three) remOne := &TestStruct{} sa.Remove(0, remOne) remTwo := &TestStruct{} sa.Remove(1, remTwo) remThree := &TestStruct{} sa.Remove(0, remThree) fmt.Printf("\nstruct values deleted [%+v] [%+v] [%+v]", remOne, remTwo, remThree) size = sa.Size() fmt.Printf("\nstruct array size %d", size) } func TestLinkedListOrdered_AddString(t *testing.T) { sa := &LinkedListOrdered{comparator: OrderedIntComparator} sa.Add("one", 1) sa.Add("two", 2) sa.Add("three", 3) size := sa.Size() fmt.Printf("\nstring array size %d", size) one := "" sa.GetValue(0, &one) two := "" sa.GetValue(1, &two) three := "" sa.GetValue(2, &three) fmt.Printf("\nstring values received [%+v] [%+v] [%+v]", one, two, three) remOne := "" sa.Remove(0, &remOne) remTwo := "" sa.Remove(1, &remTwo) remThree := "" sa.Remove(0, &remThree) fmt.Printf("\nvalues deleted [%+v] [%+v] [%+v]", remOne, remTwo, remThree) size = sa.Size() fmt.Printf("\narray size %d", size) } func TestLinkedListOrdered_AddInt(t *testing.T) { sa := &LinkedListOrdered{comparator:OrderedIntComparator} sa.Add(1, -1) sa.Add(2, 0) sa.Add(3, 1) size := sa.Size() fmt.Printf("\nstring array size %d", size) one := 0 sa.GetValue(0, &one) two := 0 sa.GetValue(1, &two) three := 0 sa.GetValue(2, &three) fmt.Printf("\nstring values received [%+v] [%+v] [%+v]", one, two, three) remOne := 0 sa.Remove(0, &remOne) remTwo := 0 sa.Remove(1, &remTwo) remThree := 0 sa.Remove(0, &remThree) fmt.Printf("\nvalues deleted [%+v] [%+v] [%+v]", remOne, remTwo, remThree) size = sa.Size() fmt.Printf("\narray size %d", size) } func TestLinkedListOrdered_Fill(t *testing.T) { sa := &LinkedListOrdered{comparator: OrderedIntComparator} for i:=0; i<1000; i++ { sa.Add(i, i % 10) } fmt.Printf("\narray size after 1000 entries %d", sa.size) for i:=0; i<999; i++ { sa.Remove(1, nil) } sa.Remove(0, nil) fmt.Printf("\narray size after deletion of 1000 entries %d", sa.size) }
a24c5fec8af68a707274f7d2e931dc1999b1406d
[ "Go", "Go Module" ]
28
Go Module
xdire/algrefresh
d7f2c59f65ed7b27e2d7cf1e649419fcb8d0fcc8
2b841b3263b7fa4852dd0c8dfce4ca916d495200
refs/heads/main
<file_sep># FP2021 1. Add files to local folder 2. Commit files and changes to github desktop 3. Push files and changes to origin 4. Go to github.com and make sure changes were updated <file_sep># Load in Libraries library("ggplot") library("lattice") # Assess data format str(AverageGasPrice) # Looks good # Assess data format str(cardatabase) # Must change data from int to numeric cardatabase$CityMPG <- as.numeric(cardatabase$CityMPG) cardatabase$YearFuelCost <- as.numeric(cardatabase$YearFuelCost) str(cardatabase) # Looks good # Assess data format str(ElectricCarData_Clean2) # Looks good # Assess data format str(UsedCarSales) # Looks good
bc06662ca678528288bd509b25cdf76143c0bc35
[ "Markdown", "R" ]
2
Markdown
Danny1991x2/FP2021
587e3e3b94a9b6bafd0d2c7d6e004add6fe415b3
518cedf095d9a22243df2cd33ef81b7ac104860c
refs/heads/master
<file_sep>json.extract! @user, :name, :description, :created_at, :updated_at <file_sep>PaperclipExample::Application.routes.draw do resources :users resources :homes root 'users#index' end <file_sep>class RemoveColumnsfromHomes < ActiveRecord::Migration[5.0] def change remove_column :homes, :avatar end end <file_sep># Paperclip Example App This is a very simple example app to demonstrate how to use the [Paperclip](https://github.com/thoughtbot/paperclip) gem in a Rails 4 project.# paperclip # paperclip
096bad7962cfe2b77e046379e75467813d40deeb
[ "Markdown", "Ruby" ]
4
Ruby
suresh407/paperclip
0949300178dc710b6ede003b00a804f3963da41b
f20e4c860be5b1cfff69af50d0537c6973abc58b
refs/heads/master
<repo_name>VertiPub/ooziebuild<file_sep>/scripts/justbuildpost4.0.0.sh #!/bin/sh -ex umask 0022 cd ${WORKSPACE}/oozie mkdir -p ${WORKSPACE}/.m2 echo "<settings></settings>" > ${WORKSPACE}/.m2/settings.xml if [ -z ${WORKSPACE} ] || [ -z ${HADOOP_VERSION} ] || [ -z ${PIG_VERSION} ] || [ -z ${HIVE_VERSION} ]; then echo "HADOOP_VERSION, PIG_VERSION, HIVE_VERSION, and WORKSPACE must be explicitly set in the environment" exit 1 fi export MVN_LOCAL="-Dmaven.repo.local=${WORKSPACE}/.m2 --settings=${WORKSPACE}/.m2/settings.xml -DskipTests -P hadoop-2 -Dhadoop.version=${HADOOP_VERSION} -Dpig.version=${PIG_VERSION} -Dhive.version=${HIVE_VERSION} -Dhadoop.auth.version=${HADOOP_VERSION}" mvn versions:set -DnewVersion=${ARTIFACT_VERSION} ${MVN_LOCAL} # hack around the lack of extensibility in the mkdistro script sed -e s/assembly\:single/assembly\:single\ \$\{MVN_LOCAL\}/ < bin/mkdistro.sh > ${WORKSPACE}/scripts/mkdistro.sh mv ${WORKSPACE}/scripts/mkdistro.sh bin/mkdistro.sh /bin/sh -ex bin/mkdistro.sh <file_sep>/scripts/justinstall.sh #!/bin/sh # this is going to be problematic for oozie, since we've already released RPMs which are 2.0.5 # this default is different than all the others so that the script doesn't cause things to break when merged. ALTISCALE_RELEASE=${ALTISCALE_RELEASE:-2.0.5} export DEST_DIR=${INSTALL_DIR}/opt mkdir -p --mode=0755 ${DEST_DIR} cd ${DEST_DIR} tar -xvzpf ${WORKSPACE}/oozie/distro/target/oozie-${ARTIFACT_VERSION}-distro/oozie-${ARTIFACT_VERSION}/oozie-client-${ARTIFACT_VERSION}.tar.gz # Make the Client RPM export RPM_NAME=vcc-oozie-client-${ARTIFACT_VERSION} cd ${RPM_DIR} fpm --verbose \ --maintainer <EMAIL> \ --vendor Altiscale \ --provides ${RPM_NAME} \ -s dir \ -t rpm \ -n ${RPM_NAME} \ -v ${ALTISCALE_RELEASE} \ --description "${DESCRIPTION}" \ --iteration ${DATE_STRING} \ --rpm-user root \ --rpm-group root \ -C ${INSTALL_DIR} \ opt # Make the Server RPM rm -rf ${DEST_DIR} mkdir -p --mode=0755 ${DEST_DIR} cd ${DEST_DIR} tar -xvzpf ${WORKSPACE}/oozie/distro/target/oozie-${ARTIFACT_VERSION}-distro.tar.gz export OOZIE_ROOT=${DEST_DIR}/oozie-${ARTIFACT_VERSION} mkdir -p -m 0775 ${OOZIE_ROOT}/libext cd ${OOZIE_ROOT}/libext wget http://s3-us-west-1.amazonaws.com/verticloud-dependencies/ext-2.2.zip EXTSUM=`sha1sum ext-2.2.zip | awk '{print $1}'` if [ "${EXTSUM}" != "a949ddf3528bc7013b21b13922cc516955a70c1b" ]; then echo "FATAL: Filed to fetch the correct ext-2.2.zip" fi cd ${OOZIE_ROOT}/conf rm -rf hadoop-conf ln -s /etc/hadoop hadoop-conf cd ${OOZIE_ROOT}/libtools ln -s /opt/mysql-connector/mysql-connector.jar mysql-connector.jar cd ${OOZIE_ROOT}/oozie-server/lib ln -s /opt/mysql-connector/mysql-connector.jar mysql-connector.jar cd ${OOZIE_ROOT}/bin cp ${WORKSPACE}/scripts/pkgadd/oozie-status.sh . chmod 755 oozie-status.sh cd ${INSTALL_DIR} find opt/oozie-${ARTIFACT_VERSION} -type d -print | awk '{print "/" $1}' > /tmp/$$.files export DIRECTORIES="" for i in `cat /tmp/$$.files`; do DIRECTORIES="--directories $i ${DIRECTORIES} "; done export DIRECTORIES rm -f /tmp/$$.files export RPM_NAME=vcc-oozie-server-${ARTIFACT_VERSION} cd ${RPM_DIR} fpm --verbose \ -C ${INSTALL_DIR} \ --maintainer <EMAIL> \ --vendor Altiscale \ --provides ${RPM_NAME} \ --depends alti-mysql-connector \ -s dir \ -t rpm \ -n ${RPM_NAME} \ -v ${ALTISCALE_RELEASE} \ ${DIRECTORIES} \ --description "${DESCRIPTION}" \ --iteration ${DATE_STRING} \ --rpm-user oozie \ --rpm-group hadoop \ opt <file_sep>/README.md # This repository has been archived. ooziebuild ========== wrapper repo for oozie builds. <file_sep>/scripts/justbuildpost4.0.sh #!/bin/sh -ex if [[ -z "$HADOOP_VERSION" || -z "$PIG_VERSION" || -z "$HIVE_VERSION" ]]; then echo "HADOOP_VERSION, PIG_VERSION and HIVE_VERSION must be explicitly set in the environment" exit 1 fi mvn package assembly:single versions:set -DnewVersion=${ARTIFACT_VERSION} -DskipTests=true -Phadoop-2 -Dhadoop.version=${HADOOP_VERSION} -Dpig.version=${PIG_VERSION} -Dhive.version=${HIVE_VERSION} <file_sep>/scripts/justbuild.sh #!/bin/sh -ex umask 0022 cd ${WORKSPACE}/oozie mkdir -p ${WORKSPACE}/.m2 echo "<settings></settings>" > ${WORKSPACE}/.m2/settings.xml export MVN_LOCAL="-Dmaven.repo.local=${WORKSPACE}/.m2 --settings=${WORKSPACE}/.m2/settings.xml -DskipTests -Dhadoop.two.version=2.0.5-alpha -Dhadoop.version=2.0.5-alpha -Dpig.version=0.11.1 -Dhive.version=0.10.0" mvn versions:set -DnewVersion=${ARTIFACT_VERSION} ${MVN_LOCAL} # hack around the lack of extensibility in the mkdistro script sed -e s/assembly\:single/assembly\:single\ \$\{MVN_LOCAL\}/ < bin/mkdistro.sh > ${WORKSPACE}/scripts/mkdistro.sh mv ${WORKSPACE}/scripts/mkdistro.sh bin/mkdistro.sh /bin/sh -ex bin/mkdistro.sh <file_sep>/scripts/pkgadd/oozie-status.sh #!/bin/bash # # 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. # # resolve links - $0 may be a softlink PRG="${0}" while [ -h "${PRG}" ]; do ls=`ls -ld "${PRG}"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "${PRG}"`/"$link" fi done BASEDIR=`dirname ${PRG}` BASEDIR=`cd ${BASEDIR}/..;pwd` source ${BASEDIR}/bin/oozie-sys.sh -silent if [ -e "${CATALINA_PID}" ]; then echo "Oozie (pid `cat ${CATALINA_PID}`) is running" exit 0 else echo "Oozie is not running" exit -1 fi
60505d4b6b9d9f60918999abfa828dd05b25e9cf
[ "Markdown", "Shell" ]
6
Shell
VertiPub/ooziebuild
4238cf3ce9be074cdc76b5f64e88da5892b2e368
c60e6cfa12c8f6ad1854bddecacddc134b61dd90
refs/heads/master
<repo_name>anothersaddeveloper/test_repo_agile_project_long_name<file_sep>/README.md # Title For this repo So far we get error 415 when hook tries to communicate with Bamboo<file_sep>/some.py print("hello") print("hello") print("Great success")
54a72b95eed10da7e413150a7aaf9a8dc4278ea4
[ "Markdown", "Python" ]
2
Markdown
anothersaddeveloper/test_repo_agile_project_long_name
a985b74eba5571be73c7df2a5b0dc75fd4b33254
00398b4b78008b36a1b2360cab70106b3b8754d1
refs/heads/main
<file_sep>import logging import os from typing import List import gspread import jaconv from oauth2client.service_account import ServiceAccountCredentials from slackbot.bot import Bot from slackbot.bot import respond_to from slackbot.dispatcher import Message handler = logging.StreamHandler() logger = logging.getLogger(__name__) logger.addHandler(handler) logger.setLevel("DEBUG") LOGGER_CHANNEL_ID = os.getenv("LOGGER_CHANNEL_ID") SPREADSHEET_KEY = os.getenv("SPREADSHEET_KEY") SPREADSHEET = f"https://docs.google.com/spreadsheets/d/{SPREADSHEET_KEY}" SCOPES = [ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/spreadsheets', ] credentials = ServiceAccountCredentials.from_json_keyfile_name("ServiceAccountCredentials.json", SCOPES) spread = gspread.authorize(credentials) def main(): bot = Bot() bot.run() @respond_to("(.*)") def search(message: Message, something: str): try: logger.debug(message.body) logger.debug(something) if something == "help" or not something: message.reply( f"知りたい用語を教えてほしいワン! `@tellme 用語` で答えるワン。 用語集の管理は <{SPREADSHEET}|用語集> ここで管理しているワン。どんどん追加して欲しいワン。") return # ログとして #bot_test_tellme に出力する if LOGGER_CHANNEL_ID: text = f"user:{message.user['name']}, channel:{message.channel._body['name']}, query:{something}" message._client.rtm_send_message(LOGGER_CHANNEL_ID, text) worksheet = spread.open_by_key(SPREADSHEET_KEY).sheet1 query: str = something.strip().lower() query = jaconv.hira2kata(query) query = jaconv.h2z(query) res_text: List[str] = [] for row in worksheet.get_all_values(): # 英数字は小文字に統一 # ひらがなは全角カタカナに統一 target: str = row[0].lower() target = jaconv.hira2kata(target) target = jaconv.h2z(target) if target == "": break elif (len(query) >= 2 and query in target) or query == target: title = ",".join(row[0].split("\n")) res_text.append(f"*{title}*\n{row[1]}") if not res_text: res_text.append(f"わからなかったワン・・・。意味が分かったら <{SPREADSHEET}|用語集> に追加して欲しいワン") message.reply("\n\n".join(res_text)) except Exception as e: logger.exception(e) message.reply("エラーが発生したワン・・・") if __name__ == "__main__": main() <file_sep>## これはなに 主に用語集を教えてくれるbotです。 ## 準備 ### SpreadSheetに用語をまとめる まずはデータとなる情報をSpreadSheetにまとめます。SpreadSheetを選んだのは誰でも追加編集削除が簡単なためです。A列に用語、B列にその説明を記載していきます。会社内で権限をオープンにしてどんどん用語を集めるのがいいでしょう。 ![](./docs/images/spreadsheet.png) ### SpreadSheetのKeyを取得する SpreadSheetのURLに含まれるKeyをメモしておきます。画像はモザイクを掛けていますが、今回の例だと `10g~Y-c` の部分がKeyになります。 ![](./docs/images/url.jpg) ### SlackAPIの作成 SlackにBotを追加します。[ワークスペースで利用するボットの作成 \| Slack](https://slack.com/intl/ja-jp/help/articles/115005265703-%E3%83%AF%E3%83%BC%E3%82%AF%E3%82%B9%E3%83%9A%E3%83%BC%E3%82%B9%E3%81%A7%E5%88%A9%E7%94%A8%E3%81%99%E3%82%8B%E3%83%9C%E3%83%83%E3%83%88%E3%81%AE%E4%BD%9C%E6%88%90) などを参考に作ってください。 tokenが作成できたらメモしておきます ![](./docs/images/apitoken.png) botにはこのアイコン使ってください。かわいいので。 ![](./docs/images/icon.png) ### GCPプロジェクトの準備 GAEを実行するためのGCPプロジェクトを準備します。作り方などは公式ドキュメントがあるので割愛します。 ### サービスアカウントの作成 SlackBotがSpreadSheetの情報を取得するのにサービスアカウントが必要なので作ります。権限はとりあえず `閲覧者` にしています。 この時のサービスアカウントのメールアドレスをメモしておき、クレデンシャルファイルをjsonでダウンロードしておきます。 ![](./docs/images/serviceaccount.jpg) ### SpreadSheetの共有権限を付与する 先程のサービスアカウントでSpreadSheetを読み取りできるように設定します。共有設定でサービスアカウントのメールアドレスを入力し、閲覧者権限を付与します。 ![](./docs/images/share.jpg) ここまでの設定で、SpreadSheetのデータをSlackBotが読み取れるようになりました。 ### サービスアカウントの保存 SlackBotがSpreadSheetにアクセスするためにサービスアカウントのクレデンシャルが必要です。秘密鍵が含まれるためgitで保存したくありません。SecretManagerを使ってサービスアカウントのクレデンシャルを保持しておき、CloudBuildを実行する際に取り込むようにしたいと思います。 先程作成したサービスアカウントのクレデンシャルをダウンロードして、シークレットの値として保存します。ここで作ったシークレットの名前を後ほど利用します。 ![](./docs/images/secret.jpg) ### CloudBuildの設定 CloudBuildのトリガーを作ります。 #### イベント 手動呼び出しにします。 #### 構成 クラウドビルド構成ファイルを選択し、以下のファイルを指定します。 `infra/cloudbuild.yaml` #### 代入変数 大事な環境変数は代入変数で指定できるようにしています。ここに今までメモしてきた値を入力します。 |変数名|値| |---|---| |_API_TOKEN|SlackのAPIトークン| |_SPREADSHEET_KEY|SpreadSheetのKey| |_CREDENTIALS|SecretManagerに保存したクレデンシャルの名前| |_LOGGER_CHANNEL_ID|オプション:用語検索のログを出力するslack channnel IDを指定する| ![](./docs/images/cloudbuild.png) ## デプロイ 先程作ったCloudBuildを使ってビルドとデプロイを行います。実行ボタンを押してビルド・デプロイを行います。 ![](./docs/images/deploy.png) これで用語を説明してくれるbotの完成です。アプリケーションを作るより用語集をみんなで育てて行く方が大変なので、みんなでがんばりましょう。 ## 使い方 ### bot呼び出し方 ``` @tellme or @tellme help ``` 簡単な使い方を教えてくれます。 ``` @tellme sku ``` 用語を送信すると説明をしてくれます #### 細かい条件 - 大文字小文字どちらでもかまいません - 2文字以上のクエリ文字は部分一致です - 1文字のクエリ文字は完全一致です(基本的に対象となる用語がない) ## 番外編 ### GASは権限で詰まる 当初GASのwebアプリケーションで作ろうとしました。GCPプロジェクトを作る必要がなくシンプルなのです。しかし、SpreadSheetが会社アカウントの場合SlackからGASにアクセスする際に認証を通す必要があり、Slackの仕組み上解決することができませんでした。SpreadSheetを完全に公開してもいい場合はGASだけで実装できます。<file_sep>import os API_TOKEN = os.getenv("API_TOKEN") DEFAULT_REPLY = "Sorry but I didn't understand you" PLUGINS = [ 'slackbot.plugins', ] print(API_TOKEN) <file_sep>[tool.poetry] name = "term_slack_bot" version = "1.0.0" description = "" authors = ["shikajiro <<EMAIL>>"] [tool.poetry.dependencies] python = "^3.8" slackbot = "^1.0.0" gspread = "^3.7.0" oauth2client = "^4.1.3" jaconv = "^0.3" [tool.poetry.dev-dependencies] [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" <file_sep>FROM python:3.8 as base WORKDIR /app ENV LC_ALL=C.UTF-8 RUN apt update && \ pip install poetry==1.1.6 COPY poetry.lock pyproject.toml ./ RUN poetry install --no-dev COPY . . CMD ["poetry", "run", "python", "run.py"]
8818522b4ef14ccf9f8d43a819eaf456cd7cc571
[ "Markdown", "TOML", "Python", "Dockerfile" ]
5
Python
kuriyosh/term-slack-bot
fbb58b31258b41e6522202a4bd18cec1cd35b5f9
cf1f5a0e1bfe9549dd500d43ff2ee8ed2a8f73bf
refs/heads/master
<file_sep>package com.thiru.learn.recursion; import java.util.Arrays; import java.util.List; public class BinaryStrings { public static void main(String[] args) { int[] array = new int[4]; printBinary(array, 4); } static void printBinary(int[] array, int len) { if (len == 0) { System.out.println(Arrays.toString(array)); } else { for (int ch : List.of(0, 1)) { array[len - 1] = ch; printBinary(array, len - 1); } } } } <file_sep>package com.thiru.learn.algorithms.math; import java.math.BigInteger; public class IsProbablePrime { public static void main(String[] args) { int[] a = {11,17,19,23,37,95,93,97}; //int[] a = {99999989}; for(int i=0;i<a.length;i++) { System.out.printf("%d is prime=%s\n", a[i],isPrime(a[i])); } } static boolean isPrime(int num) { for(int i=2;i<20 && i<num;i++) { BigInteger bi = new BigInteger(i+""); if(bi.pow(num-1).mod(new BigInteger(num+"")).intValue()!=1) { return false; } } return true; } } <file_sep>package com.thiru.learn.datastructures.lists; import java.util.Objects; import java.util.function.Consumer; public class LinkedList<T> implements OrderedList<T>{ private Node<T> head; @Override public void forEach(Consumer<T> consumer) { Node<T> tmp = head; while(tmp!=null) { consumer.accept(tmp.data); tmp = tmp.next; } } @Override public boolean addAfter(T oldData, T newData) { Node<T> cur = head; boolean added = false; while(cur!=null && !Objects.equals(cur.data, oldData)) { cur = cur.next; } //if list is empty - very first time if(isEmpty()) { head = new Node<>(); head.data = newData; head.next = null; added = true; }else if(cur!=null && Objects.equals(cur.data, oldData)) { //if node to insert after found Node<T> newNode = new Node<>(); newNode.data = newData; newNode.next = cur.next; cur.next = newNode; added = true; } return added; } @Override public boolean addBefore(T oldData, T newData) { if(isEmpty()) { head = new Node<T>(); head.data = newData; head.next = null; }else { //list is not empty Node<T> cur = head; while(cur.next!=null && !Objects.equals(cur.next.data, oldData)) { cur = cur.next; } //if(cur!=null) } return false; } @Override public boolean remove(T data) { if(head!=null && Objects.equals(head.data,data)) { head = head.next; }else { Node<T> cur = head; Node<T> prev = null; while(cur!=null && !Objects.equals(cur.data, data)) { prev = cur; cur = cur.next; } if(cur!=null && Objects.equals(cur.data, data)) { prev.next = cur.next; }else { System.out.printf("%d not found%n",data); } } return false; } @Override public boolean isEmpty() { return head == null; } @Override public boolean contains(T data) { Node<T> current = head; while(current!=null) { if(Objects.equals(current.data, data)) { return true; } current = current.next; } return false; } @Override public void add(T data) { addAfter(null, data); } } <file_sep>package com.thiru.learn.algorithms.math; import java.util.Arrays; public class FindMaxPrimeNumberLessThanX { public static void main(String[] args) { int n = 100_000_000; int p = findMaxPrimeLessThan(n); System.out.printf("Max prime less than %d is %d%n",n,p); } static int findMaxPrimeLessThan(final int n) { boolean[] isPrime = new boolean[n]; Arrays.fill(isPrime, true); //1 is neither prime or composite isPrime[0] = false; //cross out all 2 multiples for(int multiple=4;multiple<=n;multiple+=2) { isPrime[multiple-1] = false; //multiple-1 since array indexes are 1 less than the actual multiple } //print(isPrime); //cross out other multiples for(int multiple=3;multiple<=n;multiple+=2) { if(isPrime[multiple-1]) { for(int m=multiple*multiple;m<n && m>multiple;m+=2*multiple) { isPrime[m-1] = false; } //print(isPrime); } } //print(isPrime); //find max prime, the first isPrime=true from the last index for(int p=isPrime.length;p>0;p--) { if(isPrime[p-1]) { return p; } } return -1; } static void print(boolean[] primes) { for(int i=0;i<primes.length;i++) { if(primes[i]) { System.out.printf("%d ", i+1); } } System.out.println(); } } <file_sep>package com.thiru.learn.datastructures.lists; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class LinkedListTest { private List<Integer> list; @BeforeEach public void before() { list = new ImprovedLinkedList<Integer>(); } @Test public void testEmpty() { assertTrue(list.isEmpty()); list.add(10); assertFalse(list.isEmpty()); } @Test public void testAdd() { java.util.List<Integer> nums = java.util.List.of(1,2,3,4,5); for(int n: nums) { list.add(n); } java.util.List<Integer> nums2 = new ArrayList<>(); list.forEach(n-> nums2.add(n)); assertTrue(nums2.containsAll(nums)); //assertTrue(nums2.equals(nums)); } @Test public void testContains() { int n = 10; assertFalse(list.contains(n)); list.add(n); assertTrue(list.contains(n)); } @Test public void testRemove() { int n = 10; list.add(n); assertTrue(list.contains(n)); assertFalse(list.remove(n+1)); assertTrue(list.remove(n)); assertFalse(list.contains(n)); } } <file_sep>package com.thiru.learn.datastructures.lists; import java.util.function.Consumer; public interface List<T> { void forEach(Consumer<T> consumer); boolean isEmpty(); boolean contains(T data); void add(T data); boolean remove(T data); }
cf451f702e17638ec4614e55498a39ad56591fe4
[ "Java" ]
6
Java
thirunavukarasut/learn
b261530a1b4ac84db03956886ae18862ecf6e9c4
d49b5cbc7ae8293839c96b06099938d635a89470
refs/heads/master
<file_sep><?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::get('/','PostController@index'); Route::get('new','PostController@newPost'); Route::post('createpost','PostController@createPost'); Route::get('view/{id}','PostController@viewpost'); Route::post('createComment','PostController@createComment');<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Post; use App\Comment; class PostController extends Controller { // public function index(){ $post=Post::all(); return view('index')->with('posts',$post); } public function newPost(){ return view('pages.new'); } public function createPost(Request $request){ $post=new Post; $post->title=$request->title; $post->content=$request->content; $post->save(); return redirect()->action('PostController@viewpost',['id' => $post->id]); } public function viewpost($id){ $post=Post::findOrFail($id); return view('pages.view',['post' => $post]); } public function createComment(Request $request, $id){ $post=Post::findOrFail($id); $comment=new Comment; $comment->name=$request->name; $comment->content=$request->content; $post->comments()->save($comment); return redirect()->action('PostController@viewpost',['id' => $post->id]); } }
f9f3f35ba34049a1105b7fdfeaca03d27ef5f7a5
[ "PHP" ]
2
PHP
richangsharma/blog
1265b9665d409b5f55ec886e5763226e3291df2d
a785e57f185ad5316237cc5000c4b3514a4c03a5
refs/heads/master
<file_sep>const fs = require("fs"); console.log("type something..."); process.stdin.on("data", data => { console.log(`I read ${data.length -1} character of text`); }); <file_sep># lorem ipsum ## Non quam lacus ### Vel elit<file_sep>const fs = require("fs"); const writeStream =fs.createWriteStream("./node_practice/lib/myFile.txt", "UTF-8"); process.stdin.on("data", data => { writeStream.write(data); });
bbc1dba3d488d2c7c519ab185b95cd951dff8678
[ "JavaScript", "Markdown" ]
3
JavaScript
Gonzalezenios/node_practice
2be2e1b47346b5c4a69f9b99da80364ef846b905
fad8fe29e0c16d0a54a53f02edd885a035854814
refs/heads/master
<repo_name>lec92/cargomania5<file_sep>/cargomania5/formularios/guardarTarifa.php <?php extract($_POST);//con esta función se extrae todo lo que viene desde el formulario y crea una variable por campo $objGuardar=new CargoMania; //Observen que en lugar de poner $_POST["txtCodigo"] solo se pone $txtCodigo, esto lo hace extract($_POST); con cada elemento //Del formulario, para evitar estar poniendo $_POST cada vez print_r($_POST);//Imprime el arreglo $_POST $campos=array($txtCodigo,$txtPeso,$txtVol,$lstCliente); /*echo "<br />"; print_r($campos);*/ if($guardarCont=$objGuardar->guardar_tarifa($campos)){ echo "Tarifa guardada"; header("location:?mod=agregar_tarifa"); } ?><file_sep>/cargomania5/procesos/guardarContenedor.php <?php include("header.php"); extract($_POST);//con esta función se extrae todo lo que viene desde el formulario y crea una variable por campo $objGuardar=new CargoMania; $respuesta = new stdClass(); //Observen que en lugar de poner $_POST["txtCodigo"] solo se pone $txtCodigo, esto lo hace extract($_POST); con cada elemento //Del formulario, para evitar estar poniendo $_POST cada vez print_r($_POST);//Imprime el arreglo $_POST $campos=array($txtCodigo,$txtTamano,$txtNumero,$txtSello,$lstAgente); /*echo "<br />"; print_r($campos);*/ $vacios=false; for($i=0;$i<count($campos);$i++){ if($cuenta[$i]==""){ $vacios=true; } } if($vacios==true){ $respuesta->mensaje=3; }else{ if($guardarCont=$objGuardar->guardar_contenedor($campos)){ $respuesta->mensaje=1; }else{ $respuesta->mensaje=2; } } ?><file_sep>/cargomania5/procesos/autenticar.php <?php include("header.php"); session_start(); $user=$_POST["username"]; $pwd=$_POST["<PASSWORD>"]; $respuesta = new stdClass(); if($user=="" || $user==null || trim($user)=="" || $pwd=="" || $pwd==null || trim($pwd)==""){ $respuesta->mensaje = 1; //echo "Combinaci&oacute;n de usuario y contrase&ntilde;a incorrecta"; //header("Location:?mod=login&msj=1"); }else{ $objUser=new CargoMania; $log=array($user,$pwd); $consultarUsuario=$objUser->consultar_usuario($log); $c=$consultarUsuario->rowCount(); //$conuser=pg_query("select * from usuario where Usuario='".$user."' and Contrasena='".$pwd."'"); //if(pg_num_rows($conuser)==1){ //Verificando que exista ese usuario y este activo if($c==1){ //Verificando que exista ese usuario y este activo $usuario=$consultarUsuario->fetch(PDO::FETCH_OBJ); //$usuario=pg_fetch_assoc($conuser); $_SESSION["autenticado"]="si"; //$_SESSION["tipo"]=$usuario["tipousuario"]; $_SESSION["tipo"]=$usuario->tipousuario; //$_SESSION["nombre"]=$usuario["usuario"]; $_SESSION["nombre"]=$usuario->correo; //echo "Usuario encontrado"; //$_SESSION["tipo"]=$usuario->TipoUsuario; //$row=pg_fetch_array($conuser); if($usuario->tipousuario=="Administrador"){ $respuesta->mensaje = 3; }else if($usuario->tipousuario=="Empleado"){ $respuesta->mensaje = 4; }else{ $respuesta->mensaje = 5; } }else{ //Si los datos ingresados son incorrectos mostrara el mensaje de alerta $respuesta->mensaje = 2; //header("Location:?mod=login&msj=2"); } } unset($objUser); echo json_encode($respuesta); ?><file_sep>/cargomania5/formularios/frmAgregarProveedor.php <script type="text/javascript"> function validar(){ if(document.getElementById("cmdGuardar").value=="Guardar"){ document.getElementById("agregarProveedor").action="?mod=guardar_proveedor"; }else{ document.getElementById("agregarProveedor").action="?mod=actualizar_proveedor"; } }</script> <?php $objProveedor=new CargoMania; $codigo=""; $nombre=""; $pais=""; $direccion=""; $telefono=""; $correo=""; if(isset($_GET["id"])){ $consultarProveedor=$objProveedor->mostrar_proveedor($_GET["id"]); if($consultarProveedor->rowCount()==1){ $contene=$consultarProveedor->fetch(PDO::FETCH_OBJ); $codigo=$contene->proveedor_id; $nombre=$contene->nombre_prov; $pais=$contene->pais_prov; $direccion=$contene->direccion; $telefono=$contene->telefono_prov; $correo=$contene->correo_prov; } } ?> <form name="agregarProveedor" id="agregarProveedor" method="post" onSubmit="return validar();"> <table> <caption><h1>AGREGAR UN NUEVO PROVEEDOR</h1></caption> <tr> <th>Codigo:</th> <td><input type="number" name="txtCodigo" id="txtCodigo" value="<?php echo $codigo ?>" /></td> </tr> <tr> <th>Nombre:</th> <td><input type="text" name="txtNombre" id="txtNombre" value="<?php echo $nombre ?>" /></td> </tr> <tr> <th>Pais:</th> <td><input type="text" name="txtPais" id="txtPais" value="<?php echo $pais ?>" /></td> </tr> <tr> <th>Direccion:</th> <td><input type="text" name="txtDireccion" id="txtDireccion" value="<?php echo $direccion ?>" /></td> </tr> <tr> <th>Telefono:</th> <td><input type="text" name="txtTelefono" id="txtTelefono" value="<?php echo $telefono ?>" /></td> </tr> <tr> <th>Correo:</th> <td><input type="text" name="txtCorreo" id="txtCorreo" value="<?php echo $correo ?>" /></td> </tr> <tr> <tr> <td><input type="submit" name="cmdGuardar" value="<?php if(isset($_GET["id"])){echo "Actualizar";}else{echo "Guardar";}?>" id="cmdGuardar" /></td> </tr> </table> </form> <table> <tr><th>Codigo</th><th>Nombre</th><th>Pais</th><th>Direccion</th><th>Telefono</th><th>Correo</th><th>Opcion</th></tr> <?php $consultarProveedor=$objProveedor->listar_proveedor(); if($consultarProveedor->rowCount()>0){ while($proveedor=$consultarProveedor->fetch(PDO::FETCH_OBJ)){ echo "<tr><td>".$proveedor->proveedor_id."</td><td>".$proveedor->nombre_prov."</td><td>".$proveedor->pais_prov."</td> <td>".$proveedor->direccion."</td><td>".$proveedor->telefono_prov."</td><td>".$proveedor->correo_prov."</td><td><a href='?mod=agregar_proveedor&id=".$proveedor->proveedor_id."'>Mostrar</a></td></tr>"; } } ?> </table><file_sep>/cargomania5/formularios/frmAgregarServicioBodega.php <script type="text/javascript"> function validar(){ if(document.getElementById("cmdGuardar").value=="Guardar"){ document.getElementById("agregarServiciobodega").action="?mod=guardar_serviciobodega"; }else{ document.getElementById("agregarServiciobodega").action="?mod=actualizar_ServicioBodega"; } }</script> <?php $objServiciobodega=new CargoMania; $codigo=""; $nomb_serv=""; $precio_serv=""; $agente=""; if(isset($_GET["id"])){ $consultarServiciobodega=$objServiciobodega->mostrar_serviciobodega($_GET["id"]); if($consultarServiciobodega->rowCount()==1){ $contene=$consultarServiciobodega->fetch(PDO::FETCH_OBJ); $codigo=$contene->serv_bod_id; $nomb_serv=$contene->nombre_serv_bod; $precio_serv=$contene->precio_serv_bod; $agente=$contene->fk_agente_bod; } } ?> <form name="agregarServiciobodega" id="agregarServiciobodega" method="post" onSubmit="return validar();"> <table> <caption><h1>AGREGAR SERVICIOBODEGA</h1></caption> <tr> <th>Codigo:</th> <td><input type="number" name="txtCodigo" id="txtCodigo" value="<?php echo $codigo ?>" /></td> </tr> <tr> <th>Nombre del servicio:</th> <td><input type="text" name="txtnomb_serv" id="txtnomb_serv" value="<?php echo $nomb_serv ?>" /></td> </tr> <tr> <th>Precio del servicio:</th> <td><input type="text" name="txtprecio_serv" id="txtprecio_serv" value="<?php echo $precio_serv ?>" /></td> </tr> <tr> <th>Agente:</th> <td><select name="lstAgente" id="lstAgente"> <?php $consultarAgente=$objServiciobodega->consultar_agentes(); if($consultarAgente->rowCount()>0){ echo "<option value='0'>Elija un agente</option>"; while($agente=$consultarAgente->fetch(PDO::FETCH_OBJ)){ ?> <?php if($agente->aget_bod_id==$agente && $agente!=""){ $selected=" selected"; }else{ $selected=""; } ?> <option value="<?php echo $agente->aget_bod_id ?>" <?php echo $selected; ?>><?php echo $agente->nombre_aget_bod ?></option> <?php } }else{ ?> <option value="0">No hay agentes</option> <?php } ?> </select></td> </tr> <tr> <td><input type="submit" name="cmdGuardar" value="<?php if(isset($_GET["id"])){echo "Actualizar";}else{echo "Guardar";}?>" id="cmdGuardar" /></td> </tr> </table> </form> <table> <tr><th>Codigo</th><th>nombre servicio</th><th>Precio</th><th>Agente</th><th>Opcion</th></tr> <?php $consultarServiciobodega=$objServiciobodega->listar_serviciobodega(); if($consultarServiciobodega->rowCount()>0){ while($Serviciobodega=$consultarServiciobodega->fetch(PDO::FETCH_OBJ)){ $agente=$objServiciobodega->consultar_agente($Serviciobodega->fk_agente_bod)->fetch(PDO::FETCH_OBJ); echo "<tr><td>".$Serviciobodega->serv_bod_id."</td><td>".$Serviciobodega->nombre_serv_bod."</td><td>".$Serviciobodega->precio_serv_bod."</td><td>".$agente->nombre_aget_bod. "</td><td><a href='?mod=agregar_serviciobodega&id=".$Serviciobodega->serv_bod_id."'>Mostrar</a></td></tr>"; } } ?> </table><file_sep>/cargomania5/formularios/s2.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Multisport</title> <link href="../../SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" /> <link href="../../slideshow/design_slideshow.css" rel="stylesheet" type="text/css" /> <link href="../../slideshow/ulightbox.css" rel="stylesheet" type="text/css"> <link type="text/css" rel="StyleSheet" href="../../slideshow/layer6.css"> <script src="../../SpryAssets/SpryMenuBar.js" type="text/javascript"></script> <script type="text/javascript" src="../../slideshow/jquery-1_002.js"></script> <script type="text/javascript" src="../../slideshow/parametros_slideshow.js"></script> <script>var div = document.getElementsByTagName('div')[0]; div.innerHTML = '';</script> <script type="text/javascript" src="../../slideshow/jquery-1.js"></script> <script type="text/javascript" src="../../slideshow/ulightbox.js"></script> <script type="text/javascript" src="../../slideshow/uwnd.js"></script> <link href="../../SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" /> <link href="../../slideshow/design_slideshow.css" rel="stylesheet" type="text/css" /> <link href="../../slideshow/ulightbox.css" rel="stylesheet" type="text/css"> <link type="text/css" rel="StyleSheet" href="../../slideshow/layer6.css"> <script src="../../SpryAssets/SpryMenuBar.js" type="text/javascript"></script> <script type="text/javascript" src="../../slideshow/jquery-1_002.js"></script> <script type="text/javascript" src="../../slideshow/parametros_slideshow.js"></script> <script>var div = document.getElementsByTagName('div')[0]; div.innerHTML = '';</script> <script type="text/javascript" src="../../slideshow/jquery-1.js"></script> <script type="text/javascript" src="../../slideshow/ulightbox.js"></script> <script type="text/javascript" src="../../slideshow/uwnd.js"></script> <link href="../../panel/style.css" rel="stylesheet" type="text/css" /> <style type="text/css"> .UhideBlock { display: none } </style> <style type="text/css"> div.send { position: relative; width: 115px; height: 34px; overflow:hidden; background:url(../../images/enviar.png) left top no-repeat; clip:rect(0px, 80px, 24px, 0px ); } div.send input { position: absolute; left: auto; right: 0px; top: 0px; margin:0; padding:0; filter: Alpha(Opacity=0); -moz-opacity: 0; opacity: 0; } </style> <script type="text/javascript"> function popup(url,ancho,alto) { var posicion_x; var posicion_y; posicion_x=(screen.width/2)-(ancho/2); posicion_y=(screen.height/2)-(alto/2); window.open(url, "", "width="+ancho+",height="+alto+",menubar=0,toolbar=0,directories=0,scrollbars=no,resizable=no,left="+posicion_x+",top="+posicion_y+""); } </script> </head> <body> <div style="background-color:#222 "class="header"><!-- end .header --> <table width="944" border="0"> <tr> <td width="553" height="72"><img src="../imagenes/Logo.png" width="213" height="70"></td> <td width="381"><form name="form1" method="post" action=""> </form></td> </tr> </table> </div> <div class="container"> <div style="background-color:#044E7C "class="header"><!-- end .header --> <table width="1013" border="0"> <tr> <td width="1007" height="21"><form name="form1" method="post" action=""> <p> <label for="textfield"></label> </p> </form></td> </tr> </table> </div> </div> <div style="background-color:#000"><h1 align="center"><font color="#F2F2F2">Pregunta secreta</font></h1> </div> <table align="center" width="350" height="30" border="0"> <tr> <td> <?php if (isset($_GET['errorusuario'])){ if ($_GET['errorusuario']==1){ echo "<center><span class='style9'>Respuesta incorrecta</span></center>";} else{ echo ""; }} ?> </td> </tr> </table> <?php include("../conexion.php"); $correo=$_POST['txt_correo']; $result=pg_query("SELECT * FROM usuario where correo='$correo'"); $filas=pg_numrows($result); if($filas==0){ header("Location:validacion.php?errorusuario=1"); } else{ $resultado=pg_query("SELECT pregunta FROM usuario where correo='$correo'"); $row = pg_fetch_array($resultado); $pregunta = $row['pregunta']; echo "<center><b>$pregunta</b></center>"; ?> <form name="formulario" method="post" action="s3.php" > <table align="center"> <center><input name="txt_correo" type="text" size="50" value="<?php echo $correo ?>"/></center> <tr> <td align="right">Respuesta:</td> <td> <input type="text" name="txt_respuesta" id="txt_respuesta"> <a href="javascript:popup('s3.php',800,780)"><input style="height:60px; width:100px; font-size:20px" type="submit" name="Submit" value="Enviar" /></td></b></font><br/> </tr> <tr> <td colspan="2" align="center"> <div align="center" class="send"> </div> </td> </tr> </table> </form> <?php } ?> </body> </html> <file_sep>/cargomania5/js/bitacora.php <table align="center" width="100%"> <tr> <th width="10%">Fecha</th> <th width="10%">Usuario</th> <th width="70%">Accion</th> <th width="10%">Tipo Accion</th> </tr> <?php $bitacora=mysql_query('Select * from bitacora'); while($row=mysql_fetch_assoc($bitacora)){ ?> <tr> <td><?php echo $bitacora["Fecha"]; ?></td> <td><?php echo $bitacora["idUsuario"]; ?></td> <td><?php echo $bitacora["Accion"]; ?></td> <?php if($bitacora["Tipo_Accion"]==1){ $accion='Adicion'; }else if($bitacora["Tipo_Accion"]==2){ $accion='Modificacion'; }else if($bitacora["Tipo_Accion"]==3){ $accion='Eliminación/Desactivación'; } ?> <td><?php echo $accion; ?></td> </tr> <?php } ?> </table><file_sep>/cargomania5/formularios/frmAgregarCliente.php <script type="text/javascript"> function validar(){ if(document.getElementById("cmdGuardar").value=="Guardar"){ document.getElementById("agregarCliente").action="?mod=guardar_cliente"; }else{ document.getElementById("agregarCliente").action="?mod=actualizar_cliente"; } }</script> <?php $objCliente=new CargoMania; $codigo=""; $nomb_empr=""; $giro=""; $numero_reg=""; $direccion=""; $nombre_repre=""; $apellido_repre=""; $telefono_repre=""; $email_repre=""; if(isset($_GET["id"])){ $consultarCliente=$objCliente->mostrar_cliente($_GET["id"]); if($consultarCliente->rowCount()==1){ $contene=$consultarCliente->fetch(PDO::FETCH_OBJ); $codigo=$contene->cliente_id; $nomb_empr=$contene->nombre_empr; $giro=$contene->giro; $numero_reg=$contene->num_reg; $direccion=$contene->direccion; $nombre_repre=$contene->nom_represent; $apellido_repre=$contene->apellido_represent; $telefono_repre=$contene->telefono_represent; $email_repre=$contene->correo; } } ?> <form name="agregarCliente" id="agregarCliente" method="post" onSubmit="return validar();"> <table> <caption><h1>AGREGAR CLIENTE</h1></caption> <tr> <th>Codigo:</th> <td><input type="number" name="txtCodigo" id="txtCodigo" value="<?php echo $codigo ?>" /></td> </tr> <tr> <th>Nombre Empresa:</th> <td><input type="text" name="txtEmpresa" id="txtEmpresa" value="<?php echo $nomb_empr ?>" /></td> </tr> <tr> <th>Giro:</th> <td><input type="text" name="txtGiro" id="txtGiro" value="<?php echo $giro ?>" /></td> </tr> <tr> <th>Numero de Registro:</th> <td><input type="text" name="txtRegistro" id="txtRegistro" value="<?php echo $numero_reg ?>" /></td> </tr> <tr> <th>Direccion:</th> <td><input type="text" name="txtDireccion" id="txtDireccion" value="<?php echo $direccion ?>" /></td> </tr> <tr> <th>Nombre Representante:</th> <td><input type="text" name="txtNom_repre" id="txtNom_repre" value="<?php echo $nombre_repre ?>" /></td> </tr> <tr> <th>Apellido Representante:</th> <td><input type="text" name="txtApell_repre" id="txtApell_repre" value="<?php echo $apellido_repre ?>" /></td> </tr> <tr> <th>Telefono Representante:</th> <td><input type="text" name="txtTel_repre" id="txtTel_repre" value="<?php echo $telefono_repre ?>" /></td> </tr> <tr> <th>Email Representante:</th> <td><input type="text" name="txtEmail_repre" id="txtEmail_repre" value="<?php echo $email_repre ?>" /></td> </tr> <tr> <td><input type="submit" name="cmdGuardar" value="<?php if(isset($_GET["id"])){echo "Actualizar";}else{echo "Guardar";}?>" id="cmdGuardar" /></td> </tr> </table> </form> <table> <tr><th>Codigo</th><th>Tama&ntilde;o</th><th>Numero</th><th>Sello</th><th>Agente</th><th>Opcion</th></tr> <?php $consultarCliente=$objCliente->listar_cliente(); if($consultarCliente->rowCount()>0){ while($cliente=$consultarCliente->fetch(PDO::FETCH_OBJ)){ echo "<tr><td>".$cliente->cliente_id."</td><td>".$cliente->nombre_empr."</td><td>".$cliente->giro."</td> <td>".$cliente->num_reg."</td><td>".$cliente->direccion."</td><td>".$cliente->nom_represent."</td><td>".$cliente->apellido_represent."</td><td>".$cliente->telefono_represent."</td><td>".$cliente->correo."</td><td><a href='?mod=agregar_cliente&id=".$cliente->cliente_id."'>Mostrar</a></td></tr>"; } } ?> </table><file_sep>/cargomania5/formularios/servicio.php <!DOCTYPE html> <html> <head> <meta content="text/html; charset=windows-1252" http-equiv="content-type"> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="jquery-flete.js" ></script> <link href="../css/style4.css" rel="stylesheet" type="text/css"> <title>Cargomania - Servicio nuevo</title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#prove').change(function(){ var id=$('#prove').val(); $('#direccion').load('ajax.php?id='+id); $('#pais').load('ajax_pais_prov.php?id='+id); }); }); </script> <script type="text/javascript"> function popup(url,ancho,alto) { var posicion_x; var posicion_y; posicion_x=(screen.width/2)-(ancho/2); posicion_y=(screen.height/2)-(alto/2); window.open(url, "", "width="+ancho+",height="+alto+",menubar=0,toolbar=0,directories=0,scrollbars=no,resizable=no,left="+posicion_x+",top="+posicion_y+""); } </script> <?php //cliente $objCliente = new Cargomania; if(isset($_GET["id"])){ $consultarCliente=$objCliente->mostrar_cliente($_GET["id"]); if($consultarCliente->rowCount()==1){ $cliente=$consultarCliente->fetch(PDO::FETCH_OBJ); $cli=$cliente->nombre_empr; } } // $objServicio = new Cargomania; $agente=""; if(isset($_GET["id"])){ $consultarContenedor=$objContenedor->mostrar_contenedor($_GET["id"]); if($consultarContenedor->rowCount()==1){ $contene=$consultarContenedor->fetch(PDO::FETCH_OBJ); $proveedor=$contene->fk_proveedor; } } $objAduana = new Cargomania; if(isset($_GET["id"])){ $consultarAduana=$objAduana->mostrar_aduana_llegada($_GET["id"]); if($consultarAduana->rowCount()==1){ $adu=$consultarAduana->fetch(PDO::FETCH_OBJ); $adu=$contene->nombre_adu_llega; } } $objFlete = new Cargomania; if(isset($_GET["id"])){ $consultarFlete=$objFlete->mostrar_flete($_GET["id"]); if($consultarFlete->rowCount()==1){ $flete=$consultarFlete->fetch(PDO::FETCH_OBJ); $nombre=$contene->nombre_agent_fle; } } /* $sql = "SELECT * FROM cliente where cliente_id=1"; $result = pg_query($cnx,$sql); if (!$result){ echo "ocurrio un error"; exit; } */ ?> </head> <body> <img src="imagenes/logo.png" width="250px"> <form method="POST" action=""> <table class="formulario" border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td colspan="4" class="titulo" style="background-image:url(images/bar.jpg); background-repeat: repeat-x;"><span class="tittle_text">Cliente</span> <a href="javascript:popup('?mod=agregar_cliente',500,700)"><img title="Agregar cliente" src="imagenes/botones/agregar.png" align="right"></a> <a href="javascript:popup('?mod=agregar_cliente',500,700)"><img title="Editar cliente" src="imagenes/botones/editar.png" align="right"></a> <img </td> </tr> <tr> <?php if($_POST['buscador']){ $buscar = $_POST['lstCliente']; if(empty($buscar)){ echo "no se encontro nada"; }else{ $sql = "SELECT * FROM cliente WHERE cliente_id = '$buscar'"; $result = pg_query($cnx,$sql); if(!$result){ echo 'ocurrio un error'; } while($row = pg_fetch_array($result)){ ?> <!-- comienza aqui --> <td class="categoria_cliente">Codigo</td> <td><input class="text_area" name="test" disabled="disabled" value="<?php echo $row['cliente_id']; ?>" type="text"></td> <td class="categoria_cliente">País cliente</td> <td class="categoria_cliente_derecha"> <label class="text_area">el salvador (campo faltante)</label> </td> </tr> <tr> <td class="categoria_cliente">Fecha</td> <td><input class="text_area" name="test" disabled="disabled" value="<?php date_default_timezone_get('UTC'); echo date("d-m-Y") ?>" type="text"></td> <td class="categoria_cliente">Direccion cliente</td> <td> <label class="text_area"><?php echo $row['direccion'];?></label></td> </tr> <tr> <td class="categoria_cliente">Hora</td> <td><input class="text_area" name="test" disabled="disabled" value="<?php echo date('H:i:s'); ?> " type="text"></td> <td class="categoria_cliente">Telefono</td> <td> <label class="text_area"><?php echo $row['telefono_represent'];?></label> </td> </tr> <tr> <td class="categoria_cliente">Tarifa</td> <td><label class="text_area">$500</label> </td> </tr> <!-- termina aqui --> <?php } } } ?> <tr> <td class="categoria_cliente">Nombre cliente</td> <td> <select name="lstCliente" id="lstCliente" class="select_style"> <?php $consultarCliente=$objCliente->consultar_clientes(); if($consultarCliente->rowCount()>0){ echo "<option value='0'>Elija un cliente</option>"; while($cli=$consultarCliente->fetch(PDO::FETCH_OBJ)){ ?> <?php if($cli->cliente_id==$cli && $cli!=""){ $selected=" selected"; }else{ $selected=""; } ?> <option value="<?php echo $cli->cliente_id ?>" <?php echo $selected; ?>><?php echo $cli->nombre_empr ?></option> <?php } }else{ ?> <option value="0">No hay clientes</option> <?php } ?> </select> </td> <td> <input type="submit" name="buscador" value="Buscar" /> </td> <!-- tarifa--> </tr> </tbody> </table> <hr> <table class="formulario" border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td colspan="10" rowspan="1" class="titulo" style="background-image:url(images/bar.jpg); background-repeat: repeat-x;"><span class="tittle_text">Informacion de la carga</span></td> </tr> <tr class="cat_titulo"> <td>Bultos</td> <td>Peso</td> <td>Volumen (opcional)</td> <td>Tipo carga</td> <td>Servicio bodega</td> <td>Bodega</td> <td>N° Contenedor</td> <td>N° Sello</td> <td>Estado</td> <td>Agregar</td> </tr> <tr> <td> <input class="text_area2" name="test" placeholder="1000" type="text"> </td> <td> <input class="text_area2" name="test" placeholder="1000 lbs" type="text"> </td> <td> <input class="text_area2" name="test" placeholder="8.7 m3" type="text"> </td> <td> <input class="text_area3" name="test" placeholder="Computadoras" type="text"> </td> <td> <select class="select_style_bodega"> <!-- fin --> <!-- fin--> <td> <select class="select_style_bodega"> <option value="0" selected="selected">San geronimo</option> </select> </td> <td> <input class="text_area2" name="test" placeholder="SMLV 123456-7" type="text"> </td> <td> <input class="text_area2" name="test" placeholder="01443" type="text"> </td> <td> <select class="select_status_style"> <option value="0" selected="selected">En espera...</option> <option value="1">Cargado</option> <option value="2">Pendiente</option> <option value="3">Anulado</option> </select> </td> <td align="center"> <img src="imagenes/botones/plus.png"></img> </td> </tr> </tbody> </table> <hr> <table class="formulario" border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td colspan="2" class="titulo" style="background-image:url(images/bar.jpg); background-repeat: repeat-x;"><span class="tittle_text">Proveedor</span><a href="?mod=agregar_proveedor"> <a href="javascript:popup('?mod=agregar_proveedor',500,700)"><img title="Agregar cliente" src="imagenes/botones/agregar.png" align="right"></a> <a href="javascript:popup('?mod=agregar_proveedor',500,700)"><img title="Editar cliente" src="imagenes/botones/editar.png" align="right"></a></td> </tr> <tr> <td class="categoria_cliente">Nombre proveedor</td> <td> <?php $consulta=pg_query("select proveedor_id,nombre_prov from proveedor order by nombre_prov ASC"); echo "<select name='prove' id='prove' class='select_style' >"; echo "<option>seleccione proveedor</option>"; while ($fila=pg_fetch_array($consulta)){ echo "<option value='".$fila[0]."'>".utf8_encode($fila[1])."</option>"; } echo "</select>"; ?> </td> </tr> <tr> <td class="categoria_cliente">Pais</td> <td> <div id="pais"> <select name="edo" class="select_style"> <option value="">Seleccione pais </option> </select> </div> </td> </tr> <tr> <td class="categoria_cliente">Direccion Proveedor</td> <td> <div id="direccion"> <select name="edo" class="select_style" > <option value="">Seleccione Direccion </option> </select> </div> </td> </tr> </tbody> </table> <hr> <table class="formulario" border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td colspan="5" rowspan="1" class="titulo" style="background-image:url(images/bar.jpg); background-repeat: repeat-x;"><span class="tittle_text">Naviera</span></td> </tr> <tr> <td class="categoria_cliente">Dia salida</td> <td><input class="text_area" name="test" type="date"> </td> <td class="categoria_cliente">Tipo transporte</td> <td> <select class="select_status_style" id="select_transport"> <option value="maritimo">MARÍTIMO</option> <option value="aereo">AEREO</option> <option value="terrestre" >TERRESTRE</option> </select> </td> </tr> <tr> <td class="categoria_cliente">Dia llegada</td> <td><input class="text_area" name="test" type="date"> </td> <div class="barco"> <td class="categoria_cliente">Nombre barco</td> <td><input class="text_area" name="test" placeholder="<NAME>" type="text"> </td></div> </tr> <tr> <td class="categoria_cliente">Lugar de salida</td> <!-- comienza --> <td> <select name="lstAduana" id="lstAduana" class="select_style"> <?php $consultarAduana=$objAduana->consultar_aduana(); if($consultarAduana->rowCount()>0){ echo "<option value='0'>Elija un aduana</option>"; while($adu=$consultarAduana->fetch(PDO::FETCH_OBJ)){ ?> <?php if($adu->adu_llega_id==$adu && $adu!=""){ $selected=" selected"; }else{ $selected=""; } ?> <option value="<?php echo $adu->adu_llega_id ?>" <?php echo $selected; ?>><?php echo $adu->nombre_adu_llega ?></option> <?php } }else{ ?> <option value="0">No hay aduanas</option> <?php } ?> </select> <div class="avion"> <td class="categoria_cliente">numero de vuelo </td> <td><input class="text_area" name="test" placeholder="BA 100 EZE-LHT " type="text"></td> </td></div> <!-- termina --> <!--<td><input class="text_area" name="test" placeholder="CRISTOBAL" type="text"> --> </td> </tr> <td class="categoria_cliente">N° Booking</td> <td><input class="text_area" name="test" placeholder="CZL 07-13" type="text"> </td> </tr> <tr> <td class="categoria_cliente">Lugar de llegada</td> <td> <select name="lstAduana" id="lstAduana" class="select_style"> <?php $consultarAduana=$objAduana->consultar_aduana(); if($consultarAduana->rowCount()>0){ echo "<option value='0'>Elija un aduana</option>"; while($adu=$consultarAduana->fetch(PDO::FETCH_OBJ)){ ?> <?php if($adu->adu_llega_id==$adu && $adu!=""){ $selected=" selected"; }else{ $selected=""; } ?> <option value="<?php echo $adu->adu_llega_id ?>" <?php echo $selected; ?>><?php echo $adu->nombre_adu_llega ?></option> <?php } }else{ ?> <option value="0">No hay aduanas</option> <?php } ?> </select> </td> </tr> <td class="categoria_cliente">Pais naviera</td> <td> <select class="select_style_naviera"> <option value="0" selected="selected">Estados Unidos</option> <option value="1">Japon</option> </select></td> </tr> <tr> <!-- <td class="categoria_cliente">Destino final</td> <td><input class="text_area" name="test" placeholder="BODESA" type="text"> </td> --> <td class="categoria_cliente">N° BL</td> <td><input class="text_area" name="test" placeholder="73283HBL-54594" type="text"> </td> </tr> <tr> <td class="categoria_cliente"><NAME></td> <td> <select name="lstFletes" id="lstFletes" class="select_style"> <?php $consultarFlete=$objFlete->consultar_fletes(); if($consultarFlete->rowCount()>0){ echo "<option value='0'>Elija un aduana</option>"; while($flete=$consultarFlete->fetch(PDO::FETCH_OBJ)){ ?> <?php if($flete->agent_fle_id==$flete && $flete!=""){ $selected=" selected"; }else{ $selected=""; } ?> <option value="<?php echo $flete->agent_fle_id ?>" <?php echo $selected; ?>><?php echo $flete->nombre_agent_fle ?></option> <?php } }else{ ?> <option value="0">No hay fletes</option> <?php } ?> </select> </td> </tr> </tbody> </table> </br> <center> <button value="Cancelar" name="cancelar">CANCELAR</button> <button value="Cargar" name="cargar">GUARDAR</button> </center> </br> </br> <hr> <table class="formulario" border="1" cellpadding="0" cellspacing="0"> <tbody> <tr> <td colspan="13" class="titulo" style="background-image:url(images/bar.jpg); background-repeat: repeat-x;"><span class="tittle_text">Movimientos en cola</span><br> </td> </tr> <tr class="cat_titulo"> <td>N°</td> <td>Proveedor</td> <td>Cliente</td> <td>Bultos</td> <td>Peso Kgs</td> <td>Volumen</td> <td>Descripcion</td> <td>Servicio bodega</td> <td>Bodega</td> <td>Tipo Movimiento</td> <td>Estado</td> <td>Editar </td> <td>Eliminar </td> </tr> <tr> <td>SAL0501</td> <td>SAMSUNG ELECTRONICS LATINOAMERICA SA</td> <td>DISTRIBUIDORA AGELSA SA DE CV</td> <td>3</td> <td>1300.00</td> <td>8.84</td> <td>REPRODUCTOR DVD</td> <td>CINCHAS GRUESAS</td> <td>SAN GERONIMO</td> <td>MARÍTIMO</td> <td>En espera...</td> <td align="center"><img title="Editar" src="imagenes/botones/editar.png"> </td> <td align="center"><img title="Eliminar" src="imagenes/botones/eliminar.gif"> </td> </tr> <tr> <td>SAL0502</td> <td>SYL INTERNATIONAL</td> <td>DISTRIBUIDORA AGELSA SA DE CV</td> <td>1</td> <td>1177.00</td> <td>1.00</td> <td>CADENAS, EMPATE DE CADENAS, BALINERA DE BOLA</td> <td>CINCHAS GRUESAS</td> <td>SAN GERONIMO</td> <td>MARÍTIMO</td> <td>En espera...</td> <td align="center"><img title="Editar" src="imagenes/botones/editar.png"> </td> <td align="center"><img title="Eliminar" src="imagenes/botones/eliminar.gif"> </td> </tr> <tr> <td>SAL0503</td> <td>CONNEXION ZONA LIBRE SA</td> <td>DISTRIBUIDORA AGELSA SA DE CV</td> <td>181</td> <td>3291.04</td> <td>10.97</td> <td>ACCESORIOS PARA AUTOS</td> <td>CINCHAS GRUESAS</td> <td>SAN GERONIMO</td> <td>MARÍTIMO</td> <td>En espera...</td> <td align="center"><img title="Editar" src="imagenes/botones/editar.png"> </td> <td align="center"><img title="Eliminar" src="imagenes/botones/eliminar.gif"> </td> </tr> <tr> <td>SAL0504</td> <td>NORITEX SA</td> <td>DISTRIBUIDORA AGELSA SA DE CV</td> <td>647</td> <td>6393.02</td> <td>31.74</td> <td>ARTICULOS PARA EL HOGAR</td> <td>CINCHAS GRUESAS</td> <td>SAN GERONIMO</td> <td>MARÍTIMO</td> <td>En espera...</td> <td align="center"><img title="Editar" src="imagenes/botones/editar.png"> </td> <td align="center"><img title="Eliminar" src="imagenes/botones/eliminar.gif"> </td> </tr> <tr> <td>SAL0505</td> <td>ZAGA ENTERPRISSE</td> <td>DISTRIBUIDORA AGELSA SA DE CV</td> <td>70</td> <td>578.00</td> <td>2.44</td> <td>PANTALONES CORTOS PARA HOMBRES</td> <td>CINCHAS GRUESAS</td> <td><NAME></td> <td>MARÍTIMO</td> <td>En espera...</td> <td align="center"><img title="Editar" src="imagenes/botones/editar.png"> </td> <td align="center"><img title="Eliminar" src="imagenes/botones/eliminar.gif"> </td> </tr> </tbody> </table> </form> </body> </html> <file_sep>/cargomania5/header.php <link rel="shortcut icon" href="img/favicon.png"> <script type="text/javascript" src="lib/alertify.js"></script> <link rel="stylesheet" href="themes/alertify.core.css" /> <link rel="stylesheet" href="themes/alertify.default.css" /> <script src="lib/eventos.js"></script> <script type="text/javascript" src="js/jquery.min.js"></script> <table width="100%"> <tr> <td><img style='float:left;' src='imagenes/Logo.png' height='40px' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><div id="nombre"></div></td> <td> <link href="front.css" media="screen, projection" rel="stylesheet" type="text/css"> <?php if(isset($_SESSION['autenticado'])){ if($_SESSION['autenticado']=='si'){ ?> <td> <a href='?mod=logout' style='float:right;padding-left:12px;'><img src='img/logout.png' width='32' title='Cerrar Sesi&oacute;n' border='1' /></a> <a href='?mod=changePwd' style='float:right;padding-left:12px;'><img src='img/pwd.png' width='32' title='Cambiar contrase&ntilde;a' border='1' /></a> <a href='?mod=infouser' style='float:right;padding-left:12px;'><img src='img/user_info.png' width='32' title='Informací&oacute;n del usuario' border='1' /> <a href="?mod=home"><img src='img/home.png' width="32" title='Ir al inicio' style="float:right;padding-bottom:10px;"></a> </td> <?php } }else{ ?> <script src="javascripts/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $(".signin").mouseover(function(e) { e.preventDefault(); $("fieldset#signin_menu").toggle(); $(".signin").toggleClass("menu-open"); }); $("fieldset#signin_menu").mouseup(function() { return false }); $(".ocultar").onblur(function(e) { //alert("Fuera de container2"); if($(e.target).parent("a.signin").length==0) { $(".signin").removeClass("menu-open"); $("fieldset#signin_menu").hide(); } }); /*$('#midiv').click(function(event){ event.stopPropagation(); });*/ /*$(document).click(function(e) { if($(e.target).parent("a.signin").length==0) { $(".signin").removeClass("menu-open"); $("fieldset#signin_menu").hide(); } });*/ }); </script> <script src="javascripts/jquery.tipsy.js" type="text/javascript"></script> <script type='text/javascript'> $(function() { $('#forgot_username_link').tipsy({gravity: 'w'}); }); </script> <?php } ?> </td> </tr> </table> <?php if(isset($_GET["mod"])){ if($_GET["mod"]=="bandejaentrada"){ ?> <table width='100%'> <tr> <th width="50%">Asunto</th> <th width="11.35%">Fecha</th> <th width="48.65">Juzgado</th> </tr> </table> <?php }else if($_GET["mod"]=="correoEnviado"){ ?> <table width='100%' id='tcontainer'> <tr> <th width="40%" rowspan="2">Asunto</th> <th width="11.35%" rowspan="2">Fecha</th> <th colspan="3">Estado</th> </tr> <tr> <th width='16.217%'>Le&iacute;do</th> <th width='16.217%'>Tiempo</th> <th width='16.217%'>Recibido</th> </tr> </table> <?php } } ?><file_sep>/cargomania5/formularios/frmAgregarEmpleado.php <script type="text/javascript"> function validar(){ if(document.getElementById("cmdGuardar").value=="Guardar"){ document.getElementById("agregarEmpleado").action="?mod=guardar_empleado"; }else{ document.getElementById("agregarEmpleado").action="?mod=actualizar_empleado"; } }</script> <?php $objEmpleado=new CargoMania; $codigo=""; $nombre_epll=""; $apellido_epll=""; $direccion_epll=""; $telefono_epll=""; $correo_epll=""; $num_seguroo=""; $fk_sucursall=""; if(isset($_GET["id"])){ $consultarEmpleado=$objEmpleado->mostrar_empleado($_GET["id"]); if($consultarEmpleado->rowCount()==1){ $emp=$consultarEmpleado->fetch(PDO::FETCH_OBJ); $codigo=$emp->empleado_id; $nombre_epll=$emp->nombre_epl; $apellido_epll=$emp->apellido_epl; $direccion_epll=$emp->direccion_epl; $telefono_epll=$emp->telefono_epl; $correo_epll=$emp->correo_epl; $num_seguroo=$emp->num_seguro; $fk_sucursall=$emp->fk_sucursal; } } ?> <form name="agregarEmpleado" id="agregarEmpleado" method="post" onSubmit="return validar();"> <table> <caption><h1>AGREGAR EMPLEADO</h1></caption> <tr> <th>Codigo:</th> <td><input type="number" name="txtCodigo" id="txtCodigo" value="<?php echo $codigo ?>" /></td> </tr> <tr> <th>Nombre Empleado:</th> <td><input type="text" name="txtNombre" id="txtNombre" value="<?php echo $nombre_epll ?>" /></td> </tr> <tr> <th>Apellido Empleado:</th> <td><input type="text" name="txtApellido" id="txtApellido" value="<?php echo $apellido_epll ?>" /></td> </tr> <tr> <th>Direccion:</th> <td><input type="text" name="txtDireccion" id="txtDireccion" value="<?php echo $direccion_epll ?>" /></td> </tr> <tr> <th>Telefono:</th> <td><input type="text" name="txtTelefono" id="txtTelefono" value="<?php echo $telefono_epll ?>" /></td> </tr> <tr> <th>Correo:</th> <td><input type="text" name="txtCorreo" id="txtCorreo" value="<?php echo $correo_epll ?>" /></td> </tr> <tr> <th>Numero de Seguro:</th> <td><input type="text" name="txtNum_seg" id="txtNum_seg" value="<?php echo $num_seguroo ?>" /></td> </tr> <tr> <th>Sucursal:</th> <td><select name="lstSucursall" id="lstSucursall"> <?php $consultarSucursal=$objEmpleado->consultar_sucursales(); if($consultarSucursal->rowCount()>0){ echo "<option value='0'>Elija una sucursal</option>"; while($sucursal=$consultarSucursal->fetch(PDO::FETCH_OBJ)){ ?> <?php if($sucursal->sucursal_id==$sucursal && $sucursal!=""){ $selected=" selected"; }else{ $selected=""; } ?> <option value="<?php echo $sucursal->sucursal_id ?>" <?php echo $selected; ?>><?php echo $sucursal->nombre_sucu ?></option> <?php } }else{ ?> <option value="0">No hay Sucursales</option> <?php } ?> </select></td> </tr> <tr> <td><input type="submit" name="cmdGuardar" value="<?php if(isset($_GET["id"])){echo "Actualizar";}else{echo "Guardar";}?>" id="cmdGuardar" /></td> </tr> </table> </form> <table> <tr><th>Codigo</th><th>Nombre_epl</th><th>Apellido</th><th>Direccion</th><th>Telefono</th><th>Correo</th><th>N Registro</th><th>Sucursal</th><th>Modificar<th></tr> <?php $consultarEmpleado=$objEmpleado->listar_empleado(); if($consultarEmpleado->rowCount()>0){ while($empleado=$consultarEmpleado->fetch(PDO::FETCH_OBJ)){ $sucursal=$objEmpleado->consultar_sucursal($empleado->fk_sucursal)->fetch(PDO::FETCH_OBJ); echo "<tr><td>".$empleado->empleado_id."</td><td>".$empleado->nombre_epl."</td><td>".$empleado->apellido_epl."</td> <td>".$empleado->direccion_epl."</td><td>".$empleado->telefono_epl."</td><td>".$empleado->correo_epl."</td><td>".$empleado->num_seguro."</td><td>".$sucursal->nombre_sucu."</td><td><a href='?mod=agregar_empleado&id=".$empleado->empleado_id."'>Mostrar</a></td></tr>"; } } ?> </table><file_sep>/cargomania5/ConfigDB.class.php <?php class ConfigDB{ var $DB_PgSQL; var $Server_PgSQL; var $User_PgSQL; var $Password_PgSQL; function ConfigDB(){ $this->DB_PgSQL = "cargomania"; $this->Server_PgSQL = "localhost"; $this->User_PgSQL = "postgres"; $this->Password_PgSQL= "<PASSWORD>"; } } ?> <file_sep>/cargomania5/index1.php <!doctype html> <html> <head> <meta charset="utf-8"> <title>Cargomania</title> <style type="text/css"> .header table tr td form { color: #FFF; } .adm { font-size: 14px; } .header table tr td form .adm { font-size: 36px; } .header table tr td form .adm { font-family: "MS Serif", "New York", serif; } .header table tr td form .adm { font-family: Arial, Helvetica, sans-serif; } .header table tr td form .adm { font-family: Verdana, Geneva, sans-serif; } .header table tr td form .adm { font-family: Georgia, "Times New Roman", Times, serif; } .header table tr td form .adm { font-family: "Courier New", Courier, monospace; } .header table tr td form .adm { font-family: Arial, Helvetica, sans-serif; } .header table tr td form .adm { font-family: "Courier New", Courier, monospace; } </style> </head> <body> <div class="container"> <div style="background-color:#222 "class="header"><!-- end .header --> <table width="944" border="0"> <tr> <td width="553" height="72"><img src="imagenes/Logo.png" width="213" height="70"></td> <td width="381"><form name="form1" method="post" action=""> </form></td> </tr> </table> </div> <div class="container"> <table width="100%" border="0"> <tr> <td width="100%" height="100%" align="center"> <script type="text/javascript" src="lib/alertify.js"></script> <link rel="stylesheet" href="themes/alertify.core.css" /> <link rel="stylesheet" href="themes/alertify.default.css" /> <script src="lib/eventos.js"></script> <script type="text/javascript" src="js/jquery.min.js"></script> <style type="text/css"> p{ text-align: left; } #login{ padding-left: 200px; } #error{ color:red; border-radius: 10px; border-color: black; border-width: 5px; text-align: left; } </style> <script> $(document).ready(function(){ $("#submit").click(function(){ var formulario = $("#frmLogin").serializeArray(); $.ajax({ type: "POST", dataType: 'json', url: "procesos/autenticar.php", data: formulario, }).done(function(respuesta){ //$("#mensaje").html(respuesta.mensaje); //alert(respuesta.mensaje); if(respuesta.mensaje==1){ error("Por favor llene todos los campos"); }else if(respuesta.mensaje==2){ error("Combinacion de usuario y contraseña incorrecta"); }else if(respuesta.mensaje==3){ ok("Datos correctos"); location.href="index2.html"; }else if(respuesta.mensaje==4){ ok("Datos correctos"); location.href="index_user.html"; }else if(respuesta.mensaje==5){ ok("Datos correctos"); location.href="index_clien.html"; } }); }); }); </script> <link href="css/style2.css" rel="stylesheet" type="text/css" /> <div id="box" style="background-color:white;background-image:url(images/avatar.gif);background-repeat:no-repeat;background-position:center top;"> <div class="elements"> <div class="avatar"></div> <form id="frmLogin"> <input type="text" name="username" class="username" placeholder="Usuario" /> <input type="<PASSWORD>" name="password" class="password" placeholder="•••••••••" /> <div class="forget"><a href="formularios/validacion.php">¿Olvid&oacute; su contrase&ntilde;a?</a></div> <!--<div class="checkbox"> <input id="check" name="checkbox" type="checkbox" value="1" /> <label for="check">Remember?</label> </div> <div class="remember">Remember?</div>--> <input type="button" name="submit" class="submit" id="submit" value="Ingresar" /> </form> </div> <br> <div id='error'><?php if(isset($_GET['msj'])){ $msj=$_GET['msj']; if($msj==1){ echo "Llene todos los campos"; }else if($msj==2){ echo "Combinaci&oacute;n de usuario y contrase&ntilde;a incorrecta"; } } ?></div> </div> </td> <td width="467"> <iframe frameBorder="0" width="100%" height="100%" name="iframe2"></iframe> </td> </tr> </table> <div style="background-color:#044E7C "class="header"><!-- end .header --> <table width="1096" border="0"> <tr> <td height="21"><form name="form1" method="post" action=""> <label for="textfield"></label> CARGOMANIA 2013 </form></td> </tr> </table> </div> </body> </html> <file_sep>/cargomania5/js/paises.js $(function() { var availableTags = [ "Belice", "Costa Rica", "El Salvador", "Guatemala", "Honduras", "Nicaragua", "Panamá", ]; $( "#tags" ).autocomplete({ source: availableTags }); }); <file_sep>/cargomania5/jquery-flete.js $(document).ready(function() { $(".barco").hide(); $(".avion").hide(); $("#select_transport").change(function(){ var $feeschedule1 = $(".barco"); var $feeschedule2 = $(".avion"); var select = $(this).find('option:checked').val(); if (select == 'maritimo'){ $feeschedule1.show(); }else{ $feeschedule1.hide(); } if (select == 'aereo'){ $feeschedule2.show(); }else{ $feeschedule2.hide(); } }); });<file_sep>/cargomania5/formularios/frmAgregarMercaderia.php <script type="text/javascript"> function validar(){ if(document.getElementById("cmdGuardar").value=="Guardar"){ document.getElementById("agregarmercaderia").action="?mod=guardar_mercaderia"; }else{ document.getElementById("agregarmercaderia").action="?mod=actualizar_mercaderia"; } }</script> <?php $objMercaderia=new CargoMania; $codigo=""; $nombre=""; $tip=""; $des=""; if(isset($_GET["id"])){ $consultarMercaderia=$objMercaderia->mostrar_mercaderia($_GET["id"]); if($consultarMercaderia->rowCount()==1){ $contene=$consultarMercaderia->fetch(PDO::FETCH_OBJ); $codigo=$contene->cat_merca_id; $nombre=$contene->nombre_cat_merca; $tip=$contene->tipo; $des=$contene->descripcion; } } ?> <form name="agregarmercaderia" id="agregarmercaderia" method="post" onSubmit="return validar();"> <table> <caption><h1>AGREGAR UNA NUEVA MERCADERIA</h1></caption> <tr> <th>Codigo:</th> <td><input type="number" name="txtCodigo" id="txtCodigo" value="<?php echo $codigo ?>" /></td> </tr> <tr> <th>Nombre:</th> <td><input type="text" name="txtNombre" id="txtNombre" value="<?php echo $nombre ?>" /></td> </tr> <tr> <th>Tipo:</th> <td><input type="text" name="txtTipo" id="txtTipo" value="<?php echo $tip ?>" /></td> </tr> <tr> <th>Descripcion:</th> <td><input type="text" name="txtDescripcion" id="txtDescripcion" value="<?php echo $des ?>" /></td> </tr> <tr> <td> </td> <td align="center" ><input type="submit" name="cmdGuardar" value="<?php if(isset($_GET["id"])){echo "Actualizar";}else{echo "Guardar";}?>" id="cmdGuardar" /></td> </tr> </table> </form> <table> <tr><th>Codigo</th><th>Nombre mercaderia</th><th>Tipo</th><th>Descripcion</th></tr> <?php $consultarMercaderia=$objMercaderia->listar_mercaderia(); if($consultarMercaderia->rowCount()>0){ while($mercaderia=$consultarMercaderia->fetch(PDO::FETCH_OBJ)){ echo "<tr><td>".$mercaderia->cat_merca_id."</td><td>".$mercaderia->nombre_cat_merca."</td><td>".$mercaderia->tipo."</td> <td>".$mercaderia->descripcion."</td><td>"."</td><td><a href='?mod=agregar_mercaderia&id=".$mercaderia->cat_merca_id."'>Mostrar</a></td></tr>"; } } ?> </table><file_sep>/cargomania5/formularios/validacion.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Cargomania</title> <link href="../../SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" /> <link href="../../slideshow/design_slideshow.css" rel="stylesheet" type="text/css" /> <link href="../../slideshow/ulightbox.css" rel="stylesheet" type="text/css"> <link type="text/css" rel="StyleSheet" href="../../slideshow/layer6.css"> <script src="../../SpryAssets/SpryMenuBar.js" type="text/javascript"></script> <script type="text/javascript" src="../../slideshow/jquery-1_002.js"></script> <script type="text/javascript" src="../../slideshow/parametros_slideshow.js"></script> <script>var div = document.getElementsByTagName('div')[0]; div.innerHTML = '';</script> <script type="text/javascript" src="../../slideshow/jquery-1.js"></script> <script type="text/javascript" src="../../slideshow/ulightbox.js"></script> <script type="text/javascript" src="../../slideshow/uwnd.js"></script> <link href="../../SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" /> <link href="../../slideshow/design_slideshow.css" rel="stylesheet" type="text/css" /> <link href="../../slideshow/ulightbox.css" rel="stylesheet" type="text/css"> <link type="text/css" rel="StyleSheet" href="../../slideshow/layer6.css"> <script src="../../SpryAssets/SpryMenuBar.js" type="text/javascript"></script> <script type="text/javascript" src="../../slideshow/jquery-1_002.js"></script> <script type="text/javascript" src="../../slideshow/parametros_slideshow.js"></script> <script>var div = document.getElementsByTagName('div')[0]; div.innerHTML = '';</script> <script type="text/javascript" src="../../slideshow/jquery-1.js"></script> <script type="text/javascript" src="../../slideshow/ulightbox.js"></script> <script type="text/javascript" src="../../slideshow/uwnd.js"></script> <link href="../../panel/style.css" rel="stylesheet" type="text/css" /> <style type="text/css"> .UhideBlock { display: none } </style> <style type="text/css"> <!-- .style8 {color: #666666; font-size: 14px; } .style9 {color:#FF0000; font-size: 14px; } .style1 {color: #606060} --> </style> <style type="text/css"> div.send { position: relative; width: 115px; height: 34px; overflow:hidden; background:url(../../images/enviar.png) left top no-repeat; clip:rect(0px, 80px, 24px, 0px ); } div.send input { position: absolute; left: auto; right: 0px; top: 0px; margin:0; padding:0; filter: Alpha(Opacity=0); -moz-opacity: 0; opacity: 0; } </style> </head> <body> <div style="background-color:#000"><h1 align="center"><font color="#F2F2F2">Ingresa tu correo</font></h1> </div> <table align="center" width="350" height="30" border="0"> <tr> <td> <?php if (isset($_GET['errorusuario'])){ if ($_GET['errorusuario']==1){ echo "<center><span class='style9'>Correo invalido o inexistente</span></center>";} else{ echo ""; }} ?> </td> </tr> </table> <form name="formulario" method="post" action="s2.php" > <table align="center"> <tr> <td align="right">Correo:</td> <td><input type="text" name="txt_correo" id="txt_correo"> <input style="height:60px; width:100px; font-size:20px; left: 15px; right: 0px; top: 0px;" type="submit" name="Submit" value="Enviar" /></td> </tr> <tr> <td colspan="2" align="center"> <div align="center" class="send"> <input style="height:60px; width:100px; font-size:20px; left: 15px; right: 0px; top: 0px;" type="submit" name="Submit" value="Enviar"></input> </div> </td> </tr> </table> </form> </body> </html> <file_sep>/cargomania5/formularios/frmAgregar_aduana_llegada.php <script type="text/javascript"> function validar(){ if(document.getElementById("cmdGuardar").value=="Guardar"){ document.getElementById("agregar_aduana_llegada").action="?mod=guardar_aduana_llegada"; }else{ document.getElementById("agregar_aduana_llegada").action="?mod=actualizar_aduana_llegada"; } }</script> <?php $objAduana_llegada=new CargoMania; $codigo=""; $nombre=""; $direccion=""; $tipo=""; $pais=""; if(isset($_GET["id"])){ $consultarAduana_llegada=$objAduana_llegada->mostrar_aduana_llegada($_GET["id"]); if($consultarAduana_llegada->rowCount()==1){ $contene=$consultarAduana_llegada->fetch(PDO::FETCH_OBJ); $codigo=$contene->adu_llega_id; $nombre=$contene->nombre_adu_llega; $direccion=$contene->direccion_adu_llega; $tipo=$contene->tipo_adu_llega; $pais=$contene->pais_adu_llega; } } ?> <form name="agregar_aduana_llegada" id="agregar_aduana_llegada" method="post" onSubmit="return validar();"> <table> <caption><h1>AGREGAR NUEVA ADUANA </h1></caption> <tr> <th>Codigo:</th> <td><input type="number" name="txtCodigo" id="txtCodigo" value="<?php echo $codigo ?>" /></td> </tr> <tr> <th>Nombre:</th> <td><input type="text" name="txtNombre" id="txtNombre" value="<?php echo $nombre ?>" /></td> </tr> <tr> <th>Direccion:</th> <td><input type="text" name="txtDireccion" id="txtDireccion" value="<?php echo $direccion ?>" /></td> </tr> <tr> <th>Tipo</th> <td><select name="ltsTipo" id="ltsTipo"> <option value="Maritimo">Maritimo</option> <option value="Aereo">Aereo</option> <option value="Terrestre">Terrestre</option> </select></td> </tr> <tr> <th>Pais:</th> <td><input type="text" name="txtPais" id="txtPais" value="<?php echo $pais ?>" /></td> </tr> <tr> <td><input type="submit" name="cmdGuardar" value="<?php if(isset($_GET["id"])){echo "Actualizar";}else{echo "Guardar";}?>" id="cmdGuardar" /></td> </tr> </table> </form> <table> <tr><th>Codigo</th><th>Nombre</th><th>Direccion</th><th>Tipo</th><th>Pais</th><th>Opcion</th></tr> <?php $consultarAduanas_llegada=$objAduana_llegada->listar_aduana_llegada(); if($consultarAduanas_llegada->rowCount()>0){ while($aduana=$consultarAduanas_llegada->fetch(PDO::FETCH_OBJ)){ echo "<tr><td>".$aduana->adu_llega_id."</td><td>".$aduana->nombre_adu_llega."</td><td>".$aduana->direccion_adu_llega."</td> <td>".$aduana->tipo_adu_llega."</td><td>".$aduana->pais_adu_llega."</td><td><a href='?mod=agregar_aduana_llegada&id=".$aduana->adu_llega_id."'>Mostrar</a></td></tr>"; } } ?> </table><file_sep>/cargomania5/cargomania.class.php <?php class CargoMania { //constructor function CargoMania() { } /*MANTENIMIENTO DE USUARIOS*/ function consultar_usuario($campos) { $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "select * from usuario where Usuario=:Usuario and Contrasena=:Pwd and Estado=1"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":Usuario",$campos[0]); $query->bindParam(":Pwd",$campos[1]); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } /*MANTENIMIENTO DE AGENTES*/ function consultar_agentes() { $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "select * from agente_bodega"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function consultar_agente($id) { $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "select * from agente_bodega WHERE aget_bod_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } /*MANTENIMIENTO DE CONTENEDORES*/ function guardar_contenedor($campos){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "INSERT INTO contenedor VALUES(:codigo,:tamano,:numero,:sello,:agente)"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":codigo",$campos[0]); $query->bindParam(":tamano",$campos[1]); $query->bindParam(":numero",$campos[2]); $query->bindParam(":sello",$campos[3]); $query->bindParam(":agente",$campos[4]); $query->execute(); // Ejecutamos la consulta if ($query){ return $query; //pasamos el query para utilizarlo luego con fetch }else{ return false; } unset($dbh); unset($query); } function eliminar_contenedor($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "DELETE FROM contenedor WHERE contene_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function actualizar_contenedor($campos) { $con = new DBManager(); $dbh = $con->conectar("pgsql"); $sql = "UPDATE contenedor SET tamano_conte=:tamano,numero_conte=:numero,sello_conte=:sello,fk_agent_bod=:agente WHERE contene_id=:id"; $add = $dbh->prepare($sql); $add->bindParam(":id",$campos[0]); $add->bindParam(":tamano",$campos[1]); $add->bindParam(":numero",$campos[2]); $add->bindParam(":sello",$campos[3]); $add->bindParam(":agente",$campos[4]); $add->execute(); if ($add) return true; else return false; unset($dbh); unset($add); } function mostrar_contenedor($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM contenedor WHERE contene_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function listar_contenedores(){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM contenedor"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } /*MANTENIMIENTO DE CLIENTES*/ function guardar_cliente($campos){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "INSERT INTO cliente VALUES(:codigo,:nomb_empr,:giro,:numero_reg,:direccion,:nombre_repre,:apellido_repre,:telefono_repre,:email_repre)"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":codigo",$campos[0]); $query->bindParam(":nomb_empr",$campos[1]); $query->bindParam(":giro",$campos[2]); $query->bindParam(":numero_reg",$campos[3]); $query->bindParam(":direccion",$campos[4]); $query->bindParam(":nombre_repre",$campos[5]); $query->bindParam(":apellido_repre",$campos[6]); $query->bindParam(":telefono_repre",$campos[7]); $query->bindParam(":email_repre",$campos[8]); $query->execute(); // Ejecutamos la consulta if ($query){ return $query; //pasamos el query para utilizarlo luego con fetch }else{ return false; } unset($dbh); unset($query); } function eliminar_cliente($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "DELETE FROM cliente WHERE cliente_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function actualizar_cliente($campos) { $con = new DBManager(); $dbh = $con->conectar("pgsql"); $sql = "UPDATE cliente SET nombre_empr=:nomb_empr,giro=:giro,num_reg=:numero_reg,direccion=:direccion,nom_represent=:nombre_repre,apellido_represent=:apellido_repre,telefono_represent=:telefono_repre,correo=:email_repre WHERE cliente_id=:id"; $add = $dbh->prepare($sql); $add->bindParam(":id",$campos[0]); $add->bindParam(":nomb_empr",$campos[1]); $add->bindParam(":giro",$campos[2]); $add->bindParam(":numero_reg",$campos[3]); $add->bindParam(":direccion",$campos[4]); $add->bindParam(":nombre_repre",$campos[5]); $add->bindParam(":apellido_repre",$campos[6]); $add->bindParam(":telefono_repre",$campos[7]); $add->bindParam(":email_repre",$campos[8]); $add->execute(); if ($add) return true; else return false; unset($dbh); unset($add); } function mostrar_cliente($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM cliente WHERE cliente_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function listar_cliente(){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM cliente"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } /*MANTENIMIENTO DE Agente de Bodega*/ function guardar_agentebodega($campos){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "INSERT INTO agente_bodega VALUES(:codigo,:nomb_aget,:direccion_aget,:nombre_repre,:apellido_repre,:pais_aget)"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":codigo",$campos[0]); $query->bindParam(":nomb_aget",$campos[1]); $query->bindParam(":direccion_aget",$campos[2]); $query->bindParam(":nombre_repre",$campos[3]); $query->bindParam(":apellido_repre",$campos[4]); $query->bindParam(":pais_aget",$campos[5]); $query->execute(); // Ejecutamos la consulta if ($query){ return $query; //pasamos el query para utilizarlo luego con fetch }else{ return false; } unset($dbh); unset($query); } function eliminar_agentebodega($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "DELETE FROM cliente WHERE cliente_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function actualizar_agentebodega($campos) { $con = new DBManager(); $dbh = $con->conectar("pgsql"); $sql = "UPDATE agente_bodega SET nombre_aget_bod=:nomb_aget,direccion_aget_bod=:direccion_aget,nombre_repre_aget_bod=:nombre_repre,apellido_repre_aget_bod=:apellido_repre,pais_aget_bod=:pais_aget WHERE aget_bod_id=:id"; $add = $dbh->prepare($sql); $add->bindParam(":id",$campos[0]); $add->bindParam(":nomb_aget",$campos[1]); $add->bindParam(":direccion_aget",$campos[2]); $add->bindParam(":nombre_repre",$campos[3]); $add->bindParam(":apellido_repre",$campos[4]); $add->bindParam(":pais_aget",$campos[5]); $add->execute(); if ($add) return true; else return false; unset($dbh); unset($add); } function mostrar_agentebodega($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM agente_bodega WHERE aget_bod_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function listar_agentebodega(){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM agente_bodega"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } /*MANTENIMIENTO DE Servicio de Bodega*/ function guardar_serviciobodega($campos){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "INSERT INTO servicio_bodega VALUES(:codigo,:nomb_serv,:precio_serv,:agente)"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":codigo",$campos[0]); $query->bindParam(":nomb_serv",$campos[1]); $query->bindParam(":precio_serv",$campos[2]); $query->bindParam(":agente",$campos[3]); $query->execute(); // Ejecutamos la consulta if ($query){ return $query; //pasamos el query para utilizarlo luego con fetch }else{ return false; } unset($dbh); unset($query); } function eliminar_serviciobodega($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "DELETE FROM cliente WHERE cliente_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function actualizar_serviciobodega($campos) { $con = new DBManager(); $dbh = $con->conectar("pgsql"); $sql = "UPDATE servicio_bodega SET nombre_serv_bod=:nomb_serv,precio_serv_bod=:precio_serv,fk_agente_bod=:agente WHERE serv_bod_id=:id"; $add = $dbh->prepare($sql); $add->bindParam(":id",$campos[0]); $add->bindParam(":nomb_serv",$campos[1]); $add->bindParam(":precio_serv",$campos[2]); $add->bindParam(":agente",$campos[3]); $add->execute(); if ($add) return true; else return false; unset($dbh); unset($add); } function mostrar_serviciobodega($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM servicio_bodega WHERE serv_bod_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function listar_serviciobodega(){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM servicio_bodega"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } /*MANTENIMIENTO DE EMPLEADO*/ function guardar_empleado($campos){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "INSERT INTO empleado VALUES(:empleado_id,:nombre_epl,:apellido_epl,:direccion_epl,:telefono_epl,:correo_epl,:num_seguro,:fk_sucursal)"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":empleado_id",$campos[0]); $query->bindParam(":nombre_epl",$campos[1]); $query->bindParam(":apellido_epl",$campos[2]); $query->bindParam(":direccion_epl",$campos[3]); $query->bindParam(":telefono_epl",$campos[4]); $query->bindParam(":correo_epl",$campos[5]); $query->bindParam(":num_seguro",$campos[6]); $query->bindParam(":fk_sucursal",$campos[7]); $query->execute(); // Ejecutamos la consulta if ($query){ return $query; //pasamos el query para utilizarlo luego con fetch }else{ return false; } unset($dbh); unset($query); } function eliminar_empleado($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "DELETE FROM empleado WHERE empleado_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function actualizar_empleado($campos) { $con = new DBManager(); $dbh = $con->conectar("pgsql"); $sql = "UPDATE empleado SET nombre_epl=:nombre,apellido_epl=:apellido,direccion_epl=:direccion,telefono_epl=:telefono,correo_epl=:correo,num_seguro=:seguro,fk_sucursal=:sucursal WHERE empleado_id=:id"; $add = $dbh->prepare($sql); $add->bindParam(":id",$campos[0]); $add->bindParam(":nombre",$campos[1]); $add->bindParam(":apellido",$campos[2]); $add->bindParam(":direccion",$campos[3]); $add->bindParam(":telefono",$campos[4]); $add->bindParam(":correo",$campos[5]); $add->bindParam(":seguro",$campos[6]); $add->bindParam(":sucursal",$campos[7]); $add->execute(); if ($add) return true; else return false; unset($dbh); unset($add); } function mostrar_empleado($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM empleado WHERE empleado_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function listar_empleado(){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM empleado"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function consultar_sucursales() { $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "select * from sucursal"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function consultar_sucursal($id) { $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "select * from sucursal WHERE sucursal_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } /*MANTENIMIENTO DE TARIFARIO*/ function guardar_tarifa($campos){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "INSERT INTO cat_tarifa VALUES(:codigo,:peso,:vol,:cliente)"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":codigo",$campos[0]); $query->bindParam(":peso",$campos[1]); $query->bindParam(":vol",$campos[2]); $query->bindParam(":cliente",$campos[3]); $query->execute(); // Ejecutamos la consulta if ($query){ return $query; //pasamos el query para utilizarlo luego con fetch }else{ return false; } unset($dbh); unset($query); } function eliminar_tarifa($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "DELETE FROM cat_tarifa WHERE cat_tarifa_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function actualizar_tarifa($campos) { $con = new DBManager(); $dbh = $con->conectar("pgsql"); $sql = "UPDATE cat_tarifa SET cobro_peso=:peso,cobro_vol=:vol,fk_cliente=:cliente WHERE cat_tarifa_id=:id"; $add = $dbh->prepare($sql); $add->bindParam(":id",$campos[0]); $add->bindParam(":peso",$campos[1]); $add->bindParam(":vol",$campos[2]); $add->bindParam(":cliente",$campos[3]); $add->execute(); if ($add) return true; else return false; unset($dbh); unset($add); } function mostrar_tarifa($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM cat_tarifa WHERE cat_tarifa_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function listar_tarifas(){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM cat_tarifa"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function consultar_clientes() { $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "select * from cliente"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function consultar_cliente($id) { $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "select * from cliente WHERE cliente_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } /*MANTENIMIENTO DE PROVEEDOR*/ function guardar_proveedor($campos){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "INSERT INTO proveedor VALUES(:codigo,:nombre,:pais,:direccion,:telefono,:correo)"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":codigo",$campos[0]); $query->bindParam(":nombre",$campos[1]); $query->bindParam(":pais",$campos[2]); $query->bindParam(":direccion",$campos[3]); $query->bindParam(":telefono",$campos[4]); $query->bindParam(":correo",$campos[5]); $query->execute(); // Ejecutamos la consulta if ($query){ return $query; //pasamos el query para utilizarlo luego con fetch }else{ return false; } unset($dbh); unset($query); } function eliminar_proveedor($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "DELETE FROM proveedor WHERE proveedor_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function actualizar_proveedor($campos) { $con = new DBManager(); $dbh = $con->conectar("pgsql"); $sql = "UPDATE proveedor SET nombre_prov=:nombre,pais_prov=:pais,direccion=:direccion,telefono_prov=:telefono,correo_prov=:correo WHERE proveedor_id=:id"; $add = $dbh->prepare($sql); $add->bindParam(":id",$campos[0]); $add->bindParam(":nombre",$campos[1]); $add->bindParam(":pais",$campos[2]); $add->bindParam(":direccion",$campos[3]); $add->bindParam(":telefono",$campos[4]); $add->bindParam(":correo",$campos[5]); $add->execute(); if ($add) return true; else return false; unset($dbh); unset($add); } function mostrar_proveedor($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM proveedor WHERE proveedor_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function listar_proveedor(){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM proveedor"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } /*MANTENIMIENTO DE ADUANA_LLEGADA*/ function guardar_aduana_llegada($campos){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "INSERT INTO aduana_llegada VALUES(:codigo,:nombre,:direccion,:tipo,:pais)"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":codigo",$campos[0]); $query->bindParam(":nombre",$campos[1]); $query->bindParam(":direccion",$campos[2]); $query->bindParam(":tipo",$campos[3]); $query->bindParam(":pais",$campos[4]); $query->execute(); // Ejecutamos la consulta if ($query){ return $query; //pasamos el query para utilizarlo luego con fetch }else{ return false; } unset($dbh); unset($query); } function eliminar_aduana_llegada($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "DELETE FROM aduana_llegada WHERE adu_llega_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function actualizar_aduana_llegada($campos) { $con = new DBManager(); $dbh = $con->conectar("pgsql"); $sql = "UPDATE aduana_llegada SET nombre_adu_llega=:nombre,direccion_adu_llega=:direccion,tipo_adu_llega=:tipo,pais_adu_llega=:pais WHERE adu_llega_id=:id"; $add = $dbh->prepare($sql); $add->bindParam(":id",$campos[0]); $add->bindParam(":nombre",$campos[1]); $add->bindParam(":direccion",$campos[2]); $add->bindParam(":tipo",$campos[3]); $add->bindParam(":pais",$campos[4]); $add->execute(); if ($add) return true; else return false; unset($dbh); unset($add); } function mostrar_aduana_llegada($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM aduana_llegada WHERE adu_llega_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function listar_aduana_llegada(){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM aduana_llegada"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } //// -________________________________________-- function consultar_proveedores() { $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "select * from proveedor"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function mostrar_proveedores($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM proveedor WHERE proveedor_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } /*MANTENIMIENTO DE MERCADERIA*/ function guardar_mercaderia($campos){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "INSERT INTO cat_mercaderia VALUES(:codigo,:nombre,:tip,:des)"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":codigo",$campos[0]); $query->bindParam(":nombre",$campos[1]); $query->bindParam(":tip",$campos[2]); $query->bindParam(":des",$campos[3]); $query->execute(); // Ejecutamos la consulta if ($query){ return $query; //pasamos el query para utilizarlo luego con fetch }else{ return false; } unset($dbh); unset($query); } function eliminar_mercaderia($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "DELETE FROM contenedor WHERE contene_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function actualizar_mercaderia($campos) { $con = new DBManager(); $dbh = $con->conectar("pgsql"); $sql = "UPDATE cat_mercaderia SET nombre_cat_merca=:nombre,tipo=:tip,descripcion=:des WHERE cat_merca_id=:id"; $add = $dbh->prepare($sql); $add->bindParam(":id",$campos[0]); $add->bindParam(":nombre",$campos[1]); $add->bindParam(":tip",$campos[2]); $add->bindParam(":des",$campos[3]); $add->execute(); if ($add) return true; else return false; unset($dbh); unset($add); } function mostrar_mercaderia($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM cat_mercaderia WHERE cat_merca_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function listar_mercaderia(){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM cat_mercaderia"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function consultar_aduana() { $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "select * from aduana_llegada"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } // mostrar flete function mostrar_flete($id){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "SELECT * FROM agente_flete WHERE agent_fle_id=:id"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":id",$id); $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } function consultar_fletes() { $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "select * from agente_flete"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->execute(); // Ejecutamos la consulta if ($query) return $query; //pasamos el query para utilizarlo luego con fetch else return false; unset($dbh); unset($query); } } ?> <file_sep>/cargomania5/js/select_dependientes_proceso.php <script> document.getElementById("estados").disabled=true; </script> <?php // Array que vincula los IDs de los selects declarados en el HTML con el nombre de la tabla donde se encuentra su contenido include_once ('../DBManager.class.php'); include_once ('../noticias.class.php'); $listadoSelects=array( "paises"=>"lista_paises", "estados"=>"lista_estados" ); function validaSelect($selectDestino) { // Se valida que el select enviado via GET exista global $listadoSelects; if(isset($listadoSelects[$selectDestino])) return true; else return false; } function validaOpcion($opcionSeleccionada) { // Se valida que la opcion seleccionada por el usuario en el select tenga un valor numerico if(is_numeric($opcionSeleccionada)) return true; else return false; } $selectDestino=$_GET["select"]; $opcionSeleccionada=$_GET["opcion"]; //echo $selectDestino."-".$opcionSeleccionada; if(validaOpcion($opcionSeleccionada)) { $objMedio=new Noticias; $consultar=$objMedio->consultar_medio_com($opcionSeleccionada); echo "<select name='$selectDestino' id='$selectDestino' onChange='document.getElementById(\"txtMedio\").value=this.value'>"; echo "<option value='0'>Elige</option>"; $i=0; while ($data = $consultar->fetch(PDO::FETCH_OBJ)) { $i++; echo "<option value='".$data->idMedioComunicacion."'>".$data->Nombre."</option>"; } if($i==0){ ?> <script language="Javascript"> document.getElementById("estados").disabled=true; </script> <?php } echo "</select>"; } ?><file_sep>/cargomania5/formularios/etd_pdf.php <?php //ini_set('session.save_handler','files'); require_once("../lib/fpdf/fpdf.php"); class PDF extends FPDF { //Cabecera de página function Header() { //Logo $this->Image('../Imagenes/Logo.jpg',10,6,50); //Arial bold 15 $this->SetFont('Arial','B',11); //Movernos a la derecha //Título $this->Cell(230,2,'"Consolidando la Amistad y la Carga de nuestros Clientes"',0,1,'C'); $this->Ln(25); $this->SetFont('Arial','B',15); $this->Cell(200,2,'NOTIFICACION ARRIBO DE CARGA',0,1,'C'); $this->Ln(3); $this->Ln(15); //Salto de;línea } //Pie de página function Footer() { //Posición: a 1,5 cm del final $this->SetY(-35); //Arial italic 8 $this->SetFont('Arial','I',10); //Número de página $this->Cell(0,20,utf8_decode('Página ').$this->PageNo().'/{nb}',0,0,'C'); } } $con=pg_connect("user=postgres port=5434 dbname=cargomania host=localhost password=<PASSWORD>"); //$bd=pg_select($con,"cargomania",$_POST); $cons1 = pg_query($con,"SELECT c.nom_represent,c.apellido_represent, dm.cantidad_merca,dm.volumen_merca, dm.peso_merca,s.puerto_sali_serv, s.fch_sal_bod_serv,s.fch_est_llega_serv, s.puerto_llega_serv,ab.nombre_aget_bod FROM servicio s, det_mercaderia dm, servicio_bodega sb,agente_bodega ab,rol r, cliente c WHERE s.fk_det_merca = dm.det_merca_id AND s.fk_servi_bod = sb.serv_bod_id AND sb.fk_agente_bod = ab.aget_bod_id AND s.fk_rol = r.rol_id AND r.fk_cliente = c.cliente_id AND c.cliente_id =". $_POST["CID"] ); $row = pg_fetch_array($cons1); $pdf=new PDF(); /*Se define las propiedades de la página */ $pdf->AliasNbPages(); $pdf->AddPage(); /* Se añade una nueva página */ $pdf->SetFont('Arial','',12);/* Se define el tipo de fuente: Arial en negrita de ta */ $pdf->Cell(60,10,'Para: '.$row["nom_represent"].' '.$row["apellido_represent"],0,0,'L',FALSE); $pdf->Ln(8); $pdf->Cell(20,10,'Fecha: ',0,0,'L',FALSE); $pdf->Cell(20,10,date("d/m/y"),0,0,'L',FALSE); $pdf->Ln(10); $pdf->Cell(60,10,utf8_decode("Estimados Señores:") ,0,0,'L',FALSE); $pdf->Ln(10); $pdf->Cell(60,10,'Por este medio informamos a usted que la mercaderia de su proveedor fue , ',0,0,'L',FALSE); $pdf->Ln(5); $pdf->Cell(60,10,'embarcada hacia nuestro pais, se presenta el detalle a continuacion:',0,0,'L',FALSE); $pdf->Ln(15); $lk=0; $pdf->SetFont('Arial','',12); //Títulos de las columnas //$header=array(' Miembro','Nombre',); //Colores, ancho de línea y fuente en negrita $pdf->SetFillColor(160,164,166); $pdf->SetTextColor(255); $pdf->SetDrawColor(128,128,128); $pdf->SetLineWidth(.3); $pdf->SetFont('','B'); //Cabecera $w=60; for($i=0;$i<2;$i++) //$pdf->Cell($w,7,$header[0],1,0,'C',1); //$pdf->Ln(); //Restauración de colores y fuentes $pdf->SetFillColor(224,235,255); $pdf->SetTextColor(0); $pdf->SetFont(''); //Datos $fill=false; $i=0; $cons11 = pg_query($con,"SELECT c.nom_represent,c.apellido_represent, dm.cantidad_merca,dm.volumen_merca, dm.peso_merca,s.puerto_sali_serv, s.fch_sal_bod_serv,s.fch_est_llega_serv, s.puerto_llega_serv,ab.nombre_aget_bod, p.nombre_prov FROM servicio s, det_mercaderia dm, servicio_bodega sb,agente_bodega ab,rol r, cliente c,proveedor p WHERE s.fk_det_merca = dm.det_merca_id AND s.fk_servi_bod = sb.serv_bod_id AND sb.fk_agente_bod = ab.aget_bod_id AND s.fk_rol = r.rol_id AND s.fk_proveedor = p.proveedor_id AND r.fk_cliente = c.cliente_id AND c.cliente_id = ".$_POST["CID"]." "); /*while($row = pg_fetch_array($cons1) ) { $i++; */ $pdf->Cell($w,10,'Numero de Bultos','1',0,'C',FALSE); $pdf->Cell($w,10,$row[2],'1',0,'C',FALSE); $pdf->Ln(); $pdf->Cell($w,10,'Peso','1',0,'C',FALSE); $pdf->Cell($w,10,$row[3],'1',0,'C',FALSE); $pdf->Ln(); $pdf->Cell($w,10,'Volumen','1',0,'C',FALSE); $pdf->Cell($w,10,$row[4],'1',0,'C',FALSE); $pdf->Ln(); $pdf->Cell($w,10,'Origen','1',0,'C',FALSE); $pdf->Cell($w,10,$row[5],'1',0,'C',FALSE); $pdf->Ln(); $pdf->Cell($w,10,'Fecha de Salida de ','1',0,'C',FALSE); $pdf->Cell($w,10,$row[6],'1',0,'C',FALSE); $pdf->Ln(); $pdf->Cell($w,10,'Fecha de llegada a Puerto','1',0,'C',FALSE); $pdf->Cell($w,10,$row[7],'1',0,'C',FALSE); $pdf->Ln(); $pdf->Cell($w,10,'Frontera de ingreso','1',0,'C',FALSE); $pdf->Cell($w,10,$row[8],'1',0,'C',FALSE); $pdf->Ln(); $pdf->Cell($w,10,'Almacen Fiscal','1',0,'C',FALSE); $pdf->Cell($w,10,$row[9],'1',1,'C',FALSE); // $fill=!$fill; //} $pdf->Ln(); //$pdf->Cell(60,0,'','T'); $pdf->Cell(60,10,'Sin otro particular por le momento nos suscribimos de ustedes,',0,0,'L',FALSE); $pdf->Ln(5); $pdf->Cell(60,10,'Atentamente',0,1,'L',FALSE); $pdf->Ln(18); $pdf->Cell(60,10,'<NAME>',0,0,'L',FALSE); $pdf->Ln(5); $pdf->Cell(60,10,'CARGOMANIA S.A de C.V',0,0,'L',FALSE); $pdf->Ln(); $pdf->Cell(60,10,'Cond. Medicentro La Esperanza Local C-212, 25 Avenida Norte y 23 Calle ',0,0,'L',FALSE); $pdf->Ln(5); $pdf->Cell(60,10,'Poniente, San Salvador, El Salvador.',0,0,'L',FALSE); $pdf->Ln(5); $pdf->Cell(60,10,'Tels.:(503) 2235-7005, 2235.2235-7011',0,0,'L',FALSE); $pdf->Ln(5); $pdf->Cell(60,10,'Fax: (503) 2521-5301',0,0,'L',FALSE); $pdf->Output(); /* El documento se cierra y se envía al navegador */ ?> <file_sep>/cargomania5/procesos/header.php <?php if (!ini_get('display_errors')) { ini_set('display_errors', '1'); } include_once ('../DBManager.class.php'); //Clase de Conexión a las Base de Datos include('../cargomania.class.php'); include("../conf.php"); include("../conexion.php"); ?><file_sep>/README.md cargomania5 =========== conf.php //clase /****************** cotizacion**********************/ $conf['agregar_Cotizacion']=array( 'archivo'=>'frmAgregarCotizacion.php', 'layout'=>LAYOUT_CLIENTE ); $conf['guardar_Cotizacion']=array( 'archivo'=>'guardarCotizacion.php', 'layout'=>LAYOUT_CLIENTE ); $conf['actualizarcotizacion']=array( 'archivo'=>'actualizarcotizacion.php', 'layout'=>LAYOUT_CLIENTE ); ?> /***************************************************************************/ //CLASE cargomania.class.php /*GUARDAR COTIZACIONES*/ function guardar_cotizacion($campos){ $con = new DBManager(); //creamos el objeto $con a partir de la clase DBManager $dbh = $con->conectar("pgsql"); //Pasamos como parametro que la base de datos a utilizar para el caso MySQL. $sql = "INSERT INTO cotizacion(nombre,apellido,pais,telefono1,telefono2,correo,pais1,ciudad1,cpostal1,pais2,ciudad2,cpostal2,tmercaderia,tflete,peso,volumen,fecha) VALUES(:nombre,:apellido,:pais,:telefono1,:telefono2,:correo,:pais1,:ciudad1,:cpostal1,:pais2,:ciudad2,:cpostal2,:tmercaderia,:tflete,:peso,:volumen,:fecha)"; $query = $dbh->prepare($sql); // Preparamos la consulta para dejarla lista para su ejecucion $query->bindParam(":nombre",$campos[0]); $query->bindParam(":apellido",$campos[1]); $query->bindParam(":pais",$campos[2]); $query->bindParam(":telefono1",$campos[3]); $query->bindParam(":telefono2",$campos[4]); $query->bindParam(":correo",$campos[5]); $query->bindParam(":pais1",$campos[6]); $query->bindParam(":ciudad1",$campos[7]); $query->bindParam(":cpostal1",$campos[8]); $query->bindParam(":pais2",$campos[9]); $query->bindParam(":ciudad2",$campos[10]); $query->bindParam(":cpostal2",$campos[11]); $query->bindParam(":tmercaderia",$campos[12]); $query->bindParam(":tflete",$campos[13]); $query->bindParam(":peso",$campos[14]); $query->bindParam(":volumen",$campos[15]); $query->bindParam(":fecha",$campos[16]); $query->execute(); // Ejecutamos la consulta if ($query){ return $query; //pasamos el query para utilizarlo luego con fetch }else{ return false; } unset($dbh); unset($query); } <file_sep>/cargomania5/formularios/s3.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Cargomania</title> <link href="../../SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" /> <link href="../../slideshow/design_slideshow.css" rel="stylesheet" type="text/css" /> <link href="../../slideshow/ulightbox.css" rel="stylesheet" type="text/css"> <link type="text/css" rel="StyleSheet" href="../../slideshow/layer6.css"> <script src="../../SpryAssets/SpryMenuBar.js" type="text/javascript"></script> <script type="text/javascript" src="../../slideshow/jquery-1_002.js"></script> <script type="text/javascript" src="../../slideshow/parametros_slideshow.js"></script> <script>var div = document.getElementsByTagName('div')[0]; div.innerHTML = '';</script> <script type="text/javascript" src="../../slideshow/jquery-1.js"></script> <script type="text/javascript" src="../../slideshow/ulightbox.js"></script> <script type="text/javascript" src="../../slideshow/uwnd.js"></script> <link href="../../SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" /> <link href="../../slideshow/design_slideshow.css" rel="stylesheet" type="text/css" /> <link href="../../slideshow/ulightbox.css" rel="stylesheet" type="text/css"> <link type="text/css" rel="StyleSheet" href="../../slideshow/layer6.css"> <script src="../../SpryAssets/SpryMenuBar.js" type="text/javascript"></script> <script type="text/javascript" src="../../slideshow/jquery-1_002.js"></script> <script type="text/javascript" src="../../slideshow/parametros_slideshow.js"></script> <script>var div = document.getElementsByTagName('div')[0]; div.innerHTML = '';</script> <script type="text/javascript" src="../../slideshow/jquery-1.js"></script> <script type="text/javascript" src="../../slideshow/ulightbox.js"></script> <script type="text/javascript" src="../../slideshow/uwnd.js"></script> <link href="../../panel/style.css" rel="stylesheet" type="text/css" /> <style type="text/css"> .UhideBlock { display: none } </style> </head> <body> <div style="background-color:#222 "class="header"><!-- end .header --> <table width="944" border="0"> <tr> <td width="553" height="72"><img src="../imagenes/Logo.png" width="213" height="70"></td> <td width="381"><form name="form1" method="post" action=""> </form></td> </tr> </table> </div> <div style="background-color:#044E7C "class="header"><!-- end .header --> <table width="1013" border="0"> <tr> <td width="754" height="21"><form name="form1" method="post" action=""> <p> <label for="textfield"></label> </p> </form></td> <td width="108">&nbsp;</td> <td width="137"><span class="header" style="background-color:#044E7C "><a href="../index.php"><img src="../imagenes/register.png" width="16" height="16" />login</a></span></td> </tr> </table> </div> <div style="background-color:#000"><h1 align="center"><font color="#F2F2F2">Contraseña</font></h1> </div> <?php include "../conexion.php"; $respuesta=$_POST['txt_respuesta']; $correo=$_POST['txt_correo']; $result=pg_query("SELECT * FROM usuario WHERE respuesta='$respuesta' AND correo='$correo'"); $filas=pg_numrows($result); if($filas==0){ header("Location:validacion.php?errorusuario=1"); } else{ $resultado=pg_query("SELECT contrasena FROM usuario where respuesta='$respuesta' AND correo='$correo'"); $row = pg_fetch_array($resultado); $clave = $row['contrasena']; echo "<center><b>$clave</b></center>"; } ?> </body> </html> <file_sep>/cargomania5/formularios/frmAgregarAgenteBodega.php <script type="text/javascript"> function validar(){ if(document.getElementById("cmdGuardar").value=="Guardar"){ document.getElementById("agregarAgenteBodega").action="?mod=guardar_AgenteBodega"; }else{ document.getElementById("agregarAgenteBodega").action="?mod=actualizar_AgenteBodega"; } }</script> <?php $objAgenteBodega=new CargoMania; $codigo=""; $nomb_aget=""; $direccion_aget=""; $nombre_repre=""; $apellido_repre=""; $pais_aget=""; if(isset($_GET["id"])){ $consultarAgenteBodega=$objAgenteBodega->mostrar_AgenteBodega($_GET["id"]); if($consultarAgenteBodega->rowCount()==1){ $contene=$consultarAgenteBodega->fetch(PDO::FETCH_OBJ); $codigo=$contene->aget_bod_id; $nomb_aget=$contene->nombre_aget_bod; $direccion_aget=$contene->direccion_aget_bod; $nombre_repre=$contene->nombre_repre_aget_bod; $apellido_repre=$contene->apellido_repre_aget_bod; $pais_aget=$contene->pais_aget_bod; } } ?> <form name="agregarAgenteBodega" id="agregarAgenteBodega" method="post" onSubmit="return validar();"> <table> <caption><h1>AGREGAR AGENTE BODEGA</h1></caption> <tr> <th>Codigo:</th> <td><input type="number" name="txtCodigo" id="txtCodigo" value="<?php echo $codigo ?>" /></td> </tr> <tr> <th>Nombre Empresa:</th> <td><input type="text" name="txtNomb_Aget" id="txtNomb_Aget" value="<?php echo $nomb_aget ?>" /></td> </tr> <tr> <th>Giro:</th> <td><input type="text" name="txtdireccion_aget" id="txtdireccion_aget" value="<?php echo $direccion_aget ?>" /></td> </tr> <tr> <th>Numero de Registro:</th> <td><input type="text" name="txtnombre_repre" id="txtnombre_repre" value="<?php echo $nombre_repre ?>" /></td> </tr> <tr> <th>Direccion:</th> <td><input type="text" name="txtapellido_repre" id="txtapellido_repre" value="<?php echo $apellido_repre?>" /></td> </tr> <tr> <th>Nombre Representante:</th> <td><input type="text" name="txtpais_aget" id="txtpais_aget" value="<?php echo $pais_aget ?>" /></td> </tr> <tr> <td><input type="submit" name="cmdGuardar" value="<?php if(isset($_GET["id"])){echo "Actualizar";}else{echo "Guardar";}?>" id="cmdGuardar" /></td> </tr> </table> </form> <table> <tr><th>Codigo</th><th>Nombre Agente</th><th>Direccion Agente</th><th>Nombre Representante</th><th>Apellido Representante</th><th>Pais de Agente</th><th>Opcion</th></tr> <?php $consultarAgenteBodega=$objAgenteBodega->listar_agentebodega(); if($consultarAgenteBodega->rowCount()>0){ while($agentebodega=$consultarAgenteBodega->fetch(PDO::FETCH_OBJ)){ echo "<tr><td>".$agentebodega->aget_bod_id."</td><td>".$agentebodega->nombre_aget_bod."</td><td>".$agentebodega->direccion_aget_bod."</td> <td>".$agentebodega->nombre_repre_aget_bod."</td><td>".$agentebodega->apellido_repre_aget_bod."</td><td>".$agentebodega->pais_aget_bod."</td><td></td><td><a href='?mod=agregar_agentebodega&id=".$agentebodega->aget_bod_id."'>Mostrar</a></td></tr>"; } } ?> </table><file_sep>/cargomania5/formularios/frmAgregarTarifa.php <script type="text/javascript"> function validar(){ if(document.getElementById("cmdGuardar").value=="Guardar"){ document.getElementById("agregarTarifa").action="?mod=guardar_tarifa"; }else{ document.getElementById("agregarTarifa").action="?mod=actualizar_tarifa"; } }</script> <?php $objTarifa=new CargoMania; $codigo=""; $peso=""; $vol=""; $cliente=""; if(isset($_GET["id"])){ $consultarTarifa=$objTarifa->mostrar_tarifa($_GET["id"]); if($consultarTarifa->rowCount()==1){ $contene=$consultarTarifa->fetch(PDO::FETCH_OBJ); $codigo=$contene->cat_tarifa_id; $peso=$contene->cobro_peso; $vol=$contene->cobro_vol; $cliente=$contene->fk_cliente; } } ?> <form name="agregarTarifa" id="agregarTarifa" method="post" onSubmit="return validar();"> <table> <caption><h1>AGREGAR TARIFA</h1></caption> <tr> <th>Codigo:</th> <td><input type="number" name="txtCodigo" id="txtCodigo" value="<?php echo $codigo ?>" /></td> </tr> <tr> <th>Cobro por Peso:</th> <td><input type="text" name="txtPeso" id="txtPeso" value="<?php echo $peso ?>" /></td> </tr> <tr> <th>Cobro por Volumen:</th> <td><input type="text" name="txtVol" id="txtVol" value="<?php echo $vol ?>" /></td> </tr> <tr> <th>Cliente:</th> <td><select name="lstCliente" id="lstCliente"> <?php $consultarCliente=$objTarifa->consultar_clientes(); if($consultarCliente->rowCount()>0){ echo "<option value='0'>Elija un Cliente</option>"; while($cliente=$consultarCliente->fetch(PDO::FETCH_OBJ)){ ?> <?php if($cliente->cliente_id==$cliente && $cliente!=""){ $selected=" selected"; }else{ $selected=""; } ?> <option value="<?php echo $cliente->cliente_id ?>" <?php echo $selected; ?>><?php echo $cliente->nombre_empr ?></option> <?php } }else{ ?> <option value="0">No hay Clientes</option> <?php } ?> </select></td> </tr> <tr> <td><input type="submit" name="cmdGuardar" value="<?php if(isset($_GET["id"])){echo "Actualizar";}else{echo "Guardar";}?>" id="cmdGuardar" /></td> </tr> </table> </form> <table> <tr><th>Codigo</th><th>Cobro por Peso</th><th>Cobro por Volumen</th><th>Cliente</th><th>Modificar</th></tr> <?php $consultarTarifa=$objTarifa->listar_tarifas(); if($consultarTarifa->rowCount()>0){ while($tarifa=$consultarTarifa->fetch(PDO::FETCH_OBJ)){ $cliente=$objTarifa->consultar_cliente($tarifa->fk_cliente)->fetch(PDO::FETCH_OBJ); echo "<tr><td>".$tarifa->cat_tarifa_id."</td><td>".$tarifa->cobro_peso."</td><td>".$tarifa->cobro_vol."</td> <td>".$cliente->nombre_empr."</td><td><a href='?mod=agregar_tarifa&id=".$tarifa->cat_tarifa_id."'>Mostrar</a></td></tr>"; } } ?> </table><file_sep>/cargomania5/conexion.php <?php define ('DB_HOST','localhost'); //Host de postgresql (puede ser otro) define ('DB_USER','postgres'); //Usuario de postgresql (puede ser otro) define ('DB_PASS','<PASSWORD>'); //Password de postgresql (puede ser otro) define ('DB_NAME','cargomania'); //Database de postgresql (puede ser otra) define ('DB_PORT','5432'); //Puerto de postgresql (puede ser otro) $cnx = pg_connect("user=".DB_USER." port=".DB_PORT." dbname=".DB_NAME." host=".DB_HOST." password=".DB_PASS); //analisis2 ?><file_sep>/cargomania5/plantillas/cliente.php <?php date_default_timezone_set('America/Chicago'); ob_start(); session_start(); ?> <!DOCTYPE HTML> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Cargomania</title> <link href="css/main.css" rel="stylesheet" type="text/css" /> <link href="estilos.css" rel="stylesheet" type="text/css" />prueba prueba <link href="css/style5.css" rel="stylesheet" type="text/css"> <script src="js/jquery-1.8.2.js"></script> <!--<script src="js/jquery-1.8.2.js"></script>--> </head> <body> <div id="header-wrap"> <div id="header-`container"> <div id="header"> <?php include("header.php") ?> </div> </div> </div> <div style="background-color:#FFF;height:768px;"> <div id="ie6-container-wrap"> <div id="container"> <div id="content" align="center"> <?php include(MODULO_PATH . "/" . $conf[$modulo]['archivo']); ?> </div> </div> </div> </div> <div id="footer-wrap"> <div id="footer-container"> <div id="footer"> <?php include('footer.php'); ?> </div> </div> </div> </body> </html> <?php ob_end_flush(); ?><file_sep>/cargomania5/conf.php <?php define('MODULO_DEFECTO','login'); define('LAYOUT_DEFECTO','inicio.php');//Administrador define('LAYOUT_LOGIN','login.php');//Administrador define('LAYOUT_CLIENTE','cliente.php'); define('LAYOUT_ADMIN','admin.php'); define('LAYOUT_POPUP','popup.php'); define('LAYOUT_POPUP2','popup2.php'); define('LAYOUT_POPUP3','popup3.php'); define('LAYOUT_INICIO','inicio.php');//Para cualquier tipo de usuario define('MODULO_PATH',realpath('formularios')); define('LAYOUT_PATH',realpath('plantillas')); //ADMINISTRADOR DE CUENTAS ELECTRÓNICAS //Modulos de manejo usuarios $conf['login']=array( 'archivo'=>'frmLogin.php', 'layout'=>LAYOUT_LOGIN ); $conf['404']=array( 'archivo'=>'404.php', 'layout'=>LAYOUT_INICIO ); $conf['autenticar']=array( 'archivo'=>'autenticar.php', 'layout'=>LAYOUT_INICIO ); $conf['logout']=array( 'archivo'=>'logout.php', 'layout'=>LAYOUT_INICIO ); $conf['changePwd']=array( 'archivo'=>'frmCambiarContra.php', 'layout'=>LAYOUT_INICIO ); $conf['cambiarPwd']=array( 'archivo'=>'procesoFrmCambiarContra.php', 'layout'=>LAYOUT_INICIO ); $conf['resetPwdUser']=array( 'archivo'=>'pwdRecovery.php', 'layout'=>LAYOUT_INICIO ); //MODULOS DEL CLIENTE $conf['seguimiento_mercaderia']=array( 'archivo'=>'segumiento_mercaderia.html', 'layout'=>LAYOUT_CLIENTE ); $conf['menu']=array( 'archivo'=>'index2.html', 'layout'=>LAYOUT_CLIENTE ); $conf['menu2']=array( 'archivo'=>'index1.html', 'layout'=>LAYOUT_CLIENTE ); $conf['tarifa']=array( 'archivo'=>'tarifario.html', 'layout'=>LAYOUT_POPUP ); $conf['cliente']=array( 'archivo'=>'Formulario_cliente.html', 'layout'=>LAYOUT_POPUP ); $conf['empleados']=array( 'archivo'=>'empleado.html', 'layout'=>LAYOUT_POPUP ); $conf['empleados']=array( 'archivo'=>'empleado.html', 'layout'=>LAYOUT_POPUP ); $conf['proveedor']=array( 'archivo'=>'Formulario_proveedor.html', 'layout'=>LAYOUT_POPUP ); $conf['agent_bodega']=array( 'archivo'=>'agente_bodega.html', 'layout'=>LAYOUT_POPUP ); $conf['contenedor']=array( 'archivo'=>'contenedor.html', 'layout'=>LAYOUT_POPUP2 ); $conf['archivo']=array( 'archivo'=>'archivo.html', 'layout'=>LAYOUT_POPUP ); $conf['servicios']=array( 'archivo'=>'servicio.php', 'layout'=>LAYOUT_POPUP3 ); $conf['agentes']=array( 'archivo'=>'agente_flete.html', 'layout'=>LAYOUT_POPUP ); $conf['merc']=array( 'archivo'=>'mercaderia.html', 'layout'=>LAYOUT_POPUP ); $conf['adu']=array( 'archivo'=>'aduana.html', 'layout'=>LAYOUT_POPUP ); $conf['ma']=array( 'archivo'=>'manual.html', 'layout'=>LAYOUT_POPUP3 ); $conf['est']=array( 'archivo'=>'Estadistica.html', 'layout'=>LAYOUT_POPUP3 ); $conf['agregar_contenedor']=array( 'archivo'=>'frmAgregarContenedor.php', 'layout'=>LAYOUT_CLIENTE ); $conf['guardar_contenedor']=array( 'archivo'=>'guardarContenedor.php', 'layout'=>LAYOUT_CLIENTE ); $conf['actualizar_contenedor']=array( 'archivo'=>'actualizarContenedor.php', 'layout'=>LAYOUT_CLIENTE ); // MODULO CLIENTE $conf['agregar_cliente']=array( 'archivo'=>'frmAgregarCliente.php', 'layout'=>LAYOUT_CLIENTE ); $conf['guardar_cliente']=array( 'archivo'=>'guardarCliente.php', 'layout'=>LAYOUT_CLIENTE ); $conf['actualizar_cliente']=array( 'archivo'=>'actualizarCliente.php', 'layout'=>LAYOUT_CLIENTE ); // MODULO AGENTE BODEGA $conf['agregar_agentebodega']=array( 'archivo'=>'frmAgregarAgenteBodega.php', 'layout'=>LAYOUT_CLIENTE ); $conf['guardar_AgenteBodega']=array( 'archivo'=>'guardarAgenteBodega.php', 'layout'=>LAYOUT_CLIENTE ); $conf['actualizar_AgenteBodega']=array( 'archivo'=>'actualizarAgenteBodega.php', 'layout'=>LAYOUT_CLIENTE ); // MODULO SERVICIO BODEGA $conf['agregar_serviciobodega']=array( 'archivo'=>'frmAgregarServicioBodega.php', 'layout'=>LAYOUT_CLIENTE ); $conf['guardar_serviciobodega']=array( 'archivo'=>'guardar_ServicioBodega.php', 'layout'=>LAYOUT_CLIENTE ); $conf['actualizar_ServicioBodega']=array( 'archivo'=>'actualizar_ServicioBodega.php', 'layout'=>LAYOUT_CLIENTE ); //MODULO DE EMPLEADO $conf['agregar_empleado']=array( 'archivo'=>'frmAgregarEmpleado.php', 'layout'=>LAYOUT_CLIENTE ); $conf['guardar_empleado']=array( 'archivo'=>'guardarEmpleado.php', 'layout'=>LAYOUT_CLIENTE ); $conf['actualizar_empleado']=array( 'archivo'=>'actualizarEmpleado.php', 'layout'=>LAYOUT_CLIENTE ); //MODULO DE TARIFARIO $conf['agregar_tarifa']=array( 'archivo'=>'frmAgregarTarifa.php', 'layout'=>LAYOUT_CLIENTE ); $conf['guardar_tarifa']=array( 'archivo'=>'guardarTarifa.php', 'layout'=>LAYOUT_CLIENTE ); $conf['actualizar_tarifa']=array( 'archivo'=>'actualizarTarifa.php', 'layout'=>LAYOUT_CLIENTE ); //MODULO DE PROVEEDOR $conf['agregar_proveedor']=array( 'archivo'=>'frmAgregarProveedor.php', 'layout'=>LAYOUT_CLIENTE ); $conf['guardar_proveedor']=array( 'archivo'=>'guardarProveedor.php', 'layout'=>LAYOUT_CLIENTE ); $conf['actualizar_proveedor']=array( 'archivo'=>'actualizarProveedor.php', 'layout'=>LAYOUT_CLIENTE ); //MODULO DE ADUANA_LLEGADA $conf['agregar_aduana_llegada']=array( 'archivo'=>'frmAgregar_aduana_llegada.php', 'layout'=>LAYOUT_CLIENTE ); $conf['guardar_aduana_llegada']=array( 'archivo'=>'guardar_aduana_llegada.php', 'layout'=>LAYOUT_CLIENTE ); $conf['actualizar_aduana_llegada']=array( 'archivo'=>'actualizar_aduana_llegada.php', 'layout'=>LAYOUT_CLIENTE ); //traking //manifiesto $conf['contenedor']=array( 'archivo'=>'contenedor.html', 'layout'=>LAYOUT_POPUP3 ); //MODULO DE MERCADERIA $conf['agregar_mercaderia']=array( 'archivo'=>'frmAgregarMercaderia.php', 'layout'=>LAYOUT_CLIENTE ); $conf['guardar_mercaderia']=array( 'archivo'=>'guardarMercaderia.php', 'layout'=>LAYOUT_CLIENTE ); $conf['actualizar_mercaderia']=array( 'archivo'=>'actualizar_mercaderia.php', 'layout'=>LAYOUT_CLIENTE ); ?><file_sep>/cargomania5/ajax.php <?php include("conexion.php"); $consulta = pg_query("select proveedor_id,direccion from proveedor where proveedor_id=".$_GET['id']." order by direccion ASC"); echo "<select name='direccion' id='direccion' class='select_style' >"; while ($fila = pg_fetch_array($consulta)) { echo "<option value='" . $fila[0] . "'>" . utf8_encode($fila[1]) . "</option>"; } echo "</select>"; ?><file_sep>/cargomania5/formularios/etd2.php <?php function cliente_id($nombre,$valor) { include("config.inc.php"); $query = "SELECT * from cliente order by nombre_empr"; //mysql_select_db($dbname); $result = pg_query($query); echo "<select name='CID' id='$nombre'>"; echo "<option value=''>Selecciona un cliente...</option>"; while($registro=pg_fetch_array($result)) { echo "<option value='".$registro["cliente_id"]."'"; if ($registro["cliente_id"]==$valor); echo ">".$registro["nombre_empr"]."</option>\r\n"; } echo "</select>"; } function proveedor_id($nombre,$valor) { include("config.inc.php"); $query = "SELECT * FROM proveedor order by nombre_prov"; pg_select($cnx,$dbname,$_POST); $result = pg_query($query); echo "<select name='CPR' id='$nombre'>"; echo "<option value=''>Selecciona un proveedor...</option>"; while($registro=pg_fetch_array($result)) { echo "<option value='".$registro["proveedor_id"]."'"; if ($registro["proveedor_id"]==$valor); echo ">".$registro["nombre_prov"]."</option>\r\n"; } echo "</select>"; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" /> <title>SERVICIO</title> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function() { /* COMBOBOX */ $("#cliente_id").change(function(event) { var cliente_id = $(this).find(':selected').val(); $("#pidproveedor").html("<img src='loading.gif' />"); $("#pidproveedor").load('combobox.php?buscar=proveedor&cliente_id='+cliente_id); var proveedor_id = $("#proveedor_id").find(':selected').val(); $("#piddireccion").html("<img src='loading.gif' />"); $("#piddireccion").load('combobox.php?buscar=direccion&proveedor_id='+proveedor_id); $("#pidpais").html("<img src='loading.gif' />"); $("#pidpais").load('combobox.php?buscar=pais&proveedor_id='+proveedor_id); }); $("#proveedor_id").live("change",function(event) { var id = $(this).find(':selected').val(); $("#piddireccion").html("<img src='loading.gif' />"); $("#piddireccion").load('combobox.php?buscar=direccion&proveedor_id='+id); $("#pidpais").html("<img src='loading.gif' />"); $("#pidpais").load('combobox.php?buscar=pais&proveedor_id='+id); }); }); </script> <style> select{padding:5px;border:1px solid #bbb;border-radius:5px;margin:5px 0;display:block;box-shadow:0 0 10px #ddd} #resultados{margin:20px 0;padding:20px;border:10px solid #ddd;} </style> </head> <body> <h1>Documentacion</h1> <p> <strong>Generacion de ETD</strong> </p> </p> <form method="post" action="formularios/etd_pdf.php"> <fieldset> <p><label>Seleccione Cliente:</label><?php cliente_id("cliente_id","1"); ?></p> <p id="pidproveedor"><label>Seleccione Proveedor:</label><?php proveedor_id("proveedor_id","2"); ?></p> <p><input type="hidden" name="hval"><input type="submit" name="submit" value="GENERAR" /></p> </fieldset> </form> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-266167-20"); //pageTracker._setDomainName(".martiniglesias.eu"); pageTracker._trackPageview(); } catch(err) {}</script> </body> </html>
c34b187a514ae3388b434a2ecf3facaa561fc58f
[ "JavaScript", "Markdown", "PHP" ]
31
PHP
lec92/cargomania5
f449b6da8e7229bb43dc19b04d713306c47fd956
b2bd9195c907d7d63adf73d91b9177386bba81e5
refs/heads/master
<file_sep>// // CommonProtocols.h // IkasGame // // Created by <NAME> on 2014-12-24. // // #ifndef __IkasCocosGame__CommonProtocols #define __IkasCocosGame__CommonProtocols class GameHUDDelegate { public: virtual void showMenu() = 0; virtual void hideMenu() = 0; }; class GamePlayDelegate { public: virtual void loadNextGamePlay() = 0; virtual void resumeGamePlay() = 0; virtual void restartGame() = 0; virtual void updateScreenGameStats() = 0; }; #endif <file_sep>// // SceneManager.cpp // IkasGame // // Created by <NAME> on 30/01/15. // // #include "SceneManager.h" #include "AppManager.h" #include "../Scenes/Splash.h" #include "../Scenes/Main.h" #include "../Scenes/Categories.h" #include "../Scenes/Level.h" #include "../Scenes/GamePlay.h" #include "../Scenes/Pause.h" #include "../Scenes/Win.h" #include "../Scenes/Lose.h" using namespace cocos2d; // Singleton SceneManager * SceneManager::_instance = NULL; /** * Give me a pointer to Singleton! */ SceneManager* SceneManager::getInstance() { if(!_instance) _instance = new SceneManager(); return _instance; } SceneManager::SceneManager(): _sceneTypeToReturn(SceneType::MAIN), _currentSceneType(SceneType::MAIN) { } SceneManager::~SceneManager() { } void SceneManager::runSceneWithType(const SceneType sceneType) { Scene *sceneToRun = nullptr; switch (sceneType) { case SceneType::SPLASH: sceneToRun = Splash::createScene(); break; case SceneType::MAIN: sceneToRun = Main::createScene(); break; case SceneType::CATEGORIES: sceneToRun = Categories::createScene(); break; case SceneType::LEVEL: sceneToRun = Level::createScene(); break; case SceneType::GAMEPLAY: sceneToRun = GamePlay::createScene(); break; case SceneType::PAUSE: sceneToRun = Pause::createScene(); break; case SceneType::WIN: sceneToRun = Win::createScene(); break; case SceneType::LOSE: sceneToRun = Lose::createScene(); break; default: log("WARNING! Default value when trying to run scene with id %d", static_cast<int>(sceneType)); return; break; } this->runScene(sceneToRun, sceneType); } void SceneManager::runScene(Scene* sceneToRun, SceneType sceneType) { SceneType oldScene = _currentSceneType; _currentSceneType = sceneType; sceneToRun->setTag(static_cast<int>(sceneType)); if (sceneToRun == nullptr) { _currentSceneType = oldScene; return; } _sceneTypeToReturn = oldScene; if (Director::getInstance()->getRunningScene() == nullptr) { Director::getInstance()->runWithScene(sceneToRun); } else { Director::getInstance()->replaceScene(sceneToRun); } } void SceneManager::returnToLastScene() { this->runSceneWithType(_sceneTypeToReturn); } void SceneManager::saveCurrentScene() { _savedScene = Director::getInstance()->getRunningScene(); CC_SAFE_RETAIN(_savedScene); _savedSceneType = _currentSceneType; } void SceneManager::loadSavedScene() { CC_ASSERT(_savedScene != nullptr); this->runScene(_savedScene, _savedSceneType); this->removeSavedScene(); } void SceneManager::removeSavedScene() { CC_SAFE_RELEASE(_savedScene); } <file_sep>// // Lose.cpp // IkasGame // // Created by <NAME> on 11/2/15. // // #include "Lose.h" #include "../Singletons/GameSettingsManager.h" #include "../Singletons/GamePlayPointsManager.h" #include "../Singletons/SceneManager.h" #include "../Singletons/SoundManager.h" #include "../Singletons/AppManager.h" #include "../Helpers/LanguageManager.h" #include "../Helpers/ScreenSizeManager.h" #include "../Helpers/ImageManager.h" #include "../CustomGUI/SpriteButton.h" Scene* Lose::createScene() { SceneManager::getInstance()->saveCurrentScene(); auto *scene = Scene::create(); auto *layer = Lose::create(); layer->setTag(2339); scene->addChild(layer); return scene; } bool Lose::init() { if (!Layer::init()) { return false; } Rect visibleRect = ScreenSizeManager::getVisibleRect(); auto background = Sprite::create(ImageManager::getImage("background"), visibleRect); background->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50)); background->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(background); auto buttonNextGamePlay = SpriteButton::create(ImageManager::getImage("restart"), 1.0f, CC_CALLBACK_1(Lose::resetGame, this)); buttonNextGamePlay->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonNextGamePlay = ScreenSizeManager::getScreenPositionFromPercentage(50, 50); buttonNextGamePlay->setPosition(positionButtonNextGamePlay); this->addChild(buttonNextGamePlay); auto labelResume = Label::createWithTTF(LanguageManager::getLocalizedText("Lose", "reset"), MainRegularFont, 70); labelResume->setAlignment(TextHAlignment::CENTER); labelResume->setAnchorPoint(Point::ANCHOR_MIDDLE_TOP); labelResume->setTextColor(IkasGrayDark); Vec2 positionLabelResume = buttonNextGamePlay->getPosition(); positionLabelResume.y -= buttonNextGamePlay->getBoundingBox().size.height / 2; positionLabelResume.y -= ScreenSizeManager::getHeightFromPercentage(1); labelResume->setPosition(positionLabelResume); this->addChild(labelResume); std::ostringstream totalPoints; totalPoints << GamePlayPointsManager::getInstance()->getCurrentPoints() << " " << LanguageManager::getLocalizedText("Lose", "points-value"); auto labelPointsValue = Label::createWithTTF(totalPoints.str(), MainRegularFont, 75); labelPointsValue->setAlignment(TextHAlignment::CENTER); labelPointsValue->setAnchorPoint(Point::ANCHOR_MIDDLE); labelPointsValue->setTextColor(IkasGrayDark); Vec2 positionLabelPointsValue = buttonNextGamePlay->getPosition(); positionLabelPointsValue.y += buttonNextGamePlay->getBoundingBox().size.height / 2; positionLabelPointsValue.y += labelPointsValue->getBoundingBox().size.height / 2; positionLabelPointsValue.y += ScreenSizeManager::getHeightFromPercentage(1); labelPointsValue->setPosition(positionLabelPointsValue); this->addChild(labelPointsValue); auto labelPointsTitle = Label::createWithTTF(LanguageManager::getLocalizedText("Lose", "points-title"), MainRegularFont, 75); labelPointsTitle->setAlignment(TextHAlignment::CENTER); labelPointsTitle->setAnchorPoint(Point::ANCHOR_MIDDLE); labelPointsTitle->setTextColor(IkasGrayDark); Vec2 positionLabelPointsTitle = labelPointsValue->getPosition(); positionLabelPointsTitle.y += labelPointsValue->getBoundingBox().size.height / 2; positionLabelPointsTitle.y += labelPointsTitle->getBoundingBox().size.height / 2; positionLabelPointsTitle.y += ScreenSizeManager::getHeightFromPercentage(1); labelPointsTitle->setPosition(positionLabelPointsTitle); this->addChild(labelPointsTitle); auto labelTitle = Label::createWithTTF(LanguageManager::getLocalizedText("Lose", "title"), MainRegularFont, 90); labelTitle->setAlignment(TextHAlignment::CENTER); labelTitle->setAnchorPoint(Point::ANCHOR_MIDDLE); labelTitle->setTextColor(IkasPink); Vec2 positionLabelTitle = labelPointsTitle->getPosition(); positionLabelTitle.y += labelPointsTitle->getBoundingBox().size.height / 2; positionLabelTitle.y += labelTitle->getBoundingBox().size.height / 2; positionLabelTitle.y += ScreenSizeManager::getHeightFromPercentage(1); labelTitle->setPosition(positionLabelTitle); this->addChild(labelTitle); auto buttonSoundSettings = SpriteButton::create(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage), 0.30f, CC_CALLBACK_1(Lose::switchSoundSettings, this)); buttonSoundSettings->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonSoundSettings = ScreenSizeManager::getScreenPositionFromPercentage(80, 15); buttonSoundSettings->setPosition(positionButtonSoundSettings); this->addChild(buttonSoundSettings); auto buttonHome = SpriteButton::create(ImageManager::getImage("home"), 0.30f, CC_CALLBACK_1(Lose::returnHome, this)); buttonHome->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonHome = ScreenSizeManager::getScreenPositionFromPercentage(22, 15); buttonHome->setPosition(positionButtonHome); this->addChild(buttonHome); return true; } void Lose::resetGame(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); GamePlayPointsManager::getInstance()->resetCurrentPoints(); SceneManager::getInstance()->loadSavedScene(); AppManager::getInstance()->restartGame(); } void Lose::switchSoundSettings(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); GameSettingsManager::getInstance()->switchSFX(); GameSettingsManager::getInstance()->switchMusic(); SpriteButton *item = static_cast<SpriteButton*>(sender); item->setTexture(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage)); } void Lose::returnHome(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); AppManager::getInstance()->setGamePlayDelegate(NULL); SceneManager::getInstance()->runSceneWithType(SceneType::MAIN); SceneManager::getInstance()->removeSavedScene(); } <file_sep>// // MainCategory.h // ikaszopa // // Created by <NAME> on 24/2/15. // // #ifndef ikaszopa_MainCategory_h #define ikaszopa_MainCategory_h #include "cocos2d.h" #include "SubCategory.h" #include "../Constants/Constants.h" using namespace cocos2d; using namespace std; class MainCategory : public Object { public: MainCategory(){}; ~MainCategory(){}; vector<SubCategory*> getFilteredSubCategoriesByLevel(Difficulty difficulty); vector<SubCategory*> getFilteredSubCategoriesByLevel(int minLevel); CC_SYNTHESIZE(string, m_Name, Name); CC_SYNTHESIZE(string, m_FileName, FileName); CC_SYNTHESIZE(vector<SubCategory*>, m_SubCategories, SubCategories); }; #endif <file_sep>// // Level.cpp // IkasGame // // Created by <NAME> on 9/2/15. // // #include "Level.h" #include "../Singletons/GameSettingsManager.h" #include "../Singletons/GamePlayPointsManager.h" #include "../Singletons/SceneManager.h" #include "../Singletons/SoundManager.h" #include "../Helpers/LanguageManager.h" #include "../Helpers/ScreenSizeManager.h" #include "../Helpers/ImageManager.h" #include "../Scenes/GamePlay.h" #include "../Helpers/DataFileManager.h" #include "../GameModels/MainCategory.h" #define TitleSeparatorHeight 10 #define LevelsViewWidthPercentage 70 #define LevelsViewHeightPercentage 40 #define LevelsViewXPositionPercentage 50 #define LevelsViewYPositionPercentage 50 #define LevelsViewItemImageHeightPercentage 80 #define LevelsViewItemImageTitleSeparationPercentage 5 Scene* Level::createScene() { auto *scene = Scene::create(); auto *layer = Level::create(); layer->setTag(2334); scene->addChild(layer); return scene; } bool Level::init() { if ( !Layer::init() ) { return false; } Rect visibleRect = ScreenSizeManager::getVisibleRect(); auto background = Sprite::create(ImageManager::getImage("background"), visibleRect); background->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50)); background->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(background); buttonsLayer = Layer::create(); buttonsLayer->setContentSize(visibleRect.size); buttonsLayer->setPosition(0, 0); auto buttonBack = SpriteButton::create(ImageManager::getImage("back"), 0.30f, CC_CALLBACK_1(Level::changeScene, this)); buttonBack->setTag(static_cast<int>(SceneType::CATEGORIES)); buttonBack->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonBack = ScreenSizeManager::getScreenPositionFromPercentage(5, 5); positionButtonBack.x += buttonBack->getBoundingBox().size.width / 2; positionButtonBack.y += buttonBack->getBoundingBox().size.height / 2; buttonBack->setPosition(positionButtonBack); buttonsLayer->addChild(buttonBack); auto buttonHome = SpriteButton::create(ImageManager::getImage("home"), 0.30f, CC_CALLBACK_1(Level::changeScene, this)); buttonHome->setTag(static_cast<int>(SceneType::MAIN)); buttonHome->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonHome = buttonBack->getPosition(); positionButtonHome.x += buttonHome->getBoundingBox().size.width; positionButtonHome.x += ScreenSizeManager::getWidthFromPercentage(5); buttonHome->setPosition(positionButtonHome); buttonsLayer->addChild(buttonHome); auto buttonAbout = SpriteButton::create(ImageManager::getImage("info"), 0.30f, CC_CALLBACK_1(Level::openInfo, this)); buttonAbout->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonAbout = ScreenSizeManager::getScreenPositionFromPercentage(95, 5); positionButtonAbout.x -= buttonAbout->getBoundingBox().size.width / 2; positionButtonAbout.y += buttonAbout->getBoundingBox().size.height / 2; buttonAbout->setPosition(positionButtonAbout); buttonsLayer->addChild(buttonAbout); auto buttonSFXSettings = SpriteButton::create(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage), 0.30f, CC_CALLBACK_1(Level::switchSoundSettings, this)); buttonSFXSettings->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonSFXSettings = buttonAbout->getPosition(); positionButtonSFXSettings.x -= buttonSFXSettings->getBoundingBox().size.width; positionButtonSFXSettings.x -= ScreenSizeManager::getWidthFromPercentage(5); buttonSFXSettings->setPosition(positionButtonSFXSettings); buttonsLayer->addChild(buttonSFXSettings); this->addChild(buttonsLayer); auto layerCategories = Layer::create(); layerCategories->setContentSize(visibleRect.size); layerCategories->setAnchorPoint(Point::ZERO); layerCategories->setPosition(0, 0); auto layerDifficultyButtons = Layer::create(); layerDifficultyButtons->setContentSize(Size(ScreenSizeManager::getWidthFromPercentage(LevelsViewWidthPercentage), ScreenSizeManager::getHeightFromPercentage(LevelsViewHeightPercentage))); Vec2 positionLayerDifficiltyButtons = ScreenSizeManager::getScreenPositionFromPercentage(LevelsViewXPositionPercentage, LevelsViewYPositionPercentage); positionLayerDifficiltyButtons.y -= layerDifficultyButtons->getContentSize().height/2; positionLayerDifficiltyButtons.x -= layerDifficultyButtons->getContentSize().width/2; layerDifficultyButtons->setPosition(positionLayerDifficiltyButtons); // Size and positions Size sizeLevelLayer = layerDifficultyButtons->getBoundingBox().size; sizeLevelLayer.width = sizeLevelLayer.width/3; Size sizeButton = sizeLevelLayer; sizeButton.height = sizeButton.height * LevelsViewItemImageHeightPercentage/100; float buttonYCenterPosition = sizeLevelLayer.height - sizeButton.height/2; Size labelSize = sizeLevelLayer; float percentage = (float)(100 - LevelsViewItemImageHeightPercentage - LevelsViewItemImageTitleSeparationPercentage)/100; labelSize.height = labelSize.height * percentage; // Levels layers Vec2 positionLevelLayer = Vec2(0, 0); auto layerEasyLevel = Layer::create(); layerEasyLevel->setContentSize(sizeLevelLayer); positionLevelLayer.x = sizeLevelLayer.width * 0; layerEasyLevel->setPosition(positionLevelLayer); layerDifficultyButtons->addChild(layerEasyLevel); auto layerMediumLevel = Layer::create(); layerMediumLevel->setContentSize(sizeLevelLayer); positionLevelLayer.x = sizeLevelLayer.width * 1; layerMediumLevel->setPosition(positionLevelLayer); layerDifficultyButtons->addChild(layerMediumLevel); auto layerHardLevel = Layer::create(); layerHardLevel->setContentSize(sizeLevelLayer); positionLevelLayer.x = sizeLevelLayer.width * 2; layerHardLevel->setPosition(positionLevelLayer); layerDifficultyButtons->addChild(layerHardLevel); float maxSize; float scale = 1.0f; // Easy level auto buttonEasyLevel = SpriteButton::create(ImageManager::getImage("level-easy-circle"), scale, CC_CALLBACK_1(Level::selectLevel, this)); buttonEasyLevel->setTag(static_cast<int>(Difficulty::EASY)); if (sizeButton.width < sizeButton.height) { scale = sizeButton.width / buttonEasyLevel->getBoundingBox().size.width; scale -= 0.15f; maxSize = sizeButton.width * scale; } else { scale = sizeButton.height / buttonEasyLevel->getBoundingBox().size.height; scale -= 0.15f; maxSize = sizeButton.height * scale; } buttonEasyLevel->setScale(scale); buttonEasyLevel->setAnchorPoint(Point::ANCHOR_MIDDLE); buttonEasyLevel->setPosition(sizeLevelLayer.width/2, buttonYCenterPosition); layerEasyLevel->addChild(buttonEasyLevel); auto labelEasyLevel = Label::createWithTTF(LanguageManager::getLocalizedText("Level", "easy"), MainRegularFont, 70.0); labelEasyLevel->setContentSize(labelSize); labelEasyLevel->setPosition(sizeLevelLayer.width/2, 0); labelEasyLevel->setAnchorPoint(Point::ANCHOR_MIDDLE_BOTTOM); labelEasyLevel->setAlignment(TextHAlignment::CENTER); labelEasyLevel->setTag(123); labelEasyLevel->setTextColor(IkasGrayDark); layerEasyLevel->addChild(labelEasyLevel); // Medium level scale = 1.0f; auto buttonMediumLevel = SpriteButton::create(ImageManager::getImage("level-medium-circle"), scale, CC_CALLBACK_1(Level::selectLevel, this)); buttonMediumLevel->setTag(static_cast<int>(Difficulty::MEDIUM)); if (sizeButton.width < sizeButton.height) { scale = sizeButton.width / buttonMediumLevel->getBoundingBox().size.width; scale -= 0.15f; maxSize = sizeButton.width * scale; } else { scale = sizeButton.height / buttonMediumLevel->getBoundingBox().size.height; scale -= 0.15f; maxSize = sizeButton.height * scale; } buttonMediumLevel->setScale(scale); buttonMediumLevel->setAnchorPoint(Point::ANCHOR_MIDDLE); buttonMediumLevel->setPosition(sizeLevelLayer.width/2, buttonYCenterPosition); layerMediumLevel->addChild(buttonMediumLevel); auto labelMediumLevel = Label::createWithTTF(LanguageManager::getLocalizedText("Level", "medium"), MainRegularFont, 70.0); labelMediumLevel->setContentSize(labelSize); labelMediumLevel->setPosition(sizeLevelLayer.width/2, 0); labelMediumLevel->setAnchorPoint(Point::ANCHOR_MIDDLE_BOTTOM); labelMediumLevel->setAlignment(TextHAlignment::CENTER); labelMediumLevel->setTag(123); labelMediumLevel->setTextColor(IkasGrayDark); layerMediumLevel->addChild(labelMediumLevel); // Hard level scale = 1.0f; auto buttonHardLevel = SpriteButton::create(ImageManager::getImage("level-hard-circle"), scale, CC_CALLBACK_1(Level::selectLevel, this)); buttonHardLevel->setTag(static_cast<int>(Difficulty::HARD)); if (sizeButton.width < sizeButton.height) { scale = sizeButton.width / buttonHardLevel->getBoundingBox().size.width; scale -= 0.15f; maxSize = sizeButton.width * scale; } else { scale = sizeButton.height / buttonHardLevel->getBoundingBox().size.height; scale -= 0.15f; maxSize = sizeButton.height * scale; } buttonHardLevel->setScale(scale); buttonHardLevel->setAnchorPoint(Point::ANCHOR_MIDDLE); buttonHardLevel->setPosition(sizeLevelLayer.width/2, buttonYCenterPosition); layerHardLevel->addChild(buttonHardLevel); auto labelHardLevel = Label::createWithTTF(LanguageManager::getLocalizedText("Level", "hard"), MainRegularFont, 70.0); labelHardLevel->setContentSize(labelSize); labelHardLevel->setPosition(sizeLevelLayer.width/2, 0); labelHardLevel->setAnchorPoint(Point::ANCHOR_MIDDLE_BOTTOM); labelHardLevel->setAlignment(TextHAlignment::CENTER); labelHardLevel->setTag(123); labelHardLevel->setTextColor(IkasGrayDark); layerHardLevel->addChild(labelHardLevel); layerCategories->addChild(layerDifficultyButtons); auto labelDifficultyTitle = Label::createWithTTF(LanguageManager::getLocalizedText("Level", "title"), MainRegularFont, 70); labelDifficultyTitle->setAlignment(TextHAlignment::CENTER); labelDifficultyTitle->setAnchorPoint(Point::ANCHOR_MIDDLE_BOTTOM); labelDifficultyTitle->setTextColor(IkasGrayDark); Vec2 positionLabelTitle = layerDifficultyButtons->getPosition(); positionLabelTitle.x += layerDifficultyButtons->getBoundingBox().size.width/2; positionLabelTitle.y += layerDifficultyButtons->getBoundingBox().size.height; positionLabelTitle.y += ScreenSizeManager::getHeightFromPercentage(10); labelDifficultyTitle->setPosition(positionLabelTitle); layerCategories->addChild(labelDifficultyTitle); this->addChild(layerCategories); return true; } void Level::switchSoundSettings(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); GameSettingsManager::getInstance()->switchSFX(); GameSettingsManager::getInstance()->switchMusic(); SpriteButton *item = static_cast<SpriteButton*>(sender); item->setTexture(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage)); } void Level::changeScene(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); SpriteButton *item = static_cast<SpriteButton*>(sender); SceneManager::getInstance()->runSceneWithType(static_cast<SceneType>(item->getTag())); } void Level::openInfo(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); Application::getInstance()->openURL(InfoURL); } void Level::selectLevel(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); SpriteButton *item = static_cast<SpriteButton*>(sender); Difficulty difficulty = static_cast<Difficulty>(item->getTag()); vector<MainCategory*> categories = DataFileManager::getInstance()->getMainCategories(); vector<SubCategory*> subCategories = categories.at(GamePlayPointsManager::getInstance()->getCurrentCategory())->getFilteredSubCategoriesByLevel(difficulty); if (subCategories.empty()) { log("no hay subcategorias con ese nivel!!"); return; } GamePlayPointsManager::getInstance()->setCurrentDifficulty(difficulty); SceneManager::getInstance()->runSceneWithType(SceneType::GAMEPLAY); } <file_sep>// // ScreenHelper.cpp // Ikasesteka // // Created by <NAME> on 26/11/14. // // #include "ScreenSizeManager.h" Rect ScreenSizeManager::visibleScreen; void ScreenSizeManager::lazyInit() { if (visibleScreen.size.width == 0.0f && visibleScreen.size.height == 0.0f) { visibleScreen.size = Director::getInstance()->getVisibleSize(); visibleScreen.origin = Director::getInstance()->getVisibleOrigin(); } } Rect ScreenSizeManager::getVisibleRect() { lazyInit(); return Rect(visibleScreen.origin.x, visibleScreen.origin.y, visibleScreen.size.width, visibleScreen.size.height); } Vec2 ScreenSizeManager::getScreenPositionFromPercentage(int percentageX, int percentageY) { lazyInit(); float realX = visibleScreen.origin.x + (percentageX * visibleScreen.size.width / 100); float realY = visibleScreen.origin.y + (percentageY * visibleScreen.size.height / 100); return Vec2(realX, realY); } float ScreenSizeManager::getWidthFromPercentage(int widthPercentage) { lazyInit(); return widthPercentage * visibleScreen.size.width / 100; } float ScreenSizeManager::getHeightFromPercentage(int heightPercentage) { lazyInit(); return heightPercentage * visibleScreen.size.height / 100; } <file_sep>// // Level.h // IkasGame // // Created by <NAME> on 2/2/15. // // #ifndef __IkasCocosGame__Level__ #define __IkasCocosGame__Level__ #include "cocos2d.h" using namespace cocos2d; #include "../CustomGUI/SpriteButton.h" class Level : public Layer { Layer *buttonsLayer; public: virtual bool init(); static Scene* createScene(); CREATE_FUNC(Level); protected: void switchSoundSettings(Ref* sender); void changeScene(Ref* sender); void openInfo(Ref* sender); void selectLevel(Ref* sender); }; #endif /* defined(__IkasCocosGame__Level__) */ <file_sep>// // Pause.h // IkasGame // // Created by <NAME> on 11/2/15. // // #ifndef __IkasGame__Pause__ #define __IkasGame__Pause__ #include "../Constants/Constants.h" #include "cocos2d.h" using namespace cocos2d; class Pause : public Layer { public: virtual bool init(); static Scene* createScene(); CREATE_FUNC(Pause); protected: void resumeGamePlay(Ref* sender); void switchSoundSettings(Ref* sender); void returnHome(Ref* sender); }; #endif /* defined(__IkasGame__Pause__) */ <file_sep>// // ImageManager.h // IkasGame // // Created by <NAME> on 29/1/15. // // #ifndef __IkasCocosGame__ImageManager__ #define __IkasCocosGame__ImageManager__ #include "cocos2d.h" #include <string> using namespace cocos2d; class ImageManager { public: static std::string getImage(const std::string fileName); static std::string getImage(const std::string fileName, const std::string extension); }; #endif /* defined(__IkasCocosGame__ImageManager__) */ <file_sep>// // AppManager.h // IkasGame // // Created by <NAME> on 2014-12-24. // // #ifndef __IkasCocosGame__AppManager__ #define __IkasCocosGame__AppManager__ #include "cocos2d.h" #include "../Constants/Constants.h" #include "../Constants/CommonProtocols.h" using namespace cocos2d; class AppManager { public: static AppManager* getInstance(); ~AppManager(); void loadNextGamePlay() { if(_delegate) _delegate->loadNextGamePlay();}; void resumeGamePlay() { if(_delegate) _delegate->resumeGamePlay();}; void restartGame() { if(_delegate) _delegate->restartGame();}; void updateScreenGameStats() { if(_delegate) _delegate->updateScreenGameStats();}; void setGamePlayDelegate(GamePlayDelegate *delegate) { _delegate = delegate;}; void exitToMain(); protected: AppManager(); static AppManager *_instance; GamePlayDelegate *_delegate; }; #endif /* defined(__IkasCocosGame__AppManager__) */ <file_sep>// // Options.h // ikaszopa // // Created by <NAME> on 24/2/15. // // #ifndef ikaszopa_Option_h #define ikaszopa_Option_h #include "cocos2d.h" using namespace cocos2d; using namespace std; class Option : public Object { public: Option(){}; ~Option(){}; CC_SYNTHESIZE(string, m_Name, Name); CC_SYNTHESIZE(string, m_FileName, FileName); }; #endif <file_sep>// // GameSettingsManager.cpp // IkasGame // // Created by <NAME> on 30/01/15. // // #include "GameSettingsManager.h" // Singleton GameSettingsManager * GameSettingsManager::_instance = NULL; GameSettingsManager* GameSettingsManager::getInstance() { if(!_instance) _instance = new GameSettingsManager(); return _instance; } GameSettingsManager::GameSettingsManager() { this->loadSettings(); } GameSettingsManager::~GameSettingsManager() { } /** * Load ALL settings variables from UserDefault */ void GameSettingsManager::loadSettings() { UserDefault *userDefault = UserDefault::getInstance(); // set device language if (userDefault->getIntegerForKey("currentLanguage", -1) == -1) { userDefault->setIntegerForKey("currentLanguage", static_cast<int>(Application::getInstance()->getCurrentLanguage())); userDefault->flush(); } _currentLanguage = static_cast<CustomLanguage>(userDefault->getIntegerForKey("currentLanguage", 0)); _firstLaunch = userDefault->getBoolForKey("firstLaunch", true); _dataAvalaible = userDefault->getBoolForKey("newDataAvalaible", false); _music = userDefault->getBoolForKey("music", true); _sfx = userDefault->getBoolForKey("sfx", true); _zipName = userDefault->getStringForKey("zipName", ""); _zipUrl = userDefault->getStringForKey("zipUrl", ""); } /** * Set Application language */ void GameSettingsManager::setLanguage(CustomLanguage language) { _currentLanguage = language; UserDefault *userDefault = UserDefault::getInstance(); userDefault->setIntegerForKey("currentLanguage", static_cast<int>(language)); userDefault->flush(); } void GameSettingsManager::setFirstLaunch(bool firstLaunch) { _firstLaunch = firstLaunch; UserDefault *userDefault = UserDefault::getInstance(); userDefault->setBoolForKey("firstLaunch", static_cast<bool>(firstLaunch)); userDefault->flush(); } void GameSettingsManager::setDataAvalaible(bool dataAvalaible) { _dataAvalaible = dataAvalaible; UserDefault *userDefault = UserDefault::getInstance(); userDefault->setBoolForKey("newDataAvalaible", static_cast<bool>(dataAvalaible)); userDefault->flush(); } /** * If background music is playing, stop it it. Else, play it */ void GameSettingsManager::switchMusic() { _music = !_music; if (_music) { SoundManager::getInstance()->musicPlay("background"); } else { SoundManager::getInstance()->musicStop(); } UserDefault *userDefault = UserDefault::getInstance(); userDefault->setBoolForKey("music", _music); userDefault->flush(); } /** * If sound effects are enabled, disable them. Else, enable them */ void GameSettingsManager::switchSFX() { _sfx = !_sfx; UserDefault *userDefault = UserDefault::getInstance(); userDefault->setBoolForKey("sfx", _sfx); userDefault->flush(); } void GameSettingsManager::setZipName(std::string zipName) { _zipName = zipName; UserDefault *userDefault = UserDefault::getInstance(); userDefault->setStringForKey("zipName", _zipName); userDefault->flush(); } void GameSettingsManager::setZipUrl(std::string zipUrl) { _zipUrl = zipUrl; UserDefault *userDefault = UserDefault::getInstance(); userDefault->setStringForKey("zipUrl", _zipUrl); userDefault->flush(); } <file_sep>// // SoundManager.cpp // IkasGame // // Created by <NAME> on 2014-01-09. // // #include "SoundManager.h" #include "GameSettingsManager.h" SoundManager * SoundManager::_instance = NULL; static std::string audioExtension = ".wav"; SoundManager* SoundManager::getInstance() { if(!_instance) _instance = new SoundManager(); return _instance; } SoundManager::SoundManager(): _backgroundMusicId(-1) { } SoundManager::~SoundManager() { } void SoundManager::pauseAll() { AudioEngine::pauseAll(); } void SoundManager::resumeAll() { AudioEngine::resumeAll(); } void SoundManager::musicPlay(std::string file, bool loop) { if (!GameSettingsManager::getInstance()->getIsMusicOn()) { return; } std::string path; path = "audio/" + file + audioExtension; if (_backgroundMusicId > -1) { this->musicStop(); } _backgroundMusicId = AudioEngine::play2d(path, loop); } void SoundManager::musicStop() { AudioEngine::stop(_backgroundMusicId); _backgroundMusicId = -1; } void SoundManager::musicPause() { AudioEngine::pause(_backgroundMusicId); } void SoundManager::sfxPlay(std::string file) { if (!GameSettingsManager::getInstance()->getIsSFXOn()) { return; } std::string path; path = "audio/" + file + audioExtension; AudioEngine::play2d(path); } void SoundManager::successPlay() { if (!GameSettingsManager::getInstance()->getIsSFXOn()) { return; } std::string path; path = "audio/success" + audioExtension; AudioEngine::play2d(path); } void SoundManager::failurePlay() { if (!GameSettingsManager::getInstance()->getIsSFXOn()) { return; } std::string path; path = "audio/failure" + audioExtension; AudioEngine::play2d(path); }<file_sep>// // ZipManager.cpp // IkasGame // // Created by <NAME> on 24/2/15. // // #include "ZipManager.h" #include <iostream> #include <fstream> #include "external/unzip/unzip.h" #include "../Singletons/GameSettingsManager.h" #include "../Helpers/AppleHelper.h" using namespace std; #define MAX_FILENAME 512 #define READ_SIZE 8192 // Singleton ZipManager * ZipManager::_instance = NULL; ZipManager* ZipManager::getInstance() { if(!_instance) _instance = new ZipManager(); return _instance; } ZipManager::ZipManager() { } ZipManager::~ZipManager() { } std::string ZipManager::getZipFilePath() { string WritablePath = FileUtils::getInstance()->getWritablePath(); string ZipFileName = GameSettingsManager::getInstance()->getZipName(); string ZipFilePath = WritablePath + ZipFileName; return ZipFilePath; } std::string ZipManager::getDataFolderPath() { string WritablePath = FileUtils::getInstance()->getWritablePath(); string DataFolderPath = WritablePath + "data/"; return DataFolderPath; } std::string ZipManager::getDataFolderFullPath(std::string filePath) { std::string basePath = this->getDataFolderPath(); std::string fullPath = basePath + filePath; return fullPath; } bool ZipManager::saveZipDataToDisk(std::vector<char>* buffer) { log("buffet size :: %lu" , buffer->size()); FILE* fp = fopen(this->getZipFilePath().c_str() , "wb"); log("debug writtern :: %zu" , fwrite(buffer->data() , 1, buffer->size() , fp)); fclose(fp); return true; } bool ZipManager::unzipZipDataAndDeletePreviousData() { std::string savePath = this->getZipFilePath(); std::string writablePath = this->getDataFolderPath(); // Delete previous data folder FileUtils::getInstance()->removeDirectory(writablePath); FileUtils::getInstance()->createDirectory(writablePath); #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS AppleHelper::ignorePathFromiCloud(writablePath, true, true); #endif unzFile zipfile = unzOpen(savePath.c_str()); if (zipfile == NULL) { log("Error opening zip file"); exit(1); } // Get info about the zip file unz_global_info global_info; if (unzGetGlobalInfo(zipfile, &global_info ) != UNZ_OK) { printf( "could not read file global info\n" ); unzClose(zipfile); exit(2); } // Buffer to hold data read from the zip file. char read_buffer[ READ_SIZE ]; // Loop to extract all files uLong i; for ( i = 0; i < global_info.number_entry; ++i ) { // Get info about current file. unz_file_info file_info; char filename[MAX_FILENAME]; if ( unzGetCurrentFileInfo( zipfile, &file_info, filename, MAX_FILENAME, NULL, 0, NULL, 0 ) != UNZ_OK ) { printf( "could not read file info\n" ); unzClose( zipfile ); exit(3); } // Check if this entry is a directory or file. const size_t filename_length = strlen( filename ); if ( filename[ filename_length-1 ] == '/') { // Entry is a directory, so create it. std::string filePath(writablePath); filePath.append(filename); FileUtils::getInstance()->createDirectory(filePath); } else { // Entry is a file, so extract it. printf( "file:%s\n", filename ); if ( unzOpenCurrentFile( zipfile ) != UNZ_OK ) { printf( "could not open file\n" ); unzClose( zipfile ); exit(4); } // Open a file to write out the data. char *p = &filename[0]; int pos = 1; while (*p != '\0') { if (*p == '/') break; else pos++; p++; } std::string filePath(writablePath); filePath.append(filename); log("PATH: %s", filePath.c_str()); std::ofstream out(filePath.c_str(), std::ios::out | std::ios::binary); int error = UNZ_OK; do { error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE ); if ( error < 0 ) { printf( "error %d\n", error ); unzCloseCurrentFile( zipfile ); unzClose( zipfile ); exit(5); } out.write(read_buffer, error); } while ( error > 0 ); out.flush(); out.close(); } unzCloseCurrentFile( zipfile ); // Go the the next entry listed in the zip file. if ( ( i+1 ) < global_info.number_entry ) { if ( unzGoToNextFile( zipfile ) != UNZ_OK ) { printf( "cound not read next file\n" ); unzClose( zipfile ); exit(6); } } } unzClose( zipfile ); // Delete zip file FileUtils::getInstance()->removeFile(savePath); return true; } bool ZipManager::deleteZipData() { log("hola"); return false; }<file_sep>// // ImageManager.cpp // IkasGame // // Created by <NAME> on 29/1/15. // // #include "ImageManager.h" static std::string defaultExtension = "png"; std::string ImageManager::getImage(const std::string fileName) { return ImageManager::getImage(fileName, defaultExtension); } std::string ImageManager::getImage(const std::string fileName, const std::string extension) { std::string imagePath = FileUtils::getInstance()->fullPathForFilename(fileName + "." + extension); return imagePath; } <file_sep>// // Pause.cpp // IkasGame // // Created by <NAME> on 11/2/15. // // #include "Pause.h" #include "../Singletons/GameSettingsManager.h" #include "../Singletons/SceneManager.h" #include "../Singletons/SoundManager.h" #include "../Singletons/AppManager.h" #include "../Helpers/LanguageManager.h" #include "../Helpers/ScreenSizeManager.h" #include "../Helpers/ImageManager.h" #include "../CustomGUI/SpriteButton.h" Scene* Pause::createScene() { SceneManager::getInstance()->saveCurrentScene(); auto *scene = Scene::create(); auto *layer = Pause::create(); layer->setTag(2339); scene->addChild(layer); return scene; } bool Pause::init() { if (!Layer::init()) { return false; } Rect visibleRect = ScreenSizeManager::getVisibleRect(); auto background = Sprite::create(ImageManager::getImage("background"), visibleRect); background->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50)); background->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(background); auto buttonResume = SpriteButton::create(ImageManager::getImage("play"), 1.2f, CC_CALLBACK_1(Pause::resumeGamePlay, this)); buttonResume->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonResume = ScreenSizeManager::getScreenPositionFromPercentage(50, 70); buttonResume->setPosition(positionButtonResume); this->addChild(buttonResume); auto labelResume = Label::createWithTTF(LanguageManager::getLocalizedText("Pause", "resume"), MainRegularFont, 130); labelResume->setAlignment(TextHAlignment::CENTER); labelResume->setAnchorPoint(Point::ANCHOR_MIDDLE_TOP); labelResume->setTextColor(IkasGrayDark); Vec2 positionLabelResume = buttonResume->getPosition(); positionLabelResume.y -= buttonResume->getBoundingBox().size.height/2; positionLabelResume.y -= ScreenSizeManager::getHeightFromPercentage(10); labelResume->setPosition(positionLabelResume); this->addChild(labelResume); auto buttonSoundSettings = SpriteButton::create(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage), 0.30f, CC_CALLBACK_1(Pause::switchSoundSettings, this)); buttonSoundSettings->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonSoundSettings = ScreenSizeManager::getScreenPositionFromPercentage(80, 15); buttonSoundSettings->setPosition(positionButtonSoundSettings); this->addChild(buttonSoundSettings); auto buttonHome = SpriteButton::create(ImageManager::getImage("home"), 0.30f, CC_CALLBACK_1(Pause::returnHome, this)); buttonHome->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonHome = ScreenSizeManager::getScreenPositionFromPercentage(22, 15); buttonHome->setPosition(positionButtonHome); this->addChild(buttonHome); return true; } void Pause::resumeGamePlay(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); SceneManager::getInstance()->loadSavedScene(); AppManager::getInstance()->resumeGamePlay(); } void Pause::switchSoundSettings(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); GameSettingsManager::getInstance()->switchSFX(); GameSettingsManager::getInstance()->switchMusic(); SpriteButton *item = static_cast<SpriteButton*>(sender); item->setTexture(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage)); } void Pause::returnHome(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); AppManager::getInstance()->setGamePlayDelegate(NULL); SceneManager::getInstance()->runSceneWithType(SceneType::MAIN); SceneManager::getInstance()->removeSavedScene(); }<file_sep>// // LanguageManager.cpp // IkasGame // // Edited by <NAME> on 30/01/15. // // #include "LanguageManager.h" #include "../Singletons/GameSettingsManager.h" std::string LanguageManager::getLocalizedText(const char *miniDic, const char *key) { const char *dictionary; switch (GameSettingsManager::getInstance()->getCurrentLanguage()) { case CustomLanguage::SPANISH: dictionary = "languages/languages_Spanish.plist"; break; default: dictionary = "languages/languages_Euskara.plist"; break; } // Create Path and temp Dictionary std::string plistPath = FileUtils::getInstance()->fullPathForFilename(dictionary); auto languageDictionary = FileUtils::getInstance()->getValueMapFromFile(plistPath); // Check if exist Dictionary in path if (languageDictionary.empty()) { return ""; } // Check if exist Dictionary auto miniDictionary = languageDictionary.at(miniDic).asValueMap(); if (miniDictionary.empty()) { return ""; } return miniDictionary.at(key).asString(); } std::string LanguageManager::getCurrentLanguageName() { std::string toReturn; switch (GameSettingsManager::getInstance()->getCurrentLanguage()) { case CustomLanguage::SPANISH: toReturn = "Español"; break; default: toReturn = "Euskara"; break; } return toReturn; } <file_sep>// // GamePlay.h // IkasGame // // Created by <NAME> on 10/2/15. // // #ifndef __IkasGame__GamePlay__ #define __IkasGame__GamePlay__ #include "cocos2d.h" using namespace cocos2d; #include "../Constants/CommonProtocols.h" #include "../CustomGUI/SpriteButton.h" #include "../GameModels/MainCategory.h" #include "../GameModels/SubCategory.h" #include "../GameModels/Option.h" #include "../Singletons/ZipManager.h" enum class TouchState { START, MOVING, FINISH }; class GamePlay : public Layer, public GamePlayDelegate { Layer *layerPause, *layerWin, *layerLose; public: virtual bool init(); static Scene* createScene(); CREATE_FUNC(GamePlay); EventListenerTouchOneByOne *addEvents(); virtual bool touchBegan(Touch *touch, Event *pEvent); virtual void touchEnded(Touch *touch, Event *pEvent); virtual void touchMoved(Touch *touch, Event *pEvent); virtual void touchCancelled(Touch *pTouch, Event *pEvent); // GamePlayDelegate virtual void loadNextGamePlay(); virtual void resumeGamePlay(); virtual void restartGame(); virtual void updateScreenGameStats(); // Time control void timeElapsed(); private: vector<MainCategory*> _categories; vector<SubCategory*> _subCategories; vector<int> _loadedIndex; void setupLevelSettings(); void resetTimer(); void pauseGame(Ref* sender); Label *_labelCategory, *_labelPoints, *_labelLevel; Layer *_gameLayer, *_touchLayer; DrawNode *_drawTouch, *_drawSuccess, *_drawError; TouchState _touchState; Vec2 _initialTouch, _endTouch; vector<Sprite*> _images; vector<Label*> _titles; vector<int> _indexes; ProgressTimer* _progress; ProgressFromTo* _action; Sequence* _sequence; float _elapsedTime, _currentLevelTime, _maxTime; int _totalSuccessScreens; SpriteButton* _pauseButton; void checkDrawResult(int index, Vec2 imageTouchLocation, Vec2 titleTouchLocation); void checkGameStatus(); void openSuccessScreen(); }; #endif /* defined(__IkasGame__GamePlay__) */ <file_sep>// // Win.h // IkasGame // // Created by <NAME> on 11/2/15. // // #ifndef __IkasGame__Win__ #define __IkasGame__Win__ #include "../Constants/Constants.h" #include "cocos2d.h" using namespace cocos2d; class Win : public Layer { public: virtual bool init(); static Scene* createScene(); CREATE_FUNC(Win); protected: void loadNextGamePlay(Ref* sender); void switchSoundSettings(Ref* sender); void returnHome(Ref* sender); }; #endif /* defined(__IkasGame__Win__) */ <file_sep>// // Categories.h // IkasGame // // Created by <NAME> on 2/2/15. // // #ifndef __IkasCocosGame__Categories__ #define __IkasCocosGame__Categories__ #include "cocos2d.h" using namespace cocos2d; #include "../CustomGUI/SpriteButton.h" #include "../CustomGUI/PagingCCScrollView.h" #include "../CustomGUI/PagingCCTableView.h" #include "../CustomGUI/PagingCCTableViewCell.h" #include "../GameModels/MainCategory.h" #include "../GameModels/SubCategory.h" #include "../GameModels/Option.h" #include "../Singletons/ZipManager.h" class Categories : public Layer, public PagingTableViewDataSource, public PagingTableViewDelegate, public PagingScrollViewDelegate { Layer *buttonsLayer, *layerCategories; PagingTableView *tableViewCategories; Vec2 tableViewContentOffset; SpriteButton *buttonPreviousPage, *buttonNextPage; Size scrollSize, scrollItemSize; public: virtual bool init(); static Scene* createScene(); CREATE_FUNC(Categories); protected: void switchSoundSettings(Ref* sender); void changeScene(Ref* sender); void openInfo(Ref* sender); void updateTableViewPage(Ref* sender); float getPaginationOffset(); private: vector<MainCategory*> _categories; Size getScrollSize(); Size getScrollItemSize(); virtual void scrollViewDidScroll(PagingScrollView* view); virtual void tableCellTouched(PagingTableView* table, PagingTableViewCell* cell); virtual Size tableCellSizeForIndex(PagingTableView *table, ssize_t idx); virtual PagingTableViewCell* tableCellAtIndex(PagingTableView *table, ssize_t idx); virtual ssize_t numberOfCellsInTableView(PagingTableView *table); }; #endif /* defined(__IkasCocosGame__Categories__) */ <file_sep>// // Lose.h // IkasGame // // Created by <NAME> on 11/2/15. // // #ifndef __IkasGame__Lose__ #define __IkasGame__Lose__ #include "../Constants/Constants.h" #include "cocos2d.h" using namespace cocos2d; class Lose : public Layer { public: virtual bool init(); static Scene* createScene(); CREATE_FUNC(Lose); protected: void resetGame(Ref* sender); void switchSoundSettings(Ref* sender); void returnHome(Ref* sender); }; #endif /* defined(__IkasGame__Lose__) */ <file_sep>// // AppManager.cpp // IkasGame // // Created by <NAME> on 2014-12-24. // // #include "AppManager.h" #include "SceneManager.h" // Singleton AppManager * AppManager::_instance = NULL; AppManager* AppManager::getInstance() { if(!_instance) _instance = new AppManager(); return _instance; } AppManager::AppManager() { _delegate = NULL; } AppManager::~AppManager() { } void AppManager::exitToMain() { SceneManager::getInstance()->runSceneWithType(SceneType::MAIN); } <file_sep>// // SoundManager.h // IkasGame // // Created by <NAME> on 2014-01-09. // // #ifndef __IkasGame__SoundManager__ #define __IkasGame__SoundManager__ #include "cocos2d.h" #include "audio/include/AudioEngine.h" using namespace cocos2d; using namespace cocos2d::experimental; class SoundManager { public: void pauseAll(); void resumeAll(); void musicPlay(std::string file, bool loop = true); void musicStop(); void musicPause(); void sfxPlay(std::string file); void successPlay(); void failurePlay();; static SoundManager* getInstance(); ~SoundManager(); protected: SoundManager(); static SoundManager * _instance; int _backgroundMusicId; public: }; #endif /* defined(__IkasGame__SoundManager__) */ <file_sep>// // Win.cpp // IkasGame // // Created by <NAME> on 11/2/15. // // #include "Win.h" #include "../Singletons/GameSettingsManager.h" #include "../Singletons/SceneManager.h" #include "../Singletons/SoundManager.h" #include "../Singletons/AppManager.h" #include "../Helpers/LanguageManager.h" #include "../Helpers/ScreenSizeManager.h" #include "../Helpers/ImageManager.h" #include "../CustomGUI/SpriteButton.h" Scene* Win::createScene() { SceneManager::getInstance()->saveCurrentScene(); auto *scene = Scene::create(); auto *layer = Win::create(); layer->setTag(2339); scene->addChild(layer); return scene; } bool Win::init() { if (!Layer::init()) { return false; } Rect visibleRect = ScreenSizeManager::getVisibleRect(); auto background = Sprite::create(ImageManager::getImage("background"), visibleRect); background->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50)); background->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(background); auto buttonNextGamePlay = SpriteButton::create(ImageManager::getImage("play"), 1.0f, CC_CALLBACK_1(Win::loadNextGamePlay, this)); buttonNextGamePlay->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonNextGamePlay = ScreenSizeManager::getScreenPositionFromPercentage(50, 50); buttonNextGamePlay->setPosition(positionButtonNextGamePlay); this->addChild(buttonNextGamePlay); auto winTitle = Sprite::create(ImageManager::getImage("win-title")); winTitle->setScale(0.75f); Vec2 positionWinTitle = buttonNextGamePlay->getPosition(); positionWinTitle.y += buttonNextGamePlay->getBoundingBox().size.height / 2; positionWinTitle.y += ScreenSizeManager::getHeightFromPercentage(2); winTitle->setPosition(positionWinTitle); winTitle->setAnchorPoint(Point::ANCHOR_MIDDLE_BOTTOM); this->addChild(winTitle); auto labelResume = Label::createWithTTF(LanguageManager::getLocalizedText("Win", "resume"), MainRegularFont, 70); labelResume->setAlignment(TextHAlignment::CENTER); labelResume->setAnchorPoint(Point::ANCHOR_MIDDLE_TOP); labelResume->setTextColor(IkasGrayDark); Vec2 positionLabelResume = buttonNextGamePlay->getPosition(); positionLabelResume.y -= buttonNextGamePlay->getBoundingBox().size.height / 2; positionLabelResume.y -= ScreenSizeManager::getHeightFromPercentage(1); labelResume->setPosition(positionLabelResume); this->addChild(labelResume); auto buttonSoundSettings = SpriteButton::create(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage), 0.30f, CC_CALLBACK_1(Win::switchSoundSettings, this)); buttonSoundSettings->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonSoundSettings = ScreenSizeManager::getScreenPositionFromPercentage(80, 15); buttonSoundSettings->setPosition(positionButtonSoundSettings); this->addChild(buttonSoundSettings); auto buttonHome = SpriteButton::create(ImageManager::getImage("home"), 0.30f, CC_CALLBACK_1(Win::returnHome, this)); buttonHome->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonHome = ScreenSizeManager::getScreenPositionFromPercentage(22, 15); buttonHome->setPosition(positionButtonHome); this->addChild(buttonHome); return true; } void Win::loadNextGamePlay(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); SceneManager::getInstance()->loadSavedScene(); AppManager::getInstance()->loadNextGamePlay(); } void Win::switchSoundSettings(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); GameSettingsManager::getInstance()->switchSFX(); GameSettingsManager::getInstance()->switchMusic(); SpriteButton *item = static_cast<SpriteButton*>(sender); item->setTexture(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage)); } void Win::returnHome(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); AppManager::getInstance()->setGamePlayDelegate(NULL); SceneManager::getInstance()->runSceneWithType(SceneType::MAIN); SceneManager::getInstance()->removeSavedScene(); }<file_sep>// // MainCategory.cpp // IkasGame // // Created by <NAME> on 25/2/15. // // #include "MainCategory.h" vector<SubCategory*> MainCategory::getFilteredSubCategoriesByLevel(Difficulty difficulty) { int minLevel = (int)difficulty; return this->getFilteredSubCategoriesByLevel(minLevel); } /** * Returns actual level and previuos level subcategories */ vector<SubCategory*> MainCategory::getFilteredSubCategoriesByLevel(int level) { vector<SubCategory*> filteredSubcategories; filteredSubcategories.clear(); for (int x = 0; x<m_SubCategories.size(); x++) { if (m_SubCategories.at(x)->getMinLevel() == level || m_SubCategories.at(x)->getMinLevel() == level - 1) { filteredSubcategories.push_back(m_SubCategories.at(x)); } } return filteredSubcategories; }<file_sep>// // IkasAPI.cpp // IkasGame // // Created by <NAME> on 23/2/15. // // #include "IkasAPI.h" #include "../Singletons/GameSettingsManager.h" #include "../Singletons/ZipManager.h" #include "../json/cJSON.h" static const Value JsonURL = Value(ApiURL); bool IkasAPI::init() { _errorCallback = NULL; _successCallback = NULL; _resultCallback = NULL; return true; } void IkasAPI::checkForLatestZipData(const IkasResultHandler& callback, const IkasHandler& errorCallback) { this->_resultCallback = callback; this->_errorCallback = errorCallback; auto request = new HttpRequest(); request->setUrl(JsonURL.asString().c_str()); request->setRequestType(cocos2d::network::HttpRequest::Type::GET); request->setResponseCallback(CC_CALLBACK_2(IkasAPI::checkForLatestZipDataCallback ,this)); HttpClient::getInstance()->send(request); } void IkasAPI::checkForLatestZipDataCallback(HttpClient* client, HttpResponse* response) { std::vector<char>* buffer = response->getResponseData(); CCLOG("buffet size :: %lu" , buffer->size()); if (response->isSucceed() && !buffer->empty() && (response->getResponseCode() >= 200 && response->getResponseCode() < 400)) { std::string data(buffer->begin(), buffer->end()); log("%s", data.c_str()); cJSON *pRoot = cJSON_Parse(data.c_str()); if (pRoot != NULL) { std::string zipName = cJSON_GetObjectItem(pRoot, "zipValid")->valuestring; std::string zipUrl = cJSON_GetObjectItem(pRoot, "downloadZip")->valuestring; int compareResult = zipName.compare(GameSettingsManager::getInstance()->getZipName().c_str()); if (compareResult != 0) { GameSettingsManager::getInstance()->setDataAvalaible(true); GameSettingsManager::getInstance()->setZipName(zipName); GameSettingsManager::getInstance()->setZipUrl(zipUrl); if (_resultCallback) { this->_resultCallback(this, true); } } else { if (_resultCallback) { _resultCallback(this, false); } } } else { if (_resultCallback) { _resultCallback(this, false); } } } else { if (_errorCallback) { _errorCallback(this); } } } void IkasAPI::downloadLatestZip(const IkasHandler& successCallback, const IkasHandler& errorCallback) { _successCallback = successCallback; _errorCallback = errorCallback; auto request = new HttpRequest(); const char* zipUrl = GameSettingsManager::getInstance()->getZipUrl().c_str(); request->setUrl(zipUrl); request->setRequestType(cocos2d::network::HttpRequest::Type::GET); request->setResponseCallback(CC_CALLBACK_2(IkasAPI::downloadLatestZipCallback ,this)); HttpClient::getInstance()->send(request); } void IkasAPI::downloadLatestZipCallback(HttpClient* client, HttpResponse* response) { if (response->isSucceed() && (response->getResponseCode() >= 200 && response->getResponseCode() < 400)) { std::vector<char>* buffer = response->getResponseData(); bool result = ZipManager::getInstance()->saveZipDataToDisk(buffer); if (result) { if (_successCallback) { _successCallback(this); } } else { if (_errorCallback) { _errorCallback(this); } } } else { if (_errorCallback) { _errorCallback(this); } } } <file_sep>// // Splash.cpp // IkasGame // // Created by <NAME> on 29/1/15. // // #include "Splash.h" #include "../Singletons/SceneManager.h" #include "../Helpers/ImageManager.h" #include "../Helpers/ScreenSizeManager.h" #include "../Constants/Constants.h" const Value SplashTime = Value(1.5);//In seconds Scene* Splash::createScene() { auto *scene = Scene::create(); auto *layer = Splash::create(); layer->setTag(2334); scene->addChild(layer); return scene; } bool Splash::init() { if ( !Layer::init() ) { return false; } Rect visibleRect = ScreenSizeManager::getVisibleRect(); auto background = Sprite::create(ImageManager::getImage("splash"), visibleRect); background->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50)); background->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(background); DelayTime *delayAction = DelayTime::create(SplashTime.asFloat()); CallFunc *mySelector = CallFunc::create(CC_CALLBACK_0(Splash::launchMainScene, this)); this->runAction(Sequence::create(delayAction, mySelector, nullptr)); return true; } void Splash::launchMainScene() { SceneManager::getInstance()->runSceneWithType(SceneType::MAIN); }<file_sep>#include "InterfaceJNI.h" #include "platform/android/jni/JniHelper.h" using namespace cocos2d; void InterfaceJNI::sendMail(const char *to, const char *subject, const char *message) { JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxHelper", "sendEMail", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V")) { jstring jto = t.env->NewStringUTF(to); jstring jsubject = t.env->NewStringUTF(subject); jstring jmessage = t.env->NewStringUTF(message); t.env->CallStaticVoidMethod(t.classID, t.methodID, jto, jsubject, jmessage); t.env->DeleteLocalRef(t.classID); } } void InterfaceJNI::openWeb(const char *direction) { JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxHelper", "openWeb", "(Ljava/lang/String;)V")) { jstring StringArg1 = t.env->NewStringUTF(direction); t.env->CallStaticVoidMethod(t.classID, t.methodID,StringArg1); t.env->DeleteLocalRef(t.classID); } } void InterfaceJNI::openMarketApp(const char *idAndroid) { JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxHelper", "openMarketApp", "(Ljava/lang/String;)V")) { jstring StringArg1 = t.env->NewStringUTF(idAndroid); t.env->CallStaticVoidMethod(t.classID, t.methodID, StringArg1); t.env->DeleteLocalRef(t.classID); } } void InterfaceJNI::openMarketApps(const char *idAndroid) { JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxHelper", "openMarketApps", "(Ljava/lang/String;)V")) { jstring StringArg1 = t.env->NewStringUTF(idAndroid); t.env->CallStaticVoidMethod(t.classID, t.methodID, StringArg1); t.env->DeleteLocalRef(t.classID); } } void InterfaceJNI::openTwitterProfile(const char *username) { JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxHelper", "openTwitterUser", "(Ljava/lang/String;)V")) { jstring StringArg1 = t.env->NewStringUTF(username); t.env->CallStaticVoidMethod(t.classID, t.methodID, StringArg1); t.env->DeleteLocalRef(t.classID); } } void InterfaceJNI::sendTweet(const char *message) { JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxHelper", "sendTweet", "(Ljava/lang/String;)V")) { jstring jmessage = t.env->NewStringUTF(message); t.env->CallStaticVoidMethod(t.classID, t.methodID, jmessage); t.env->DeleteLocalRef(t.classID); } } <file_sep>// // IkasAPI.h // IkasGame // // Created by <NAME> on 23/2/15. // // #ifndef __IkasAPI__ #define __IkasAPI__ #include "../Constants/Constants.h" #include "cocos2d.h" using namespace cocos2d; #include "network/HttpClient.h" using namespace cocos2d::network; class IkasAPI : public Ref { public: virtual bool init(); CREATE_FUNC(IkasAPI); void checkForLatestZipData(const IkasResultHandler& callback, const IkasHandler& errorCallback); void downloadLatestZip(const IkasHandler& successCallback, const IkasHandler& errorCallback); protected: IkasResultHandler _resultCallback; IkasHandler _successCallback, _errorCallback; private: void checkForLatestZipDataCallback(HttpClient* client , HttpResponse* response); void downloadLatestZipCallback(HttpClient* client , HttpResponse* response); }; #endif /* defined(__IkasGame__IkasAPI__) */ <file_sep>#ifndef __INTERFACE_JNI_H__ #define __INTERFACE_JNI_H__ #include "cocos2d.h" #include <jni.h> #include <android/log.h> class InterfaceJNI { public: ////////////////// // C++ to Java ////////////////// // Email static void sendMail(const char *to, const char *subject, const char *message); // Web static void openWeb(const char* direction); // Market static void openMarketApp(const char* idAndroid); static void openMarketApps(const char* idAndroid); // Twitter static void openTwitterProfile(const char* username); static void sendTweet(const char *message); protected: }; #endif // __INTERFACE_JNI_H__ <file_sep>// // AppleHelper.h // IkasGame // // Created by <NAME> on 24/2/15. // // #ifndef __IkasGame__AppleHelper__ #define __IkasGame__AppleHelper__ #include "cocos2d.h" #include <string> using namespace cocos2d; class AppleHelper { public: static void ignorePathFromiCloud(std::string path , bool isDir, bool ignore); }; #endif /* defined(__IkasGame__AppleHelper__) */ <file_sep>// // GamePlayPointsManager.h // IkasGame // // Created by <NAME> on 16/2/15. // // #ifndef __IkasGame__GamePlayPointsManager__ #define __IkasGame__GamePlayPointsManager__ #include "cocos2d.h" #include "../Constants/Constants.h" using namespace cocos2d; class GamePlayPointsManager { public: static GamePlayPointsManager* getInstance(); ~GamePlayPointsManager(); void loadSettings(); void saveSettings(); void setCurrentCategory(int category); void setCurrentDifficulty(Difficulty difficulty); void addSuccessPoints(); void resetCurrentPoints(); void resetCurrentGamePlaySettings(); CC_SYNTHESIZE_READONLY(int, _currentCategory, CurrentCategory); CC_SYNTHESIZE_READONLY(Difficulty, _currentDifficulty, CurrentDifficulty); CC_SYNTHESIZE_READONLY(int, _currentPoints, CurrentPoints); protected: GamePlayPointsManager(); static GamePlayPointsManager * _instance; void setCurrentPoints(int points); }; #endif /* defined(__IkasGame__GamePlayPointsManager__) */ <file_sep>// // Splash.h // IkasGame // // Created by <NAME> on 29/1/15. // // #ifndef __IkasCocosGame__Splash__ #define __IkasCocosGame__Splash__ #include "cocos2d.h" using namespace cocos2d; class Splash : public Layer { public: virtual bool init(); static Scene* createScene(); CREATE_FUNC(Splash); private: void launchMainScene(); }; #endif /* defined(__IkasCocosGame__Splash__) */ <file_sep>// // DataFileManager.cpp // ikaszopa // // Created by <NAME> on 24/2/15. // // #include "DataFileManager.h" #include "../Singletons/ZipManager.h" using namespace cocos2d; DataFileManager * DataFileManager::_instance = NULL; DataFileManager* DataFileManager::getInstance() { if(!_instance) _instance = new DataFileManager(); return _instance; } DataFileManager::DataFileManager() { } DataFileManager::~DataFileManager() { } void DataFileManager::parseDataFile() { _categories.clear(); string fullPath = ZipManager::getInstance()->getDataFolderFullPath("data.json"); if (fullPath.empty()) { return; } unsigned char* fileContent = NULL; ssize_t bufferSize = 0; fileContent = CCFileUtils::getInstance()->getFileData(fullPath.c_str(), "r", &bufferSize); if (fileContent == NULL) { return; } cocos2d::CCString *ccStr = cocos2d::CCString::createWithData(fileContent, bufferSize); free(fileContent); cJSON *pRoot = cJSON_Parse(ccStr->getCString()); int numItems = cJSON_GetArraySize(pRoot); for (int i = 0; i < numItems; i++) { MainCategory *pCat = new MainCategory(); cJSON * item = cJSON_GetArrayItem(pRoot, i); pCat->setName(cJSON_GetObjectItem(item, "name")->valuestring); pCat->setFileName(cJSON_GetObjectItem(item, "fileName")->valuestring); cJSON *pSubCategories = cJSON_GetObjectItem(item, "element"); vector<SubCategory*> subCategories; int numSubCategories = cJSON_GetArraySize(pSubCategories); for (int j = 0; j < numSubCategories; j++) { cJSON *jsonSubCategories = cJSON_GetArrayItem(pSubCategories, j); SubCategory *pSub = new SubCategory(); pSub->setName(cJSON_GetObjectItem(jsonSubCategories, "name")->valuestring); pSub->setFileName(cJSON_GetObjectItem(jsonSubCategories, "fileName")->valuestring); pSub->setMinLevel(cJSON_GetObjectItem(jsonSubCategories, "minLevel")->valueint); pSub->setMainColor(cJSON_GetObjectItem(jsonSubCategories, "mainColor")->valuestring); cJSON *pOptions = cJSON_GetObjectItem(jsonSubCategories, "options"); vector<Option*> options; int numOptions = cJSON_GetArraySize(pOptions); for (int k = 0; k < numOptions; k++) { cJSON *jsonOption = cJSON_GetArrayItem(pOptions, k); Option *pOpt = new Option(); pOpt->setName(cJSON_GetObjectItem(jsonOption, "name")->valuestring); pOpt->setFileName(cJSON_GetObjectItem(jsonOption, "fileName")->valuestring); options.push_back(pOpt); } pSub->setOptions(options); subCategories.push_back(pSub); } pCat->setSubCategories(subCategories); _categories.push_back(pCat); } cJSON_Delete(pRoot); } <file_sep>// // Main.h // IkasGame // // Created by <NAME> on 30/01/15. // // #ifndef __IkasCocosGame__Main__ #define __IkasCocosGame__Main__ #include "cocos2d.h" #include "../Constants/Constants.h" #include "../Helpers/IkasAPI.h" using namespace cocos2d; class Main : public Layer { Layer *playLayer, *loadingLayer; public: virtual bool init(); ~Main(); static Scene* createScene(); CREATE_FUNC(Main); void forceFirstData(Ref* sender, bool result); void forceFirstDataErrorCallback(Ref* sender); void successDataDownloaded(Ref* sender); void errorDataDownloaded(Ref* sender); protected: void switchSoundSettings(Ref* sender); void changeScene(Ref* sender); void openInfo(Ref* sender); void onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event); private: void showLoading(bool show); IkasAPI *_api; void checkNewData(); void downloadLatestData(const IkasHandler& successCallback, const IkasHandler& errorCallback); }; #endif /* defined(__IkasCocosGame__Main__) */ <file_sep>// // Categories.cpp // IkasGame // // Created by <NAME> on 2/2/15. // // #include "./Categories.h" #include "../Singletons/GameSettingsManager.h" #include "../Singletons/GamePlayPointsManager.h" #include "../Singletons/SceneManager.h" #include "../Singletons/SoundManager.h" #include "../Helpers/LanguageManager.h" #include "../Helpers/ScreenSizeManager.h" #include "../Helpers/ImageManager.h" #include "../Helpers/DataFileManager.h" #define TitleSeparatorHeight 10 #define TableViewWidthPercentage 70 #define TableViewHeightPercentage 40 #define TableViewItemsPerPage 3 #define TableViewXPositionPercentage 50 #define TableViewYPositionPercentage 50 #define TableViewItemImageHeightPercentage 80 #define TableViewItemImageTitleSeparationPercentage 5 enum class TablewViewPageDirection { PREVIOUS, NEXT }; Scene* Categories::createScene() { auto *scene = Scene::create(); auto *layer = Categories::create(); layer->setTag(2334); scene->addChild(layer); return scene; } bool Categories::init() { if ( !Layer::init() ) { return false; } DataFileManager *dataManager = DataFileManager::getInstance(); dataManager->parseDataFile(); _categories = dataManager->getMainCategories(); Rect visibleRect = ScreenSizeManager::getVisibleRect(); auto background = Sprite::create(ImageManager::getImage("background"), visibleRect); background->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50)); background->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(background); buttonsLayer = Layer::create(); buttonsLayer->setContentSize(visibleRect.size); buttonsLayer->setPosition(0, 0); auto buttonBack = SpriteButton::create(ImageManager::getImage("back"), 0.30f, CC_CALLBACK_1(Categories::changeScene, this)); buttonBack->setTag(static_cast<int>(SceneType::MAIN)); buttonBack->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonBack = ScreenSizeManager::getScreenPositionFromPercentage(5, 5); positionButtonBack.x += buttonBack->getBoundingBox().size.width / 2; positionButtonBack.y += buttonBack->getBoundingBox().size.height / 2; buttonBack->setPosition(positionButtonBack); buttonsLayer->addChild(buttonBack); auto buttonAbout = SpriteButton::create(ImageManager::getImage("info"), 0.30f, CC_CALLBACK_1(Categories::openInfo, this)); buttonAbout->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonAbout = ScreenSizeManager::getScreenPositionFromPercentage(95, 5); positionButtonAbout.x -= buttonAbout->getBoundingBox().size.width / 2; positionButtonAbout.y += buttonAbout->getBoundingBox().size.height / 2; buttonAbout->setPosition(positionButtonAbout); buttonsLayer->addChild(buttonAbout); auto buttonSFXSettings = SpriteButton::create(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage), 0.30f, CC_CALLBACK_1(Categories::switchSoundSettings, this)); buttonSFXSettings->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonSFXSettings = buttonAbout->getPosition(); positionButtonSFXSettings.x -= ScreenSizeManager::getWidthFromPercentage(5); positionButtonSFXSettings.x -= buttonSFXSettings->getBoundingBox().size.width; buttonSFXSettings->setPosition(positionButtonSFXSettings); buttonsLayer->addChild(buttonSFXSettings); this->addChild(buttonsLayer); /* PagingTablewView */ layerCategories = Layer::create(); layerCategories->setContentSize(visibleRect.size); layerCategories->setPosition(0, 0); tableViewCategories = PagingTableView::create(this, Size(ScreenSizeManager::getWidthFromPercentage(TableViewWidthPercentage), ScreenSizeManager::getHeightFromPercentage(TableViewHeightPercentage))); tableViewCategories->setDirection(PagingScrollView::Direction::HORIZONTAL); tableViewCategories->setDelegate(this); tableViewCategories->setEnablePaging(true); tableViewCategories->setPageSize(tableViewCategories->getBoundingBox().size/TableViewItemsPerPage); Vec2 positionTablewView = ScreenSizeManager::getScreenPositionFromPercentage(TableViewXPositionPercentage, TableViewYPositionPercentage); positionTablewView.x -= tableViewCategories->getBoundingBox().size.width/2; positionTablewView.y -= tableViewCategories->getBoundingBox().size.height/2; tableViewCategories->setPosition(positionTablewView); tableViewCategories->setTag(static_cast<int>(false)); layerCategories->addChild(tableViewCategories); auto labelCategoriesTitle = Label::createWithTTF(LanguageManager::getLocalizedText("Categories", "title"), MainRegularFont, 70); labelCategoriesTitle->setAlignment(TextHAlignment::CENTER); labelCategoriesTitle->setAnchorPoint(Point::ANCHOR_MIDDLE_BOTTOM); labelCategoriesTitle->setTextColor(IkasGrayDark); Vec2 positionLabelTableView = tableViewCategories->getPosition(); positionLabelTableView.x += tableViewCategories->getBoundingBox().size.width/2; positionLabelTableView.y += tableViewCategories->getBoundingBox().size.height; positionLabelTableView.y += ScreenSizeManager::getHeightFromPercentage(TitleSeparatorHeight); labelCategoriesTitle->setPosition(positionLabelTableView); layerCategories->addChild(labelCategoriesTitle); buttonPreviousPage = SpriteButton::create(ImageManager::getImage("left"), 0.70f, 10.0f, CC_CALLBACK_1(Categories::updateTableViewPage, this)); buttonPreviousPage->setTag(static_cast<int>(TablewViewPageDirection::PREVIOUS)); buttonPreviousPage->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonPreviousPage = positionTablewView; positionButtonPreviousPage.y += tableViewCategories->getBoundingBox().size.height / 2; positionButtonPreviousPage.x -= buttonPreviousPage->getBoundingBox().size.width / 2; buttonPreviousPage->setPosition(positionButtonPreviousPage); layerCategories->addChild(buttonPreviousPage); buttonNextPage = SpriteButton::create(ImageManager::getImage("right"), 0.70f, 10.0f, CC_CALLBACK_1(Categories::updateTableViewPage, this)); buttonNextPage->setTag(static_cast<int>(TablewViewPageDirection::NEXT)); buttonNextPage->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonNextPage = positionTablewView; positionButtonNextPage.y += tableViewCategories->getBoundingBox().size.height / 2; positionButtonNextPage.x += tableViewCategories->getBoundingBox().size.width; positionButtonNextPage.x += buttonNextPage->getBoundingBox().size.width / 2; buttonNextPage->setPosition(positionButtonNextPage); layerCategories->addChild(buttonNextPage); this->addChild(layerCategories); tableViewCategories->reloadData(); return true; } ssize_t Categories::numberOfCellsInTableView(PagingTableView *table) { return _categories.size(); } Size Categories::tableCellSizeForIndex(PagingTableView *table, ssize_t idx) { return this->getScrollItemSize(); } PagingTableViewCell* Categories::tableCellAtIndex(PagingTableView *table, ssize_t idx) { MainCategory mainCategory = *_categories.at(idx); auto string = String::createWithFormat(mainCategory.getName().c_str(), (int)idx); PagingTableViewCell *cell = table->dequeueCell(); Size itemSize = this->getScrollItemSize(); if (!cell) { cell = new PagingTableViewCell(); cell->autorelease(); } cell->removeAllChildren(); Size spriteSize = itemSize; spriteSize.height = spriteSize.height * TableViewItemImageHeightPercentage/100; float maxSize = 0; float scale = 1.0f; // Create circle auto circle = SpriteButton::create(ImageManager::getImage("category-circle"), scale, NULL); if (spriteSize.width < spriteSize.height) { maxSize = spriteSize.width; scale = spriteSize.width / circle->getBoundingBox().size.width; } else { maxSize = spriteSize.height; scale = spriteSize.height / circle->getBoundingBox().size.height; } // Append min margin scale -= 0.15f; circle->setScale(scale); circle->setAnchorPoint(Point::ANCHOR_MIDDLE); circle->setPosition(Vec2(itemSize.width/2, itemSize.height - spriteSize.height/2)); cell->addChild(circle); // Add category image // Reset values maxSize = 0; scale = 1.0f; spriteSize = circle->getBoundingBox().size; auto categoryImage = SpriteButton::create(ZipManager::getInstance()->getDataFolderFullPath("hd/topics/" + mainCategory.getFileName()), scale, NULL); float maxSizePercentage = 0.80; if (spriteSize.width < spriteSize.height) { maxSize = spriteSize.width; scale = spriteSize.width * maxSizePercentage / categoryImage->getBoundingBox().size.width; } else { maxSize = spriteSize.height; scale = spriteSize.height * maxSizePercentage / categoryImage->getBoundingBox().size.height; } categoryImage->setScale(scale); categoryImage->setAnchorPoint(Point::ANCHOR_MIDDLE); categoryImage->setPosition(circle->getPosition()); cell->addChild(categoryImage); Size labelSize = itemSize; labelSize.height = labelSize.height * (1 - TableViewItemImageHeightPercentage/100 - TableViewItemImageTitleSeparationPercentage/100); auto label = Label::createWithTTF(string->getCString(), MainRegularFont, 70.0); label->setContentSize(labelSize); label->setPosition(Vec2(itemSize.width/2, 0)); label->setAnchorPoint(Point::ANCHOR_MIDDLE_BOTTOM); label->setAlignment(TextHAlignment::CENTER); label->setTag(123); label->setTextColor(IkasRed); cell->addChild(label); return cell; } void Categories::tableCellTouched(PagingTableView* table, PagingTableViewCell* cell) { SoundManager::getInstance()->sfxPlay("button"); if (_categories.at((int)cell->getIdx())->getSubCategories().empty()) { log("subcategorias en blanco!"); return; } GamePlayPointsManager::getInstance()->setCurrentCategory((int)cell->getIdx()); SceneManager::getInstance()->runSceneWithType(SceneType::LEVEL); } Size Categories::getScrollSize() { if (scrollSize.width == 0 && scrollSize.height == 0) { scrollSize = Size(ScreenSizeManager::getWidthFromPercentage(TableViewWidthPercentage), ScreenSizeManager::getHeightFromPercentage(TableViewHeightPercentage)); } return scrollSize; } Size Categories::getScrollItemSize() { if (scrollItemSize.width == 0 && scrollItemSize.height == 0) { Size mScrollSize = this->getScrollSize(); float itemWidth = mScrollSize.width/TableViewItemsPerPage; float itemHeight = mScrollSize.height; scrollItemSize = Size(itemWidth, itemHeight); } return scrollItemSize; } void Categories::switchSoundSettings(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); GameSettingsManager::getInstance()->switchSFX(); GameSettingsManager::getInstance()->switchMusic(); SpriteButton *item = static_cast<SpriteButton*>(sender); item->setTexture(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage)); } void Categories::changeScene(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); SpriteButton *item = static_cast<SpriteButton*>(sender); SceneManager::getInstance()->runSceneWithType(static_cast<SceneType>(item->getTag())); } void Categories::openInfo(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); Application::getInstance()->openURL(InfoURL); } void Categories::updateTableViewPage(Ref* sender) { if (static_cast<bool>(tableViewCategories->getTag()) == false) { tableViewContentOffset = tableViewCategories->getContentOffset(); tableViewCategories->setTag(static_cast<int>(true)); } SoundManager::getInstance()->sfxPlay("button"); SpriteButton *item = static_cast<SpriteButton*>(sender); TablewViewPageDirection direction = static_cast<TablewViewPageDirection>(item->getTag()); if (TablewViewPageDirection::PREVIOUS == direction) { if (-tableViewContentOffset.x > 0) { tableViewContentOffset.x += this->getPaginationOffset(); } } else { if (-tableViewContentOffset.x < tableViewCategories->getContentSize().width - tableViewCategories->getBoundingBox().size.width) { tableViewContentOffset.x -= this->getPaginationOffset(); } } tableViewCategories->setContentOffsetInDuration(tableViewContentOffset, 0.25f); } float Categories::getPaginationOffset() { return tableViewCategories->getBoundingBox().size.width/TableViewItemsPerPage; } void Categories::scrollViewDidScroll(PagingScrollView* view) { float value = -view->getContentOffset().x; float nearItemPosition = value / this->getPaginationOffset(); float decimal = nearItemPosition - (int)nearItemPosition; if (decimal >= 0.5f) { nearItemPosition = nearItemPosition + 1; } nearItemPosition = (int)nearItemPosition; float nearItemOffset = nearItemPosition * this->getPaginationOffset(); tableViewContentOffset.x = -nearItemOffset; } <file_sep>// // GamePlayPointsManager.cpp // IkasGame // // Created by <NAME> on 16/2/15. // // #include "GamePlayPointsManager.h" #include "AppManager.h" const int SuccessAnswerPoints = 100; // Singleton GamePlayPointsManager * GamePlayPointsManager::_instance = NULL; GamePlayPointsManager* GamePlayPointsManager::getInstance() { if(!_instance) _instance = new GamePlayPointsManager(); return _instance; } GamePlayPointsManager::GamePlayPointsManager() { this->loadSettings(); } GamePlayPointsManager::~GamePlayPointsManager() { } /** * Load ALL settings variables from UserDefault */ void GamePlayPointsManager::loadSettings() { UserDefault *userDefault = UserDefault::getInstance(); _currentCategory = userDefault->getIntegerForKey("currentCategory", -1); _currentDifficulty = static_cast<Difficulty>(userDefault->getIntegerForKey("currentDifficulty", static_cast<int>(Difficulty::EMPTY))); _currentPoints = userDefault->getIntegerForKey("currentPoints", 0); } /** * Save ALL gameplay settings */ void GamePlayPointsManager::saveSettings() { UserDefault *userDefault = UserDefault::getInstance(); userDefault->setIntegerForKey("currentCategory", _currentCategory); userDefault->setIntegerForKey("currentDifficulty", static_cast<int>(_currentDifficulty)); userDefault->setIntegerForKey("currentPoints", _currentPoints); userDefault->flush(); AppManager::getInstance()->updateScreenGameStats(); } /** * Set current gameplay category */ void GamePlayPointsManager::setCurrentCategory(int category) { _currentCategory = category; UserDefault *userDefault = UserDefault::getInstance(); userDefault->setIntegerForKey("currentCategory", category); userDefault->flush(); AppManager::getInstance()->updateScreenGameStats(); } /** * Set current gameplay difficulty */ void GamePlayPointsManager::setCurrentDifficulty(Difficulty difficulty) { _currentDifficulty = difficulty; UserDefault *userDefault = UserDefault::getInstance(); userDefault->setIntegerForKey("currentDifficulty", static_cast<int>(difficulty)); userDefault->flush(); AppManager::getInstance()->updateScreenGameStats(); } /** * Set current gameplay points */ void GamePlayPointsManager::setCurrentPoints(int points) { _currentPoints = points; UserDefault *userDefault = UserDefault::getInstance(); userDefault->setIntegerForKey("currentPoints", points); userDefault->flush(); AppManager::getInstance()->updateScreenGameStats(); } /** * Add success anwer points to current gameplay */ void GamePlayPointsManager::addSuccessPoints() { float levelPoints = 0; switch (_currentDifficulty) { break; case Difficulty::EASY: levelPoints = SuccessAnswerPoints * 0.75f; break; case Difficulty::MEDIUM: levelPoints = SuccessAnswerPoints * 1.0f; break; case Difficulty::HARD: levelPoints = SuccessAnswerPoints * 1.25f; break; default: levelPoints = 0; break; } this->setCurrentPoints(_currentPoints + levelPoints); } /** * Reset current points */ void GamePlayPointsManager::resetCurrentPoints() { this->setCurrentPoints(0); } /** * Reset ALL gameplay settings */ void GamePlayPointsManager::resetCurrentGamePlaySettings() { _currentCategory = -1; _currentDifficulty = Difficulty::EMPTY; _currentPoints = 0; this->saveSettings(); }<file_sep>// // DataFileManager.h // ikaszopa // // Created by <NAME> on 24/2/15. // // #ifndef __ikaszopa__DataFileManager__ #define __ikaszopa__DataFileManager__ #include <stdio.h> #include "cocos2d.h" #include "../json/cJSON.h" #include "../GameModels/MainCategory.h" #include "../GameModels/SubCategory.h" #include "../GameModels/Option.h" using namespace cocos2d; using namespace std; class DataFileManager { public: static DataFileManager* getInstance(); ~DataFileManager(); void parseDataFile(); CC_SYNTHESIZE_READONLY(vector<MainCategory*>, _categories, MainCategories); protected: DataFileManager(); static DataFileManager * _instance; }; #endif /* defined(__ikaszopa__DataFileManager__) */ <file_sep>// // SceneManager.h // IkasGame // // Created by <NAME> on 30/01/15. // // #ifndef __IkasCocosGame__SceneManager__ #define __IkasCocosGame__SceneManager__ #include "cocos2d.h" #include "../Constants/Constants.h" class SceneManager { public: static SceneManager* getInstance(); ~SceneManager(); void runSceneWithType(const SceneType sceneType); void returnToLastScene(); void saveCurrentScene(); void loadSavedScene(); void removeSavedScene(); private: void runScene(Scene* scene, SceneType sceneType); Scene *_savedScene; SceneType _savedSceneType; SceneType _sceneTypeToReturn; SceneType _currentSceneType; static SceneManager * _instance; SceneManager(); }; #endif /* defined(__IkasCocosGame__SceneManager__) */ <file_sep>// // Main.cpp // IkasGame // // Created by <NAME> on 30/01/15. // // #include "Main.h" #include "../Singletons/GameSettingsManager.h" #include "../Singletons/GamePlayPointsManager.h" #include "../Singletons/SceneManager.h" #include "../Singletons/SoundManager.h" #include "../Singletons/ZipManager.h" #include "../Helpers/LanguageManager.h" #include "../Helpers/ScreenSizeManager.h" #include "../Helpers/ImageManager.h" #include "../CustomGUI/SpriteButton.h" const Value DelayMinTime = Value(5.0f); Scene* Main::createScene() { auto *scene = Scene::create(); auto *layer = Main::create(); layer->setTag(2334); scene->addChild(layer); return scene; } Main::~Main() { _api = NULL; } bool Main::init() { if ( !Layer::init() ) { return false; } // Reset game play settings to defaults GamePlayPointsManager::getInstance()->resetCurrentGamePlaySettings(); Rect visibleRect = ScreenSizeManager::getVisibleRect(); auto background = Sprite::create(ImageManager::getImage("background"), visibleRect); background->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50)); background->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(background); auto logo = Sprite::create(ImageManager::getImage("logo")); logo->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 70)); logo->setAnchorPoint(Point::ANCHOR_MIDDLE); logo->setScale(0.90f); this->addChild(logo); /* Play Layer */ playLayer = Layer::create(); playLayer->setContentSize(visibleRect.size); playLayer->setPosition(0, 0); playLayer->setVisible(false); auto buttonPlay = SpriteButton::create(ImageManager::getImage("play"), 0.5f, CC_CALLBACK_1(Main::changeScene, this)); buttonPlay->setTag(static_cast<int>(SceneType::CATEGORIES)); buttonPlay->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionPlay = ScreenSizeManager::getScreenPositionFromPercentage(50, 50); positionPlay.y -= ScreenSizeManager::getHeightFromPercentage(18); // Adjust views to strech screens float logoBottom = logo->getPosition().y - logo->getBoundingBox().size.height/2; float playTop = positionPlay.y + buttonPlay->getBoundingBox().size.height/2; int margin = 10; if (logoBottom <= (playTop + margin)) { positionPlay.y = logoBottom - margin - buttonPlay->getBoundingBox().size.height/2; } buttonPlay->setPosition(positionPlay); playLayer->addChild(buttonPlay); auto labelPlay = Label::createWithTTF(LanguageManager::getLocalizedText("Main", "play"), MainRegularFont, 70); labelPlay->setAlignment(TextHAlignment::CENTER); labelPlay->setAnchorPoint(Point::ANCHOR_MIDDLE_TOP); labelPlay->setTextColor(IkasGrayDark); Vec2 positionLabelPlay = buttonPlay->getPosition(); positionLabelPlay.y -= ScreenSizeManager::getHeightFromPercentage(2); positionLabelPlay.y -= buttonPlay->getBoundingBox().size.height / 2; labelPlay->setPosition(positionLabelPlay); playLayer->addChild(labelPlay); auto buttonAbout = SpriteButton::create(ImageManager::getImage("info"), 0.30f, CC_CALLBACK_1(Main::openInfo, this)); buttonAbout->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionAbout = ScreenSizeManager::getScreenPositionFromPercentage(95, 5); positionAbout.x -= buttonAbout->getBoundingBox().size.width / 2; positionAbout.y += buttonAbout->getBoundingBox().size.height / 2; buttonAbout->setPosition(positionAbout); playLayer->addChild(buttonAbout); auto buttonSFXSettings = SpriteButton::create(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage), 0.30f, CC_CALLBACK_1(Main::switchSoundSettings, this)); buttonSFXSettings->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionSFXSettings = buttonAbout->getPosition(); positionSFXSettings.x -= ScreenSizeManager::getWidthFromPercentage(5); positionSFXSettings.x -= buttonSFXSettings->getBoundingBox().size.width; buttonSFXSettings->setPosition(positionSFXSettings); playLayer->addChild(buttonSFXSettings); this->addChild(playLayer); // Loading Layer loadingLayer = Layer::create(); loadingLayer->setContentSize(visibleRect.size); loadingLayer->setPosition(0, 0); loadingLayer->setVisible(false); auto loadingAnimation = Sprite::create(ImageManager::getImage("loading")); loadingAnimation->setScale(0.40f); loadingAnimation->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionLoadingAnimation = ScreenSizeManager::getScreenPositionFromPercentage(50, 50); positionLoadingAnimation.y -= ScreenSizeManager::getHeightFromPercentage(20); // Adjust views to strech screens margin = 45; float loadingTop = positionLoadingAnimation.y + loadingAnimation->getBoundingBox().size.height/2; if (logoBottom <= (loadingTop + margin)) { positionLoadingAnimation.y = logoBottom - margin - loadingAnimation->getBoundingBox().size.height/2; } loadingAnimation->setPosition(positionLoadingAnimation); loadingLayer->addChild(loadingAnimation); ActionInterval* rotate = RotateBy::create(1.0f, 360.0f); RepeatForever *repeat = RepeatForever::create(rotate); loadingAnimation->runAction(repeat); auto labelLoadingAnimation = Label::createWithTTF(LanguageManager::getLocalizedText("Main", "loading"), MainRegularFont, 60); labelLoadingAnimation->setAlignment(TextHAlignment::CENTER); labelLoadingAnimation->setAnchorPoint(Point::ANCHOR_MIDDLE_TOP); labelLoadingAnimation->setTextColor(Color4B(IkasPinkAlpha)); Vec2 positionLabelLoadingAnimation = loadingAnimation->getPosition(); positionLabelLoadingAnimation.y -= loadingAnimation->getBoundingBox().size.height / 2; positionLabelLoadingAnimation.y -= ScreenSizeManager::getHeightFromPercentage(2); labelLoadingAnimation->setPosition(positionLabelLoadingAnimation); loadingLayer->addChild(labelLoadingAnimation); this->addChild(loadingLayer); // Initializing and binding auto keyboardListener = EventListenerKeyboard::create(); keyboardListener->onKeyReleased = CC_CALLBACK_2(Main::onKeyReleased, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this); _api = new IkasAPI(); if(GameSettingsManager::getInstance()->getIsFirstLaunch()) { this->checkNewData(); } else { if (GameSettingsManager::getInstance()->getIsNewDataAvalaible()) { this->showLoading(true); this->downloadLatestData(CC_CALLBACK_1(Main::successDataDownloaded, this), CC_CALLBACK_1(Main::errorDataDownloaded, this)); } else { this->showLoading(false); this->checkNewData(); } } return true; } void Main::switchSoundSettings(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); GameSettingsManager::getInstance()->switchSFX(); GameSettingsManager::getInstance()->switchMusic(); SpriteButton *item = static_cast<SpriteButton*>(sender); item->setTexture(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage)); } void Main::changeScene(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); SpriteButton *item = static_cast<SpriteButton*>(sender); SceneManager::getInstance()->runSceneWithType(static_cast<SceneType>(item->getTag())); } void Main::openInfo(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); Application::getInstance()->openURL(InfoURL); } void Main::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event) { if (static_cast<int>(keyCode) != 6) return; log("[Main] BACK key pressed!"); } void Main::showLoading(bool show) { loadingLayer->setVisible(show); playLayer->setVisible(!show); } void Main::checkNewData() { if(!GameSettingsManager::getInstance()->getIsNewDataAvalaible() || GameSettingsManager::getInstance()->getIsFirstLaunch()) { if (GameSettingsManager::getInstance()->getIsFirstLaunch()) { this->showLoading(true); _api->checkForLatestZipData(CC_CALLBACK_2(Main::forceFirstData, this), CC_CALLBACK_1(Main::forceFirstDataErrorCallback, this)); } else { _api->checkForLatestZipData(NULL, NULL); } } } void Main::forceFirstData(Ref* sender, bool result) { if (result) { this->downloadLatestData(CC_CALLBACK_1(Main::successDataDownloaded, this), CC_CALLBACK_1(Main::errorDataDownloaded, this)); } else { // Download again GameSettingsManager::getInstance()->setZipUrl(""); GameSettingsManager::getInstance()->setZipName(""); GameSettingsManager::getInstance()->setFirstLaunch(true); this->checkNewData(); } } void Main::forceFirstDataErrorCallback(Ref* sender) { DelayTime *delayAction = DelayTime::create(DelayMinTime.asFloat()); CallFunc *mySelector = CallFunc::create(CC_CALLBACK_0(Main::checkNewData, this)); this->runAction(Sequence::create(delayAction, mySelector, nullptr)); } void Main::downloadLatestData(const IkasHandler& successCallback, const IkasHandler& errorCallback) { _api->downloadLatestZip(successCallback, errorCallback); } void Main::successDataDownloaded(Ref* sender) { GameSettingsManager::getInstance()->setFirstLaunch(false); GameSettingsManager::getInstance()->setDataAvalaible(false); bool res = ZipManager::getInstance()->unzipZipDataAndDeletePreviousData(); if (res) { this->showLoading(false); } else { // Download again GameSettingsManager::getInstance()->setZipUrl(""); GameSettingsManager::getInstance()->setZipName(""); GameSettingsManager::getInstance()->setFirstLaunch(true); DelayTime *delayAction = DelayTime::create(DelayMinTime.asFloat()); CallFunc *mySelector = CallFunc::create(CC_CALLBACK_0(Main::checkNewData, this)); this->runAction(Sequence::create(delayAction, mySelector, nullptr)); } } void Main::errorDataDownloaded(Ref* sender) { // Download again GameSettingsManager::getInstance()->setZipUrl(""); GameSettingsManager::getInstance()->setZipName(""); GameSettingsManager::getInstance()->setFirstLaunch(true); DelayTime *delayAction = DelayTime::create(DelayMinTime.asFloat()); CallFunc *mySelector = CallFunc::create(CC_CALLBACK_0(Main::checkNewData, this)); this->runAction(Sequence::create(delayAction, mySelector, nullptr)); } <file_sep>**Ikasesteka** ============= Deskribapena ------------ >[Ikasesteka][1] umeek bere lehenengo urratsak euskaraz eman ditzaten aplikazio mugikorra da. Oso joko erraza da, txikienengan pentsatuta: pantaila ukitu besterik ez dute egin behar marrazkiak hitzekin lotzeko eta horrela bere hiztegia handitu sail ezberdinetan: Ohiko objektuak, Etxeko gauzak, Gorputzeko atalak, Janaria, Eskola, Familia, Arropa, Koloreak, Zenbakiak… Libreriak ----------- * [Cocos2d-x v3.4][2] Lizentzia ---- * [The MIT License (MIT)][3] [1]:http://ikastek.net/aplikazioak/umeentzako/ikasesteka/ [2]:http://www.cocos2d-x.org/ [3]:https://github.com/irontec/Ikasesteka/blob/master/LICENSE <file_sep>// // ZipManager.h // IkasGame // // Created by <NAME> on 24/2/15. // // #ifndef __IkasGame__ZipManager__ #define __IkasGame__ZipManager__ #include "cocos2d.h" #include "../Constants/Constants.h" using namespace cocos2d; class ZipManager { public: static ZipManager* getInstance(); ~ZipManager(); bool saveZipDataToDisk(std::vector<char>* buffer); bool unzipZipDataAndDeletePreviousData(); bool deleteZipData(); std::string getDataFolderPath(); std::string getDataFolderFullPath(std::string filePath); protected: ZipManager(); static ZipManager * _instance; std::string getZipFilePath(); }; #endif /* defined(__IkasGame__ZipManager__) */ <file_sep>// // // GamePlay.cpp // IkasGame // // Created by <NAME> on 10/2/15. // // #include "GamePlay.h" #include "../Singletons/GameSettingsManager.h" #include "../Singletons/GamePlayPointsManager.h" #include "../Singletons/AppManager.h" #include "../Singletons/SceneManager.h" #include "../Singletons/SoundManager.h" #include "../Helpers/LanguageManager.h" #include "../Helpers/ScreenSizeManager.h" #include "../Helpers/ImageManager.h" #include "../Helpers/DataFileManager.h" const Value PlayMaxTime = Value(40.0f); const Value TimeToReduce = Value(2.0f); const Value TimeMinPercentage = Value(25); const Value SuccessTime = Value(1.5); const float BorderWidth = 2; const Color4B BorderColor = IkasGrayLight; const float LineRadius = 30; const Color4F LineColorTouch = Color4F(Color4B(235, 235, 235, 255)); const Color4F LineColorSuccess = Color4F(Color4B(216, 225, 158, 255)); const Color4F LineColorError = Color4F(Color4B(240, 173, 182, 255)); Scene* GamePlay::createScene() { auto *scene = Scene::create(); auto *layer = GamePlay::create(); layer->setTag(2339); scene->addChild(layer); return scene; } bool GamePlay::init() { if (!Layer::init()) { return false; } DataFileManager *dataManager = DataFileManager::getInstance(); _categories = dataManager->getMainCategories(); if (_categories.empty()) { dataManager->parseDataFile(); _categories = dataManager->getMainCategories(); } _subCategories = _categories.at(GamePlayPointsManager::getInstance()->getCurrentCategory())->getFilteredSubCategoriesByLevel(GamePlayPointsManager::getInstance()->getCurrentDifficulty()); AppManager::getInstance()->setGamePlayDelegate(this); Rect visibleRect = ScreenSizeManager::getVisibleRect(); auto background = Sprite::create(ImageManager::getImage("background"), visibleRect); background->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50)); background->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(background); _gameLayer = LayerColor::create(Color4B(255, 255, 255, 255)); float margins = ScreenSizeManager::getHeightFromPercentage(3); Size gameLayerSize = Size(0, 0); gameLayerSize.height = ScreenSizeManager::getHeightFromPercentage(100); gameLayerSize.height -= margins * 2; gameLayerSize.width = ScreenSizeManager::getWidthFromPercentage(65); _gameLayer->setContentSize(gameLayerSize); _gameLayer->setPosition(ScreenSizeManager::getWidthFromPercentage(100) - margins - _gameLayer->getBoundingBox().size.width, this->getBoundingBox().size.height / 2 - _gameLayer->getBoundingBox().size.height / 2); auto borderLayer = LayerColor::create(BorderColor); Size borderLayerSize = _gameLayer->getBoundingBox().size; borderLayerSize.width += 2 * BorderWidth; borderLayerSize.height += 2 * BorderWidth; borderLayer->setContentSize(borderLayerSize); Vec2 borderLayerPosition = _gameLayer->getPosition(); borderLayerPosition.x -= BorderWidth; borderLayerPosition.y -= BorderWidth; borderLayer->setPosition(borderLayerPosition); this->addChild(borderLayer); this->addChild(_gameLayer); // Create empty sprites for (int x = 0; x < 3; x++) { float itemHeight = gameLayerSize.height/3; float margin = ScreenSizeManager::getWidthFromPercentage(2); auto image = Sprite::create(); image->setPosition(margin, itemHeight/2 + itemHeight * x); image->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); _gameLayer->addChild(image); _images.push_back(image); auto label = Label::createWithTTF("Tit", MainRegularFont, 70); label->setHeight(itemHeight); label->setVerticalAlignment(TextVAlignment::CENTER); label->setHorizontalAlignment(TextHAlignment::RIGHT); label->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); label->setTextColor(IkasGrayDark); label->setPosition(_gameLayer->getBoundingBox().size.width - margin, itemHeight/2 + itemHeight * x); _gameLayer->addChild(label); _titles.push_back(label); } _drawError = DrawNode::create(); _drawSuccess = DrawNode::create(); _drawTouch = DrawNode::create(); _touchLayer = Layer::create(); _touchLayer->setContentSize(gameLayerSize); _gameLayer->addChild(_touchLayer); _touchLayer->addChild(_drawError); _touchLayer->addChild(_drawSuccess); _touchLayer->addChild(_drawTouch); auto listener = addEvents(); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, _touchLayer); _touchState = TouchState::FINISH; auto hudLayer = Layer::create(); Size hudLayerSize = Size(0, 0); hudLayerSize.width = _gameLayer->getBoundingBox().origin.x - 2 * margins; hudLayerSize.height = _gameLayer->getBoundingBox().size.height; hudLayer->setContentSize(hudLayerSize); hudLayer->setPosition(margins, this->getBoundingBox().size.height / 2 - hudLayer->getBoundingBox().size.height / 2); this->addChild(hudLayer); Size miniLayerSizes = Size(0, 0); miniLayerSizes.width = hudLayer->getBoundingBox().size.width; miniLayerSizes.height = hudLayer->getBoundingBox().size.height / 10; auto layerCategory = Layer::create(); layerCategory->setPosition(margins / 2, hudLayer->getBoundingBox().size.height * 0.55); auto labelTitleCategory = Label::createWithTTF(LanguageManager::getLocalizedText("GamePlay", "category-title"), MainRegularFont, 45); labelTitleCategory->setWidth(miniLayerSizes.width); labelTitleCategory->setAnchorPoint(Point::ANCHOR_TOP_LEFT); labelTitleCategory->setVerticalAlignment(TextVAlignment::BOTTOM); labelTitleCategory->setTextColor(IkasGrayDark); layerCategory->addChild(labelTitleCategory); _labelCategory = Label::createWithTTF("0", MainBoldFont, 50); _labelCategory->setWidth(miniLayerSizes.width); _labelCategory->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); _labelCategory->setVerticalAlignment(TextVAlignment::TOP); _labelCategory->setTextColor(IkasRed); layerCategory->addChild(_labelCategory); miniLayerSizes.height = labelTitleCategory->getContentSize().height + _labelCategory->getContentSize().height; layerCategory->setContentSize(miniLayerSizes); labelTitleCategory->setPosition(0, layerCategory->getBoundingBox().size.height); _labelCategory->setPosition(0, 0); hudLayer->addChild(layerCategory); auto layerLevel = Layer::create(); layerLevel->setPosition(margins / 2, hudLayer->getBoundingBox().size.height * 0.4); auto labelTitleLevel = Label::createWithTTF(LanguageManager::getLocalizedText("GamePlay", "level-title"), MainRegularFont, 45); labelTitleLevel->setWidth(miniLayerSizes.width); labelTitleLevel->setAnchorPoint(Point::ANCHOR_TOP_LEFT); labelTitleLevel->setVerticalAlignment(TextVAlignment::BOTTOM); labelTitleLevel->setTextColor(IkasGrayDark); layerLevel->addChild(labelTitleLevel); _labelLevel = Label::createWithTTF("0", MainBoldFont, 50); _labelLevel->setWidth(miniLayerSizes.width); _labelLevel->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); _labelLevel->setVerticalAlignment(TextVAlignment::TOP); _labelLevel->setTextColor(IkasRed); layerLevel->addChild(_labelLevel); miniLayerSizes.height = labelTitleLevel->getContentSize().height + _labelLevel->getContentSize().height; layerLevel->setContentSize(miniLayerSizes); labelTitleLevel->setPosition(0, layerLevel->getBoundingBox().size.height); _labelLevel->setPosition(0, 0); hudLayer->addChild(layerLevel); auto layerPoints = Layer::create(); layerPoints->setPosition(margins / 2, hudLayer->getBoundingBox().size.height * 0.25); auto labelTitlePoints = Label::createWithTTF(LanguageManager::getLocalizedText("GamePlay", "points-title"), MainRegularFont, 45); labelTitlePoints->setWidth(miniLayerSizes.width); labelTitlePoints->setAnchorPoint(Point::ANCHOR_TOP_LEFT); labelTitlePoints->setVerticalAlignment(TextVAlignment::BOTTOM); labelTitlePoints->setTextColor(IkasGrayDark); layerPoints->addChild(labelTitlePoints); _labelPoints = Label::createWithTTF("0", MainBoldFont, 50); _labelPoints->setWidth(miniLayerSizes.width); _labelPoints->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); _labelPoints->setVerticalAlignment(TextVAlignment::TOP); _labelPoints->setTextColor(IkasRed); layerPoints->addChild(_labelPoints); miniLayerSizes.height = labelTitlePoints->getContentSize().height + _labelPoints->getContentSize().height; layerPoints->setContentSize(miniLayerSizes); labelTitlePoints->setPosition(0, layerPoints->getBoundingBox().size.height); _labelPoints->setPosition(0, 0); hudLayer->addChild(layerPoints); _pauseButton = SpriteButton::create(ImageManager::getImage("pause"), 0.4f, CC_CALLBACK_1(GamePlay::pauseGame, this)); _pauseButton->setPosition(hudLayer->getBoundingBox().size.width / 2, hudLayer->getBoundingBox().size.height * 0.10); _pauseButton->setAnchorPoint(Point::ANCHOR_MIDDLE); hudLayer->addChild(_pauseButton); // Timer! Sprite* timerBackground = Sprite::create(ImageManager::getImage("timer-background")); timerBackground->setScale(0.6f); timerBackground->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 centerPos = Vec2(hudLayer->getBoundingBox().size.width / 2, hudLayer->getBoundingBox().size.height * 0.85); timerBackground->setPosition(centerPos); Sprite* timer = Sprite::create(ImageManager::getImage("timer-in")); _progress = ProgressTimer::create(timer); _progress->setScale(timerBackground->getScale()); _progress->setAnchorPoint(timerBackground->getAnchorPoint()); _progress->setPosition(timerBackground->getPosition()); hudLayer->addChild(timerBackground); hudLayer->addChild(_progress); _progress->setType(ProgressTimer::Type::RADIAL); _progress->setMidpoint(Point::ANCHOR_MIDDLE); this->setupLevelSettings(); this->restartGame(); return true; } void GamePlay::setupLevelSettings() { _totalSuccessScreens = 0; Difficulty difficulty = GamePlayPointsManager::getInstance()->getCurrentDifficulty(); switch (difficulty) { break; case Difficulty::EASY: _maxTime = PlayMaxTime.asFloat() * 1.50f; break; case Difficulty::MEDIUM: _maxTime = PlayMaxTime.asFloat() * 1.00f; break; case Difficulty::HARD: _maxTime = PlayMaxTime.asFloat() * 0.85f; break; default: _maxTime = PlayMaxTime.asFloat(); break; } } void GamePlay::resetTimer() { _action = NULL; _sequence = NULL; _progress->stopAllActions(); _action = ProgressFromTo::create(_currentLevelTime - _elapsedTime, _elapsedTime / _currentLevelTime * 100, 100); CallFunc* callback = CallFunc::create(CC_CALLBACK_0(GamePlay::timeElapsed, this)); _sequence = Sequence::create(_action, callback, NULL); _progress->runAction(_sequence); } void GamePlay::pauseGame(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); SceneManager::getInstance()->runSceneWithType(SceneType::PAUSE); _elapsedTime += _sequence->getElapsed(); _progress->stopAction(_sequence); } // GamePlayDelegate void GamePlay::loadNextGamePlay() { _drawError->clear(); _drawSuccess->clear(); _drawTouch->clear(); _indexes.clear(); // Aleatory unique order if (_loadedIndex.size() >= _subCategories.size() * 0.75) { _loadedIndex.clear(); } int subCategoryPosition; do { subCategoryPosition = rand() % _subCategories.size(); if (_subCategories.at(subCategoryPosition)->getOptions().size() < 3) { subCategoryPosition = -1; _loadedIndex.push_back(subCategoryPosition); } } while (find(_loadedIndex.begin(), _loadedIndex.end(), subCategoryPosition) != _loadedIndex.end() || subCategoryPosition == -1); _loadedIndex.push_back(subCategoryPosition); vector<Option*> options = _subCategories.at(subCategoryPosition)->getOptions(); vector<int> loadedOptions; for (int x = 0; x < 3; x++) { // Aleatory option int optionPosition; do { optionPosition = rand() % options.size(); } while (find(loadedOptions.begin(), loadedOptions.end(), optionPosition) != loadedOptions.end()); loadedOptions.push_back(optionPosition); std::string optionImageName = options.at(optionPosition)->getFileName(); std::string optionTitle = options.at(optionPosition)->getName(); int titleIndex; do { titleIndex = rand() % _images.size(); } while (find(_indexes.begin(), _indexes.end(), titleIndex) != _indexes.end()); _indexes.push_back(titleIndex); auto image = _images.at(x); auto title = _titles.at(titleIndex); image->setTexture(ZipManager::getInstance()->getDataFolderFullPath("hd/options/" + optionImageName)); image->setTag(static_cast<int>(false)); image->setScale(0.4f); title->setString(optionTitle); title->setTag(static_cast<int>(false)); title->setWidth(title->getContentSize().width); } _elapsedTime = 0; float timeDifficulty =_totalSuccessScreens * TimeToReduce.asFloat(); _currentLevelTime = _maxTime; _currentLevelTime -= timeDifficulty; float minValue = (_maxTime * TimeMinPercentage.asInt() / 100); _currentLevelTime = (minValue > _currentLevelTime ? minValue : _currentLevelTime); this->resetTimer(); } void GamePlay::resumeGamePlay() { this->resetTimer(); } void GamePlay::restartGame() { GamePlayPointsManager::getInstance()->resetCurrentPoints(); this->loadNextGamePlay(); } void GamePlay::timeElapsed() { _elapsedTime = 0; _progress->stopAction(_sequence); SceneManager::getInstance()->runSceneWithType(SceneType::LOSE); } void GamePlay::updateScreenGameStats() { Difficulty difficulty = GamePlayPointsManager::getInstance()->getCurrentDifficulty(); std::string levelString = ""; switch (difficulty) { case Difficulty::EASY: levelString = LanguageManager::getLocalizedText("Level", "easy"); break; case Difficulty::MEDIUM: levelString = LanguageManager::getLocalizedText("Level", "medium"); break; case Difficulty::HARD: levelString = LanguageManager::getLocalizedText("Level", "hard"); break; default: break; } _labelLevel->setString(levelString); float points = GamePlayPointsManager::getInstance()->getCurrentPoints(); std::ostringstream pointsString; pointsString << points; _labelPoints->setString(pointsString.str()); int index = GamePlayPointsManager::getInstance()->getCurrentCategory(); std::string categoryName = _categories.at(index)->getName(); _labelCategory->setString(categoryName); } EventListenerTouchOneByOne *GamePlay::addEvents() { auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(false); listener->onTouchBegan = [&](cocos2d::Touch* touch, Event* event) { Vec2 touchLocation = _touchLayer->convertTouchToNodeSpace(touch); Rect rect = _touchLayer->getBoundingBox(); if (!rect.containsPoint(touchLocation)) { return false; } return GamePlay::touchBegan(touch, event); }; listener->onTouchMoved = [=](Touch* touch, Event* event) { Vec2 touchLocation = _touchLayer->convertTouchToNodeSpace(touch); Rect rect = _touchLayer->getBoundingBox(); if (!rect.containsPoint(touchLocation)) { _drawTouch->clear(); _touchState = TouchState::FINISH; return; } GamePlay::touchMoved(touch, event); }; listener->onTouchEnded = [=](Touch* touch, Event* event) { Vec2 touchLocation = _touchLayer->convertTouchToNodeSpace(touch); Rect rect = _touchLayer->getBoundingBox(); if (!rect.containsPoint(touchLocation)) { _drawTouch->clear(); _touchState = TouchState::FINISH; return; } GamePlay::touchEnded(touch, event); }; listener->onTouchCancelled = [=](Touch* touch, Event* event) { Vec2 touchLocation = _touchLayer->convertTouchToNodeSpace(touch); Rect rect = _touchLayer->getBoundingBox(); if (!rect.containsPoint(touchLocation)) { _drawTouch->clear(); _touchState = TouchState::FINISH; return; } GamePlay::touchCancelled(touch, event); }; return listener; } void GamePlay::checkDrawResult(int index, Vec2 imageTouchLocation, Vec2 titleTouchLocation) { Sprite *image = _images.at(index); if (static_cast<bool>(image->getTag())){ // Cancel touch if selected return; } Label *title = _titles.at(_indexes.at(index)); if (image->getBoundingBox().containsPoint(imageTouchLocation) && title->getBoundingBox().containsPoint(titleTouchLocation)) { Vec2 imagePos = image->getPosition(); imagePos.x += image->getBoundingBox().size.width; imagePos.x += ScreenSizeManager::getWidthFromPercentage(3); Vec2 titlePos = title->getPosition(); titlePos.x -= title->getBoundingBox().size.width; titlePos.x -= ScreenSizeManager::getWidthFromPercentage(3); image->setTag(static_cast<int>(true)); title->setTag(static_cast<int>(true)); _drawSuccess->drawSegment(imagePos, titlePos, LineRadius, LineColorSuccess); SoundManager::getInstance()->successPlay(); checkGameStatus(); } else { for (int x = 0; x < 3; x++) { title = _titles.at(x); if (title->getBoundingBox().containsPoint(titleTouchLocation)) { if (static_cast<bool>(title->getTag())){ // Cancel touch if selected return; } Vec2 imagePos = image->getPosition(); imagePos.x += image->getBoundingBox().size.width; imagePos.x += ScreenSizeManager::getWidthFromPercentage(3); Vec2 titlePos = title->getPosition(); titlePos.x -= title->getBoundingBox().size.width; titlePos.x -= ScreenSizeManager::getWidthFromPercentage(3); _drawError->drawSegment(imagePos, titlePos, LineRadius, LineColorError); SoundManager::getInstance()->failurePlay(); break; } } } } void GamePlay::checkGameStatus() { for (int x = 0; x < _images.size(); x++) { Sprite *image = _images.at(x); if (!static_cast<bool>(image->getTag())) { return; } } _pauseButton->setVisible(false); _elapsedTime += _sequence->getElapsed(); _progress->stopAction(_sequence); // All image success DelayTime *delayAction = DelayTime::create(SuccessTime.asFloat()); CallFunc *mySelector = CallFunc::create(CC_CALLBACK_0(GamePlay::openSuccessScreen, this)); this->runAction(Sequence::create(delayAction, mySelector, nullptr)); } void GamePlay::openSuccessScreen() { _totalSuccessScreens++; GamePlayPointsManager::getInstance()->addSuccessPoints(); SceneManager::getInstance()->runSceneWithType(SceneType::WIN); _pauseButton->setVisible(true); } bool GamePlay::touchBegan(Touch *touch, Event *pEvent) { if (_touchState != TouchState::FINISH) { return false; } _touchState = TouchState::START; _drawTouch->clear(); _drawError->clear(); Vec2 touchLocation = _touchLayer->convertTouchToNodeSpace(touch); _initialTouch = touchLocation; _endTouch = touchLocation; return true; } void GamePlay::touchEnded(Touch *touch, Event *pEvent) { if (_touchState == TouchState::FINISH) { return; } Vec2 touchLocation = _touchLayer->convertTouchToNodeSpace(touch); _endTouch = touchLocation; // Check valid touch for (int x = 0; x < _indexes.size(); x++) { Sprite *image = _images.at(x); Rect imageRect = image->getBoundingBox(); if (imageRect.containsPoint(_initialTouch)) { checkDrawResult(x, _initialTouch, _endTouch); break; } else if(imageRect.containsPoint(_endTouch)) { checkDrawResult(x, _endTouch, _initialTouch); break; } } _drawTouch->clear(); _touchState = TouchState::FINISH; } void GamePlay::touchMoved(Touch *touch, Event *pEvent) { if (_touchState == TouchState::FINISH) { return; } _touchState = TouchState::MOVING; Vec2 newTouch = _touchLayer->convertTouchToNodeSpace(touch); if (_pauseButton->isVisible()) { _drawTouch->drawSegment(_endTouch, newTouch, LineRadius, LineColorTouch); _endTouch = newTouch; } } void GamePlay::touchCancelled(Touch *pTouch, Event *pEvent) { _drawTouch->clear(); _touchState = TouchState::FINISH; } <file_sep>// // Constants.h // IkasGame // // Created by <NAME> on 30/01/15. // // #ifndef __IkasCocosGame__Constants #define __IkasCocosGame__Constants #include "cocos2d.h" using namespace cocos2d; /** * URL´s */ static std::string ApiURL = "http://ikastek.net/ikastek-klear/apps-data/ikasesteka"; static std::string InfoURL = "http://ikastek.net/aplikazioak/umeentzako/ikasesteka/"; /** * Custom callbacks */ typedef std::function<void(Ref*)> IkasHandler; typedef std::function<void(Ref*, bool)> IkasResultHandler; /** * Main fonts names */ static std::string MainRegularFont = "fonts/Oxygen-Regular.ttf"; static std::string MainBoldFont = "fonts/Oxygen-Bold.ttf"; static std::string MainLightFont = "fonts/Oxygen-Light.ttf"; /** * Sound settings filename */ static std::string SoundEnableImage = "sound-on"; static std::string SoundDisableImage = "sound-off"; /** * App colors */ static cocos2d::Color4B IkasPink = cocos2d::Color4B(231, 58, 82, 255); static cocos2d::Color4B IkasRed = cocos2d::Color4B(190, 22, 34, 255); static cocos2d::Color4B IkasGrayLight = cocos2d::Color4B(173, 173, 173, 255); static cocos2d::Color4B IkasGrayDark = cocos2d::Color4B(87, 87, 87, 255); static cocos2d::Color4B IkasPinkAlpha = cocos2d::Color4B(231, 58, 82, 130); /** * Different scenes used */ enum class SceneType { NONE, SPLASH, MAIN, CATEGORIES, LEVEL, GAMEPLAY, PAUSE, WIN, LOSE }; /** * Game difficuty options */ enum class Difficulty { EMPTY = -1, EASY = 0, MEDIUM = 1, HARD = 2 }; /** * Different checkBox types used in Game Settings Scene */ enum class CheckBoxType { NONE, MUSIC, SFX }; /** * Different checkBox types used in Game Settings Scene */ enum class CustomLanguage { EUSKARA = 0, SPANISH }; #endif <file_sep>// // CheckBox.h // IkasGame // // Created by <NAME> on 2014-03-20. // // #ifndef __IkasCocosGame__ButtonSpriteLabelOnOff__ #define __IkasCocosGame__ButtonSpriteLabelOnOff__ #include "cocos2d.h" #include "../Constants/Constants.h" using namespace cocos2d; class CheckBox : public MenuItemLabel { public: CheckBox() {} virtual ~CheckBox(); static CheckBox* create(std::string onString, std::string offString, bool isOn, const ccMenuCallback& callback); bool initWithString(std::string onString, std::string offString, bool isOn, const ccMenuCallback& callback); virtual void activate() override; protected: std::string _onString; std::string _offString; bool _on; }; #endif /* defined(__IkasCocosGame__ButtonSpriteLabelOnOff__) */ <file_sep>// // SpriteButton.cpp // // // Created by <NAME> on 30/01/15. // // #include "./SpriteButton.h" #define kZoomActionTag 111 #define kDefaultZoomPercentage 5 SpriteButton::SpriteButton() {} SpriteButton::~SpriteButton() {} SpriteButton* SpriteButton::create(std::string filename, float scale, const ccMenuCallback& callback) { return SpriteButton::create(filename, scale, kDefaultZoomPercentage, callback); } SpriteButton* SpriteButton::create(std::string filename, float scale, float zoomPercentage, const ccMenuCallback& callback) { SpriteButton* pSprite = new SpriteButton(); if (pSprite->initWithFile(filename)) { pSprite->m_state = kSpriteStateUngrabbed; pSprite->scale = scale; pSprite->callback = callback; zoomPercentage = zoomPercentage / 100; pSprite->zoomPercentage = zoomPercentage; pSprite->autorelease(); pSprite->initOptions(); auto listener = pSprite->addEvents(); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, pSprite); return pSprite; } CC_SAFE_DELETE(pSprite); return NULL; } void SpriteButton::initOptions() { if (scale != 1.0f) { setScale(scale); } } void SpriteButton::setScale(float fScale) { scale = fScale; Sprite::setScale(fScale); } void SpriteButton::setEnabled(bool enabled) { if (enabled) { m_state = kSpriteStateUngrabbed; } else { m_state = kSpriteStateDisabled; } } EventListenerTouchOneByOne *SpriteButton::addEvents() { auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(false); listener->onTouchBegan = [&](cocos2d::Touch* touch, Event* event) { return SpriteButton::touchBegan(touch, event); }; listener->onTouchMoved = [=](Touch* touch, Event* event) { SpriteButton::touchMoved(touch, event); }; listener->onTouchEnded = [=](Touch* touch, Event* event) { SpriteButton::touchEnded(touch, event); }; listener->onTouchCancelled = [=](Touch* touch, Event* event) { SpriteButton::touchCancelled(touch, event); }; return listener; } bool SpriteButton::touchBegan(Touch *touch, Event *pEvent) { Vec2 touchLocation = getParent()->convertTouchToNodeSpace(touch); Rect rect = this->getBoundingBox(); if(m_state != kSpriteStateUngrabbed || !rect.containsPoint(touchLocation)) return false; m_state = kSpriteStateGrabbed; Action *action = getActionByTag(kZoomActionTag); if (action) { stopAction(action); } float scaleValue = 1.05f * scale; Action *zoomAction = CCScaleTo::create(zoomPercentage, scaleValue); zoomAction->setTag(kZoomActionTag); runAction(zoomAction); return true; } void SpriteButton::touchEnded(Touch *touch, Event *pEvent) { m_state = kSpriteStateUngrabbed; Action *action = getActionByTag(kZoomActionTag); if (action) { stopAction(action); } float scaleValue = 1.0f * scale; Action *zoomAction = CCScaleTo::create(zoomPercentage, scaleValue); zoomAction->setTag(kZoomActionTag); runAction(zoomAction); Vec2 touchLocation = getParent()->convertTouchToNodeSpace(touch); Rect rect = this->getBoundingBox(); if(rect.containsPoint(touchLocation) && callback != nullptr) { callback(this); } } void SpriteButton::touchMoved(Touch *touch, Event *pEvent) { Vec2 touchLocation = getParent()->convertTouchToNodeSpace(touch); Rect rect = this->getBoundingBox(); if(m_state == kSpriteStateGrabbed && !rect.containsPoint(touchLocation)) { float scaleValue = 1.0f * scale; Action *zoomAction = CCScaleTo::create(zoomPercentage, scaleValue); zoomAction->setTag(kZoomActionTag); runAction(zoomAction); m_state = kSpriteStateUngrabbed; }; } void SpriteButton::touchCancelled(Touch *pTouch, Event *pEvent) { log("SpriteButton - touchCancelled"); } <file_sep>// // SubCategory.h // ikaszopa // // Created by <NAME> on 24/2/15. // // #ifndef ikaszopa_SubCategory_h #define ikaszopa_SubCategory_h #include "cocos2d.h" #include "Option.h" using namespace cocos2d; using namespace std; class SubCategory : public Object { public: SubCategory(){}; ~SubCategory(){}; CC_SYNTHESIZE(string, m_Name, Name); CC_SYNTHESIZE(string, m_FileName, FileName); CC_SYNTHESIZE(int, m_MinLevel, MinLevel); CC_SYNTHESIZE(string, m_MainColor, MainColor); CC_SYNTHESIZE(vector<Option*>, m_Options, Options); }; #endif <file_sep>// // SpriteButton.h // // // Created by <NAME> on 30/01/15. // // #ifndef __SpriteButton__ #define __SpriteButton__ #include "cocos2d.h" using namespace cocos2d; typedef enum tagSpriteState { kSpriteStateGrabbed, kSpriteStateUngrabbed, kSpriteStateDisabled } SpriteState; class SpriteButton : public Sprite { SpriteState m_state; float scale; float zoomPercentage; public: SpriteButton(); ~SpriteButton(); static SpriteButton* create(std::string filename, float scale, const ccMenuCallback& callback); static SpriteButton* create(std::string filename, float scale, float zoomPercentage, const ccMenuCallback& callback); void initOptions(); void setEnabled(bool enabled); virtual void setScale(float fScale); EventListenerTouchOneByOne *addEvents(); virtual bool touchBegan(Touch *touch, Event *pEvent); virtual void touchEnded(Touch *touch, Event *pEvent); virtual void touchMoved(Touch *touch, Event *pEvent); virtual void touchCancelled(Touch *pTouch, Event *pEvent); protected: ccMenuCallback callback; private: }; #endif /* defined(___SpriteButton__) */<file_sep>// // GameSettingsManager.h // IkasGame // // Created by <NAME> on 30/01/15. // // #ifndef __IkasCocosGame__GameSettingsManager__ #define __IkasCocosGame__GameSettingsManager__ #include "cocos2d.h" #include "SoundManager.h" #include "../Constants/Constants.h" using namespace cocos2d; class GameSettingsManager { public: static GameSettingsManager* getInstance(); ~GameSettingsManager(); void loadSettings(); void setLanguage(CustomLanguage language); void setFirstLaunch(bool firstLaunch); void setDataAvalaible(bool dataAvalaible); void switchMusic(); void switchSFX(); void setZipName(std::string zipName); void setZipUrl(std::string zipUrl); CC_SYNTHESIZE_READONLY(CustomLanguage, _currentLanguage, CurrentLanguage); CC_SYNTHESIZE_READONLY(bool, _firstLaunch, IsFirstLaunch); CC_SYNTHESIZE_READONLY(bool, _dataAvalaible, IsNewDataAvalaible); CC_SYNTHESIZE_READONLY(bool, _music, IsMusicOn); CC_SYNTHESIZE_READONLY(bool, _sfx, IsSFXOn); CC_SYNTHESIZE_READONLY(std::string, _zipName, ZipName); CC_SYNTHESIZE_READONLY(std::string, _zipUrl, ZipUrl); protected: GameSettingsManager(); static GameSettingsManager * _instance; }; #endif /* defined(__IkasCocosGame__GameSettingsManager__) */ <file_sep>// // LanguageManager.h // IkasGame // // Edited by <NAME> on 30/01/15. // // #ifndef __IkasCocosGame__LanguageManager__ #define __IkasCocosGame__LanguageManager__ #include <string> class LanguageManager { public: static std::string getLocalizedText(const char *miniDic, const char *key); static std::string getCurrentLanguageName(); }; #endif /* defined(__IkasCocosGame__LanguageManager__) */ <file_sep>// // CheckBox.cpp // IkasGame // // Created by <NAME> on 2014-03-20. // // #include "CheckBox.h" CheckBox::~CheckBox() { } CheckBox* CheckBox::create(std::string onString, std::string offString, bool isOn, const ccMenuCallback& callback) { CheckBox *ret = new CheckBox(); ret->initWithString(onString, offString, isOn, callback); ret->autorelease(); return ret; } bool CheckBox::initWithString(std::string onString, std::string offString, bool isOn, const ccMenuCallback& callback) { _onString = onString; _offString = offString; _on = isOn; Label *label = Label::createWithSystemFont(_on ? _onString : _offString, "", 30); MenuItemLabel::initWithLabel(label, callback); return true; } void CheckBox::activate() { _on = !_on; this->setString(_on ? _onString : _offString); MenuItem::activate(); }<file_sep>// // ScreenHelper.h // Ikasesteka // // Created by <NAME> on 26/11/14. // // #ifndef __Ikasesteka__ScreenHelper__ #define __Ikasesteka__ScreenHelper__ #include "cocos2d.h" using namespace cocos2d; class ScreenSizeManager { private: static void lazyInit(); static Rect visibleScreen; public: static Rect getVisibleRect(); static Vec2 getScreenPositionFromPercentage(int percentageX, int percentageY); static float getWidthFromPercentage(int widthPercentage); static float getHeightFromPercentage(int heightPercentage); }; #endif /* defined(__Ikasesteka__ScreenHelper__) */
659bf3edc2fc412de11ca884221e5e59a75c4d09
[ "Markdown", "C++" ]
52
C++
irontec/Ikasesteka
e5c33445f7ed4aefae7cebbc4f60b00fc943c6eb
be143e0a9a47a498d9bdb9beaab9b8441ee4836b
refs/heads/master
<file_sep> public class tarjeta { // instance variables - replace the example below with your own private float saldo; public tarjeta() { // initialise instance variables saldo = 0; } public void depositar(float dinero) { // put your code here saldo = saldo + dinero; } public float retirar(float dinero) { if (saldo>=dinero){ } return dinero; } }
532dba91f51879ccbe969fd4d17a4d5f6119b450
[ "Java" ]
1
Java
MarioHdz1093/targejta
26e0718402c68e5ec036e6c6bfcf72be3d959b31
f174d352003a127593159875b1014957fa715395
refs/heads/master
<file_sep>//[EXAM] Create bouncy simulator. Get board from ExampleInput.js. // Y – when bouncing objects enters it move it to random direction // other that it came and Y turns into 0, X – border, 0 – boards object can travel, // 1 – bouncing object. The program is to show how the object would travel and bounce // against the walls. Bouncing objects starts in any corner. 1 and Y position may vary. "use strict"; const board = [ ["X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X"], ["X", "0", "0", "X", "X", "X", "X", "X", "X", "X", "X", "X"], ["X", "0", "0", "0", "X", "X", "X", "X", "X", "X", "X", "X"], ["X", "0", "0", "0", "0", "X", "X", "X", "X", "X", "X", "X"], ["X", "0", "0", "0", "0", "0", "X", "X", "X", "X", "X", "X"], ["X", "0", "0", "0", "0", "0", "0", "X", "X", "X", "X", "X"], ["X", "0", "0", "0", "0", "0", "0", "0", "X", "X", "X", "X"], ["X", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "X"], ["X", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "X"], ["X", "0", "0", "0", "X", "0", "0", "0", "0", "Y", "0", "X"], ["X", "0", "0", "X", "X", "X", "0", "0", "0", "0", "0", "X"], ["X", "0", "0", "0", "X", "0", "0", "0", "0", "0", "0", "X"], ["X", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "X"], ["X", "0", "0", "Y", "0", "0", "0", "0", "0", "0", "0", "X"], ["X", "1", "0", "0", "0", "0", "0", "0", "0", "0", "0", "X"], ["X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X"], ]; let canvas = document.getElementById("myCanvas"); let ctx = canvas.getContext("2d"); let ballRadius = 10; let dx = 1; let dy = -1; let brickWidth = 20; let brickHeight = 20; let counter = 0; let requestId; canvas.height = board.length * brickWidth; canvas.width = board[0].length * brickHeight; class Game { constructor(board) { this.board = board; this.initialize(); } initialize() { let bricks = []; for (let i = 0; i < board.length; i++) { bricks[i] = []; for (let j = 0; j < board[i].length; j++) { const current = board[i][j]; // console.log(`current: ${current}`); if (current === "Y") { bricks[i][j] = { status: true, wall: false }; } else if (current === "X") { bricks[i][j] = { wall: true }; } else if (current == "1") { this.x = brickWidth * j + ballRadius; this.initialX = this.x; this.y = brickWidth * i + ballRadius; this.initialY = this.y; } } } this.bricks = bricks; } collisionDetection() { let x = this.x; let y = this.y; let bricks = this.bricks; for (let c = 0; c < board.length; c++) { for (let r = 0; r < board[c].length; r++) { let b = bricks[c][r]; if (b && b.status === true && b.wall === false) { if ( x > b.x - ballRadius && x < b.x + brickWidth + ballRadius && y > b.y - ballRadius && y < b.y + brickHeight + ballRadius ) { dy = -dy; b.status = false; counter++; console.log(`x: ${x}`); console.log(`b.x: ${b.x}`); } } else if (b && b.wall === true) { if ( x > b.x - ballRadius && x < b.x + brickWidth + ballRadius && y > b.y - ballRadius && y < b.y + brickHeight + ballRadius ) { if (dx < 0 && dy < 0) { dx = -Math.abs(dx); dy = Math.abs(dy); } else if (dx < 0 && dy > 0) { dx = Math.abs(dx); dy = Math.abs(dy); } else if (dx > 0 && dy < 0) { dx = -Math.abs(dx); dy = -Math.abs(dy); } else if (dx > 0 && dy > 0) { dx = Math.abs(dx); dy = -Math.abs(dy); } counter++; return; } } } } } drawBall() { ctx.beginPath(); ctx.arc(this.x, this.y, ballRadius, 0, Math.PI * 2); ctx.fillStyle = "red"; ctx.fill(); ctx.closePath(); } drawBricks() { let bricks = this.bricks; for (let c = 0; c < board.length; c++) { for (let r = 0; r < board[c].length; r++) { if (board[c][r] === "Y" && bricks[c][r].status == true) { let brickX = r * brickWidth; let brickY = c * brickHeight; bricks[c][r].x = brickX; bricks[c][r].y = brickY; ctx.beginPath(); ctx.rect(brickX, brickY, brickWidth, brickHeight); ctx.fillStyle = "green"; ctx.fill(); ctx.closePath(); } else if (board[c][r] === "X") { let brickX = r * brickWidth; let brickY = c * brickHeight; bricks[c][r].x = brickX; bricks[c][r].y = brickY; ctx.beginPath(); ctx.rect(brickX, brickY, brickWidth, brickHeight); ctx.fillStyle = "black"; ctx.fill(); ctx.closePath(); } } } } draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); this.drawBricks(); this.drawBall(); this.collisionDetection(); let x = this.x; let y = this.y; x += dx; y += dy; this.x = x; this.y = y; if (counter == 100) { window.cancelAnimationFrame(requestId); return; } else { requestId = requestAnimationFrame(this.draw.bind(this)); } } } let game = new Game(board); game.draw(); <file_sep>//[EXAM] Create bouncy simulator. Get board from ExampleInput.js. X – border, 0 – boards object can travel, // 1 – bouncing object. The program is to show how the object would travel and bounce against the walls. // The program is to end when object comes back to original position. // brickX -> to wartosc w pikselach; poczatek narysowanego prostokata // x -> to srodek kulki ktora uderza w przeszkody "use strict"; const board = [ ["X", "X", "X", "X", "X", "X", "X", "X", "X", "X"], ["X", "0", "0", "0", "0", "0", "0", "1", "0", "X"], ["X", "0", "0", "0", "0", "0", "0", "0", "0", "X"], ["X", "0", "0", "0", "0", "0", "0", "0", "0", "X"], ["X", "0", "0", "0", "0", "0", "0", "0", "0", "X"], ["X", "0", "0", "0", "0", "0", "0", "0", "0", "X"], ["X", "0", "0", "0", "0", "0", "0", "0", "0", "X"], ["X", "0", "0", "0", "0", "0", "0", "0", "0", "X"], ["X", "0", "0", "0", "0", "0", "0", "0", "0", "X"], ["X", "X", "X", "X", "X", "X", "X", "X", "X", "X"], ]; let canvas = document.getElementById("myCanvas"); let ctx = canvas.getContext("2d"); let ballRadius = 10; let dx = 1; let dy = -1; let brickWidth = 20; let brickHeight = 20; let requestId; canvas.height = board.length * brickWidth; canvas.width = board[0].length * brickHeight; class Game { constructor(board) { this.board = board; this.initialize(); } initialize() { let bricks = []; //wrzucamy wszystkie przeszkody(zadanie2) i sciany for (let i = 0; i < board.length; i++) { bricks[i] = []; for (let j = 0; j < board[i].length; j++) { const current = board[i][j]; console.log(`current: ${current}`); if (current === "X") { bricks[i][j] = true; } else if (current == "1") { this.x = brickWidth * j + ballRadius; this.initialX = this.x; this.y = brickWidth * i + ballRadius; this.initialY = this.y; } } } this.bricks = bricks; console.log(bricks); } drawBall() { ctx.beginPath(); //Tworzy nową ścieżkę. Po jej utworzeniu, wszelkie kolejne funkcje rysujące // będą się do niej odwoływały oraz kontynuowały jej rysunek. ctx.arc(this.x, this.y, ballRadius, 0, Math.PI * 2); ctx.fillStyle = "red"; ctx.fill(); ctx.closePath(); } drawBricks() { let bricks = this.bricks; for (let c = 0; c < bricks.length; c++) { for (let r = 0; r < bricks[c].length; r++) { if (bricks[c][r]) { let brickX = r * brickWidth; let brickY = c * brickHeight; ctx.beginPath(); ctx.rect(brickX, brickY, brickWidth, brickHeight); ctx.fillStyle = "black"; ctx.fill(); ctx.closePath(); } } } } draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); //Wymazuje prostokątny obszar, w wyniku czego staje się // on całkiem przezroczysty. Działą to jak gumka w formie prostokąta. this.drawBricks(); this.drawBall(); let x = this.x; let y = this.y; if ( x + dx + brickWidth > canvas.width - ballRadius || x + dx - brickWidth < ballRadius ) { dx = -dx; } if ( y + dy + brickHeight > canvas.height - ballRadius || y + dy - brickHeight < ballRadius ) { dy = -dy; } x += dx; y += dy; this.x = x; this.y = y; // Metoda window.cancelAnimationFrame anuluje żądanie ramki animacji zaplanowane // wcześniej za pomocą wywołania funkcji window.requestAnimationFrame (). if (x == this.initialX && y == this.initialY) { window.cancelAnimationFrame(requestId); return; } else { requestId = requestAnimationFrame(this.draw.bind(this)); } } } let game = new Game(board); game.draw();
c45e8a3c141713a82e18afaa5f22dc96b49cf2ee
[ "JavaScript" ]
2
JavaScript
dworakowska/egzamin_JS
d83cb0ced5337000ebc3c5611309a27f169b1638
d34172e91f573159f94f46da98dd3d883986be5b
refs/heads/master
<file_sep>import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'app-reference', templateUrl: './reference.component.html', styleUrls: ['./reference.component.css'], encapsulation: ViewEncapsulation.None }) export class ReferenceComponent implements OnInit { constructor( public route: ActivatedRoute, public router: Router) { } ngOnInit(): void { console.info('ngOnInit', this, this.route.snapshot); } } <file_sep>import { Component, OnInit, ViewEncapsulation, ChangeDetectionStrategy } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'app-pictures', templateUrl: './pictures.component.html', styleUrls: ['./pictures.component.css'], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush }) export class PicturesComponent implements OnInit { images: any[]; constructor( public route: ActivatedRoute, public router: Router) { } ngOnInit(): void { console.info('ngOnInit', this, this.route.snapshot); this.initImages(); } initImages() { if ( this.images && this.images.length > 0 ) { return; } this.images = []; this.images.push({source: 'assets/images/wall-paint-01.jpg', alt: 'Description for Image 1', title: 'Title 1'}); this.images.push({source: 'assets/images/wall-paint-02.jpg', alt: 'Description for Image 1', title: 'Title 1'}); this.images.push({source: 'assets/images/wall-paint-03.jpg', alt: 'Description for Image 1', title: 'Title 1'}); this.images.push({source: 'assets/images/wall-paint-04.jpg', alt: 'Description for Image 1', title: 'Title 1'}); this.images.push({source: 'assets/images/wall-paint-05.jpg', alt: 'Description for Image 1', title: 'Title 1'}); this.images.push({source: 'assets/images/wall-paint-06.jpg', alt: 'Description for Image 1', title: 'Title 1'}); this.images.push({source: 'assets/images/wall-paint-07.jpg', alt: 'Description for Image 1', title: 'Title 1'}); } onImageClicked(event: any): void { console.info('onImageClicked', event); } onImageChange(event: any): void { console.info('onImageChange', event); } } <file_sep>import { Component, OnInit, ViewEncapsulation, Inject } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'app-introduction', templateUrl: './introduction.component.html', styleUrls: ['./introduction.component.css'], encapsulation: ViewEncapsulation.None }) export class IntroductionComponent implements OnInit { images: any[]; constructor(public route: ActivatedRoute, public router: Router) { } ngOnInit(): void { console.info('ngOnInit', this, this.route.snapshot); this.images = []; this.images.push({source: 'assets/images/profile.jpg', alt: 'Description for Image 1', title: 'Title 1'}); this.images.push({source: 'assets/images/rapidscoper_small.png', alt: 'Description for Image 1', title: 'Title 1'}); } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ConfirmationService, MessageService, AutoCompleteModule, RadioButtonModule, AccordionModule, InputTextModule, DataGridModule, DataScrollerModule, DialogModule, SharedModule, SliderModule, SelectButtonModule, MessageModule, FieldsetModule, TreeModule, PaginatorModule, CardModule, MessagesModule, InplaceModule, SplitButtonModule, ToggleButtonModule, ListboxModule, DataListModule, FileUploadModule, PickListModule, ProgressBarModule, DeferModule, CheckboxModule, TriStateCheckboxModule, DropdownModule, MenubarModule, OverlayPanelModule, PanelModule, PanelMenuModule, SpinnerModule, TabViewModule, ToolbarModule, MultiSelectModule, ButtonModule, CalendarModule, ConfirmDialogModule, InputTextareaModule, GalleriaModule } from 'primeng/primeng'; import { TableModule } from 'primeng/table'; import { TreeTableModule } from 'primeng/treetable'; import { ToastModule } from 'primeng/toast'; import { AppRoutingModule } from './app-routing.module'; import { AppErrorHandlerModule } from './error/app.error.handler'; import { AppComponent } from './app.component'; import { MenuComponent } from './menu/menu.component'; import { IntroductionComponent } from './view/introduction.component'; import { ReferenceComponent } from './view/reference.component'; import { PicturesComponent } from './view/pictures.component'; import { ContactComponent } from './view/contact.component'; import { ProfilesComponent } from './view/profiles.component'; import { DownloadsComponent } from './view/downloads.component'; @NgModule({ declarations: [ AppComponent, IntroductionComponent, ReferenceComponent, MenuComponent, PicturesComponent, ContactComponent, ProfilesComponent, DownloadsComponent ], imports: [ BrowserModule, // primeng modules: AutoCompleteModule, RadioButtonModule, AccordionModule, InputTextModule, DataGridModule, DataScrollerModule, DialogModule, SharedModule, SliderModule, SelectButtonModule, MessageModule, FieldsetModule, TreeModule, PaginatorModule, CardModule, MessagesModule, InplaceModule, SplitButtonModule, ToggleButtonModule, ListboxModule, DataListModule, FileUploadModule, PickListModule, ProgressBarModule, DeferModule, CheckboxModule, TriStateCheckboxModule, DropdownModule, MenubarModule, OverlayPanelModule, PanelModule, PanelMenuModule, SpinnerModule, TabViewModule, ToolbarModule, MultiSelectModule, ButtonModule, CalendarModule, ConfirmDialogModule, TableModule, TreeTableModule, ToastModule, InputTextareaModule, GalleriaModule, AppRoutingModule, AppErrorHandlerModule ], providers: [ ConfirmationService , MessageService ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component, OnInit, ViewEncapsulation, ViewChild, ElementRef } from '@angular/core'; import { MenuItem } from 'primeng/api'; import { OverlayPanel, ConfirmationService } from 'primeng/primeng'; @Component({ selector: 'app-menu', templateUrl: './menu.component.html', styleUrls: ['./menu.component.css', './menu.hamburger.css'], encapsulation: ViewEncapsulation.None }) export class MenuComponent implements OnInit { responsive: boolean = false; items: MenuItem[]; @ViewChild('userOverlay', { static: false }) userOverlay: OverlayPanel; @ViewChild('hamburger', { static: true }) hamburger: ElementRef; constructor() { } ngOnInit() { this.items = [ {label: 'Bemutatkozás', icon: 'fa fa-download', routerLink: ['/introduction']}, {label: 'Referenciák', icon: 'fa fa-download', routerLink: ['/reference'], queryParams: {'recent': 'true'}}, {label: 'Képek', icon: 'fa fa-download', routerLink: ['/pictures']}, {label: 'Kapcsolat', icon: 'fa fa-download', routerLink: ['/contact']}, {label: 'Profiljaink', icon: 'fa fa-download', routerLink: ['/profiles']}, {label: 'Letöltések', icon: 'fa fa-download', routerLink: ['/downloads']} ]; } toggleMenu(): void { if ( !this.hamburger.nativeElement ) { return; } if (this.hamburger.nativeElement.className.indexOf('is-active') !== -1) { this.hamburger.nativeElement.className = 'hamburger hamburger--slider'; } else { this.hamburger.nativeElement.className += ' is-active'; } this.responsive = !this.responsive; } closeMenu(): void { if ( !this.hamburger.nativeElement ) { return; } this.hamburger.nativeElement.className = 'hamburger hamburger--slider'; this.responsive = false; } private initItemClick(event: any): any { let item = event.item; if (item.disabled) { event.originalEvent.preventDefault(); return; } this.closeMenu(); return item; } itemClick(event: any): void { let item = this.initItemClick(event); if (!item) { return; } // if (this.utilService.isDefined(item.externalUrl)) { // let url = item.externalUrl + item.manualRouterLink; // if (this.dealId) { // url += '?dealId=' + this.dealId; // } // window.location.href = url; // } else { // this.navigateTo(item.manualRouterLink); // } } } <file_sep>import { ErrorHandler, Inject, Injector, NgModule, InjectionToken } from '@angular/core'; import * as Rollbar from 'rollbar'; import { Router } from '@angular/router'; // tslint:disable:no-console export class AppErrorHandler extends ErrorHandler { constructor(@Inject(Injector) private injector: Injector) { super(); } handleError(error: any): void { this.logError(this.findOriginalError(error)); } public logError(error: any): any { let errorLabel = (error.name) ? error.name : (error.message) ? error.message : 'Unexpected Error'; console.group(errorLabel); console.error(error.name, error.message); console.error(error.stack); console.groupEnd(); } // I attempt to find the underlying error in the given Wrapped error. findOriginalError(error: any): any { while (error && (error.originalError || error.error)) { error = (error.originalError) ? error.originalError : error.error; } return (error); } private get router(): Router { return this.injector.get(Router); } private get rollbar(): Rollbar { return this.injector.get(RollbarService); } } // tslint:disable-next-line:max-classes-per-file @NgModule({ providers: [{provide: ErrorHandler, useClass: AppErrorHandler}] }) export class AppErrorHandlerModule {} /** * Rollbar npm install rollbar --save * https://www.npmjs.com/package/rollbar * https://docs.rollbar.com/docs/angular **/ export const RollbarService = new InjectionToken<Rollbar>('rollbar'); export function rollbarFactory() { return new Rollbar({ accessToken: 'POST_CLIENT_ITEM_TOKEN', captureUncaught: true, captureUnhandledRejections: true, }); } // tslint:disable-next-line:max-classes-per-file @NgModule({ providers: [{provide: RollbarService, useFactory: rollbarFactory}] }) export class RollbarServiceModule {} <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { IntroductionComponent } from './view/introduction.component'; import { ReferenceComponent } from './view/reference.component'; import { PicturesComponent } from './view/pictures.component'; import { ContactComponent } from './view/contact.component'; import { ProfilesComponent } from './view/profiles.component'; import { DownloadsComponent } from './view/downloads.component'; import { environment } from 'src/environments/environment'; const routes: Routes = [ { path: '', component: IntroductionComponent, data: { title: 'Introduction' } }, { path: 'introduction', component: IntroductionComponent, data: { title: 'Introduction' } }, { path: 'reference', component: ReferenceComponent, data: { title: 'Reference' } }, { path: 'pictures', component: PicturesComponent, data: { title: 'Pictures' } }, { path: 'contact', component: ContactComponent, data: { title: 'Contact' } }, { path: 'profiles', component: ProfilesComponent, data: { title: 'Profiles' } }, { path: 'downloads', component: DownloadsComponent, data: { title: 'downloads' } }, // otherwise redirect to home { path: '**', redirectTo: '' } ]; @NgModule({ // imports: [RouterModule.forRoot(routes)], imports: [RouterModule.forRoot(routes, {useHash: true, enableTracing: false })], exports: [RouterModule] }) export class AppRoutingModule { }
f5de1b600d14a8b62edbdc132860a4a22499b6b6
[ "TypeScript" ]
7
TypeScript
bidziil/hoho
de5815789f159c759ea99a3d51b442060f4c3473
fc1cf4e5dc8ae61835dc0c85f1b0b436fae09475
refs/heads/master
<repo_name>miwanowski/med_projekt<file_sep>/src/lib/candidate.cpp #include "candidate.h" Candidate::Candidate(Partition* newPartition) { partition_ = newPartition; }<file_sep>/src/main.cpp #include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> #include "fun.h" #include "utils.h" void displayUsage(char* argv[]) { std::cerr << "Usage: " << argv[0] << " <filename> <target_col> \"<col1>,...,<coln>\" [options]"; std::cerr << std::endl; std::cerr << "Available options:" << std::endl; std::cerr << " --holds : use Holds (default)" << std::endl; std::cerr << " --sholds : use StrippedHolds" << std::endl; std::cerr << " --rsholds : use ReducedStrippedHolds" << std::endl; std::cerr << " --prsholds : use PartReducedStrippedHolds" << std::endl; std::cerr << " --product : use Product (default)" << std::endl; std::cerr << " --sproduct : use StrippedProduct" << std::endl; std::cerr << " --optprune : use optional pruning" << std::endl; std::cerr << " --nooptprune : don't use optional pruning (default)" << std::endl; } int main(int argc, char* argv[]) { // display usage when given too few arguments: if (argc < 2) { displayUsage(argv); return 1; } // get obligatory arguments: std::string filename = argv[1]; bool paramsInsideDataFile = false; // check if params are defined inside data file: std::string headerLine; std::ifstream dataFile (filename.c_str()); if (dataFile.is_open()) { std::getline(dataFile, headerLine); if (headerLine[0] == '#') { paramsInsideDataFile = true; } dataFile.close(); } if (!paramsInsideDataFile && argc < 4) { displayUsage(argv); return 1; } std::string targetColString; std::string colString; if (paramsInsideDataFile) { std::vector<std::string> splitFileParams = split(headerLine.substr(1), ' '); if (splitFileParams.size() != 2) { std::cerr << "Improper parameters defined inside the data file!" << std::endl; std::cerr << "Correct format of the optional first line inside the data file is:" << std::endl; std::cerr << "#<target_col> <col1>,...,<coln>" << std::endl; return 1; } targetColString = splitFileParams[0]; colString = splitFileParams[1]; } int i; // get command line arguments: if (argc >= 4 && argv[2][0] != '-' && argv[3][0] != '-') { targetColString = argv[2]; colString = argv[3]; i = 4; } else { i = 2; } // parse target column: std::istringstream ss(targetColString); int targetCol; ss >> targetCol; std::cout<< "targetCol=" << targetCol << std::endl; std::cout<< "cols=" << colString << std::endl << std::endl; // parse columns: std::vector<std::string> splitColString = split(colString, ','); std::vector<int> cols; for (std::vector<std::string>::iterator i = splitColString.begin(); i != splitColString.end(); ++i) { std::istringstream ss(*i); int currentCol; ss >> currentCol; cols.push_back(currentCol); } // parse options: for (; i < argc; ++i) { std::string option = argv[i]; if (option == "--holds") { Fun::holdsVariant_ = &Fun::holds; // std::cout << "using regular holds" << std::endl; } else if (option == "--sholds") { Fun::holdsVariant_ = &Fun::strippedHolds; // std::cout << "using stripped holds" << std::endl; } else if (option == "--rsholds") { Fun::holdsVariant_ = &Fun::reducedStrippedHolds; // std::cout << "using reduced stripped holds" << std::endl; } else if (option == "--prsholds") { Fun::holdsVariant_ = &Fun::partReducedStrippedHolds; // std::cout << "using part reduced stripped holds" << std::endl; } else if (option == "--product") { Fun::productVariant_ = &Fun::product; // std::cout << "using regular product" << std::endl; } else if (option == "--sproduct") { Fun::productVariant_ = &Fun::strippedProduct; // std::cout << "using stripped product" << std::endl; } else if (option == "--optprune") { Fun::optionalPruning = true; // std::cout << "using optional pruning" << std::endl; } else if (option == "--nooptprune") { Fun::optionalPruning = false; // std::cout << "not using optional pruning" << std::endl; } else { std::cerr << "Unrecognized option: " << option << std::endl; return 1; } } // execute the algorithm: CandidateSet res = Fun::fun(filename, cols, targetCol); // output results: std::cout << "\nResults:" << std::endl; for (int i = 0; i < res.getSize(); ++i) { printAttributeList(res[i]->getAttributeList()); std::cout << std::endl; } return 0; }<file_sep>/src/include/partition.h /* * Class representing a partition with respect to a given * set of attributes (Candidate object). */ #ifndef PARTITION_H #define PARTITION_H #include <vector> #include <set> class Partition { public: // temporary, maybe other data structures would be better: typedef std::set<long> Group; typedef std::vector<long> ArrayRepresentation; typedef std::vector<Group*> SetRepresentation; private: // internal representation based on sets: SetRepresentation setRepresentation_; long tableSize_; long singletonGroups_; public: // construct an empty partition: Partition(); Partition(long tableSize); // delete all groups: ~Partition(); // get the number of groups: long getGroupCount() const; // accessors for tableSize_: long getTableSize() const { return tableSize_; } void setTableSize(long tableSize) { tableSize_ = tableSize; } // accessors for singletonGroups_: long getSingletonGroups() const { return singletonGroups_; } void setSingletonGroups(long singletonGroups) { singletonGroups_ = singletonGroups; } // get the array representation: ArrayRepresentation* getArrayRepresentation() const; // add a new group to partition: void addGroup(Group* newGroup); // get a group by index: Group* getGroup(long index) const; // delete a group by index: void deleteGroup(long index); // print to stdout for debugging: void print() const; }; #endif<file_sep>/src/include/utils.h /* * Helper utilities. */ #ifndef UTILS_H #define UTILS_H #include <vector> #include <string> #include <sstream> std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems); std::vector<std::string> split(const std::string &s, char delim); void printArrayRepresentation(std::vector<long>* ar); void printAttributeList(std::vector<int> al); bool isSubset(std::vector<int> A, std::vector<int> B); #endif<file_sep>/src/include/candidateset.h /* * Class representing a set of candidates or reducts (verified * candidates). */ #ifndef CANDIDATESET_H #define CANDIDATESET_H #include "candidate.h" class CandidateSet { // internal data type for candidate list representation: typedef std::vector<Candidate*> CandidateList; private: CandidateList candidateList_; public: // create an empty candidate set: CandidateSet() { } ; // get the number of candidates in the set: long getSize() const; // access candidates by index: Candidate* operator[] (const long index) const; // add a new candidate: void addCandidate(Candidate* newCandidate); // delete a candidate by index: void deleteCandidate(long index); // for merging candidate sets: CandidateSet& operator+=(const CandidateSet& rhs); // delete Partition objects from all contained candidates: void deletePartitions(); }; #endif<file_sep>/src/lib/readme.txt Implementacje klas (.cpp) <file_sep>/src/tests/nurseryTest.sh #!/bin/bash TIMEFORMAT=%R > results/nres.txt cat ./nursery.csv | head -n 4500 > ./nursery4500.csv cat ./nursery.csv | head -n 6500 > ./nursery6500.csv cat ./nursery.csv | head -n 7000 > ./nursery7000.csv cat ./nursery.csv | head -n 9000 > ./nursery9000.csv nurseryArray=( "./nursery4500.csv" "./nursery6500.csv" "./nursery7000.csv" "./nursery9000.csv" "./nursery.csv") echo 'Nursery tests' echo '_____________' for filename in "${nurseryArray[@]}" do echo $filename echo $'\nH' time ../fun $filename 8 "0,1,2,3,4,5,6,7" >> results/nres.txt echo $'\nH/P' time ../fun $filename 8 "0,1,2,3,4,5,6,7" --optprune >> results/nres.txt echo $'\nSH' time ../fun $filename 8 "0,1,2,3,4,5,6,7" --sholds --sproduct >> results/nres.txt echo $'\nSH/P' time ../fun $filename 8 "0,1,2,3,4,5,6,7" --sholds --sproduct --optprune >> results/nres.txt echo $'\nPRSH' time ../fun $filename 8 "0,1,2,3,4,5,6,7" --prsholds --sproduct >> results/nres.txt echo $'\nRSH' time ../fun $filename 8 "0,1,2,3,4,5,6,7" --rsholds --sproduct >> results/nres.txt done rm *0.csv<file_sep>/src/lib/partition.cpp #include <vector> #include <set> #include <iostream> #include "partition.h" Partition::Partition(long tableSize) { setRepresentation_ = Partition::SetRepresentation(); tableSize_ = tableSize; singletonGroups_ = 0; } Partition::Partition() { setRepresentation_ = Partition::SetRepresentation(); singletonGroups_ = 0; } Partition::~Partition() { for (SetRepresentation::iterator it = setRepresentation_.begin(); it != setRepresentation_.end(); ++it) { delete *it; } } long Partition::getGroupCount() const { return setRepresentation_.size() + singletonGroups_; } Partition::ArrayRepresentation* Partition::getArrayRepresentation() const { Partition::ArrayRepresentation* ar = new Partition::ArrayRepresentation(tableSize_, -1); long groupId = 0; for (SetRepresentation::const_iterator it = setRepresentation_.begin(); it != setRepresentation_.end(); ++it) { for (Group::iterator jt = (*it)->begin(); jt != (*it)->end(); ++jt) { (*ar)[*jt] = groupId; } groupId++; } return ar; } void Partition::addGroup(Partition::Group* newGroup) { setRepresentation_.push_back(newGroup); } Partition::Group* Partition::getGroup(long index) const { return setRepresentation_[index]; } // delete a group by index: void Partition::deleteGroup(long index) { setRepresentation_.erase(setRepresentation_.begin() + index); } void Partition::print() const { std::cout << "{"; for (SetRepresentation::const_iterator it = setRepresentation_.begin(); it != setRepresentation_.end(); ++it) { std::cout << "{"; for (Group::iterator jt = (*it)->begin(); jt != (*it)->end(); ++jt) { std::cout << *jt << ","; } std::cout << "},"; } std::cout << "}" << std::endl; }<file_sep>/src/include/hashtree.h /* * Class representing a hash tree for storing candidates * and quick lookup of subsets of a given candidate. */ #ifndef HASHTREE_H #define HASHTREE_H #include <vector> #include "hashnode.h" #include "candidate.h" class HashTree { public: typedef std::vector<int> CandidateRepresentation; typedef Candidate::AttributeList AttributeList; typedef LeafNode::CandidateList CandidateList; private: // restricted, not implemented argumentless constructor: HashTree(); // order of the tree: int order_; // root node: HashNode* root_; public: // construct a tree of a given order HashTree(int order); ~HashTree(); // insert a new candidate into the tree void insertCandidate(Candidate* newCandidate, bool includeGroupCount=false); // find how many subsets of a given candidate already exist in a tree int findNumberOfPresentSubsets(Candidate* c, long groupCount=0) const; // check if the tree contains a given candidate: bool contains(AttributeList& al, long groupCount=0) const; // delete a candidate from the tree void deleteCandidate(Candidate *c); // for debugging: void printTree() const; }; #endif<file_sep>/src/include/readme.txt Naglowki klas (.h) <file_sep>/src/tests/letterRecognitionTest.sh #!/bin/bash TIMEFORMAT=%R > results/lrres.txt cat ./letter-recognition.csv | head -n 100 > ./letter-recognition100.csv cat ./letter-recognition.csv | head -n 200 > ./letter-recognition200.csv cat ./letter-recognition.csv | head -n 500 > ./letter-recognition500.csv cat ./letter-recognition.csv | head -n 1000 > ./letter-recognition1000.csv cat ./letter-recognition.csv | head -n 2000 > ./letter-recognition2000.csv cat ./letter-recognition.csv | head -n 5000 > ./letter-recognition5000.csv cat ./letter-recognition.csv | head -n 10000 > ./letter-recognition10000.csv cat ./letter-recognition.csv | head -n 15000 > ./letter-recognition15000.csv lrArray=( "./letter-recognition100.csv" "./letter-recognition200.csv" "./letter-recognition500.csv" "./letter-recognition1000.csv" "./letter-recognition2000.csv" ) echo 'Letter Recognition tests' echo '_____________' for filename in "${lrArray[@]}" do echo $filename echo $'\nH' time ../fun $filename 0 "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16" >> results/lrres.txt echo $'\nH/P' time ../fun $filename 0 "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16" --optprune >> results/lrres.txt echo $'\nSH' time ../fun $filename 0 "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16" --sholds --sproduct >> results/lrres.txt echo $'\nSH/P' time ../fun $filename 0 "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16" --sholds --sproduct --optprune >> results/lrres.txt echo $'\nPRSH' time ../fun $filename 0 "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16" --prsholds --sproduct >> results/lrres.txt echo $'\nRSH' time ../fun $filename 0 "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16" --rsholds --sproduct >> results/lrres.txt done rm *0.csv<file_sep>/src/tests/krkoptTests.sh #!/bin/bash TIMEFORMAT=%R > results/krkoptres.txt cat ./krkopt.csv | head -n 2000 > ./krkopt2000.csv cat ./krkopt.csv | head -n 5000 > ./krkopt5000.csv cat ./krkopt.csv | head -n 10000 > ./krkopt10000.csv cat ./krkopt.csv | head -n 15000 > ./krkopt15000.csv cat ./krkopt.csv | head -n 20000 > ./krkopt20000.csv cat ./krkopt.csv | head -n 25000 > ./krkopt25000.csv krkoptArray=( "./krkopt2000.csv" "./krkopt5000.csv" "./krkopt10000.csv" "./krkopt15000.csv" "./krkopt20000.csv" "./krkopt25000.csv" "./krkopt.csv") echo 'krkopt tests' echo '_____________' for filename in "${krkoptArray[@]}" do echo $filename echo $'\nH' time ../fun $filename 6 "0,1,2,3,4,5" >> results/krkoptres.txt echo $'\nH/P' time ../fun $filename 6 "0,1,2,3,4,5" --optprune >> results/krkoptres.txt echo $'\nSH' time ../fun $filename 6 "0,1,2,3,4,5" --sholds --sproduct >> results/krkoptres.txt echo $'\nSH/P' time ../fun $filename 6 "0,1,2,3,4,5" --sholds --sproduct --optprune >> results/krkoptres.txt echo $'\nPRSH' time ../fun $filename 6 "0,1,2,3,4,5" --prsholds --sproduct >> results/krkoptres.txt echo $'\nRSH' time ../fun $filename 6 "0,1,2,3,4,5" --rsholds --sproduct >> results/krkoptres.txt done rm *0.csv <file_sep>/src/tests/readme.txt Skrypty testowe, zbiory danych. (.sh, .csv, etc.) <file_sep>/src/lib/hashtree.cpp #include <vector> #include <string> #include "hashtree.h" #include "utils.h" // construct a tree of a given order HashTree::HashTree(int order) { order_ = order; root_ = new InternalNode(order_); } HashTree::~HashTree() { delete root_; } // insert a new candidate into the tree void HashTree::insertCandidate(Candidate* newCandidate, bool includeGroupCount) { AttributeList al = newCandidate->getAttributeList(); AttributeList::iterator at = al.begin(); HashNode* currentNode = root_; HashNode* parentNode = NULL; int lastHash = -1; int depth = 0; // find the place in the tree to add the candidate: while (!currentNode->isLeaf() && at != al.end()) { parentNode = currentNode; currentNode = ((InternalNode*)currentNode)->getChild(*at % order_); lastHash = *at % order_; at++; depth++; if (currentNode == NULL) break; } if (currentNode == NULL) { // arrived at a "hanging" branch, need to create a new leaf node: currentNode = new LeafNode(); ((LeafNode*)currentNode)->candidates_.push_back(al); // for optional pruning: if (includeGroupCount) ((LeafNode*)currentNode)->groupCounts_.push_back(newCandidate->getPartition()->getGroupCount()); ((InternalNode*)parentNode)->setChild(lastHash, currentNode); } else if (at != al.end()) { // arrived at a leaf node and still have elements to hash, // need to transform the leaf node into an internal node InternalNode* newInternalNode = new InternalNode(order_); ((InternalNode*)parentNode)->setChild(lastHash, newInternalNode); for (CandidateList::iterator it = ((LeafNode*)currentNode)->candidates_.begin(); it != ((LeafNode*)currentNode)->candidates_.end(); ++it) { int newHash = (*it)[depth] % order_; if (newInternalNode->getChild(newHash) == NULL) { newInternalNode->setChild(newHash, new LeafNode()); } ((LeafNode*)newInternalNode->getChild(newHash))->candidates_.push_back(*it); // for optional pruning: if (includeGroupCount) { // move group counts from old leaf node to new leaf nodes: int offset = it - ((LeafNode*)currentNode)->candidates_.begin(); long oldGroupCount = ((LeafNode*)currentNode)->groupCounts_[offset]; ((LeafNode*)newInternalNode->getChild(newHash))->groupCounts_.push_back(oldGroupCount); } } int newHash = *at % order_; if (newInternalNode->getChild(newHash) == NULL) { newInternalNode->setChild(newHash, new LeafNode()); } ((LeafNode*)newInternalNode->getChild(newHash))->candidates_.push_back(al); // for optional pruning: if (includeGroupCount) ((LeafNode*)newInternalNode->getChild(newHash))-> groupCounts_.push_back(newCandidate->getPartition()->getGroupCount()); delete currentNode; } else { // arrived at a leaf node and there are no more elements to hash, // need to append the candidate to the list ((LeafNode*)currentNode)->candidates_.push_back(al); // for optional pruning: if (includeGroupCount) ((LeafNode*)currentNode)->groupCounts_.push_back(newCandidate->getPartition()->getGroupCount()); } } // delete a candidate from the tree void HashTree::deleteCandidate(Candidate *c) { AttributeList al = c->getAttributeList(); HashNode* currentNode = root_; for (AttributeList::iterator at = al.begin(); at != al.end(); ++at) { int newHash = *at % order_; currentNode = ((InternalNode*)currentNode)->getChild(newHash); if (currentNode->isLeaf()) break; } CandidateList::iterator ca = ((LeafNode*)currentNode)->candidates_.begin(); while (ca != ((LeafNode*)currentNode)->candidates_.end()) { if (std::equal(ca->begin(), ca->end(), al.begin())) { ca = ((LeafNode*)currentNode)->candidates_.erase(ca); } else { ++ca; } } } // check if the tree contains a given candidate: bool HashTree::contains(AttributeList& al, long groupCount) const { HashNode* currentNode = root_; for (AttributeList::iterator at = al.begin(); at != al.end(); ++at) { int newHash = *at % order_; currentNode = ((InternalNode*)currentNode)->getChild(newHash); if (currentNode == NULL) return false; if (currentNode->isLeaf()) break; } for (CandidateList::iterator c = ((LeafNode*)currentNode)->candidates_.begin(); c != ((LeafNode*)currentNode)->candidates_.end(); ++c) { if (std::equal(c->begin(), c->end(), al.begin())) { if (groupCount != 0) { // optional pruning: int offset = c - ((LeafNode*)currentNode)->candidates_.begin(); long testedGroupCount = ((LeafNode*)currentNode)->groupCounts_[offset]; if (testedGroupCount == groupCount) return false; else return true; } else { return true; } } } return false; } // find how many subsets of a given candidate already exist in a tree: int HashTree::findNumberOfPresentSubsets(Candidate* c, long groupCount) const { AttributeList al = c->getAttributeList(); int count=0; for (AttributeList::iterator it = al.begin(); it != al.end(); ++it) { AttributeList subset = al; int offset = it - al.begin(); subset.erase(subset.begin() + offset); if (contains(subset, groupCount)) count++; } return count; } // for debugging: void HashTree::printTree() const { std::cout << std::endl; root_->printNode(0); std::cout << std::endl; }<file_sep>/src/lib/utils.cpp #include <vector> #include <string> #include <sstream> #include <iostream> #include <algorithm> #include "utils.h" #include "fun.h" std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; } void printArrayRepresentation(std::vector<long>* ar) { int i = 0; for (std::vector<long>::iterator it = ar->begin(); it != ar->end(); ++it) { std::cout << i << ": " << *it << ", "; i++; } std::cout << std::endl; } void printAttributeList(std::vector<int> al) { for (std::vector<int>::iterator it = al.begin(); it != al.end(); ++it) { std::cout << Fun::attributeMap[*it] << "(" << *it << ")" << " "; } } bool isSubset(std::vector<int> A, std::vector<int> B) { std::sort(A.begin(), A.end()); std::sort(B.begin(), B.end()); return std::includes(A.begin(), A.end(), B.begin(), B.end()); }<file_sep>/src/lib/candidateset.cpp #include <iostream> #include "candidateset.h" // get the number of candidates in the set: long CandidateSet::getSize() const { return candidateList_.size(); } // access candidates by index: Candidate* CandidateSet::operator[] (const long index) const { return candidateList_[index]; } // add a new candidate: void CandidateSet::addCandidate(Candidate* newCandidate) { candidateList_.push_back(newCandidate); } // delete a candidate by index: void CandidateSet::deleteCandidate(long index) { candidateList_.erase(candidateList_.begin() + index); } // for merging candidate sets: CandidateSet& CandidateSet::operator+=(const CandidateSet& rhs) { for (int i=0; i < rhs.getSize(); ++i) { addCandidate(rhs[i]); } return *this; } // delete Partition objects from all contained candidates: void CandidateSet::deletePartitions() { for (int i=0; i < getSize(); ++i) { delete candidateList_[i]->getPartition(); candidateList_[i]->setPartition(NULL); } }<file_sep>/doc/readme.txt Pliki texa, obrazki, opracowane wyniki testow. (.tex, .bib, .xls, etc.) <file_sep>/src/Makefile CXX=g++ RM=rm -f CPPFLAGS=-O3 -I include/ LDFLAGS= SRCS=main.cpp lib/partition.cpp lib/candidate.cpp lib/candidateset.cpp lib/fun.cpp lib/utils.cpp lib/hashtree.cpp lib/hashnode.cpp OBJS=$(subst .cpp,.o,$(SRCS)) all: main main: $(OBJS) g++ $(LDFLAGS) -o fun $(OBJS) clean: $(RM) $(OBJS)<file_sep>/src/lib/fun.cpp #include <cstddef> #include <fstream> #include <string> #include <iostream> #include <algorithm> #include <map> #include "fun.h" #include "utils.h" #include "candidate.h" #include "candidateset.h" #include "hashtree.h" // initialize the pointer to "holds" variant to default value: regular "holds": bool (*Fun::holdsVariant_)(Candidate* c, Partition* d) = &Fun::holds; // initialize the pointer to "product" variant to default value: regular "product": Partition* (*Fun::productVariant_)(Partition* a, Partition* b) = &Fun::product; // hash tree for candidate pruning: HashTree* Fun::hashTree = NULL; // the default order of the used hash tree: int Fun::hashTreeOrder = 3; // flag indicating whether optional pruning is used: bool Fun::optionalPruning = false; // mapping of attribute ids to names: Fun::AttributeMap Fun::attributeMap = Fun::AttributeMap(); Partition* Fun::product(Partition* a, Partition* b) { Partition* c = new Partition(a->getTableSize()); ArrayRepresentation* t = a->getArrayRepresentation(); std::vector<Group*> s = std::vector<Group*>(a->getTableSize()); for (long groupId = 0; groupId < b->getGroupCount(); ++groupId) { Group* group = b->getGroup(groupId); Group aGroupIds; for (Group::const_iterator it = group->begin(); it != group->end(); ++it) { long j = (*t)[*it]; if (s[j] == NULL) s[j] = new Group(); s[j]->insert(*it); aGroupIds.insert(j); } for (Group::const_iterator it = aGroupIds.begin(); it != aGroupIds.end(); ++it) { c->addGroup(s[*it]); s[*it] = NULL; } } delete t; return c; } Partition* Fun::strippedProduct(Partition* a, Partition* b) { Partition* c = new Partition(a->getTableSize()); long groupCount = b->getGroupCount(); ArrayRepresentation* t = a->getArrayRepresentation(); std::vector<Group*> s = std::vector<Group*>(a->getTableSize()); for (long groupId = 0; groupId < b->getGroupCount() - b->getSingletonGroups(); ++groupId) { Group* group = b->getGroup(groupId); Group aGroupIds; for (Group::const_iterator it = group->begin(); it != group->end(); ++it) { long j = (*t)[*it]; if (j == -1) { groupCount++; } else { if (s[j] == NULL) s[j] = new Group(); s[j]->insert(*it); aGroupIds.insert(j); } } for (Group::const_iterator it = aGroupIds.begin(); it != aGroupIds.end(); ++it) { if (s[*it]->size() > 1) { c->addGroup(s[*it]); } groupCount++; s[*it] = NULL; } groupCount--; } delete t; c->setSingletonGroups(groupCount - c->getGroupCount()); return c; } bool Fun::holds(Candidate* c, Partition* d) { ArrayRepresentation* t = d->getArrayRepresentation(); Partition* cp = c->getPartition(); for (long groupId = 0; groupId < cp->getGroupCount(); ++groupId) { Group* group = cp->getGroup(groupId); Group::const_iterator it = group->begin(); long firstGroup = (*t)[*it]; ++it; for (; it != group->end(); ++it) { if (firstGroup != (*t)[*it]) { delete t; return false; } } } delete t; return true; } bool Fun::strippedHolds(Candidate* c, Partition* d) { ArrayRepresentation* t = d->getArrayRepresentation(); Partition* cp = c->getPartition(); for (long groupId = 0; groupId < cp->getGroupCount() - cp->getSingletonGroups(); ++groupId) { Group* group = cp->getGroup(groupId); Group::const_iterator it = group->begin(); long firstGroup = (*t)[*it]; if (firstGroup == -1) { return false; } ++it; for (; it != group->end(); ++it) { if (firstGroup != (*t)[*it]) { delete t; return false; } } } delete t; return true; } bool Fun::reducedStrippedHolds(Candidate* c, Partition* d) { ArrayRepresentation* t = d->getArrayRepresentation(); Partition* cp = c->getPartition(); bool holdsFlag = true; //std::cout << "groupCount=" << cp->getGroupCount() << std::endl; //std::cout << "singletonGroups=" << cp->getSingletonGroups() << std::endl; for (long groupId = 0; groupId < cp->getGroupCount() - cp->getSingletonGroups(); ++groupId) { //std::cout << " groupid=" << groupId << std::endl; Group* group = cp->getGroup(groupId); Group::const_iterator it = group->begin(); long firstGroup = (*t)[*it]; //std::cout << " firstGroup=" << firstGroup << std::endl; if (firstGroup == -1) { holdsFlag = false; } else { ++it; long nextGroup; for (; it != group->end(); ++it) { nextGroup = (*t)[*it]; //std::cout << " nextGroup=" << nextGroup << std::endl; if (firstGroup != nextGroup) { holdsFlag = false; break; } } if (firstGroup == nextGroup) { //std::cout << "deleting group " << groupId << std::endl; cp->deleteGroup(groupId); groupId--; } } } //std::cout << "holds returning " << holdsFlag << std::endl; delete t; return holdsFlag; } bool Fun::partReducedStrippedHolds(Candidate* c, Partition* d) { ArrayRepresentation* t = d->getArrayRepresentation(); Partition* cp = c->getPartition(); for (long groupId = 0; groupId < cp->getGroupCount() - cp->getSingletonGroups(); ++groupId) { Group* group = cp->getGroup(groupId); Group::const_iterator it = group->begin(); long firstGroup = (*t)[*it]; if (firstGroup == -1) { return false; } ++it; for (; it != group->end(); ++it) { if (firstGroup != (*t)[*it]) { delete t; return false; } } cp->deleteGroup(groupId); groupId--; } delete t; return true; } void Fun::generateInitialCandidates(const std::string& dataFilePath, // path to data file const AttributeIds aIds, // list of attribute Ids const AttributeId targetId, // target attribute Id CandidateSet* cs, // return: candidate set Partition* targetPartition) { // return: target partition std::ifstream dataFile (dataFilePath.c_str()); if (dataFile.is_open()) { std::string headerLine; std::getline(dataFile, headerLine); if (headerLine[0] == '#') { // skip the optional line containing program params std::getline(dataFile, headerLine); } std::vector<std::string> splitHeader = split(headerLine, ','); hashTree = new HashTree(hashTreeOrder); for (AttributeIds::const_iterator it = aIds.begin(); it != aIds.end(); ++it) { attributeMap[*it] = splitHeader[*it]; Candidate* newCandidate = new Candidate(new Partition()); newCandidate->addAttributeToList(*it); cs->addCandidate(newCandidate); hashTree->insertCandidate(newCandidate, optionalPruning); } std::string line; std::vector<std::vector<std::string> > attributeLevels; // initialize the vector of vectors of levels: for (AttributeIds::const_iterator it = aIds.begin(); it != aIds.end(); ++it) { attributeLevels.push_back(std::vector<std::string>()); } std::vector<std::string> targetLevels; long dataLines = 0; while (std::getline(dataFile, line)) { dataLines++; //std::cout << "parsing line: " << line << std::endl; std::vector<std::string> splitLine = split(line, ','); long instanceId = dataLines-1; // update attribute partitions: for (AttributeIds::const_iterator it = aIds.begin(); it != aIds.end(); ++it) { int attNo = it - aIds.begin(); int attCol = *it; //std::cout << "parsing attribute " << attNo << " with column " << attCol << std::endl; // find if the current attribute value is already among attribute levels: std::vector<std::string>::iterator l = std::find(attributeLevels[attNo].begin(), attributeLevels[attNo].end(), splitLine[attCol]); if (l == attributeLevels[attNo].end()) { attributeLevels[attNo].push_back(splitLine[attCol]); Group* newGroup = new Group(); newGroup->insert(instanceId); (*cs)[attNo]->getPartition()->addGroup(newGroup); } else { int groupId = l - attributeLevels[attNo].begin(); (*cs)[attNo]->getPartition()->getGroup(groupId)->insert(instanceId); } } // update target attribute partition: std::vector<std::string>::iterator l = std::find(targetLevels.begin(), targetLevels.end(), splitLine[targetId]); if (l == targetLevels.end()) { targetLevels.push_back(splitLine[targetId]); Group* newGroup = new Group(); newGroup->insert(instanceId); targetPartition->addGroup(newGroup); } else { int groupId = l - targetLevels.begin(); targetPartition->getGroup(groupId)->insert(instanceId); } } for (int i=0; i < cs->getSize(); ++i) { (*cs)[i]->getPartition()->setTableSize(dataLines); } targetPartition->setTableSize(dataLines); // drop singleton groups if stripped partitions are used: if (holdsVariant_ != holds) { // for each candidate: for (int i=0; i < cs->getSize(); ++i) { Partition* p = (*cs)[i]->getPartition(); // for each group: for (long j=0; j < p->getGroupCount() - p->getSingletonGroups(); ++j){ if (p->getGroup(j)->size() == 1) { // delete singleton groups: p->deleteGroup(j); j--; // but keep them counted: p->setSingletonGroups(p->getSingletonGroups()+1); } } } // drop singleton groups from the target partition: for (long j=0; j < targetPartition->getGroupCount(); ++j){ if (targetPartition->getGroup(j)->size() == 1) { // delete singleton groups: targetPartition->deleteGroup(j); // but keep them counted: targetPartition->setSingletonGroups(targetPartition->getSingletonGroups()+1); } } } dataFile.close(); } else { std::cout << "Unable to open the requested file." << std::endl; } } // main method: CandidateSet Fun::fun(const std::string& dataFilePath, // path to data file const AttributeIds aIds, // list of attribute Ids const AttributeId targetId // target attribute Id ) { CandidateSet* c1 = new CandidateSet(); Partition* d = new Partition(); generateInitialCandidates(dataFilePath, aIds, targetId, c1, d); std::vector<CandidateSet*> candidateSets; std::vector<CandidateSet*> resultSets; candidateSets.push_back(c1); // main loop: for (int k=1; candidateSets[k-1]->getSize() != 0; ++k) { std::cout << "Iteration " << k << "..." << std::endl; resultSets.push_back(new CandidateSet()); for (int i=0; i < candidateSets[k-1]->getSize(); ++i) { if ( (*holdsVariant_)((*candidateSets[k-1])[i], d) ) { resultSets[k-1]->addCandidate((*candidateSets[k-1])[i]); hashTree->deleteCandidate((*candidateSets[k-1])[i]); candidateSets[k-1]->deleteCandidate(i); i--; } } candidateSets.push_back(funGen(candidateSets[k-1])); candidateSets[k-1]->deletePartitions(); } // merge result sets: CandidateSet resultSet; for (int i=0; i < resultSets.size(); ++i) { resultSet += *resultSets[i]; } return resultSet; } CandidateSet* Fun::funGen(CandidateSet* ck) { CandidateSet* resultSet = new CandidateSet(); for (int i=0; i < ck->getSize()-1; ++i) { for (int j=i+1; j < ck->getSize(); ++j) { Candidate* cA = (*ck)[i]; Candidate* cB = (*ck)[j]; AttributeList alA = cA->getAttributeList(); AttributeList alB = cB->getAttributeList(); AttributeList::iterator itA = alA.begin(); AttributeList::iterator itB = alB.begin(); while(itA != alA.end()) { if (itA - alA.begin() == alA.size() - 1) { Partition* newPartition = (*productVariant_)(cA->getPartition(), cB->getPartition()); Candidate* newCandidate = new Candidate(newPartition); newCandidate->setAttributeList(alA); newCandidate->addAttributeToList(alB.back()); resultSet->addCandidate(newCandidate); // std::cout << "generating "; // printAttributeList(newCandidate->getAttributeList()); // std:: cout << " from "; // printAttributeList(alA); // std:: cout << " and "; // printAttributeList(alB); // std::cout << std::endl; } else { if (*itA != *itB) break; } itA++; itB++; } } } // candidate pruning using hash tree: for (int i=0; i < resultSet->getSize(); ++i) { long groupCount = optionalPruning ? (*resultSet)[i]->getPartition()->getGroupCount() : 0; if (hashTree->findNumberOfPresentSubsets((*resultSet)[i], groupCount) != (*resultSet)[i]->getAttributeCount()) { resultSet->deleteCandidate(i); i--; } } delete hashTree; hashTree = new HashTree(hashTreeOrder); for (int i=0; i < resultSet->getSize(); ++i) { hashTree->insertCandidate((*resultSet)[i], optionalPruning); } return resultSet; }<file_sep>/src/include/candidate.h /* * Class representing a single candidate (a set of attributes). * Should allow accessing individual attributes and contain a * pointer to associated Partition object. */ #ifndef CANDIDATE_H #define CANDIDATE_H #include <vector> #include <string> #include <iostream> #include "partition.h" class Candidate { public: // temporary, maybe attributeType should be something different: typedef int AttributeType; typedef std::vector<AttributeType> AttributeList; private: // pointer to associated partition object: Partition* partition_; AttributeList attributeList_; public: // construct a candidate with a given partition: Candidate(Partition* newPartition); // accessors for partition_: Partition* getPartition() const { return partition_; } void setPartition(Partition* newPartition) { partition_ = newPartition; } // accessors for attributeList_: AttributeList getAttributeList() const { return attributeList_; } void setAttributeList(AttributeList newAttributeList) { attributeList_ = newAttributeList; } void addAttributeToList(AttributeType newAtt) { attributeList_.push_back(newAtt); } int getAttributeCount() const { return attributeList_.size(); }; }; #endif<file_sep>/README.md med_projekt =========== <file_sep>/src/include/fun.h /* * Main class of fun algorithm. */ #ifndef FUN_H #define FUN_H #include <string> #include <map> #include "partition.h" #include "candidate.h" #include "candidateset.h" #include "hashtree.h" class Fun { private: Fun() { }; public: typedef Partition::ArrayRepresentation ArrayRepresentation; typedef Partition::Group Group; typedef Candidate::AttributeList AttributeList; typedef int AttributeId; typedef std::vector<AttributeId> AttributeIds; typedef std::map<AttributeId, std::string> AttributeMap; // the order of the used hash tree: static int hashTreeOrder; // hash tree for candidate pruning: static HashTree* hashTree; // mapping of attribute ids to names: static AttributeMap attributeMap; // pointer to the selected "holds" function variant static bool (*holdsVariant_)(Candidate* c, Partition* d); // pointer to the selected "product" function variant static Partition* (*productVariant_)(Partition* a, Partition* b); // flag indicating whether optional pruning is used: static bool optionalPruning; // main method: static CandidateSet fun(const std::string& dataFilePath, // path to data file const AttributeIds aIds, // list of attribute Ids const AttributeId targetId // target attribute Id ); // generate C_k+1 candidates from C_k: static CandidateSet* funGen(CandidateSet* ck); // all variants of "Holds" function: static bool holds(Candidate* c, Partition* d); static bool strippedHolds(Candidate* c, Partition* d); static bool reducedStrippedHolds(Candidate* c, Partition* d); static bool partReducedStrippedHolds(Candidate* c, Partition* d); // all variants of "Product" function: static Partition* product(Partition* a, Partition* b); static Partition* strippedProduct(Partition* a, Partition* b); // helper method for reading data file and generating initial candidates and partitions: static void generateInitialCandidates(const std::string& dataFilePath, // path to data file const AttributeIds aIds, // list of attribute Ids const AttributeId targetId, // target attribute Id CandidateSet* cs, // return: candidate set Partition* targetPartition); // return: target partition }; #endif<file_sep>/src/lib/hashnode.cpp #include "hashnode.h" void InternalNode::printNode(int level) { for (int i=0; i < level; ++i) { std::cout << "-"; } std::cout << " internal node: ["; for (int i=0; i < order_; ++i) { if (children_[i] == NULL) std::cout << "n,"; else if (children_[i]->isLeaf()) std::cout << "l,"; else std::cout << "i,"; } std::cout << "]" << std::endl; for (int i=0; i < order_; ++i) { if (children_[i] != NULL) children_[i]->printNode(level+1); } } void LeafNode::printNode(int level) { for (int i=0; i < level; ++i) { std::cout << "-"; } std::cout << " leaf node with candidates:" << std::endl; for (int j=0; j < candidates_.size(); ++j) { for (int i=0; i < level; ++i) { std::cout << "-"; } std::cout << " "; for (int k=0; k < candidates_[j].size(); ++k) { std::cout << candidates_[j][k] << " "; } std::cout << std::endl; } } InternalNode::~InternalNode() { for (int i=0; i < order_; ++i) { if (children_[i] != NULL) { delete children_[i]; } } }<file_sep>/src/include/hashnode.h /* * A group of classes for hash tree node representation. */ #ifndef HASHNODE_H #define HASHNODE_H #include <vector> #include <iostream> // abstract class for a hash tree node: class HashNode { public: // for node type identification virtual bool isLeaf() = 0; virtual void printNode(int level) = 0; }; // node with the hash table of pointers: class InternalNode : public HashNode { public: // type for storing pointers to children nodes: typedef std::vector<HashNode*> Children; private: // order of the hashing tree: int order_; // pointers to children: Children children_; public: // constructor initializing order_ field and children table with NULLs: InternalNode(int order) : order_(order), children_(order, (HashNode*)0 ) { }; // destructor that deletes children first: ~InternalNode(); // type identification: bool isLeaf() { return false; }; // children pointers accessors: HashNode* getChild(int number) { return children_[number]; }; bool setChild(int number, HashNode* child) { children_[number] = child; } // text representation: void printNode(int level); }; class LeafNode : public HashNode { public: // list type for storing candidates: typedef std::vector<std::vector<int> > CandidateList; // list type for storing group count in the corresponding partition: typedef std::vector<long> GroupCounts; // empty constructor: LeafNode() { }; // type identification: bool isLeaf() { return true; }; // text representation: void printNode(int level) ; // public member with the list of candidates: CandidateList candidates_; // public member with the list of group counts in the partition // corresponding to each stored candidate: GroupCounts groupCounts_; }; #endif
9fc257c4f78ace0db3fba34869aea3fce8023b6f
[ "Markdown", "Makefile", "Text", "C++", "Shell" ]
24
C++
miwanowski/med_projekt
c9a4ee8576ef9a5bf084fd83256efb6ced2f19f7
b49fbcd8028e1765128fac4ecdb0d46f972ff707
refs/heads/master
<repo_name>Mat08251/exoalgo16-03-2020<file_sep>/README.md "# exoalgo16-03-2020" <file_sep>/exo.js var a = 4; var b = 5; if (a > b){ console.log ('a est plus grand que b'); } else { console.log ('il est plus grand'); } var c = 2; var d = 15; c, d = d, c; console.log(d, c); var result= a + b; console.log (result); var min = 1; var max = 100; var random = Math.floor (Math.random() * (max - min)) + min; console.log(random); var d =6; var e=7; console.log("addition : "+addition(d,e)); function addition(a,b){ return a+b; } var z=random_int(0,5); exo9(z); function exo9(x){ var z; switch (x) { case 1: console.log("AAA"); break; case 2: console.log("BBB"); break; case 3: console.log("CCC"); break; case 4: console.log("DDD"); break; default: console.log("je suis une peruche"); } } function random_int(min, max){ return Math.floor(min + (Math.tandom() * Math.floor(max-min))); } for(var i=0;i<10;i++){ document.write('Nombre aléatoire n°'+(i+1)+' : '+ random_int(0,1000)+'<br>'); } var tableau = []; for(var i=0;i<10;i++){ tableau[i] = random_int(0,1000); } var i = 1; tableau.forEach(element => { document.write('Valeur '+i+' : '+element+'<br>') i++; }); var total = 0; for (var i=0; i<tableau.length; i++) { total += tableau[i]; } document.write('Total '+total+'<br>'); <file_sep>/exo.php <?php // Question 1 $a = 4; $b = 6; echo ('question 1 <br><br>'); if ($a < $b){ echo "La variable b est la plus grande est égale à : ".$b; } elseif ($a == $b){ echo "Les variables sont équivalentes est égale à :"; } elseif ($b < $a){ echo "la variable a est la plus grande"; } else { echo "ce que vous avez rentré est de la merde."; } echo ('<br><br>question 1 - bis <br><br>'); echo max($a, $b); echo ('<br><br>question 2 <br><br>'); if ($a > $b){ echo "La variable b est la plus petite"; } elseif ($a == $b){ echo "Les variables sont équivalentes"; } elseif ($b > $a){ echo "la variable a est la plus petite"; } else { echo "ce que vous avez rentré est de la merde."; } echo ('<br><br>question 3 <br><br>'); $a = 4; $b = 6; $temp = 0 ; echo $a; echo "<br>"; echo $b; echo "<br>";echo "<br>"; $temp = $a; $a = $b; $b = $temp; echo $a; echo "<br>"; echo $b; echo ('<br><br>question 4 <br><br>'); $resultat = $a + $b; echo $resultat; echo ('<br><br>question 5 <br><br>'); $resultat = rand(1,100); echo $resultat; echo ('<br><br>question 6 <br><br>'); $resultat = rand(5,10); echo $resultat; echo ('<br><br>question 7 <br><br>'); function addition($x, $y) { $result = $x + $y; return $result; } $a = 5; $b = 6; $resultat = addition($a, $b); echo $resultat;echo "<br>"; $b = 10; $g = 6; $resultat = addition($b, $g); $res1 = addition ($resultat, $g); echo $res1;echo "<br>"; ?>
6007c2360502c8ce731fcaa6b9e70401035c6016
[ "Markdown", "JavaScript", "PHP" ]
3
Markdown
Mat08251/exoalgo16-03-2020
1ea40b0808744e0cc626028ec14fa284a8e5c5ea
cd0ee27672440d21ebfa6bae7006fdb07ca089c1
refs/heads/master
<repo_name>lavatahir/NHLFantasyAI<file_sep>/README.md "# NHLFantasyAI" <file_sep>/src/Lineup.java import java.util.*; public class Lineup{ private LinkedList<Skater> forwardLine; private LinkedList<Skater> defenseLine; private LinkedList<Player> goalieLine; static final RosterGenerator rg = new RosterGenerator(); static final Player[] randForward = new Player[] {rg.getPlayer("Crosby"), rg.getPlayer("Backstrom")}; static final Player[] randDefense = new Player[] {rg.getPlayer("Barrie"), rg.getPlayer("Krug"), rg.getPlayer("Mcquaid")}; static final Player[] randGoalie = new Player[] {rg.getPlayer("Condon"), rg.getPlayer("Miller"), rg.getPlayer("Jones")}; static Random r = new Random(); private static final int goalsCap = 90; private static final int assistsCap = 200; private static final int shotsCap = 100; private static final int pimsCap = 100; private static final int winsCap = 35; private static final int savesCap = 1500; public Lineup(){ forwardLine = new LinkedList<Skater>(); defenseLine = new LinkedList<Skater>(); goalieLine = new LinkedList<Player>(); } public Lineup(LinkedList<Skater> forwardLine, LinkedList<Skater> defenseLine, LinkedList<Player> goalieLine){ this.forwardLine = new LinkedList<Skater>(forwardLine); this.defenseLine = new LinkedList<Skater>(defenseLine); this.goalieLine = new LinkedList<Player>(goalieLine); } public int playersInLineup(){ return forwardLine.size() + defenseLine.size() + goalieLine.size(); } public void addPlayer(Player p){ if(p instanceof Forward && !forwardLine.contains(p)){ if(forwardLine.size() < 3 && !forwardLine.contains(p)){ forwardLine.add((Skater)p); } else{ int index = getIndexWorstSkater(forwardLine); forwardLine.remove(index); forwardLine.add((Skater)p); } } else if(p instanceof Defensemen && !defenseLine.contains(p)){ if(defenseLine.size() < 2){ if(!defenseLine.contains(p)){ defenseLine.addFirst((Skater)p); } } else{ int index = getIndexWorstSkater(defenseLine); defenseLine.remove(index); defenseLine.addFirst((Skater)p); } } else if(p instanceof Goalie && !goalieLine.contains(p)){ if(goalieLine.size() == 0 && !goalieLine.contains(p)){ goalieLine.add(p); } else{ goalieLine.remove(); //goalieLine.remove(goalieLine.size()-1); goalieLine.add(p); } } } private int getIndexWorstSkater(LinkedList<Skater> line) { int index = -1; for (int i = 0; i < line.size(); i++){ for (int j = 0; j < line.size(); j++) { if(line.get(i).isBetter(line.get(j))) { index = j; } } } return index; } public String toString(){ String s = ""; s+= "Forwards:\n"; for(Player p : forwardLine){ s+= p + "\n"; s+="\n"; } s+= "Defensemen:\n"; for(Player p : defenseLine){ s+= p + "\n"; s+="\n"; } s+= "Goalie:\n"; for(Player p : goalieLine){ s+= p + "\n"; s+="\n"; } s+="\n"; return s; } public boolean containsPlayer(Player p){ for(Player f : forwardLine){ if(p.equals(f)){ return true; } } for(Player d : defenseLine){ if(p.equals(d)){ return true; } } for(Player g : goalieLine){ if(p.equals(g)){ return true; } } return false; } public void combination(ArrayList<Forward> arr, int len, int startPosition, ArrayList<Player> forwards){ if (len == 0){ return; } for (int i = startPosition; i <= arr.size()-len; i++){ forwards.set(forwards.size() - len, arr.get(i)); combination(arr, len-1, i+1, forwards); } } public HashSet<Lineup> generateSuccessors(){ HashSet<Lineup> successors = new HashSet<Lineup>(); for(Player p : rg.roster){ Lineup l = new Lineup(forwardLine, defenseLine, goalieLine); if(!l.containsPlayer(p)){ l.addPlayer(p); successors.add(l); } } return successors; } public boolean isGoalState(){ int lineGoals = 0; int lineAssists = 0; int lineShots = 0; int linePims = 0; int lineWins = 0; int lineSaves = 0; if(forwardLine.size() < 3 || defenseLine.size() < 2 || goalieLine.size() < 1){ return false; } for(Player p : forwardLine){ lineGoals += ((Forward) p).getGoals(); lineAssists += ((Forward) p).getAssists(); lineShots += ((Forward) p).getShots(); linePims += ((Forward) p).getPenaltyMins(); } for(Player p : defenseLine){ lineGoals += ((Defensemen) p).getGoals(); lineAssists += ((Defensemen) p).getAssists(); lineShots += ((Defensemen) p).getShots(); linePims += ((Defensemen) p).getPenaltyMins(); } for(Player p : goalieLine){ lineWins += ((Goalie) p).getWins(); lineSaves += ((Goalie) p).getSaves(); } if(lineGoals >= goalsCap && lineAssists >= assistsCap && lineShots >= shotsCap && linePims >= pimsCap && lineWins >= winsCap && lineSaves >= savesCap){ //System.out.println("G:"+lineGoals + " A:"+lineAssists + " Sh:"+lineShots + " PIMS:"+linePims + " W:"+lineWins + " Sa:"+lineSaves); return true; } return false; } @Override public int hashCode(){ int lineGoals = 0; int lineAssists = 0; int lineShots = 0; int linePims = 0; int lineWins = 0; int lineSaves = 0; for(Player p : forwardLine){ lineGoals += ((Forward) p).getGoals(); lineAssists += ((Forward) p).getAssists(); lineShots += ((Forward) p).getShots(); linePims += ((Forward) p).getPenaltyMins(); } for(Player p : defenseLine){ lineGoals += ((Defensemen) p).getGoals(); lineAssists += ((Defensemen) p).getAssists(); lineShots += ((Defensemen) p).getShots(); linePims += ((Defensemen) p).getPenaltyMins(); } for(Player p : goalieLine){ lineWins += ((Goalie) p).getWins(); lineSaves += ((Goalie) p).getSaves(); } int result = 1; result = lineGoals + lineAssists + lineShots +linePims +lineWins +lineSaves; return result; } public double findCost(){ return 1; } public void subsetForwards(ArrayList<Forward> possiblecombos, int k, int start, int currLen, boolean[] used, ArrayList<Forward> allcombos) { if (currLen == k) { for (int i = 0; i < possiblecombos.size(); i++) { if (used[i] == true) { allcombos.add(possiblecombos.get(i)); } } return; } if (start == possiblecombos.size()) { return; } // For every index we have two options, // 1.. Either we select it, means put true in used[] and make currLen+1 used[start] = true; subsetForwards(possiblecombos, k, start + 1, currLen + 1, used, allcombos); // 2.. OR we dont select it, means put false in used[] and dont increase // currLen used[start] = false; subsetForwards(possiblecombos, k, start + 1, currLen, used, allcombos); } public void subsetDefense(ArrayList<Defensemen> possiblecombos, int k, int start, int currLen, boolean[] used, ArrayList<Defensemen> allcombos) { if (currLen == k) { for (int i = 0; i < possiblecombos.size(); i++) { if (used[i] == true) { allcombos.add(possiblecombos.get(i)); } } return; } if (start == possiblecombos.size()) { return; } // For every index we have two options, // 1.. Either we select it, means put true in used[] and make currLen+1 used[start] = true; subsetDefense(possiblecombos, k, start + 1, currLen + 1, used, allcombos); // 2.. OR we dont select it, means put false in used[] and dont increase // currLen used[start] = false; subsetDefense(possiblecombos, k, start + 1, currLen, used, allcombos); } static <T> List<List<T>> chopped(List<T> list, final int L) { List<List<T>> parts = new ArrayList<List<T>>(); final int N = list.size(); for (int i = 0; i < N; i += L) { parts.add(new ArrayList<T>( list.subList(i, Math.min(N, i + L))) ); } return parts; } public List<List<Forward>> getForwardCombos(){ ArrayList<Forward> possiblecombos = rg.getForwards(); ArrayList<Forward> allcombos = new ArrayList<Forward>(); boolean[] B = new boolean[possiblecombos.size()]; subsetForwards(possiblecombos, 3, 0, 0, B, allcombos); List<List<Forward>> forwardcombos = chopped(allcombos, 3); return forwardcombos; } public List<List<Defensemen>> getDefenseCombos(){ ArrayList<Defensemen> possiblecombos = rg.getDefensemen(); ArrayList<Defensemen> allcombos = new ArrayList<Defensemen>(); boolean[] B = new boolean[possiblecombos.size()]; subsetDefense(possiblecombos, 3, 0, 0, B, allcombos); List<List<Defensemen>> defensecombos = chopped(allcombos, 3); return defensecombos; } public int getTotalScore(){ int lineGoals = 0; int lineAssists = 0; int lineShots = 0; int linePims = 0; int lineWins = 0; int lineSaves = 0; if(forwardLine.size() < 3 || defenseLine.size() < 2 || goalieLine.size() < 1){ return 0; } for(Player p : forwardLine){ lineGoals += ((Forward) p).getGoals(); lineAssists += ((Forward) p).getAssists(); lineShots += ((Forward) p).getShots(); linePims += ((Forward) p).getPenaltyMins(); } for(Player p : defenseLine){ lineGoals += ((Defensemen) p).getGoals(); lineAssists += ((Defensemen) p).getAssists(); lineShots += ((Defensemen) p).getShots(); linePims += ((Defensemen) p).getPenaltyMins(); } for(Player p : goalieLine){ lineWins += ((Goalie) p).getWins(); lineSaves += ((Goalie) p).getSaves(); } if(lineGoals >= goalsCap && lineAssists >= assistsCap && lineShots >= shotsCap && linePims >= pimsCap && lineWins >= winsCap && lineSaves >= savesCap){ //System.out.println("G:"+lineGoals + " A:"+lineAssists + " Sh:"+lineShots + " PIMS:"+linePims + " W:"+lineWins + " Sa:"+lineSaves); return 100000; } return lineGoals + lineAssists + lineShots + linePims + lineWins + lineSaves; } public boolean goaliePass(){ return !goalieLine.isEmpty() && ((Goalie)goalieLine.getFirst()).getWins() > winsCap && ((Goalie)goalieLine.getFirst()).getSaves() > savesCap; } public boolean moreForwardPass(Lineup l){ return !forwardLine.isEmpty() && getTotalScore() == 100000; } public boolean defensePass(){ return !defenseLine.isEmpty() && getTotalScore() == 100000; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("Enter the desired search. A-Star, BFS, SHC, or SSHC"); String search = sc.next(); Lineup l = new Lineup(); l.addPlayer(l.randForward[l.r.nextInt(l.randForward.length)]); System.out.println(l); l.addPlayer(l.randDefense[l.r.nextInt(l.randDefense.length)]); System.out.println(l); l.addPlayer(l.randGoalie[l.r.nextInt(l.randGoalie.length)]); if(search.equals("BFS")){ BFSearch.search(l); } else if(search.equals("A-Star")){ AStar.search(l, 't'); } else if(search.equals("SHC")){ SimpleHillClimb.search(l); } else if(search.equals("SSHC")){ SteepHillClimb.search(l); } //SteepHillClimb.search(l); //SimpleHillClimb.search(l); //AStar.search(l, 't'); //BFSearch.search(l); } } <file_sep>/src/SimpleHillClimb.java import java.util.*; public class SimpleHillClimb { public static void search(Lineup l) { performSearch(l); } public static void performSearch(Lineup l) { int cost = 3; while(!l.isGoalState()){ HashSet<Lineup> neighbors = l.generateSuccessors(); for(Lineup nn : neighbors){ if(nn.isGoalState()){ System.out.println("The total cost was:"+cost); System.exit(0); } else if(nn.getTotalScore() > l.getTotalScore() || nn.moreForwardPass(l) || nn.goaliePass() || nn.defensePass()){ l = nn; } /* else if(nn.moreForwardPass(l)){ l = nn; } else if(nn.goaliePass()){ l = nn; } else if(nn.defensePass()){ l = nn; } */ } cost++; System.out.println(l); } } } <file_sep>/src/RosterGenerator.java import java.util.*; public class RosterGenerator { public ArrayList<Player> roster = new ArrayList<Player>(); public RosterGenerator(){ Forward crosby = new Forward("Crosby",41,40,230,24); Forward backstrom = new Forward("Backstrom",22,56,142,36); Forward granlund = new Forward("Granlund",25,41,164,12); Forward paajarvi = new Forward("Paajarvi",6,3,35,4); Forward roussel = new Forward("Roussel",12,15,82,115); Forward jokinen = new Forward("Jokinen",11,16,109,35); Forward burrows = new Forward("Burrows",13,14,128,53); Forward versteeg = new Forward("Versteeg",13,16,116,44); Forward landeskog = new Forward("Landeskog",15,14,138,58); Forward smith = new Forward("Smith",16,16,131,61); Defensemen karlsson = new Defensemen("Karlsson",14,52,201,22); Defensemen krug = new Defensemen("Krug",7,41,194,33); Defensemen barrie = new Defensemen("Barrie",6,28,157,16); Defensemen green = new Defensemen("Green",11,21,106,38); Defensemen phaneuf = new Defensemen("Phaneuf",9,21,143,94); Defensemen mcquaid = new Defensemen("Mcquaid",2,7,59,69); Goalie bobrovsky = new Goalie("Bobrovsky",1515, 39); Goalie jones = new Goalie("Jones",1523, 32); Goalie condon = new Goalie("Condon",951, 18); Goalie miller = new Goalie("Miller",1396,18); roster.add(crosby); roster.add(backstrom); roster.add(granlund); roster.add(paajarvi); roster.add(roussel); roster.add(jokinen); roster.add(burrows); roster.add(versteeg); roster.add(landeskog); roster.add(smith); roster.add(karlsson); roster.add(krug); roster.add(barrie); roster.add(green); roster.add(phaneuf); roster.add(mcquaid); roster.add(bobrovsky); roster.add(jones); roster.add(condon); roster.add(miller); } public ArrayList<Player> getRoster() { return roster; } public Player getPlayer(String name){ for(Player p : roster){ if(p.getName().equals(name)){ return p; } } return null; } public ArrayList<Forward> getForwards(){ ArrayList<Forward> forwards = new ArrayList<Forward>(); for(Player p : roster){ if(p instanceof Forward){ forwards.add((Forward)p); } } return forwards; } public ArrayList<Defensemen> getDefensemen(){ ArrayList<Defensemen> defensemen = new ArrayList<Defensemen>(); for(Player p : roster){ if(p instanceof Defensemen){ defensemen.add((Defensemen)p); } } return defensemen; } public ArrayList<Goalie> getGoalies(){ ArrayList<Goalie> goalie = new ArrayList<Goalie>(); for(Player p : roster){ if(p instanceof Goalie){ goalie.add((Goalie)p); } } return goalie; } } <file_sep>/src/Forward.java public class Forward extends Skater{ public Forward(String name, int goals, int assists, int shots, int penaltyMins) { super(name, goals, assists, shots, penaltyMins); } public Forward(){ this("worst",0,0,0,0); } } <file_sep>/src/SteepHillClimb.java import java.util.*; public class SteepHillClimb { public static void search(Lineup l) { performSearch(l); } public static void performSearch(Lineup l) { /* l.addPlayer(l.randForward[l.r.nextInt(l.randForward.length)]); System.out.println(l); l.addPlayer(l.randDefense[l.r.nextInt(l.randDefense.length)]); System.out.println(l); l.addPlayer(l.randGoalie[l.r.nextInt(l.randGoalie.length)]); System.out.println(l); */ Lineup succ = l; int cost = 3; while(!l.isGoalState()){ int nextLineTotalScore = 0; Lineup nextLineupClosest = null; HashSet<Lineup> neighbors = l.generateSuccessors(); for(Lineup nn : neighbors){ if(nn.isGoalState()){ System.out.println("The total cost was:"+cost); System.exit(0); } else if(nn.moreForwardPass(succ)){ succ = nn; } else if(nn.goaliePass()){ succ = nn; } if(nn.getTotalScore() > nextLineTotalScore){ nextLineTotalScore = nn.getTotalScore(); nextLineupClosest = nn; } } if(succ.moreForwardPass(l)){ l = succ; } else if(succ.goaliePass()){ l = succ; } else{ l = nextLineupClosest; } cost++; System.out.println(l); } } }
0b8cea5f19f9b75d5823e4133a5f7393f6fe388d
[ "Markdown", "Java" ]
6
Markdown
lavatahir/NHLFantasyAI
90f56d9ba80254f8b10a32461d03567a35a426c4
a7c9e17374992121f1bc36561444a41519fb6b1b
refs/heads/master
<repo_name>UniDomi/geopitalBackend<file_sep>/app/controllers/attribute_types_controller.rb include AttributeTypesHelper class AttributeTypesController < ApplicationController def index @types = AttributeType.all end def parse upload = Upload.find(params[:id]) data = Spreadsheet.open 'public'+upload.attachment_url sheet = data.worksheet params[:sheet] @types = read_and_store_attribute_types(sheet) end end <file_sep>/test/helpers/locations_helper_test.rb require 'test_helper' include LocationsHelper include HospitalsHelper class LocationsHelperTest < ActionDispatch::IntegrationTest test "should store locations from excel" do sheet_name_loc = "Standorte 2016 KZP16" sheet_name_hosp = "KZ2016_KZP16" data = Spreadsheet.open Rails.root.join("test/fixtures/files/kzp16_daten.xls") sheet_loc = data.worksheet sheet_name_loc sheet_hosp = data.worksheet sheet_name_hosp read_and_store_hospitals(sheet_hosp, sheet_name_hosp) returns = read_and_store_locations(sheet_loc) assert returns[0].count == 1 assert returns[1].count == 0 hospital_without_loc_id = Hospital.find_by_name("<NAME>").id hospital_with_loc_id = Hospital.find_by_name("Groupement Hospitalier de l'Ouest Lémanique (GHOL) SA").id assert_nil HospitalLocation.find_by_hospital_id(hospital_without_loc_id) assert_not_nil HospitalLocation.find_by_hospital_id(hospital_with_loc_id) end end<file_sep>/config/initializers/geocoder.rb Geocoder::Configuration.lookup = :google Geocoder::Configuration.timeout = 15 Geocoder::Configuration.use_https = true Geocoder::Configuration.api_key = ENV['GEO_KEY'] <file_sep>/test/models/hospital_attribute_test.rb require 'test_helper' class HospitalAttributeTest < ActiveSupport::TestCase def setup @hospital_attribute = hospital_attributes(:KTInsel16) end test "hospital attribute should be valid" do assert @hospital_attribute.valid? end test "code should be present" do @hospital_attribute.code = "" assert_not @hospital_attribute.valid? end test "year should be present" do @hospital_attribute.year = "" assert_not @hospital_attribute.valid? end test "value should be present" do @hospital_attribute.value = "" assert_not @hospital_attribute.valid? end test "reference to hospital should be present" do @hospital_attribute.hospital_id = nil assert_not @hospital_attribute.valid? end test "code, year and hospital_id should be unique" do hospital_attribute_duplicate = hospital_attributes(:OpsInsel16) hospital_attribute_duplicate.code = @hospital_attribute.code hospital_attribute_duplicate.year = @hospital_attribute.year hospital_attribute_duplicate.hospital_id = @hospital_attribute.hospital_id assert_not hospital_attribute_duplicate.valid? end end <file_sep>/app/helpers/api_helper.rb require 'oj' module ApiHelper def create_json max_year = HospitalAttribute.maximum("year") hospitals = Hospital.includes(:hospital_attributes).where(:hospital_attributes => {:year => max_year}) hash = Rails.cache.fetch(Hospital.cache_key(hospitals)) do hospitals.as_json(:except => [:created_at, :updated_at], :include => [:hospital_attributes => {:except => [:id, :hospital_id, :created_at, :updated_at]}]) end return Oj.dump(hash) end end <file_sep>/test/models/hospital_test.rb require 'test_helper' class HospitalTest < ActiveSupport::TestCase def setup @hospital = hospitals(:Insel) end test "hospital should be valid" do assert @hospital.valid? end test "name should be present" do @hospital.name = "" assert_not @hospital.valid? end test "name should be unique" do @hospital_duplicate = hospitals(:Linde) @hospital_duplicate.name = @hospital.name.upcase assert_not @hospital_duplicate.valid? end test "destroy all hospital locations when destroying hospital" do test = false begin @hospital.destroy @hospital_location = hospital_locations(:InselOne) rescue Exception => e test = true end assert test end test "destroy all hospital attributes when destroying hospital" do test = false begin @hospital.destroy @hospital_attribute = hospital_attributes(:KTInsel16) rescue Exception => e test = true end assert test end end <file_sep>/app/controllers/api_controller.rb require 'oj' include ApiHelper class ApiController < ApplicationController def hospitals render :json => create_json() end def attributeTypes render :json => {:attribute_types_string => AttributeType.where(:category => "string"), :attribute_types_number => AttributeType.where(:category => "number")} end end <file_sep>/test/controllers/api_controller_test.rb require 'test_helper' class ApiControllerTest < ActionDispatch::IntegrationTest test "should get attributeTypes" do get api_attributeTypes_url parsed_json = ActiveSupport::JSON.decode(@response.body) assert parsed_json["attribute_types_string"][0]["code"] == "LA" assert parsed_json["attribute_types_number"][0]["code"] == "Ops" assert_response :success end test "should return all hospitals in json format" do get api_hospitals_url parsed_json = ActiveSupport::JSON.decode(@response.body) assert parsed_json[0]["name"] == "Inselspital" assert parsed_json[0]["hospital_attributes"][0]["code"] == "Ops" #get upload_path(id: 345) #response.body end end <file_sep>/test/helpers/geocoder_test.rb require 'test_helper' class GeocoderTest < ActiveSupport::TestCase def setup @address = hospitals(:Insel).streetAndNumber + ", " + hospitals(:Insel).zipCodeAndCity end test "Should return coordinates" do @coordinates = Geocoder.coordinates(@address) assert @coordinates[0] == 46.9477087 assert @coordinates[1] == 7.4255497 end end<file_sep>/app/helpers/attribute_types_helper.rb module AttributeTypesHelper def read_and_store_attribute_types(sheet) @types = Array.new @desc = ['','',''] i = 1 s = 'string' while i < sheet.rows.length row = sheet.row(i) if row[0].present? if row[1].present? @code = (row[0]+row[1]) else @code = (row[0]) end else if row[2].present? s = 'number' if row[2] == 'Akutbehandlung' || row[2] == 'Psychiatrie' || row[2] == 'Rehabilitation / Geriatrie' || row[2] == 'Geburtshaus' @desc[0] = row[2] + ': ' @desc[1] = row[3] + ': ' @desc[2] = row[4] + ': ' end end end if @code == 'AnzStand' s = 'number' end if @code == 'SA' s = 'string' end if @code == 'Amb' || @code == 'Stat' || @code == 'Amb, Stat' || @code == 'Inst, Adr, Ort' || @code == 'KT' || @code == 'Standort' || @code.equal?('KZ-Code') i += 1 next end if !AttributeType.where(code: @code).exists? @types << AttributeType.create(code: @code, nameDE: @desc[0]+row[2], nameFR: @desc[1]+row[3], nameIT: @desc[2]+row[4], category: s) end i += 1 end return @types end end <file_sep>/test/models/hospital_location_test.rb require 'test_helper' class HospitalLocationTest < ActiveSupport::TestCase def setup @hospital_location = hospital_locations(:InselOne) end test "hospital location should be valid" do assert @hospital_location.valid? end test "name should be present" do @hospital_location.name = "" assert_not @hospital_location.valid? end test "reference to hospital should be present" do @hospital_location.hospital_id = nil assert_not @hospital_location.valid? end test "name, streetAndNumber and zipCodeAndCity should be unique" do hospital_location_duplicate = hospital_locations(:InselTwo) assert hospital_location_duplicate.valid? hospital_location_duplicate.name = @hospital_location.name hospital_location_duplicate.streetAndNumber = "New street and number" assert hospital_location_duplicate.valid? hospital_location_duplicate.streetAndNumber = @hospital_location.streetAndNumber hospital_location_duplicate.zipCodeAndCity = "New zip code and city" assert hospital_location_duplicate.valid? hospital_location_duplicate.zipCodeAndCity = @hospital_location.zipCodeAndCity assert_not hospital_location_duplicate.valid? end end <file_sep>/test/controllers/uploads_controller_test.rb require 'test_helper' class UploadsControllerTest < ActionDispatch::IntegrationTest test "should get index" do get uploads_index_url assert_response :success end test "should get new" do get uploads_new_url assert_response :success end test "should get create and then destroy" do get uploads_create_path(upload: {name: "test", attachment: 'files/kzp16_daten.xls'}) assert_redirected_to(:controller => "uploads") id = Upload.find_by_name("test").id get uploads_destroy_path(id: id) assert_redirected_to(:controller => "uploads") end end <file_sep>/app/controllers/locations_controller.rb include LocationsHelper class LocationsController < ApplicationController def parse upload = Upload.find(params[:id]) data = Spreadsheet.open 'public'+upload.attachment_url sheet = data.worksheet params[:sheet] returns = read_and_store_locations(sheet) @locs = returns[0] @errors = returns[1] end end <file_sep>/test/controllers/hospitals_controller_test.rb require 'test_helper' class HospitalsControllerTest < ActionDispatch::IntegrationTest setup do @id = hospitals(:Insel).id end test "should get index" do get hospitals_index_url assert_response :success end test "should return hospital with params id" do get hospitals_details_path(id: @id) assert_response :success end end <file_sep>/test/controllers/parsers_controller_test.rb require 'test_helper' class ParsersControllerTest < ActionDispatch::IntegrationTest end <file_sep>/test/controllers/locations_controller_test.rb require 'test_helper' class LocationsControllerTest < ActionDispatch::IntegrationTest end <file_sep>/app/models/hospital_location.rb class HospitalLocation < ApplicationRecord validates(:name, presence: true, uniqueness: {scope: [:streetAndNumber, :zipCodeAndCity]}) validates(:hospital_id, presence: true) belongs_to :hospital end <file_sep>/app/controllers/parsers_controller.rb require 'spreadsheet' class ParsersController < ApplicationController Spreadsheet.client_encoding = 'UTF-8' def details @upload = Upload.find(params[:id]) @data = Spreadsheet.open 'public'+@upload.attachment_url @kennZ = @data.worksheet 1 end def parse @upload = Upload.find(params[:id]) @name = (params[:sheet]) @data = Spreadsheet.open 'public'+@upload.attachment_url @sheet = @data.worksheet @name end end <file_sep>/db/migrate/20180512132130_create_attribute_types.rb class CreateAttributeTypes < ActiveRecord::Migration[5.2] def change create_table :attribute_types do |t| t.string :code t.string :category t.string :nameDE t.string :nameFR t.string :nameIT t.timestamps end end end <file_sep>/test/helpers/attribute_types_helper_test.rb require 'test_helper' include AttributeTypesHelper class AttributeTypesHelperTest < ActionDispatch::IntegrationTest test "should store attribute types from excel" do sheet_name = "Kennzahlen" data = Spreadsheet.open Rails.root.join("test/fixtures/files/kzp16_daten.xls") sheet = data.worksheet sheet_name read_and_store_attribute_types(sheet) assert_nil AttributeType.find_by_code("Amb") assert_nil AttributeType.find_by_code("Stat") assert_nil AttributeType.find_by_code("Amb, Stat") assert_nil AttributeType.find_by_code("Inst, Adr, Ort") assert AttributeType.find_by_code("AnzStand").category == "number" assert AttributeType.find_by_code("KT").category == "string" end end<file_sep>/app/helpers/hospitals_helper.rb module HospitalsHelper def get_coordinates(hospital) if hospital.zipCodeAndCity == nil return 'No address found for: ' + hospital.name end if hospital.streetAndNumber == nil address = hospital.zipCodeAndCity else address = hospital.streetAndNumber + ", " + hospital.zipCodeAndCity end sleep(0.2) begin @coordinates = Geocoder.coordinates(address) rescue => error return 'No coordinates found for: ' + hospital.name + ' ' + address end if @coordinates != nil hospital.latitude = @coordinates[0] hospital.longitude = @coordinates[1] hospital.save else return 'No coordinates found for: ' + hospital.name + ' ' + address end end def read_and_store_hospitals(sheet, sheet_name) @legend = sheet.row(0) @hosps = Array.new @year = sheet_name.gsub(/[^0-9]/,'')[0..3] j = 0 while j < sheet.rows.length @hospital = sheet.row(j) @hospData = Hash.new i = 0 while i < @legend.length @hospData.store(@legend[i], @hospital[i]) @hospData.delete("Amb") @hospData.delete("Stat") @hospData.delete("Amb, Stat") i += 1 end if @hospData["Inst"] != nil && @hospData["Inst"] != "Inst" if !Hospital.exists?(name: @hospData["Inst"]) @hosp = Hospital.create(name:@hospData["Inst"], streetAndNumber:@hospData["Adr"], zipCodeAndCity:@hospData["Ort"]) @hosps << @hosp else @hosp = Hospital.where(name:@hospData["Inst"]).first end @hospData.each do |attr| @attribute = @hosp.hospital_attributes.create(code:attr[0], value:attr[1], year:@year) end end j += 1 end return @hosps end end <file_sep>/test/models/upload_test.rb require 'test_helper' class UploadTest < ActiveSupport::TestCase def setup @upload = Upload.new(name: "upload", attachment: 'files/kzp16_daten.xls') end test "upload should be vaild" do assert @upload.valid? end test "name should be present" do @upload.name = "" assert_not @upload.valid? end end <file_sep>/app/models/hospital_attribute.rb class HospitalAttribute < ApplicationRecord validates(:code, presence: true) validates(:year, presence: true) validates(:value, presence: true) validates(:hospital_id, presence: true) validates(:code, uniqueness: {scope: [:year, :hospital_id]}) belongs_to :hospital, touch: true end <file_sep>/test/models/attribute_type_test.rb require 'test_helper' class AttributeTypeTest < ActiveSupport::TestCase def setup @attribute_type = attribute_types(:KT) end test "hospital attribute should be valid" do assert @attribute_type.valid? end test "code should be present" do @attribute_type.code = "" assert_not @attribute_type.valid? end test "nameDE should be present" do @attribute_type.nameDE = "" assert_not @attribute_type.valid? end test "nameFR should be present" do @attribute_type.nameFR = "" assert_not @attribute_type.valid? end test "nameIT should be present" do @attribute_type.nameIT = "" assert_not @attribute_type.valid? end test "category should be present with value string or number" do @attribute_type.category = "" assert_not @attribute_type.valid? @attribute_type.category = "hallo" assert_not @attribute_type.valid? @attribute_type.category = "string" assert @attribute_type.valid? @attribute_type.category = "number" assert @attribute_type.valid? end test "code should be unique" do attribute_type_duplicate = attribute_types(:Ops) attribute_type_duplicate.code = @attribute_type.code.downcase assert attribute_type_duplicate.valid? attribute_type_duplicate.code = @attribute_type.code assert_not attribute_type_duplicate.valid? end end <file_sep>/app/helpers/locations_helper.rb module LocationsHelper def read_and_store_locations(sheet) @legend = sheet.row(0) @hospitals = Array.new @locs = Array.new @errors = Array.new j = 1 while j < sheet.rows.length @location = sheet.row(j) @LocationData = Hash.new i = 0 while i < @legend.length @LocationData.store(@legend[i], @location[i]) i += 1 end @hospital = Hospital.where(name: @LocationData["Inst"]).first if @hospital == nil @errors << 'Not found ' + @LocationData["Inst"] else if !(@hospital.streetAndNumber == (@LocationData["Adr_Standort"])) @locs << @hospital.hospital_locations.create(name: @LocationData["Standort"], kanton: @LocationData["KT"], streetAndNumber: @LocationData["Adr_Standort"], zipCodeAndCity: @LocationData["Ort_Standort"], la: @LocationData["LA"]) end end j += 1 end return [@locs, @errors] end end <file_sep>/app/models/attribute_type.rb class AttributeType < ApplicationRecord validates(:code, presence: true, uniqueness: true) validates(:category, presence: true, inclusion: { in: %w(string number) }) validates(:nameDE, presence: true) validates(:nameFR, presence: true) validates(:nameIT, presence: true) end <file_sep>/test/helpers/hospitals_helper_test.rb require 'test_helper' include HospitalsHelper class HospitalsHelperTest < ActionDispatch::IntegrationTest test "should get coordinates for hospital" do hospital = hospitals(:NoCoords) get_coordinates(hospital) updatedHospital = hospitals(:NoCoords) assert_not_nil updatedHospital.latitude assert_not_nil updatedHospital.longitude end test "should store hospitals from excel" do sheet_name = "KZ2016_KZP16" data = Spreadsheet.open Rails.root.join("test/fixtures/files/kzp16_daten.xls") sheet = data.worksheet sheet_name hosps = read_and_store_hospitals(sheet, sheet_name) hospital = Hospital.find_by_name("<NAME>") assert hosps.count == 2 assert_not_nil hospital assert_not_nil HospitalAttribute.where(:hospital_id => hospital.id, :year => 2016) end end<file_sep>/app/models/hospital.rb class Hospital < ApplicationRecord validates(:name, presence: true, uniqueness: {case_sensitive: false}) has_many :hospital_locations, :dependent => :destroy has_many :hospital_attributes, :dependent => :destroy def self.cache_key(hospitals) { serializer: 'hospitals', stat_record: hospitals.maximum(:updated_at) } end end <file_sep>/app/controllers/hospitals_controller.rb include HospitalsHelper class HospitalsController < ApplicationController def index @hospitals = Hospital.all end def details @hospital = Hospital.find(params[:id]) end def coords_single @hospital = Hospital.find(params[:id]) error = get_coordinates(@hospital) @message = case error when true "Geocoding successfull" when false "Validation and saving of hospital failed" else error end end def edit @hospital = Hospital.find(params[:id]) end def delete if Hospital.destroy(params[:id]) render 'deleted' else render 'edit' end end def parse upload = Upload.find(params[:id]) sheet_name = params[:sheet] data = Spreadsheet.open 'public'+upload.attachment_url sheet = data.worksheet sheet_name @hosps = read_and_store_hospitals(sheet, sheet_name) end def coords @hospitals = Hospital.where(latitude: nil) @errors = Array.new @hospitals.each do |hospital| error = get_coordinates(hospital) case error when true when false @errors << "Validation and saving of hospital failed" else @errors << error end hospital.hospital_locations.each do |loc| error = get_coordinates(loc) case error when true when false @errors << "Validation and saving of location failed" else @errors << error end end end end end <file_sep>/config/routes.rb Rails.application.routes.draw do # Hospital Locations post 'locations/parse' # Hospitals get 'hospitals/coords' get 'hospitals/details' get 'hospitals/index' get 'hospitals/edit' post 'hospitals/delete' post 'hospitals/coords_single' post 'hospitals/parse' # API get 'api/hospitals' get 'api/attributeTypes' # attribute types get 'attribute_types/index' post 'attribute_types/parse' # Excel Parser get 'parsers/details' get 'parsers/parse' # Uploads resources :uploads, only: [:index, :new, :create, :destroy] get 'uploads/index' get 'uploads/new' get 'uploads/create' get 'uploads/destroy' root 'uploads#index' end
59293f3c823392f57d133b79460a9ab09970cef9
[ "Ruby" ]
30
Ruby
UniDomi/geopitalBackend
da012e32cc403c5b4a53ad77075daee3c741d953
91961053a50eb3822ffa1993310c879a576c2d72
refs/heads/master
<file_sep>/* * resultset.h * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-11-26 * */ #pragma once #include <string> namespace senrigan { class ResultSet { public: virtual bool next() = 0; virtual int64_t rowsCount() = 0; virtual bool getBoolean(const std::string &key) = 0; bool getBoolean(const char *key) { return getBoolean(std::string(key)); } virtual double getDouble(const std::string &key) = 0; double getDouble(const char *key) { return getDouble(std::string(key)); } virtual int32_t getInt(const std::string &key) = 0; int32_t getInt(const char *key) { return getInt(std::string(key)); } virtual std::string getString(const std::string &key) = 0; std::string getString(const char *key) { return getString(std::string(key)); } }; } // namespace senrigan <file_sep>/* * image.h * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-11-28 * */ #pragma once #include <memory> #include <string> #include <vector> #include "position.h" namespace senrigan { class Image { public: std::shared_ptr<Image> copyTo(std::string path); // void toCvMat(); int64_t id() const { return id_; } std::string path() const { return path_; } double theta() const { return theta_; } const Position& position() const { return position_; } const std::vector<int>& src_ids() const { return src_ids_; } bool is_processed() const { return is_processed_; } const std::string& created_at() const { return created_at_; } static std::shared_ptr<Image> create(int64_t id, std::string path, const Position& position, double theta, bool is_processed, std::string created_at); static std::shared_ptr<Image> create(std::string path, const Position& position, double theta, std::vector<int> src_ids, std::string created_at); private: Image(int64_t id, std::string path, const Position& position, double theta, std::vector<int> src_ids, bool is_processed, std::string created_at); int64_t id_; std::string path_; double theta_; Position position_; std::vector<int> src_ids_; bool is_processed_; std::string created_at_; }; } <file_sep>CREATE TABLE `image_master_table` ( `image_id` int(11) NOT NULL auto_increment, `path` varchar(255) NOT NULL, `latitude` double NOT NULL, `longitude` double NOT NULL, `height` double NOT NULL, `row` double NOT NULL, `pitch` double NOT NULL, `yaw` double NOT NULL, `image_size_height` int(11) NOT NULL, `image_size_width` int(11) NOT NULL, `created_date` timestamp NULL DEFAULT NULL, `converted` tinyint(1) DEFAULT '0', PRIMARY KEY (`image_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `image_processed_tables` ( `id` int(11) NOT NULL AUTO_INCREMENT, `path` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `x` int(11) DEFAULT NULL, `y` int(11) DEFAULT NULL, `z` int(11) DEFAULT NULL, `create_date` datetime DEFAULT NULL, `taken_date` datetime DEFAULT NULL, `theta` int(11) DEFAULT NULL, `height` int(11) DEFAULT NULL, `width` int(11) DEFAULT NULL, `source_image_ids` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `position_index` (`x`,`y`,`z`,`theta`,`height`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; <file_sep>/* * crawler.h * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-11-28 * */ #pragma once #include <memory> #include <vector> namespace senrigan { class Database; class Position; class Crawler { public: Crawler(std::shared_ptr<Database> database); std::vector<std::shared_ptr<Position>> waitUntilNewPlace(); private: std::shared_ptr<Database> database_; }; } <file_sep>{ 'includes': [ 'common.gypi', ], 'targets': [ { 'target_name': 'combinator', 'product_name': 'SenriganCombinator', 'type': 'executable', 'include_dirs': [ '../combinator', ], 'sources': [ '../combinator/cell.cpp', '../combinator/combinator.cpp', '../combinator/crawler.cpp', '../combinator/image.cpp', '../combinator/imageprocessor.cpp', '../combinator/main.cpp', '../combinator/mysqldatabase.cpp', '../combinator/mysqlresultset.cpp', '../combinator/position.cpp', '../combinator/utils.cpp', ], 'link_settings': { 'libraries': [ '-lmysqlcppconn', '-lyaml-cpp', '-lglog' ], } } ] } <file_sep>/* * utils.cpp * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2015-01-05 * */ #include "utils.h" #include <time.h> using namespace senrigan; using namespace std; string senrigan::current_datetime(string format) { time_t now = time(nullptr); const struct tm* tstruct = localtime(&now); char buf[80]; strftime(buf, sizeof(buf), format.c_str(), tstruct); return string(buf); } <file_sep>/* * cell.cpp * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-12-18 * */ #include "cell.h" #include <exception> #include <map> #include <glog/logging.h> #include "database.h" #include "position.h" #include "image.h" #include "imageprocessor.h" #include "utils.h" using namespace senrigan; using namespace std; // TODO: position should wrap in the center of each cell Cell::Cell(shared_ptr<Database> database, shared_ptr<Position> position) : database_(database), position_(*position) { LOG(INFO) << position->toString() << endl; // Retrieve images related to this position // TODO: yaw will be renamed to theta or direction const string pickup_sql = string("select image_id, path, latitude, longitude, " "height, yaw, converted, created_date " "from image_master_table where ") + position->toSQLCondition(Position::LATITUDE | Position::LONGITUDE | Position::HEIGHT); LOG(INFO) << pickup_sql << endl; // TODO: pick images up which are related to this cell and store to // [[images_]] database_->open(); shared_ptr<ResultSet> result = database_->execute(pickup_sql); database_->close(); // Store each image information into [[Image]] container while(result->next()) { int32_t image_id = result->getInt("image_id"); string path = result->getString("path"); double theta = result->getDouble("yaw"); string created_at = result->getString("created_date"); LOG(INFO) << "---- Query Result ----" << endl << "image_id: " << image_id << endl << "path: " << path << endl << "latitude: " << result->getDouble("latitude") << endl << "longitude: " << result->getDouble("longitude") << endl << "height: " << result->getDouble("height") << endl << "theta: " << theta << endl << "created_at: " << created_at << endl; auto image = Image::create(image_id, path, position_, theta, result->getBoolean("converted"), created_at); images_.push_back(image); } } // static shared_ptr<Cell> Cell::create(shared_ptr<Database> database, shared_ptr<Position> position) { shared_ptr<Cell> cell(new Cell(database, position)); return cell; } void Cell::update(shared_ptr<ImageProcessor> processor) { // TODO: implement here LOG(INFO) << "Cell::update(): started!" << endl; // Search the latest four images map<ImageProcessor::Direction, shared_ptr<Image>> nesw_images; for (auto image : images_) { ImageProcessor::Direction key; if (image->theta() > 315 || image->theta() < 45) key = ImageProcessor::NORTH; else if (image->theta() < 135) key = ImageProcessor::EAST; else if (image->theta() < 225) key = ImageProcessor::SOUTH; else key = ImageProcessor::WEST; if (!nesw_images[key] || nesw_images[key]->created_at() < image->created_at()) nesw_images[key] = image; } LOG(INFO) << "start processing! num of images: " << images_.size() << ", " <<nesw_images.size(); auto processed_images = processor->process(nesw_images); LOG(INFO) << "processed! generated: " << processed_images.size(); // Update Database database_->open(); database_->executeUpdate("start transaction"); // Mark as processed for (auto image_pair : nesw_images) { auto image = image_pair.second; if (!image->is_processed()) { stringstream sql; sql << "update image_master_table set converted = True where image_id = " << image->id(); LOG(INFO) << sql.str() << endl; database_->executeUpdate(sql.str()); LOG(INFO) << "image_id = " << image->id() << endl; } } // Insert information of new images for (auto image_pair : processed_images) { stringstream sql; sql << "insert into image_processed_tables " "(path, x, y, z, create_date, taken_date, " "theta, height, width, source_image_ids) " "values "; auto image = image_pair.second; LOG(INFO) << "id: " << image->id() << ", " << "path: " << image->path(); // Set each parameter sql << "(" << "\"" << image->path() << "\", " << image->position().x() << ", " << image->position().y() << ", " << image->position().z() << ", " << "\"" << current_datetime() << "\", " << "\"" << image->created_at() << "\", " << image->theta() << ", " << 0 << ", " << 0 << ", "; // TODO: source_image_ids should be an array of integer int64_t src_id = -1; if (!image->src_ids().empty()) { src_id = image->src_ids()[0]; sql << src_id; } else { sql << "null"; } sql << ") "; sql << "on duplicate key update " << "path = \"" << image->path() << "\", " << "create_date = \"" << current_datetime() << "\", " << "source_image_ids = "; if (src_id > 0) sql << src_id; else sql << "null"; // Execute SQL database_->executeUpdate(sql.str()); LOG(INFO) << "QUERY: " << sql.str(); } // Finalize Database database_->executeUpdate("commit"); database_->close(); LOG(INFO) << "Cell::update(): finished!" << endl; } <file_sep>//! g++ -o main.bin main.cpp -W -Wall -std=c++0x #include "combinator.h" int main(int argc, char* argv[]) { senrigan::Combinator combinator; return combinator.run(argc, argv); } <file_sep>/* * imageprocessor.h * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-12-22 * */ #pragma once #include <map> #include <memory> #include <string> #include <yaml-cpp/yaml.h> namespace senrigan { class Database; class Image; class ImageProcessor { public: enum Direction { NORTH, SOUTH, WEST, EAST }; ImageProcessor(const YAML::Node& config); std::map<Direction, std::shared_ptr<Image>> process( const std::map<Direction, std::shared_ptr<Image>> input_nesw_image); private: std::string out_dir_; }; }; // namespace senrigan <file_sep>/* * combinator.h * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-11-26 * */ #pragma once #include <string> namespace senrigan { class Combinator { public: int run(int argc, const char * const argv[]); }; } <file_sep>/* * debug.h * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-11-26 * */ #pragma once #ifdef DEBUG # include <cassert> # define DCHECK(expr) assert(expr) #else # define DCHECK(expr) #endif <file_sep>Requirements ---- * g++ * ninja On ubuntu, you can install ninja using `apt` as ``` $ sudo apt-get install ninja-build ``` Install ---- ``` $ cd tools/gyp $ python setup.py install # if you use system-wide python, sudo is needed $ cd ../../third_party/ $ cd mysql-connector-c++-1.1.4 $ cmake . && make -j5 && sudo make install $ cd ../yaml-cpp-0.5.1 $ cmake . && make -j5 && sudo make install $ cd ../google-glog $ ./configure && make -j5 && sudo make install $ cd ../../ ``` How to build ---- ``` $ gyp -f ninja --depth . build/combinator.gyp # generate build.ninja $ ninja -C out/Release ``` How to Execute ---- w/o logging ``` $ ./out/Release/SenriganCombinator ``` w/ logging ``` $ mkdir log $ GLOG_log_dir=./log ./out/Release/SenriganCombinator ``` <file_sep>/* * mysqlresultset.cpp * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-11-26 * */ #include "mysqlresultset.h" #include "debug.h" using namespace senrigan; MySQLResultSet::MySQLResultSet(sql::ResultSet *raw_results) : results_(raw_results) { DCHECK(raw_results != nullptr); } <file_sep>/* * combinator.cpp * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-11-26 * */ #include "combinator.h" #include <iostream> #include <memory> #include <vector> #include <glog/logging.h> #include <yaml-cpp/yaml.h> #include "cell.h" #include "cmdline.h" #include "crawler.h" #include "image.h" #include "mysqldatabase.h" #include "imageprocessor.h" using namespace senrigan; using namespace std; int Combinator::run(int argc, const char * const argv[]) { google::InitGoogleLogging(argv[0]); cmdline::parser parser; parser.add<string>( "config", 'c', "path to configurations in yaml", false, string("config/config.yml")); parser.add("help", 'h', "print help"); if (!parser.parse(argc, argv) || parser.exist("help")) { cerr << parser.error_full() << parser.usage(); return 1; } // Parse configuration file string yaml_path = parser.get<string>("config"); LOG(INFO) << "yaml: " << yaml_path << endl; YAML::Node config = YAML::LoadFile(yaml_path); if (!config["database"] || !config["processor"]) throw runtime_error("Config file must set the parameters: " "{database: {...}, processor: {}}"); // Configure each components shared_ptr<Database> database(new MySQLDatabase(config["database"])); shared_ptr<Crawler> crawler(new Crawler(database)); shared_ptr<ImageProcessor> processor(new ImageProcessor(config["processor"])); // Main Loop // TODO: Move to another thread while (1) { LOG(INFO) << "Crawler::waitUntilNewPlace()" << endl; auto positions = crawler->waitUntilNewPlace(); for (auto position : positions) { LOG(INFO) << "Cell::create()" << endl; auto cell = Cell::create(database, position); LOG(INFO) << "Cell::update()" << endl; cell->update(processor); } } return 0; } <file_sep>create user `user` identified by '<PASSWORD>'; create database senrigandb; grant all on senrigandb.* to `user`; <file_sep>/* * mysqldatabase.cpp * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-11-27 * */ #include "mysqldatabase.h" #include <exception> #include <iostream> #include <cppconn/connection.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <mysql_connection.h> #include <mysql_driver.h> #include "mysqlresultset.h" using namespace senrigan; using namespace std; MySQLDatabase::MySQLDatabase(const YAML::Node &config) { // Validate settings if (!(config["user"] && config["password"] && config["host"] && config["dbname"])) { throw runtime_error("Config file must set the parameters: " "{database: {user:, password:, host:, dbname:}}"); } // Connect to mysql auto driver = sql::mysql::get_mysql_driver_instance(); shared_ptr<sql::Connection> connection( driver->connect(config["host"].as<string>(), config["user"].as<string>(), config["password"].as<string>())); // Set member variables dbname_ = config["dbname"].as<string>(); connection_ = connection; } bool MySQLDatabase::open() { // TODO: Check if this is succeeded shared_ptr<sql::Statement> statement(connection_->createStatement()); statement_ = statement; statement_->execute(string("use ") + dbname_); return true; } void MySQLDatabase::close() { } shared_ptr<ResultSet> MySQLDatabase::execute(const std::string &sql) { return shared_ptr<ResultSet> ( new MySQLResultSet(statement_->executeQuery(sql))); } int MySQLDatabase::executeUpdate(const std::string &sql) { return statement_->executeUpdate(sql); } <file_sep>/* * crawler.cpp * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-11-28 * */ #include "crawler.h" #include <glog/logging.h> #include <unistd.h> #include "database.h" #include "position.h" using namespace senrigan; using namespace std; Crawler::Crawler(shared_ptr<Database> database) : database_(database) { } vector<shared_ptr<Position>> Crawler::waitUntilNewPlace() { LOG(INFO) << "waiting new data...." << endl; vector<shared_ptr<Position>> positions; // TODO: yaw will be changed const string target_position_sql = "select latitude, longitude, height " "from image_master_table where converted = False " "group by latitude, longitude, height"; database_->open(); auto result = database_->execute(target_position_sql); int64_t n_rows = result->rowsCount(); LOG(INFO) << "n_rows: " << n_rows << endl; // When nothing was found while (n_rows == 0) { LOG(INFO) << "wait for 10s..." << endl; sleep(10); // Search result = database_->execute(target_position_sql); n_rows = result->rowsCount(); LOG(INFO) << "n_rows: " << n_rows << endl; } // When some updates were found while (result->next()) { double longitude = result->getDouble("longitude"); double latitude = result->getDouble("latitude"); double height = result->getDouble("height"); shared_ptr<Position> position(new Position(longitude, latitude, height)); positions.push_back(position); } database_->close(); LOG(INFO) << "generated!: num = " << positions.size() << endl; return positions; } <file_sep>/* * position.h * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-12-12 * */ #pragma once #include <iomanip> #include <iostream> #include <string> #include <sstream> #include <utility> namespace senrigan { class Position { public: // TODO: Implement me // Position(int64_t _x, int64_t _y, int64_t _z, double _theta = 0.0) : // longitude_(_x), latitude_(_y), height_(_z), theta_(_theta) {}; Position(double _longitude, double _latitude, double _height, double _theta = 0.) : longitude_(_longitude), latitude_(_latitude), height_(_height), theta_(_theta) {}; /* the origin point is on four corners of meshes */ int64_t x() const { return to_x(longitude_); } int64_t y() const { return to_y(latitude_); } int64_t z() const { return to_z(height_); } double longitude() const { return longitude_; } double latitude() const { return latitude_; } double height() const { return height_; } double theta() const { return theta_; } // Utilities // Return a pair of (lower bound, higher bound) std::pair<double, double> range_longitude() const; std::pair<double, double> range_latitude() const; std::pair<double, double> range_height() const; // enum Element { X = 1 << 1, Y = 1 << 2, Z = 1 << 3, LONGITUDE = 1 << 4, LATITUDE = 1 << 5, HEIGHT = 1 << 6, THETA = 1 << 7 }; // [[flag]] is OR-ed [[Element]] enum std::string toSQLCondition(uint32_t flag) const; std::string toString() const; private: double longitude_, latitude_, height_, theta_; // Converters static int64_t to_x(double longitude); static int64_t to_y(double latitude); static int64_t to_z(double height); static double to_longitude(int64_t x); // calculate the lower bound of x static double to_latitude(int64_t y); // calculate the lower bound of y static double to_height(int64_t z); // calculate the lower bound of z // Constants static const double mesh_scale_; static const double longitude_unit_size_; // Unit: [deg/m] static const double latitude_unit_size_; // Unit: [deg/m] static const double height_unit_size_; // Unit: [m/m] }; }; // namespace senrigan <file_sep>/* * database.h * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-11-26 * */ #pragma once #include <memory> #include <string> #include "resultset.h" namespace senrigan { class Database { public: virtual bool open() = 0; virtual void close() = 0; virtual std::shared_ptr<ResultSet> execute(const std::string &sql) = 0; virtual int executeUpdate(const std::string &sql) = 0; }; }; <file_sep>/* * mysqlresultset.h * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-11-26 * */ #pragma once #include <memory> #include <string> #include <cppconn/resultset.h> #include "resultset.h" namespace senrigan { class MySQLResultSet : public ResultSet { public: MySQLResultSet(sql::ResultSet *raw_results); bool next() override { return results_->next(); } int64_t rowsCount() override { return results_->rowsCount(); } bool getBoolean(const std::string &key) override { return results_->getBoolean(key); } double getDouble(const std::string &key) override { return results_->getDouble(key); } int32_t getInt(const std::string &key) override { return results_->getInt(key); } std::string getString(const std::string &key) override { return results_->getString(key); } private: std::shared_ptr<sql::ResultSet> results_; }; } // namespace senrigan <file_sep>/* * imageprocessor.cpp * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-12-22 * */ #include "imageprocessor.h" #include <exception> #include <glog/logging.h> #include "image.h" using namespace senrigan; using namespace std; static string basename(const string& path) { return path.substr(path.find_last_of('/') + 1); } ImageProcessor::ImageProcessor(const YAML::Node& config) { if (!config["output_dir"]) throw runtime_error("Config file must set the parameters: " "{processor: {output_dir:}}"); out_dir_ = config["output_dir"].as<string>(); LOG(INFO) << "ImageProcessor: output_dir = \"" << out_dir_ << "\""; } map<ImageProcessor::Direction, shared_ptr<Image>> ImageProcessor::process( const map<ImageProcessor::Direction, shared_ptr<Image>> input_nesw_image) { map<ImageProcessor::Direction, shared_ptr<Image>> output_nesw_image; for (auto image_pair : input_nesw_image) { auto image = image_pair.second; string filename = basename(image->path()); string out_path = out_dir_ + "/" + filename; auto out_image = image->copyTo(out_path); output_nesw_image[image_pair.first] = out_image; LOG(INFO) << "Image is copied to " << out_path; } return output_nesw_image; } <file_sep>/* * cell.h * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-12-18 * */ #pragma once #include <memory> #include <vector> #include <yaml-cpp/yaml.h> #include "position.h" namespace senrigan { class Database; class Image; class ImageProcessor; class Cell { public: void update(std::shared_ptr<ImageProcessor> processor); static std::shared_ptr<Cell> create(std::shared_ptr<Database> database, std::shared_ptr<Position> position); private: Cell(std::shared_ptr<Database> database, std::shared_ptr<Position> position); // TODO: Change the type of container to make it faster to search a image std::vector<std::shared_ptr<Image>> images_; std::shared_ptr<Database> database_; Position position_; }; }; <file_sep>/* * position.cpp * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2015-01-08 * */ #include "position.h" #include <math.h> using namespace senrigan; using namespace std; // static const double Position::mesh_scale_ = 1.0; // static const double Position::longitude_unit_size_ = 0.000010966382364; // static const double Position::latitude_unit_size_ = 0.000008983148616; // static const double Position::height_unit_size_ = 1.0; // static int64_t Position::to_x(double longitude) { return floor(longitude / (mesh_scale_ * longitude_unit_size_)); } // static int64_t Position::to_y(double latitude) { return floor(latitude / (mesh_scale_ * latitude_unit_size_)); }; // static int64_t Position::to_z(double height) { return floor(height / (mesh_scale_ * height_unit_size_)); } // static double Position::to_longitude(int64_t x) { return mesh_scale_ * longitude_unit_size_ * x; } // static double Position::to_latitude(int64_t y) { return mesh_scale_ * latitude_unit_size_ * y; } // static double Position::to_height(int64_t z) { return mesh_scale_ * height_unit_size_ * z; } pair<double, double> Position::range_longitude() const { double lower = to_longitude(x()); double higher = to_longitude(x()+1); return pair<double, double>(lower, higher); } pair<double, double> Position::range_latitude() const { double lower = to_latitude(y()); double higher = to_latitude(y()+1); return pair<double, double>(lower, higher); } pair<double, double> Position::range_height() const { double lower = to_height(z()); double higher = to_height(z()+1); return pair<double, double>(lower, higher); } static inline void maybe_append_add_operator(bool& is_first, stringstream& sql) { if (is_first) is_first = false; else sql << "and "; } string Position::toSQLCondition(uint32_t flag) const { stringstream sql; bool is_first = true; // Set format sql << setprecision(20); if (flag & X) { maybe_append_add_operator(is_first, sql); sql << "x = " << x() << " "; } if (flag & Y) { maybe_append_add_operator(is_first, sql); sql << "y = " << y() << " "; } if (flag & Z) { maybe_append_add_operator(is_first, sql); sql << "z = " << z() << " "; } if (flag & LONGITUDE) { maybe_append_add_operator(is_first, sql); auto range = range_longitude(); sql << "longitude >= " << range.first << " and "; sql << "longitude < " << range.second << " "; } if (flag & LATITUDE) { maybe_append_add_operator(is_first, sql); auto range = range_latitude(); sql << "latitude >= " << range.first << " and "; sql << "latitude < " << range.second << " "; } if (flag & HEIGHT) { maybe_append_add_operator(is_first, sql); auto range = range_height(); sql << "height >= " << range.first << " and "; sql << "height < " << range.second << " "; } if (flag & THETA) { maybe_append_add_operator(is_first, sql); sql << "theta = " << theta() << " "; } return sql.str(); } string Position::toString() const { stringstream str; // Set format str << setprecision(20); str << "<Position: " << "longitude = " << longitude_ << ", " << "latitude = " << latitude_ << ", " << "height = " << height_ << ", " << "theta = " << theta_ << ", " << "x = " << x() << ", " << "y = " << y() << ", " << "z = " << z() << ", " << "mesh_longitude_range = (" << to_longitude(x()) << ", " << to_longitude(x()+1) << "), " << "mesh_latitude_range = (" << to_latitude(y()) << ", " << to_latitude(y()+1) << "), " << "mesh_height_range = (" << to_height(z()) << ", " << to_height(z()+1) << "), " << ">"; return str.str(); } <file_sep>/* * mysqldatabase.h * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-11-27 * */ #pragma once #include "database.h" #include <memory> #include <cppconn/connection.h> #include <cppconn/statement.h> #include <yaml-cpp/yaml.h> namespace senrigan { class MySQLDatabase : public Database { public: MySQLDatabase(const YAML::Node& config); bool open() override; void close() override; std::shared_ptr<ResultSet> execute(const std::string& sql) override; int executeUpdate(const std::string& sql) override; private: std::string dbname_; std::shared_ptr<sql::Connection> connection_; std::shared_ptr<sql::Statement> statement_; }; } // namespace senrigan <file_sep>/* * utils.h * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2015-01-05 * */ #pragma once #include <string> namespace senrigan { // Default: 2014-01-05 23:00:01 std::string current_datetime(std::string format = "%F %H:%M:%S"); }; <file_sep>/* * image.cpp * * Author: <NAME> <<EMAIL>> * URL: https://amiq11.tumblr.com * License: MIT License * Created: 2014-12-22 * */ #include "image.h" #include <fstream> #include <glog/logging.h> using namespace senrigan; using namespace std; Image::Image(int64_t id, string path, const Position& position, double theta, vector<int> src_ids, bool is_processed, string created_at) : id_(id), path_(path), position_(position), theta_(theta), src_ids_(src_ids), is_processed_(is_processed), created_at_(created_at) { } shared_ptr<Image> Image::create(int64_t id, string path, const Position& position, double theta, bool is_processed, string created_at) { shared_ptr<Image> image( new Image( id, path, position, theta, vector<int> (), is_processed, created_at)); return image; } shared_ptr<Image> Image::create(string path, const Position& position, double theta, vector<int> src_ids, string created_at) { shared_ptr<Image> image( new Image(-1, path, position, theta, src_ids, false, created_at)); return image; } shared_ptr<Image> Image::copyTo(string path) { LOG(INFO) << "copyTo: " << path; // Copy image file ifstream src(path_, ios::binary); ofstream dst(path, ios::trunc | ios::binary); dst << src.rdbuf(); // Create [[Image]] object // TODO: not created_at but current time shared_ptr<Image> dst_image( new Image( id_, path, position_, theta_, src_ids_, is_processed_, created_at_)); return dst_image; }
fa81c4ebb8bd2057a05cb3bebba0f0a78696a7d6
[ "SQL", "Markdown", "Python", "C", "C++" ]
26
C++
cloudpbl-senrigan/combinator
91a45ac5d471f4a7527375db29e06b0fda2eea0d
02faf1ace746672a466f97864590de88e6801b8d
refs/heads/master
<file_sep>==================== period documentation ==================== Contents: .. toctree:: :maxdepth: 5 :numbered: :glob: source_doc/period todo Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` <file_sep># -*- coding: utf-8 -*- import argparse def main(): """main command line utility """ pass <file_sep># -*- coding: utf-8 -*- """setuptools installer for period.""" import os import uuid from pip.req import parse_requirements from setuptools import find_packages from setuptools import setup from setuptools.command.build_py import build_py # local imports try: from build_scripts.version import get_git_version except: pass here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() NEWS = open(os.path.join(here, 'NEWS.rst')).read() version = None try: version = get_git_version() except: pass if version is None or not version: try: file_name = "period/RELEASE-VERSION" version_file = open(file_name, "r") try: version = version_file.readlines()[0] version = version.strip() except Exception: version = "0.0.0" finally: version_file.close() except IOError: version = "0.0.0" class my_build_py(build_py): def run(self): # honor the --dry-run flag if not self.dry_run: target_dirs = [] target_dirs.append(os.path.join(self.build_lib, 'period')) target_dirs.append('period') # mkpath is a distutils helper to create directories for dir in target_dirs: self.mkpath(dir) try: for dir in target_dirs: fobj = open(os.path.join(dir, 'RELEASE-VERSION'), 'w') fobj.write(version) fobj.close() except: pass # distutils uses old-style classes, so no super() build_py.run(self) test_reqs_gen = parse_requirements("test-requirements.txt", session=uuid.uuid1()) reqs_gen = parse_requirements("requirements.txt", session=uuid.uuid1()) setup(name='period', version=version, description="basic time period checking libary for Python", long_description=README + '\n\n' + NEWS, cmdclass={'build_py': my_build_py}, classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: Artistic License", "Operating System :: POSIX :: Linux", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords='date time period', author='<NAME>', author_email='', url='https://github.com/LinkCareServices/period', license='Artistic License 2.0', packages=find_packages(exclude=['ez_setup']), package_data={'': ['*.rst', ], }, include_package_data=True, zip_safe=False, test_suite='nose.collector', tests_require=[str(ir.req) for ir in test_reqs_gen], install_requires=[str(ir.req) for ir in reqs_gen], ) <file_sep>period ====== Period is a basic time period checking library. Period is based on period.py by <NAME>. (available at https://www.biostat.wisc.edu/~annis/creations/period.py.html) and ported to python3 with a few improvements. Period.py was in part inspired by perl's Time::Period module and the time class mechanism of Cfengine. <file_sep>period source documentation =========================== .. automodule:: period <file_sep># -*- coding: utf-8 -*- import pkg_resources __version__ = "unknown" try: __version__ = pkg_resources.resource_string("period", "RELEASE-VERSION").strip() except IOError: __version__ = "0.0.0" from period.main import PeriodParser, PeriodSyntax, Stack, in_period, is_holiday <file_sep># -*- coding: utf-8 -*- # $Id: period.py,v 2.5 2002-01-07 11:07:57-06 annis Exp $ # $Source: /u/annis/code/python/lib/period/RCS/period.py,v $ # # Copyright (c) 2001 - 2002 <NAME>. All rights reserved. # This is free software; you can redistribute it and/or modify it # under the same terms as Perl (the Artistic Licence). Developed at # the Department of Biostatistics and Medical Informatics, University # of Wisconsin, Madison. """Deal with time periods The single function in_period(time, period) determines if a given time period string matches the time given. The syntax is based loosely on the class specifications used in Cfengine (http://www.iu.hioslo.no/cfengine). """ from __future__ import print_function from builtins import range from builtins import object import string import re import time import os WEEK_MAP = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] MONTH_MAP = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] DAYTYPE_MAP = ['Weekday', 'Weekend'] # Used by the PeriodParser class. def _remove_otiose(lst): """lift deeply nested expressions out of redundant parentheses""" listtype = type([]) while type(lst) == listtype and len(lst) == 1: lst = lst[0] return lst class PeriodParser(object): """Parse time period specifications.""" def __init__(self): self.SPECIAL = "().|!" pass def parse(self, str=None): if str: self.str = str self.i = 0 self.len = len(str) self.level = 0 expr = [] tok = self.get_token() while tok != '': if tok == ')': self.level = self.level - 1 if self.level < 0: break # too many closing parens... catch error below else: return expr elif tok == '(': self.level = self.level + 1 sexpr = _remove_otiose(self.parse()) expr.append(sexpr) else: expr.append(tok) tok = self.get_token() # If the level isn't correct, then some extra parens are # involved. Complain about that. if self.level == 0: return expr elif self.level > 0: raise Exception("mismatched opening parenthesis in expression") else: raise Exception("mismatched closing parenthesis in expression") def get_token(self): if self.i >= self.len: return '' if self.str[self.i] in self.SPECIAL: self.i = self.i + 1 return self.str[self.i - 1] else: tok = "" while self.i < self.len - 1: if self.str[self.i] in self.SPECIAL: break else: tok = tok + self.str[self.i] self.i = self.i + 1 if not self.str[self.i] in self.SPECIAL: tok = tok + self.str[self.i] self.i = self.i + 1 return tok # A basic stack... very convenient. class Stack(object): def __init__(self): self.s = [] def push(self, datum): self.s.append(datum) def pop(self): return self.s.pop() def empty(self): return len(self.s) == 0 def __repr__(self): return repr(self.s) # For determining the order of operations. _precedence = {'.': 10, '|': 5, '!': 30} # This is a little scary, since I didn't avail myself of the several # parser generator tools available for python, largely because I like # my modules to be self-sufficient whenever possible. Also, most of # the generators are still in development. # # The operations have a precedence. Since I only make a single pass over # the parsed tokens, I keep track of the number of items in a precedence # group. When an operator of higher precedence is seen, all the operations # are popped off the op stack before any more reading takes place. This # ensures that members of a precedence group are evaluated together. # I take the same approach with unary operators. After every item # added to the syntax list I check for unary operators in that stack. # This strange approach allows me to correctly negate sub-expressions. # It might be the standard way of doing this... I don't know. Perhaps # some day I should take a compilers class. class PeriodSyntax(object): def __init__(self): self.ops = [".", "|", "!"] # To know operations. self.uops = ["!"] # Unary operations. def flatten(self, lst=None): """syntax.flatten(token_stream) - compile period tokens This turns a stream of tokens into p-code for the trivial stack machine that evaluates period expressions in in_period. """ tree = [] uops = [] # accumulated unary operations s = Stack() group_len = 0 # in current precendence group for item in lst: if type(item) == type([]): # Subexpression. tree = tree + self.flatten(item) group_len = group_len + 1 # Unary ops dump, for things like: '!(Monday|Wednesday)' for uop in uops: tree.append(uop) uops = [] elif item in self.ops and item not in self.uops: # Operator. if not s.empty(): prev_op = s.pop() # If the precendence of the previous operation is # higher then dump out everything so far, ensuring the # order of evaluation. if _precedence[prev_op] > _precedence[item]: s.push(prev_op) # put it back for i in range(group_len - 1): tree.append(s.pop()) group_len = 0 else: s.push(prev_op) s.push(item) else: s.push(item) elif item in self.uops: uops.append(item) else: # Token of some sort. tree.append(item) group_len = group_len + 1 # Dump any unary operations. for uop in uops: tree.append(uop) uops = [] while not s.empty(): tree.append(s.pop()) # Drop any remaining unary operations. for uop in uops: tree.append(uop) return tree class _Time(object): """Utility class for symbolic date manipulation.""" def __init__(self, tyme=None): if not tyme: self.time = time.localtime(time.time()) else: self.time = time.localtime(tyme) self._set_props() def _set_props(self): (self.weekday, self.month, self.day, self.hr, self.minute, self.week, self.year) = str.split(time.strftime("%A %B %d %H %M %U %Y", self.time)) if self.weekday in ['Saturday', 'Sunday']: self.daytype = 'Weekend' else: self.daytype = 'Weekday' # For use in the in_period function. _parser = PeriodParser() _syntax = PeriodSyntax() def in_period(period, tyme=None): now = _Time(tyme) periodcode = _syntax.flatten(_parser.parse(period)) s = Stack() # Run the period code through a trivial stack machine. try: for item in periodcode: if item == '.': # Have to pre-pop, otherwise logical short-circuiting will # sometimes miss syntax errors like "Monday||Tuesday". a = s.pop() b = s.pop() s.push(a and b) elif item == '|': a = s.pop() b = s.pop() s.push(a or b) elif item == "!": s.push(not s.pop()) else: s.push(_check_timespec(item, now)) return s.pop() except IndexError: raise Exception("bad period (too many . or | operators?): %s" % period) def _check_timespec(timespec, now): if timespec[0:2] == 'Yr': return now.year in _parse_Yr(timespec) elif timespec[0:2] == 'Hr': return now.hr in _parse_Hr(timespec) elif timespec[0:3] == 'Min': return now.minute in _parse_Min(timespec) elif timespec[0:3] == 'Day': return now.day in _parse_Day(timespec) elif timespec in WEEK_MAP: return now.weekday == timespec # Could be 'Week02' or 'Weekday' here. elif timespec[0:4] == 'Week': if timespec in DAYTYPE_MAP: return now.daytype == timespec else: return now.week in _parse_Week(timespec) elif timespec in MONTH_MAP: return now.month == timespec elif timespec == 'Always': return 1 elif timespec == 'Never': return 0 elif '-' in timespec: first = timespec[0:str.index(timespec,'-')] if first in MONTH_MAP: return now.month in _compose_symbolic_range('month', timespec) elif first in WEEK_MAP: return now.weekday in _compose_symbolic_range('weekday', timespec) else: raise Exception("Bad range specification: %s" % timespec) else: raise Exception("Bad time specification: %s" % timespec) def _parse_Yr(year): """Return a hash of the matching years, coping with ranges.""" return _compose_range("Yr", year, fill=4) def _parse_Hr(hour): """Return a hash of the matching hours, coping with ranges.""" return _compose_range("Hr", hour, fill=2) def _parse_Min(min): """Return a hash of the matching days, coping with ranges.""" return _compose_range("Min", min, fill=2) def _parse_Day(day): """Return a hash of the matching days, coping with ranges.""" return _compose_range("Day", day, fill=2) def _parse_Week(week): """Return a hash of the matching weeks, coping with ranges.""" return _compose_range("Week", week, fill=2) def _compose_range(pattern, rule, fill=2): """oc._compose_range('Week', 'Week04-Week09', fill=2) - hash a range. This takes apart a range of times and returns a dictionary of all intervening values appropriately set. The fill value is used to format the time numbers. """ keys = [] mask = len(pattern) for rule in str.split(rule, ","): if not '-' in rule: if rule[:mask] == pattern: keys.append(rule[mask:]) else: keys.append(rule) else: (start, end) = str.split(rule, '-') if rule[:mask] == pattern: start = int(start[mask:]) else: start = int(start) # Since I allow both "Week00-15" and "Week00-Week15", I need # to check for the second week. if end[0:mask] == pattern: end = int(end[mask:]) else: end = int(end) key = "%%0%ii" % fill for i in range(start, end + 1): keys.append(key % i) #print keys return keys def _compose_symbolic_range(pattern, rule): # Are we cycling through day or month names? if pattern == 'weekday': cycle = WEEK_MAP elif pattern == 'month': cycle = MONTH_MAP else: raise Exception("Unknown cycle name: %s" % pattern) # Length of the cycle (for modulo arithmetic). clen = len(cycle) keys = [] for rule in str.split(rule, ","): if not '-' in rule: keys.append(rule) else: (start, end) = str.split(rule, '-') if not (start in cycle and end in cycle): raise Exception("Unknown %s name: %s" % (pattern, rule)) start_i = cycle.index(start) while cycle[start_i] != end: keys.append(cycle[start_i]) start_i = (start_i + 1) % clen keys.append(cycle[start_i]) # Include the final member return keys def is_holiday(now=None, holidays="/etc/acct/holidays"): """is_holiday({now}, {holidays="/etc/acct/holidays"}""" now = _Time(now) # Now, parse holiday file. if not os.path.exists(holidays): raise Exception("There is no holidays file: %s" % holidays) f = open(holidays, "r") # First, read all leading comments. line = f.readline() while line[0] == '*': line = f.readline() # We just got the year line. (year, primestart, primeend) = str.split(line) # If not the right year, we have no idea for certain. Skip. if not year == now.year: return 0 # Now the dates. Check each against now. while line != '': # Of course, ignore comments. if line[0] == '*': line = f.readline() continue try: # Format: "1/1 New Years Day" (month, day) = str.split(str.split(line)[0], "/") # The _Time class has leading-zero padded day numbers. if len(day) == 1: day = '0' + day # Get month number from index map (compensate for zero indexing). month = MONTH_MAP[int(month) - 1] # Check the date. #print month, now.month, day, now.day if month == now.month and day == now.day: return 1 line = f.readline() except: # Skip malformed lines. line = f.readline() continue # If no match found, we must not be in a holiday. return 0 if __name__ == '__main__': for a in ['Friday', 'Friday.January', 'Friday.January.Day04', 'Friday.January.Day05', 'Friday.January.Day02-12', 'Friday.January.!Day02-12', 'April.Yr1988-2001', '(January|April).Yr1988-2002', 'May.Hr05-12', 'Tuesday.Hr07-23', 'January.Hr05-09,11-21', 'Week00', 'Week02', '!Week00', '!Week02', 'Hr12|Hr13|Hr14|Hr15', '(Hr12|Hr13|Hr14|Hr15)', 'Weekday', 'Weekend', 'Weekday.Min50-55', 'Weekday.Min05-50', 'Weekday.Hr07-23', 'Monday-Friday', 'December-February', 'January-March.Monday-Friday', '!January-March.Monday-Friday', 'January-March.!Weekend', '(Monday|Friday).Hr09-17', '!!!Weekday', '!!!!Weekday', '((((Yr2002))))', 'Friday-Flopday', # must fail 'Monday||Tuesday', # must fail '(Monday|Tuesday', # must fail 'Monday|Tuesday)', # must fail '(Monday|Friday)).Hr09-17', # must fail '(Monday|!(Weekday)).Hr11-14', '(Monday|(Weekday)).Hr11-14', '(Monday|(Friday.December-March)).Yr2002' ]: try: print("*", a, in_period(a)) except Exception as e: print("ERR", e) # Test holiday file. if os.path.exists("holidays"): print("*", "holiday", is_holiday(holidays="holidays")) # EOF <file_sep>nose coverage flake8 mock pylint sphinx ipython pudb
690321615d69b7cf35e7994540eb9f1e32a2c765
[ "Python", "Text", "reStructuredText" ]
8
reStructuredText
swills/period
014f3c766940658904c52547d8cf8c12d4895e07
5c542a262427ec93b2672c180f283eba6844fa21
refs/heads/master
<file_sep>bintree: main.c bst.c bst.h tree_tests.c tree_tests.h gcc -o bintree main.c bst.c bst.h tree_tests.c tree_tests.h debug: main.c bst.c bst.h tree_tests.c tree_tests.h gcc -g -o debug main.c bst.c bst.h tree_tests.c tree_tests.h clean: rm bintree debug core debug.txt <file_sep>#include <stdio.h> #include <stdlib.h> int main (void) { char str[50]; FILE *fp; if ( (fp = fopen("test.txt", "r")) == NULL) { fprintf(stderr, "Error opening file.\n"); exit(1); } fgets(str, 50, fp); printf("%s", str); fclose(fp); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char *argv[]) { FILE* new = fopen("p2txt.txt", "w"); int scom = fork(); if(scom < 0) { fprintf(stderr, "fork failure\n"); exit(1); } else if (scom == 0) { //childs path fprintf(new, "Child write\n\n"); } else { //parents path fprintf(new, "Parent write\n\n"); } } <file_sep>#ifndef TABLE_TESTS_H_INCLUDED #define TABLE_TESTS_H_INCLUDED #include "open_address_table.h" // TEST METHODS // void test_false(const char*, bool); void test_true(const char*, bool); void test_null(const char*, void*); void test_longs(const char*, long, long); // ADDREESS BOOK ACCESSORY METHODS // size_t hash_string(const void*); int compare_strings(const void*, const void*); char* address_book_entry_to_string(const void*); // HELPERS // HashTable* empty_table(); bool fill_table(); // INSERT TESTS // void add_to_null_table_fails(); void add_null_key_fails(); void add_null_value_fails(); void test_build_full_table(); void overfilled_table_fails(); // SEARCH TESTS // void search_null_table_fails(); void search_null_key_fails(); void search_empty_table_fails(); void failed_search_fails(); void normal_search_works(); // REMOVE TESTS // void remove_from_null_fails(); void remove_null_key_fails(); void remove_key_not_present_fails(); void normal_remove_works(); // REPLACE TESTS // void replace_in_null_table_fails(); void replace_null_key_fails(); void replace_null_value_fails(); void replace_key_not_present_fails(); void normal_replace_works(); // COMBINATION TESTS // void add_duplicate_key_fails(); void test_remove_then_add_full_table(); // GROUPINGS // void insert_tests(); void search_tests(); void remove_tests(); void replace_tests(); void combo_tests(); #endif <file_sep>def minimumBribes(q): offset = 1 total_bribes = 0 for x in q: if x != q.index(x)+offset: total_bribes += x - (q.index(x)+offset) if total_bribes > 2: print("Too chaotic") return offset -= 1 print(total_bribes) test = [1,3,2,5,4] minimumBribes(test) <file_sep><!doctype html> <html> <body> <?php echo "This", "statement", "has", "multiple", "arguments\n"; print "<h1>Hello World!</h1><br>"; echo "<a href='https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=RickAstleyVEVO' This is not a rick roll</a>"; ?> </body> </html> <file_sep><?php //$_POST = array("name"=>"Jim", "flavor"=>"Chocolate"); $name = $_POST["name"]; $filename = "CCV_" . $name . ".xml"; $dom = new DOMDocument; $dom->load($filename); $children = $dom->documentElement->childNodes; foreach($children as $chitlins) { echo $chitlins->nodeValue; } /* $out_name = $dom->documentElement->childNodes[1]->nodeValue; $out_flavor = $dom->documentElement->childNodes[2]->nodeValue; */ ?> <file_sep>#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> char *concat(char string[50], ...); char string1[50] = "Live "; char string2[50] = "Long "; char string3[50] = "and "; char string4[50] = "prosper.\n"; void main () { char *farewell; farewell = concat(string1, string2, string3, string4); printf("%s", farewell); } char *concat(char string[50], ... ) { va_list arg_ptr; int count; va_start(arg_ptr, string); for (count = 1; count <4; count++) strcat(string1, va_arg(arg_ptr, char*)); va_end(arg_ptr); } <file_sep>graph: main.cpp graph.cpp graph.h g++ -g -o graph main.cpp graph.cpp graph.h <file_sep># include <stdio.h> int x; int eightyeight[88]; int main (void) { for ( x=0 ; x < 87 ; x++ ) { eightyeight[x] = 88; printf("%d\n", eightyeight[x]); } return 0; } <file_sep>def commonSubstring(a, b): for i in range(len(a)): for ea in a[i]: if ea in b[i]: print("YES") break else: print("NO") a = ["hello","hi"] b = ["world","bye"] commonSubstring(a,b) <file_sep>#Day 5 Packaging Code in Functions **function**- named independent section of code that performs a specific task and optioanlly returns a value to the calling program **function prototype**- name, list of variables that CAN be passed to it, and type of variable it returns provides compiler with description of a function that will be defined at a later point. alwasy end with a semicolon return-type function_name( arg-type name-1, argtype2 name-2 ); **function definition**- the function itself CAN be placed below main- contains header, statements, local variables (if you want), and return statement. header should be identical to prototype return-type function_name( arg-type type-name1 ...) { statements; } **argument**- program data sent to the function if return type anything other than void, needs a return statement return can be local variable or set of actions. puts can be a return **PLAN** when writing programs- top down approach for each argument that is passed to a function **parameter** list must contain one entry **local variables**- private to that function function parameters are considered variable definitions so variables in parameter list are also available local variables can have same names as global variables, but local variables will take precedence when execution reaches return statement expression is evaluated and result passed back to calling line return statement terminates the function. can have multiple return statements however without some control first one is executed stdio.h header is for standard input/output functions function called with name and arguments- name(arg1) once declared, function can be used where any C expression used **recursion**- function calls itself either directly or indirectly **indirect recursion**- one function calls another function then calls the first function C allows recursion inline functuion: inline int function(arg1). inline declaration good for short functions trying to make code more efficient- compiler will try to move function block to call <file_sep>#include <stdio.h> #include <stdlib.h> char *message; void main () { char message = (char *) malloc(81); printf("Please provide some input:\n"); scanf("%hhd", message); printf("You typed:\n %s\n", *message); free(message); } <file_sep>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main(int argc, char *argv[]) { printf("Start process PID: %d\n", (int) getpid()); int scom = fork(); if(scom < 0) { fprintf(stderr, "fork failure\n"); exit(1); } else if (scom == 0) { //childs path printf("Child process"); close(STDOUT_FILENO); printf("Child print after stdout close?"); } else { //parents path printf("If this works, the parent can still print\n"); } } <file_sep>#ifndef RECORD_H_INCLUDED #define RECORD_H_INCLUDED #include <stdlib.h> #include <string.h> /* * struct: Record * ---------------------------- * A (key, value) pair in a hash table * */ typedef struct Record { void* key; void* value; } Record; Record* create_record(const void*, const size_t, const void*, const size_t); void delete_record(Record*); #endif <file_sep>#Week 1 Notes- Programming in C main is same as green flag clicked in scratch printf- f is for formatted ./ run the program in my current directory get_string- gets a string from standard input (cs50.h) string answer = get_string("What is your name? \n"); ALWAYS start with very first error message if compiler lists a lot of mistakes string.c:5:5 string.c line 5 character 5 make [program name] looks for the .c file associated compiles and links assignment from right to left i is convention for counter integer balance nesting functions for concise code vs easy to read code- design decision nuances computers can only store finite amount of info 1 / 10 will not perfectly be .1 if you let out enough decimal places when run out of bits in storage space get an overflow and computer will restart at 0. adds a flag for overflow- like carrying the 1 integer overflow -> Y2K <file_sep># Ch 22 Beyond Physical Memory: policies memory pressure forces the OS to start paging out pages to make room for actively used pages deciding which page to evict is encapsulated within the replacement policy given that memory holds some subset of all the pages in the system, it can be viewed as a **cache** our goal in picking a replacement policy is to minimize the number of cache misses - minimize number of times we have to fetch a page from disk **AMAT** - average memory access time AMAT = Tm + (Pmiss * Td) - Tm cost of accessing memory - Pmiss probability - Td cost of accessing disk always have to pay the cost of accessing the data in memory - where miss must pay additional cost of I/O as hit rate approaches 100%, AMAT approaches Tm cost of I/O so high even tiny miss rate will dominat the overall AMAT optimal replacement policy leads to the fewest number of misses overall - replaces the page that will be accessed furthest in the future - looks at history of accesses to determine future cache begins in empty state - **cold start** as the first few misses are compulsory as cache gets filled 3 types of cache misses: 1. cold start 2. capacity miss - cache ran out of space and had to evict and item to bring new one into cache 3. conflict miss - limits on where an item can be placed in hardware cache due to set-associativity - OS page cache are always fully-associative FIFO - simple but crude - 57.1% after cold start random - 40% but must have large sample **LRU** - the shit. - uses recency of access (frequency based) - based on principle of locality - Last Frequently Used policy replaces least frequently used page when an eviction must take place types of locality: 1. spatial locality - if P is accessed likely that P+1 or P-1 will also be needed 2. temporal locality - states that have been accessed in near past are likely to be accessed in near future - principle of locality not hard and fast - designing to optimize for locality not guarantee of success all policies will converge tp 100% hit rate when all referenced blocks fit in cache LRU more likely to hold onto hot pages improvement over other policies COULD be a big deal just depends upon how expensive I/O is to implement well upon each page access must update some data structure to move this page to the front of the list - which means system has to do accounting on EVERY memory reference - could be expensive COULD (add hardware) and update a time field - place in array - but now need to scan that **approximate the LRU** use bit or reference bit clock algorithm all pages in system arranged in clock. clock hand points to rando page to start. checks if currently pointed page hsa use bit 1 or 0. If a 1 implies recently used and NOT a good candidate for replacement. so sets to 0 then goes to P+1. continues until finds use bit of 0 COULD also add a **dirty** bit which just tracks if page has been modified. if modified must be written back to disk to evict it which is expensive. if clean eviction is free and physical frame can be used for other purposes w/o additional I/O. prefer to evict clean pages over dirty for most pages, OS uses **demand paging** - when accessed brought in **prefetching** - guess that a page needed soon and grab cluster writes to disk - more efficient **thrashing** - running processes exceeds system memory system will be constantly paging **scan resistance** - algorithms like LRU but try to avoid worst case behavior of LRU (looping sequential workload) <file_sep>## Types of disk files text streams are associated with **text-mode files** line in a text mode file not same as string- no terminating null character when use text-mode stream translation between C's newline and whatever OS uses mark end of lines **binary streams** associated binary files. any and all data written and read unchanged, no separation or end of line characters some file I/O functions restricted one file mode, others use either mode ## Using filenames must use file name when dealing with disk files ## Opening a file **opening**- stream linked to a disk file when open becomes available for reading, writing, or both when done using a file **YOU MUST CLOSE IT** prototype for **fopen()** FILE \*fopen(const char \*filename, const char \*mode); returns a pointer to type file (structure in stdio.h) for that file **for each file want to open must declared a pointer to type file** creates instance of file structure and returns a pointer if fopen() fails, returns NULL argument **mode** specifies in which mode to open the file. pg 442 for modes default mode is text open in binary mode, append a b to mode argument ## Writing and Reading File Data 3 ways write to disk file: 1. use **formatted output** to save formatted data to a file. only with text mode files. primarily used create files with text and numeric data to be read by other programs 2. use **character output** to save single characters or lines of characters to files. shoudl restrict text mode files. to save text in a form that can be read by C as well as other programs 3. use **direct output** to save contents of section of memory directly to disk file. binary files only. best way save data for later use by C programs generally read data same mode saved in ### Formatted File Input and Output text and numeric data foramtted specific way #### Formatted File output fprintf() int fprintf(FILE *fp, char *fmt, ...); 1. pointer to type file 2. format string. same rules as printf() 3. names of variables to be outputted to specific stream (like printf) #### formatted file input fscanf() int fscanf(FILE *fp, const char *fmt, ...); like scanf ### Character input and output refers to single characters as well as lines of characters #### character input getc() and fgetc() input single character from specified stream int getc(FILE *fp) fgets() read line of characters from file char *fgets(char *str, int n, FILE *fp); str pointer to buffer which input stored. n maximum nubmer of characters to be input. fp is pointer to type FILE from fopen() #### character output fputs() write line of characters to stream char (fputs(char *str, FILE *fp); ###Direct file input and output most often used save data to be read later by the same or different c program only used binary files blocks of data written from disk to memory fwrite() writes block of data from memory to binary-mode file int fwrite(void *buf, int size, int count, FILE *fp); buf- pointer to region of memory holding data to be written to file. size- size in bytes of individual items. count- number of items to be written. fp- pointer to file returned by fopen() returns number of items written on success. if value less than count there was an error good way to usually write: if ( (fwrite(buf, size, count, fp)) != count) fprintf(stderr, "Error writing to file."); fread() reads a block of data from a binary mode file into memory int fread(void *buf, int size, int count, FILE *fp); "" always do something to ensure fopens() fwrite() and fread() function correctly: if ( (fp = fopen("direct.txt", "wb")) == NULL) { fprintf(stderr, "Error opening file."); exit(1) } if (fwrite(array1, sizeof(int), SIZE, fp) != SIZE) { fprintf(stderr, "Error writing to file."); exit(1); } fclose(fp); if (fread(array2, sizeof(int), SIZE, FP) != SIZE) { fprintf(stderr, "Error reading file."); exit(1); } ## File Buffering: Closing and Flushing Files must always close with fclose() int fclose(FILE, *fp); returns 0 on success, -1 on error. when close file's buffer is flushed (written to the file) can close all open streams except standard ones with fcloseall() int fcloseall(void); when program terminates either by reaching end of main or exiting prematurely, streams closed. can be a good idea to close explicitly when create stream to disk file buffer automatically created and associated with the stream as program writes data to the stream, data is saved in the buffer until the buffer is full and then the entire contents of the buffer are written as a block to the disk can flush streams buffers without closing by using fflush() or flushall() int fflush(FILE *fp); int flushall(void); ## Understanding Sequential vs Random Memory Access every open file has position indicator associated with it. specifies where read and write operations take place in file when new file opened, position indicator at beginning of file. position 0 when exisitng file opened, indicator at end of file in append mode or at beginning of file if opened in any other mode reading and writing operations occur at location of position indicator and update position indicator as well don't need to be concerned about position indicator for reading by controlling position indicator can perform **random file access**- read or write data to any position in a file without reading or writing all of the proceeding data rewind()- set position indicator at beginning of file void rewind(FILE *fp); ftell()- determine value of file's position indicator long ftell9FILE *fp); fseek()- set position indicator anywhere in the file int fseek(FILE *fp, long offset, int origin); offset distance want pointer to go origin specifies moves relative starting point. SEEK_SET- move offset bytes from beginning of file. SEEK_CUR- move offset bytes from current position. SEEK_END- move offset bytes from end of file returns 0 if indicator successfully moved or nonzero if error occurred. make sure you are not reading beyond the EOF ##Detecting end of file symbolic constant in stdio.h is -1 for text-mode file: while ( (c = fgetc( fp )) !=EOF ) can't use -1 with binary either: int feof(FILE *fp); feof() returns 0 if end of file has not been reached or nonzero if has been reached if EOF reached, no further read operations permitted until a rewind(), fseek() or file closed and reopened while (!feof(fp)) { fgets(buf, BUFSIZE, fp); printf("%s", buf); } ## File Management Functions deleting, renaming, copying remove()- deleting file forever int remove(const char *filename); 0 on success, -1 on failure rename() int rename( const char *oldname, const char *newname ); both names must refer to the same disk drive no explicit copy function: 1. open source file for reading in binary mode 2. open destination file in binary mode 3. read a character from source file 4. if feof indicates at end of source file can close both files 5. if have not reached eof write character to destination file and loop back to step 3 ## Using temp files tmpnam()- creates temp filename does not exist anywhere in file system char *tmpnam(char *s); s is pointer to buffer large enuf hold file name. can also pass null in which case stored in buffer internal to tmpnam and function returns poitner to buffer <file_sep>#! /usr/bin/python3 # comprehend the list - if of certain type, move into its own list import sys ar = [2,2,3,3,3,4,4,4,5] capture = [] for y in range(100): if y in ar: capture.append(y) print(capture) <file_sep>/* *OOP Ch.5 HW pt 1 Prob 5.7 *@author <NAME> */ package vtc.oop.week6.hw; public class Rational { private int numerator; private int denominator; /** * Constructs a rational number from inputted numerator and denominator * @param num any integer value * @param denom any integer value other than 0 * @throws ArithmeticException if denominator is 0 */ public Rational(int num, int denom) throws ArithmeticException{ if (denom == 0) throw new ArithmeticException(); numerator = num; denominator = denom; repOk(); } /** * Shows the abstract value of the Rational number as a fraction and a decimal * @return a String of the this */ public String toString() { double rational = numerator/denominator; String daString = numerator + "/" + denominator + " " + rational; return daString; } /** * numerator can be any integer number * denominator can be any integer number other than 0 * Rational cannot be null */ private void repOk() { assert(denominator != 0) : "Denominator cannot be 0"; assert(this != null) : "Rational objects cannot be null"; } } <file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign06 - Advanced Web Development</h2> <h2>Research</h2> <!--writeup goes here--> <p>I read ch.4 and ch.5. Geat stuff.</p> <h2>Before & After CODE</h2> <p>Here is the link to my wordpress site:</p> <a href="https://jmd06260.classweb.ccv.edu/WP1/">Jim's Wordpress Site</a> </div> <?php include 'footer.php';?> </body> </html> <file_sep>//Insertion sort #include "../jimSort.h" #include <stdio.h> #include <stdlib.h> #include <time.h> void insertionSort(int* sortArray, int arraySize) { int o = 1; while( o < arraySize ) { int i = o; while((i > 0) && (sortArray[i-1] > sortArray[i])) { int tmp = sortArray[i]; sortArray[i] = sortArray[i-1]; sortArray[i-1] = tmp; i--; }//end inner loop o++; }//end outer loop } int main(void) { int arraySize = 0; printf("\nArray Size?: \n"); scanf("%d", &arraySize); int* testArray = malloc(sizeof(int)*arraySize); srand(time(0)); printf("\nBefore:\n"); for(int i = 0; i < arraySize; i++) { testArray[i] = rand() % 20; printf("testArray[%d] = %d\n", i, testArray[i]); } insertionSort(testArray, arraySize); printf("\nAfter:\n"); for(int i = 0; i < arraySize; i++) { printf("testArray[%d] %d\n", i, testArray[i]); } free(testArray); return 0; } <file_sep>import sys print("Number: ") cred = input() try: credit = [int(x) for x in str(cred)] except: print("INVALID") exit(1) #American Express 34 37 #MasterCard 51, 52, 53, 54, or 55 #Visa 4 if((credit[0] == 3) and ((credit[1] == 4) or (credit[1] == 7))): card = "AMEX" elif((credit[0] == 5) and (credit[1] <= 5)): card = "MASTERCARD" elif(credit[0] == 4): card = "VISA" else: print("INVALID") exit(1) #reverse reverse! credit.reverse() sectolast = 0 #every other digit starting from second to last for x in range(1, len(credit), 2): tmp = credit[x] * 2 tmpex = 0 if tmp > 10: tmpex = tmp % 10 tmp = 1 sectolast = sectolast + tmp + tmpex firtolast = 0 #every other digit starting from the last for x in range(0, len(credit), 2): tmp = credit[x] firtolast = firtolast + tmp if(((sectolast+firtolast) % 10) == 0): print(card) else: print("INVALID") exit(1) <file_sep> <?php $servername = "localhost"; $username = "username"; $password = "<PASSWORD>"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?> <file_sep># Day 8 Using Numeric Arrays each storage location in an array is called an array element each element is the equivalent of 1 variable at the variable type all of C's data types can be used for arrays expenses[10]=expenses[11] copied index 10 to index 11 expenses[a[2]]= 100; set at index whatever a[2] is (if integer array) C compiler does not recognize if program uses array subscript that is out of bounds %.2f will print to 2 decimal places when using in printf() **multi-dimensional array**- has more that one subscript ex: int checker[8][8] no limit to number of dimensions an array can have, however is limit to total size \#define MONTHS 12. int array[MONTHS]; cannot declare with symbolic constant created by const. const int MONTHS = 12; int array[MONTHS] is a no no scanf("%d", &grades[idx]); can initialize all or part of an array when you first declare it if you do not explicity initialize an array element cannot be sure what value it holds for multidimensional arrays- assigned to elements in order with last subscript changing first. array[4][3] = {1, 2, 3, 4, 5,.....] would add the values in this order: int array[0][0] = 1. array[0][1] = 2. array[0][2] = 3. array[1][0] = 4. array[1][1] = 5.... array[3][2] = n. clearer: int array[4][3] = { {1,2,3} , {4,5,6} , .... } getchar() pauses program until the user presses Enter key pg 186 increments 3 dimension array across addresses by using 3 nested for loops: int array[a][b][c] for (increment a) for (increment b) for (increment c) int array[a][b][c] = rand() } } } **calculate memory needed**- multiply nubmer elements in array by element size- 500 element array with int variables. each int is 4 bytes (pg188 for table) so 500\*4=2000 bytes sizeof() unary operator determining size of argument programming tasks that involve repetitive data processing lend themselves to array storage should always initialize variables so you know exactly what is in them cannot add arrays together but could make a function that increments and adds each element at each address <file_sep># Algorithms Generic Sorting HW ## Why generic sorting algorithms are slower I believe that the chief reason for a generic sorting algorithm to run slower than a purpose-built algorithm is complexity. My version of the generic quicksort algorithm uses 6 additional functions that the purpose built does not. This could be an oversimplification but each additional call is another set of processes that have to occur and return. I read up on some profiling tools (I tried gprof and Callgrind from the Valgrind suite) and tested them on the programs. Frankly, I had a hard time understanding the output. But, it made it easier for me to see that the extra steps that the generic version had to undergo did have a significant (well in processor terms) cost in terms of processing time. Generic quicksort observes the same asymptotic behavior because it has the same structure, it just has to undergo additional steps to complete its task. <file_sep>$sql = "SELECT * FROM Orders LIMIT 30"; <file_sep># include <stdio.h> float x; float y; float answer; void main () { puts("\nInput two numbers:"); scanf("%f%f", &x, &y); answer = x +y; printf("\nThe answer is %f\n", answer); } <file_sep># Ch.17 Free Space Management easy when space is divided into fixed sized units - difficult with variable sized units malloc and free control processes's virtual heap space and the subsequent free list **external fragmentation** - is relative to the OS managing the entire memory map **internal fragmentation** - is relative to a particular process once space allocated for a process it is "owned" by that process and cannot be removed - compaction could only be used in a system that was implementing segmentation system call **sbrk()** used to grow the heap for a particular process - reaches into whole virtual memory and maps some additional space to the requesting process ## low-level mechanisms **splitting and coalescing and free list** **free list** - contains a set of elements that describe the free space still remaining in the heap linked list **splitting** - find a free chunk of memory, take what is requested, leave the rest **coalescing** - when memory is free mechanism for chunking it back into a nearby space (if free) then just update free list for new sized chunk ### tracking the size of allocated regions most allocators store a little extra info in a header block just before handed out chunk of memory so a chunk of memory looks like: ----------------- | header | | | ----------------- | | | | | memory | | | | | ----------------- header may also have additional pointers to speed up deallocation, magic number for integrity checking, and pointers to next allocated space how this goes down slim: ----------------------- 1. gets a pointer with free 2. calculates header body 3. checks magic number 4. adds region + header 5. adds to free list (coalescing if possible) ### embedding a free list when process gets heap space (from system call **mmap()**) create a struct for the head pointer - contains address of space - size of the space - initially, heads next pointer will point to NULL then we just build more of these nodes as space is allocated mechanisms will chunk memory as freed to GROW the heap process calls **sbrk()** which finds a free physical page, maps it into the address space of the requesting process, and returns the value of the end of the new heap ## Basic Strategies (brief overview of each) ideal allocator is both fast and minimizes fragmentation **best fit** - search through free list and find chunks of free memory as big or bigger then return the smallest candidate **worst fit** - find largest chunk and return requested amount, keep remaining large chunk on the free list - tries to leave big chunks free instead of lots of little chunks **first fit** - finds first block with enough space and returns it **next fit** - keeps extra pointer to the location within the list where one was looking last **segregated lists** - if a particular process makes similar requests, keep a separate list and space just for those lots of allocator strategies have issues with scaling - more advanced allocators make use of different data structures to achieve better performance <file_sep># OS3 Ch.1 Into to Operating Systems running program executes instructions processor **fetches** instruction from memory decodes it and executes it Von Neumann model of computing - execute 1 instruction at a time HOW does the Operating System virtualize resources sometimes call OS a virtual machine take physical resource and make it into more useful virtual resource OS provides system calls for resources and standard library for applications also called resource manager virtualizing the CPU - executing multiple processes simultaneously **policy** used to determine which program runs at a time virtualizing memory means giving each process its own address space **thread** - function running within same memory space as other functions with more than 1 active at a time **persiostence** not volatile memory syscalls to file system can include open() write() close() want to **isolate** processes from one another syscall transfers control to OS while simultaneously raising hardware privilege level user applications run in user mode - hardware restricts what applications can do cant do things like write to disk sooo when you make a restricted syscall, control transferred to **trap handler** then raises privilege to kernel mode when done passes control back to user with return-from-trap instruction <file_sep> cp -r ../../notebook/3050-Alogorithms/1week/jimSort/* sorts cp -r ../../notebook/3050-Alogorithms/3week/mergesort/* mergesort cp -r ../../notebook/3050-Alogorithms/3week/quicksort/* quicksort cp -r ../../notebook/3050-Alogorithms/4week/heapsort/* heapsort cp -r ../../notebook/3050-Alogorithms/5week/genericsort/* genericsort cp -r ../../notebook/3050-Alogorithms/7week/* bucketsort cp -r ../../notebook/3050-Alogorithms/9week/oldlink/* linkedlists cp -r ../../notebook/3050-Alogorithms/11week/binaryhw/* binarysearch cp -r ../../notebook/3050-Alogorithms/12week/hashhw/* hashtables cp -r ../../notebook/3050-Alogorithms/14week/* maps la * <file_sep>#CS50X Week 5- Data Structures- Notes resize array- how to resize? have to copy data, free old memory, then add new data if you allocate memory to a pointer from malloc, can still use [] to access the contents of each block: int *ex = malloc(3*sizeof(int)); if(list == NULL) { return 1; } //always good practice ex[0] = 1; ex[1] = 2; ex[2] = 3; [0] is first byte. [1] is 4 bytes over. [2] is 8 bytes over. now to resize: int *tmp = malloc(4* sizeof(int)); if(tmp == NULL) { return 1; } to do it O(n) use for loop, then free original chunk, then reassign pointer new function: **realloc**(original chunk, new size); can resize a previously sized chunk of memory **data structure**- allow store information differently in memory **linked list**- data structure multiple chunks of memory linked together by pointers. have to store info as well as pointers typedef struct node { int number; struct node *next; } node; typedef just creates that alias of node so its easier to use later **node**- general term to describe the data plus the pointer to next element in list node *n = malloc(sizeof(node)); (*n).number = 2; need () around \*n porque need to be specific "go there first, then access the .number field and assign 2 to it" the same thing is accomplished by n->number = 2; n->next = NULL; however since a malloc is happening, usually want to do this way: if( n!= NULL) { n->number = 2; n->next = NULL; } use \*tmp pointer to move through list while (tmp->next != NULL) { tmp = tmp->next; } bc NULL is supposed to be the value of the last item in the list so want to add to end of list, follow breadcrumbs until null then do the assigning and reassigning operations add item to beginning of list n->next = listbeginning; list = n; price we paid is searching the data structure is O(n) when the sorted array can be O(log n) incrementing across a list. "list" is beginning n->next = NULL; list->next->next = n; iterate across linked list with for loop: for(node *tmp = list; tmp != NULL; tmp = tmp->next) action; could create fancier structure with 2 pointers to set for instance left or right can create a **binary search tree** so recursively every element to left is "less" every element to the "right" is greater brought our O to O(log n) maintain pointer to the "root" or the top which is the direct middle. then comapre and set from there 2 dimensions recursive binary tree search: bool search(node *tree) { if(tree == NULL) { return false; } else if(50 < tree->number) { return search(tree->left) } else if(50 > tree->number) { return search(tree->right) } else if(50 == tree->number) { return true; } } so using recursive function to search recursive data structure **hash table**- combination of array and linked lists inside of it. conceptually vertical horizontally linked list index into with **hash function** decides given name tag what bucket to put that in for names it is looking at first letter ideal hash function- no input data collides with any other data to preserve O(1) random access. but that is going to create a lot of buckets, so hash tables considered O(n) **trie**- short for retrieval. use lot of memory but give actual time lookup. tree each of whose nodes is an array. so for names each letter becomes a node. each node is a whole 26 character array. then link down a chain. Names that share the first few letters would share the same node-arrays. This results in a search time of O(1) or really the best its gonna get memory requirement is HUUUUUUUUUGE **abstract data structures**- applying the data structures to real-world **queue**- data structure first in first out enqueue- to get in line dequeue- to get out of line **stacks**- LIFO push- put onto stack pop- pulling off of stack **dictionary**- abstraction get on top of hash table. has keys and values. ##Data Structures ##Singly Linked Lists structures that are self-referential need to have temp name and if using typedef a final name: typedef struct temp { VALUE val; struct *temp next; } final; first element of list could be a global variable to keep track of it could call it head good practice to copy the head then use the copy to begin moves could call it trav to insert at end must start at beginning then work to end making that insertion O(n) if insert at beginning happens at O(1) step 1 malloc space for new node step 2 new node point to second element step 3 head point to new item operations to work with linked list: 1. create a linked list when does not exist 2. search through linked list to find and element 3. insert a new node into the linked list 4. delete a single element from a linked list 5. delete an entire linked list to delete single element may need 2 pointers- one to move through and find, and another to perform the bridging operation to the element atfer the deleted element ##Hash Tables combine array with linked list- gain back random access insertion, deletion, lookup can get close to constant time only use if don't care if data is sorted **hash function**- returns nonnegative integer value called a hash code run our data through hash function say int hash("John") and it retunrns 4. Then store "John" at index 4 of array. now if you want to lookup position 4 reverse hash. could return position in array by hashing input good hash function: 1. all of the data needs to be hashed 2. use only the data to be hashed 3. be deterministic 4. uniformly distribute data 5. generate very different codes for similar data **collision**- two pieces of data go through hash function and return same hash code **linear probing**- if have collision, could do index +1, then if something there index +2. now if he is not at search index, know how to look push too many elements- lose the theta as the average case time of operatrions trends towards O(n). creates **clustering**- increasing changes of collision more elements bump with linear probing lends to **chaining**- each element of array can be head pointer o linked list and grow arbitrarily. the lookup is not O(n) like a normal linked list but is O(n) / arraySize easiest to insert new item at beginning ##Tries key guaranteed to be unique. value could be simple boolean tell you whether data exists in the structure if can follow data from beginning to end then know exists in the trie no collisions unless data is duplicated have root node then jump down from there typedef struct _trie { char university[20]; struct _trie*[10]; } trie; <file_sep>#include "algorithms.h" int partition(void* sortArray, int innerBound, int outerBound, int (*comparator)(void*a,void*b), size_t element_size) { void* pivot = shift(sortArray, outerBound, element_size); int i = innerBound - 1; for(int j = innerBound; j <= outerBound-1; j++) { //get a pointer to sortArray[j] and pass into applicable comparison function void* aj = shift(sortArray, j, element_size); if((comparator(pivot, aj)) > 0) { i++; void* ai = shift(sortArray, i, element_size); swap(sortArray, aj, ai, element_size); } } void* ai1 = shift(sortArray, i+1, element_size); void* ao = shift(sortArray, outerBound, element_size); swap(sortArray, ai1, ao, element_size); return i + 1; }//end partition void quicksort(void* sortArray, int innerBound, int outerBound, int (*comparator)(void*a,void*b), size_t element_size){ if(innerBound < outerBound) { int p = partition(sortArray, innerBound, outerBound, comparator, element_size); quicksort(sortArray, innerBound, p - 1, comparator, element_size); quicksort(sortArray, p + 1, outerBound, comparator, element_size); } }//end quicksort <file_sep>$sql = "SELECT flavor FROM ice_cream LIMIT 10"; <file_sep>#include <stdio.h> int x = 55; int y = 23; int main () { printf("\nY is %d\n", (y = (1 < x < 20) ? x : y )); return 0; } <file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign11 - Advanced Web Development</h2> <p>This is a redo on the form I created for Assignment 5 that does the reading from XML file better.</p> <?php include 'assign11/form.php';?> </div> <?php include 'footer.php';?> </body> </html> <file_sep>#Understanding Variable Scope **scope**- refers to the extent to which a variable is visible/accessible. important because structured approach divides program into **INDEPENDENT** functions **external variable**- variable defined outside of any function- also called global variable use external variables rarely- violate principle modular independence only make external when all or most of the program's functions need access good practice: *extern type name* local variables are **automatic** by default. that is they are created anew each time a function is called and destroyed when complete to retain value of local variable between function calls use **static** **local scope**- variable that is contained in a functions heading parameter parameter variables always start with the value passed to the corresponding argument ordinary external variable visible to other files static external variable only visible to functions in own file below point of definition **register variable**- store variable in cpu register. suggestion if possible. **register** keyword. good for variables frequently used such as counter variable in loop only be used simple numeric variables not arrays or structures programs defined in main() function created when program begins and die when it ends no difference automatic and static variables in main() function can define variables local to any block {} Guidelines for picking storage classes (chart pg 297) 1. give each variable an automatic local storage class to begin with 2. if the variable will be manipulated frequently provide *register* keyword to definition 3. in functions other than main() make a variable static if its value must be retained between calls to the function 4. if a variable is used by most or all of the program's functions then define it with an external storage class global variables take up memory as long as program is running if local variable and global variable have same name program will ignore global over local <file_sep> int valkey(string key) { //test string string key = "<KEY>"; //evalutate key length if(strlen(key) != 26) { printf("not correct length %lu\n", strlen(key)); return(0); } //evaluate for non-letters for(int i = 0; i < 26; i++) { if ( !(isalpha(key[i])) ) { printf("non letter present\n"); return(0); } } //evaluate for repeated characters for(int letter = 97; letter < 123; letter++) { int repeat = 0; for(int i = 0; i < 26; i++) { if( tolower(key[i]) == letter ) repeat++; } if ( repeat > 1) { printf("multiple use of same character\n"); return(0); } }//end repeated characters loop return 1; }//end valkey <file_sep>#include <stdio.h> #include <stdlib.h> void main (void) { char ch; int count[127], index; for(index = 0; index < 127; index++) count[index] = 0; while (1) { ch = fgetc(stdin); if( ch == EOF ) break; if( ch > 31 && ch < 127 ) count[ch]++; // printf("%c\n", ch); } for( index = 32; index < 127; index++ ) printf("[%c]\t%d\n", index, count[index]); } <file_sep>//pg 168 enter ages and incomes of up to 100 people //prints a report based upon numbers entered #include <stdio.h> #define MAX 100 #define YES 1 #define NO 0 long income[MAX]; //holds incomes int month[MAX], day[MAX], year[MAX]; //to hold birthdays int x,y,ctr; //for counters int cont; //for program control long month_total, grand_total; //for totals int main(void); int display_instructions(void); void get_data(void); void display_report(void); int continue_function(void); int main(void) { cont = display_instructions(); if( cont == YES ) { get_data(); display_report(); } else printf( "\nProgram Aborted by User\n\n"); return 0; } int display_instructions( void ) { printf("\n\n"); printf("\nThis program enables you to enter up to 99 people\'s"); printf("\nincomes and birthdays. It then prints the incomes by"); printf("\nmonth along with the overall income and overall average."); printf("\n"); cont = continue_function(); return( cont ); } void get_data(void) { for( cont = YES, ctr = 0; ctr < MAX && cont == YES; ctr++ ) { printf("\nEnter information for Person %d.", ctr+1); printf("\n\tEnter birthday:"); do { printf("\n\tMonth (0 - 12):"); scanf("%d", &month[ctr]); }while (month[ctr] < 0 || month[ctr] > 12); do { printf("\n\tDay (0 - 31):"); scanf("%d", &day[ctr]); }while (day[ctr] < 0 || day[ctr] >31); do { printf("\n\tYear (0 - 2020):"); scanf("%d", &year[ctr]); }while (year[ctr] < 0 || year[ctr] >2020); printf("\nEnter Yearly Income (whole dollars): "); scanf("%ld", &income[ctr]); cont = continue_function(); } } void display_report() { grand_total = 0; printf("\n\n\n"); printf("\n SALARY SUMMARY"); printf("\n =============="); for( x = 0; x <= 12; x++) { month_total = 0; for( y = 0; y < ctr; y++ ) { if( month[y] == x ) month_total += income[y]; } printf("\nTotal for month %d is %ld", x,month_total); grand_total += month_total; } printf("\n\nReport totals:"); printf("\nTotal Income is %ld", grand_total); printf("\nAverage Income is %ld", grand_total/ctr); printf("\n\n* * * End of Report * * *\n"); } int continue_function( void ) { printf("\n\nDo you wish to continue? (0=NO/1=YES): "); scanf("%d", &x); while( x < 0 || x > 1 ) { printf("\n%d is invalid!", x); printf("\nPlease enter 0 to Quit or 1 to continue: "); } if (x == 0) return(NO); else return(YES); } <file_sep>#include "table_tests.h" using namespace std; int main() { HashTable* table = empty_table(); printf("%s\n", table_to_string(table)); insert_tests(); search_tests(); remove_tests(); replace_tests(); combo_tests(); } <file_sep>#include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> int main(int argc, char* argv[]){ int p = (int) getpid(); printf("PID: %d\n", p); long memsize = atol(argv[1]); memsize *= 1000000; char* buffer = malloc(memsize * sizeof(char)); int i = 0; while(1){ char a = buffer[i]; i++; if(i == memsize) i = 0; } return 0; } <file_sep>#include <stdio.h> int x; int main () { printf("\nInput your age: "); scanf("%d", &x); if (x < 21) printf("\nYou are a mere child!\n"); else if ( x > 65) printf("\nSit down grandpa!\n"); else printf("\nYou are an adult\n"); return 0; } <file_sep># Day 20 Working with Memory ## Type Conversions ### Automatic Type Conversions often referred to as implicit conversions when C expression evaluated, if all components in the expression have the same type, resulting type is that type as well int x,y; z= x+y; z will be int least comprehensive to most comprehensive (like order of data types) char short int long long long float double long double so ex: expression with int and char evaluates to type int kinda like an order of operations to determine data type after evaluation so: Y + X * 2 will determine data type of x\*2 THEN determine data type of Y + (X\*2) within expressions operands can be **promoted** in pairs for each binary operator in the expression following these rules: 1. if either operand is a long double, the other is promoted to type long double 2. if either is a double, the other is promoted to double 3. if either is a float, other promoted to float 4. either a long, other promoted to long just makes a copy will not change underlying data type ### Conversion by Assignment assignment operator = expression on right side always promoted to type of data object on left side could cause a "demotion" rather than a "promotion" ### Explicit conversions with typecasts consists of a type name, in paranthesis before an expression. can be performed on arithmetic expressions and pointers (float)i most common use for arithmetic is to avoid losing fractional part of answer in integer division f1 = (float)i1/i2; ## Allocating Memory Storage Space static memory allocation- like array dynamic memory allocation- allocating memory storage at runtime requires stdlib.h some compilers malloc.h **all allocation functions return type void pointer** every program needs a way to check to ensure memory was allocated correctly and means to gracefully exit if not ### malloc() can allocate storage for any storage need void *malloc(size_t num); num is number of bytes to allocate and returns pointer to first byte int *ptr; ptr = malloc(sizeof(int)); ### calloc() void *calloc(size_t num, size_t size); num number objects to allocate, size size in bytes of each object. returns pointer to first byte ###realloc() changes size of block of memory previously allocated with malloc() or calloc() void *realloc(void *ptr, size_t size); ptr to original block of memory. new size specified in bytes outcomes: 1. if sufficient space memory allocated and returns ptr to adjusted block 2. if space does not exist, new block for size is allocated and exisitng data copied from old block to new, old block freed, returns poitner to new block 3. if ptr is null, acts like malloc() ie allocating a block of size bytes and returning pointer to it 4. argument size is 0, memory ptr points to is freed, and function returns to null 5. if memory insufficient for reallocation, function returns null and original block is unchanged ### free() void free(void *ptr); ## Manipulating Memory Blocks **memset()**- set all bytes in a block of memory to a particular value void *memset(void *dest, int c, size_t count); c is value to set, count is number of bytes, starting at dest, to be set. could do something like ex: changing array[50] do array+5 to change starting at 5th index c range 0 to 255 **memcpy()**- copies blocks of data between memory blocks- does not care about data type void *memcpy(void *dest, void *src, size_t count); dest and src point to destination and source memory blocks. count specifies number bytes to be copied. dest return value. does not handle overlapping memory blocks, therefore **should just use** **memmove()**- same as memcpy() just handles overlapping memory blocks better ## Bits C bitwise operators let you manipulate individual bits of integer variables **shift operators**- shift bits in integer variable by specified number of positions using << shift to left >> shift to right x << n shifts bits in x n positions to the left for right-shift 00s placed in high order bits. for left-shift 00s placed low order bits **left shift multiplying by 2^n** **right shift divide by 2^n** does not exceed 255 though, shifting left will bring you back around also lose fractional parts **bitwise logical operators**- perform logic across bytes: AND 1110 &1010 _____ 1010 inclusinve OR 1110 |1010 _____ 1110 exclusive OR 1110 ^1010 _____ 0100 **complement operator**- unary operator that reverses every bit in operand **bit fields in structures**- structure field that contains specified number of bits. can have field with 1, 2 or 3 bits (lose advantage over 3 bits as might as well use int) can store 8 yes or no values in single char **must be listed in structure first** specify size of field in bits following member name with colon and number of bits struct emp_data { unsigned dental :1; unsigned college :2; char fname[20]; char lname[20]; }; <file_sep><?php $servername = "localhost"; $username = "username"; $password = "<PASSWORD>"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "INSERT INTO ice_cream(flavor, company, tastiness) VALUES ('strawberry', 'ben&jerrys', '10');"; $sql .= "INSERT INTO ice_cream(flavor, company, tastiness) VALUES ('vanilla', 'hood', '10');"; $sql .= "INSERT INTO ice_cream(flavor, company, tastiness) VALUES ('chocolate', 'hood', '8');"; //the append and equals operator is pretty cool I wish more languages did that //they really like their strictly strictly equal operator huh? === does same thing as == for primitives if ($conn->multi_query($sql) === TRUE) { echo "New records created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?> <file_sep>#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <sys/wait.h> #include <sched.h> #define RUNS 100 double timer(clock_t, clock_t); int main(int argc, char *argv[]) { printf("Parent process PID: %d\n", (int) getpid()); int fd1[2]; int fd2[2]; int child1; clock_t start, end; cpu_set_t set; //pipe fd1 parent to child for this representation //fd1[0] pipe 1 read end, fd1[1] pipe 2 write end pipe(fd1); //pipe fd2 child to parent for this representation //fd2[0] pipe 2 read end, fd2[1] pipe 2 write end pipe(fd2); //establish sched_affinity so runs on only 1 core CPU_ZERO(&set); CPU_SET(1, &set); sched_setaffinity(0, sizeof(cpu_set_t), &set); child1 = fork(); if(child1 < 0) { fprintf(stderr, "fork failure\n"); return 1; } else if (child1 == 0) { //child1 path for(int i = 0; i < RUNS; i++) { int j_rec = 0; read(fd1[0], &j_rec, sizeof(int)); //printf("Child receives %d\n", j_rec); j_rec++; write(fd2[1], &j_rec, sizeof(int)); //printf("Child sends back %d\n", j_rec); } } else { //parent path int j = 0; write(fd2[1], &j, sizeof(int)); start = clock(); for(int i = 0; i < RUNS; i++){ j = i; read(fd2[0], &j, sizeof(int)); //printf("Parent receives back %d\n", j); j++; write(fd1[1], &j, sizeof(int)); //printf("Parent sends %d\n", j); } end = clock(); printf("Context Switch avg time: %f\n", (timer(start, end) / RUNS)); } return 0; } double timer(clock_t start, clock_t end){ return ((double) (end - start)) / CLOCKS_PER_SEC; } <file_sep>CC = gcc FLAG = -o DFLAG = -g -o genquicksort: main.c genquicksort.h algorithms.h ${CC} ${FLAG} genquicksort main.c genquicksort.h algorithms.h debug: main.c genquicksort.h algorithms.h ${CC} ${DFLAG} debug main.c genquicksort.h algorithms.h clean: rm -f genquicksort debug *.txt core <file_sep>predefined function- contains C code that that has already benn written printf() library function editor -> compiler -> linker if compiler does not find any errors produces obhject file gcc -o <old file> path> <file_sep>#include <stdio.h> int main( void ) { char buf[80]; fgets(buf, 100, stdin); printf("The input was: %s\n", buf); return 0; } <file_sep>#include <stdio.h> #include <math.h> int main (void) { double x; printf("Enter a number: "); scanf("%lf", &x); printf("\n\nOriginal value: %lf", x); printf("\nCeil: %lf", ceil(x)); printf("\nFloor: %lf", floor(x)); if (x>=0) printf("\nSquare root: %lf", sqrt(x) ); else printf("\nNegative number"); printf("\nCosine: %lf\n", cos(x)); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #define SIZE 129 void main() { FILE *fp; char buffer[SIZE], filename[25]; int i = 0, a = 1, point = 129; printf("Which file would you like to translate: "); scanf("%s", filename); if((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "File was unable to open. You suck. Goodbye."); exit(1); } while( feof(fp) != 1) { if(fread(buffer, sizeof(char), sizeof(filename), fp) != sizeof(filename)) { printf("Unable to read file because you suck."); exit(1); } printf("\nBlock %d Hexadecimal\n\n", a); for(i=0; i < SIZE; i++) printf("%x", buffer[i]); printf("\nBlock %d ASCII\n\n", a); for(i=0; i < SIZE; i++) printf("%c", buffer[i]); a++; if((fseek(fp, point, SEEK_SET)) != 0) { printf("Unable to move pointer because you suck."); exit(1); } point = point + SIZE; } fclose(fp); } <file_sep> # Bubblesort.py # takes as input an array of unsorted ints, returns a sorted array def bubblesort(arr): for x in range(len(arr) - 1): for y in range(len(arr) - 1): if arr[y] > arr[y+1]: z = arr[y] arr[y] = arr[y+1] arr[y+1] = z # main arr = [1,9,20,4,5,1,78,54,0,23] bubblesort(arr) print(arr) <file_sep># Ch.18 Paging Intro solution to segmentation's fragmentation: paging - fixed size pieces of memory with a fully developed paging approach the system will be able to support the abstraction of an address space no need to worry about direction heap and stack growing in OS just keeps a free list of all free pages and grabs the first one off of the list when requested **page table** - OS keeps a per process data structure to store the address translations for each of the virtual pages - placed in physical memory ### translating virtual to physical split virtual address into 2 components: **virtual page number** and **offset** virtual address size = x 2^x = address space in bytes or size of VPN portion of virtual address = y 2^y = page size with a page size of 16 bytes 2 higher order bytes the VPN, lower 4 the offset into that page every virtual page corresponds to a physical page - physical frame number of physical page number note: offset is not translated only the virtual page number VPN = (VirtualAddress & VPN_MASK) >> SHIFT PTEAddr = PhysicakPageTableBaseRegister * (VPN * sizeof(PTE)) offset = VirtualAddress & OFFSET_MASK PFN = PTE[PTEAddr]-> PFN PhysAddr = (PFN << SHIFT) | offset end === for 32 bit address space: - page tables take lots of space - if need 4 bytes per page table entry,thats 4MB for each page table maintained in physical memory due to size can virtualize OS memory as well can also write pages to disk **linear page table** array of pointers to a page table entry - many variations of this - index array by virtual page number, looks up the PFN in the PTE common features - valid bit - indicate whether particular translation is valid - code and heap at one end, stack at other - space inbetween marked invalid - protection bit - rwx - present bit - indicate if page in memory or on disk (**swapped** out) - dirty bit - indicate if page modified since last brought into memory - reference bit - indicate if been accessed recently **2 problems to solve with paging**: 1. slower machine (lots of cycles just to access memory) 2. wasteful use of memory space <file_sep>memo = {} def fib(n): if (n in memo): return memo[n] elif n <= 2: return 1 else: # breakpoint() memo[n] = fib(n-1) + fib(n-2) return memo[n] n = int(input("N = ")) print(fib(n)) <file_sep># include <stdio.h> # include <stdlib.h> int x,y; int array[5][4]; int main (void) { for ( x = 0 ; x < 5 ; x++) { for ( y = 0 ; y < 4 ; y++) { array[x][y] = rand(); printf("%d,%d : %d\n", x, y, array[x][y]); } } return 0; } <file_sep># Bonus Day 3 Working with C++ Classes and Objects ## working with complex data in C++ can add functions as members to structures to call use member operator, for struct time with member function print time: struct time { int hours; ... void print_time(); } time.print_time(); to create its prototype: void time::print_time(void){ function } ## Using classes just like structure: class time { int variables... }; in C++ and object is simply a declared data item created by using a class **instantiating**- when create an instance of a class determine which routines have access to data by using three additional keywords: public private protected by default classes are **private**- meaning data members and member functions are only accessible to themselves structures are default public **public**- any external source within program can access usually member data is kept private or protected for inherited classes, and member functions are public and set up to modify private member data class time { private: int hours; public: void add_hour(void); }; allows you to **encapsulate** programs functionality allows you to change data members without having to change all the programs that use your class use classes instead of structures if member functions are going to be used ## Constructors and Destructors **constructor**- specialized member function- included with class. same name as class- used to create classes- modify definition to initialize data members **destructor**- same name as class but has ~ in front. destroys object. destroyed when goes out of scope or program ends **very valuable to overload class's constructor** allows for more dynamic input ## Using Classes as data members class inception access same way as nested structure: line1.start.x uses example of class to record x and y of point nested in a line class that uses 2 point classes to define the line ## Inheriting in C++ **inheritance** capability to create new classes by building upon existing classes **base class**- class that is inherited from by another class **subclass**- class that inherits from another class to declare: class subclass: public base class { protected: long subclassvariables; public: void sublcassfunction(); } actually creating base class THEN creating subclass for desctuctors- first subclass is called then base class is called <file_sep> <?php $servername = "localhost"; $username = "username"; $password = "<PASSWORD>"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // sql to create table $sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; if ($conn->query($sql) === TRUE) { echo "Table MyGuests created successfully"; } else { echo "Error creating table: " . $conn->error; } $conn->close(); ?> <file_sep>#include <stdio.h> int main () { int x; char array[26] = {"Here is my test string"}; for ( x=0 ; x < 26 ; x++) { printf("%c\n", array[x]); } return 0; } <file_sep>def rotleft(a, d): for n in range(d): a.append(a.pop(0)) return a test = [1,2,3,4,5,6,7,8] print(rotleft(test, 7)) <file_sep>package inheritance; /** * Represents a function which is the quotient of two other function * @author jeremy * */ public class Quotient implements Function { private Function num; private Function den; /** * Constructs a new quotient function given a function for the numerator * and a function for the denominator. * * @param num * @param den */ public Quotient(Function num, Function den) { this.num = num; this.den = den; } @Override public double evaluate(double x) { return num.evaluate(x) / den.evaluate(x); } @Override public String toString() { return "(" + num.toString() + ") / (" + den.toString() + ")"; } } <file_sep>#include "table_tests.h" using namespace std; /********************************* CONSTANTS *********************************/ const string NAMES[] = {"Alice", "Bob", "Chris", "Dave", "Emily", "Frank", "Grace", "Harry", "Ingrid", "Jeremy"}; const long NUMBERS[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; const string KATE = "Kate"; const long KATE_NUMBER = 11; const string JEREMY = "Jeremy"; const long JEREMY_NUMBER = 10; /******************************** TEST METHODS ********************************/ /* * Function: test_false * ---------------------------- * runs a test where the expected output is false * */ void test_false(const char* test_name, bool result) { printf("Test: %s... ", test_name); if (!result) { printf("passed\n"); } else { printf("FAILED."); } } /* * Function: test_true * ---------------------------- * runs a test where the expected output is true * */ void test_true(const char* test_name, bool result) { printf("Test: %s... ", test_name); if (result) { printf("passed\n"); } else { printf("FAILED."); } } /* * Function: test_NULL * ---------------------------- * runs a test where the expected output is NULL * */ void test_null(const char* test_name, void* result) { printf("Test: %s... ", test_name); if (result == NULL) { printf("passed\n"); } else { printf("FAILED."); } } /* * Function: test_with_longs * ---------------------------- * runs a test where the expected output is a long * */ void test_longs(const char* test_name, const long result, const long expected) { printf("Test: %s... ", test_name); if (result == expected) { printf("passed\n"); } else { printf("FAILED. Expected %ld (result %ld)\n", expected, result); } } /* * function: hash_string * ---------------------------- * Uses std::hash to calculate the hash of a given string * aString: string to hash * * returns: hash of the string * */ size_t hash_string(const void* aString) { string s = *((string*) aString); return hash<string>{}(s); } /* * function: compare_strings * ---------------------------- * Uses the std::string class to compare two strings * p1: pointer to a string * p2: pointer to another string * * returns: -1 if string at p1 comes before string at p2 in lexicographical order * +1 if string at p1 comes after string at p2 in lexicographical order * 0 if strings at p1 and p2 are equivalent * */ int compare_strings(const void* p1, const void* p2) { string s1 = *((string*) p1); string s2 = *((string*) p2); return s1.compare(s2); } /* * function: address_book_entry_to_string * ---------------------------- * Returns a char* representation of a record * * p: pointer to a record */ char* address_book_entry_to_string(const void* p) { Record* record = (Record*) p; string name = *((string*) record->key); long number = *((long*) record->value); int area_code = number / 10000000; int exchange = (number % 10000000) / 10000; int last_four = number % 10000; char* buff = (char*) malloc(256 * sizeof(char)); sprintf(buff, "%s: (%03d) %03d-%04d", name.c_str(), area_code, exchange, last_four); return buff; } /********************************** HELPERS **********************************/ HashTable* empty_table() { HashTable* table = create_table(10, hash_string, compare_strings, address_book_entry_to_string, sizeof(string), sizeof(long)); return table; } bool fill_table(HashTable* table) { bool success = true; for (int i = 0; i < 10; i++) { success = success && insert(table, &NAMES[i], &NUMBERS[i]); } return success; } /********************************** INSERT **********************************/ void add_to_null_table_fails(){ test_false("Can't add to NULL table", insert(NULL, &KATE, &KATE_NUMBER)); } void add_null_key_fails(){ HashTable* table = empty_table(); test_false("Can't add NULL key", insert(table, NULL, &KATE_NUMBER)); } void add_null_value_fails(){ HashTable* table = empty_table(); test_false("Can't add NULL key", insert(table, &KATE, NULL)); } void add_duplicate_key_fails() { HashTable* table = empty_table(); fill_table(table); test_false("Add duplicate key fails", insert(table, &JEREMY, &JEREMY_NUMBER)); } void test_build_full_table(){ HashTable* table = empty_table(); test_true("Successful build of full table", fill_table(table)); } void overfilled_table_fails() { HashTable* table = empty_table(); fill_table(table); test_false("Can't overfill OA Table", insert(table, &KATE, &KATE_NUMBER)); } /********************************** SEARCH **********************************/ void search_null_table_fails() { test_null("Can't search NULL table", search(NULL, &KATE)); } void search_null_key_fails() { HashTable* table = empty_table(); fill_table(table); test_null("Can't search for NULL key", search(table, NULL)); } void search_empty_table_fails() { HashTable* table = empty_table(); test_null("Searching an empty table fails", search(table, &KATE)); } void failed_search_fails() { HashTable* table = empty_table(); fill_table(table); test_null("Failed search fails", search(table, &KATE)); } void normal_search_works() { HashTable* table = empty_table(); fill_table(table); long* lookup = (long*) search(table, &JEREMY); test_longs("Normal lookup works", *lookup, JEREMY_NUMBER); } /********************************** REMOVE **********************************/ void remove_from_null_fails() { test_false("Can't remove from NULL table", remove(NULL, &JEREMY)); } void remove_null_key_fails() { HashTable* table = empty_table(); fill_table(table); test_false("Can't remove NULL key", remove(table, NULL)); } void remove_key_not_present_fails() { HashTable* table = empty_table(); fill_table(table); test_false("Can't remove key not in table", remove(table, &KATE)); } void normal_remove_works() { HashTable* table = empty_table(); fill_table(table); if (remove(table, &JEREMY)) { test_null("Key successfully removed from table", search(table, &JEREMY)); } else { // Print a failure test_true("Removal operation works", false); } } /********************************** REPLACE **********************************/ void replace_in_null_table_fails() { test_false("Can't replace in NULL table", replace(NULL, &JEREMY, &KATE_NUMBER)); } void replace_null_key_fails() { HashTable* table = empty_table(); fill_table(table); test_false("Can't replace with NULL key", replace(table, NULL, &KATE_NUMBER)); } void replace_null_value_fails() { HashTable* table = empty_table(); fill_table(table); test_false("Can't replace with NULL value", replace(table, &JEREMY, NULL)); } void replace_key_not_present_fails() { HashTable* table = empty_table(); fill_table(table); test_false("Can't replace key not in table", remove(table, &KATE)); } void normal_replace_works() { HashTable* table = empty_table(); fill_table(table); if (replace(table, &JEREMY, &KATE_NUMBER)) { // Replace says it did things right, let's check long* number = (long*) search(table, &JEREMY); test_longs("Replacement successful", *number, KATE_NUMBER); } else { // Print a failure test_true("Replacement operation works", false); } } /******************************** COMBINATIONS ********************************/ void test_remove_then_add_full_table() { HashTable* table = empty_table(); fill_table(table); remove(table, &JEREMY); if (insert(table, &KATE, &KATE_NUMBER)) { long* number = (long*) search(table, &KATE); test_longs("Entry added after delete from full table", *number, KATE_NUMBER); } else { // Fail message test_true("Add operation after delete from full table", false); } } /******************************** TEST GROUPS ********************************/ void insert_tests() { add_to_null_table_fails(); add_null_key_fails(); add_null_value_fails(); add_duplicate_key_fails(); test_build_full_table(); overfilled_table_fails(); } void search_tests() { search_null_table_fails(); search_null_key_fails(); search_empty_table_fails(); failed_search_fails(); normal_search_works(); } void remove_tests() { remove_from_null_fails(); remove_null_key_fails(); remove_key_not_present_fails(); normal_remove_works(); } void replace_tests() { replace_in_null_table_fails(); replace_null_key_fails(); replace_null_value_fails(); replace_key_not_present_fails(); normal_replace_works(); } void combo_tests() { test_remove_then_add_full_table(); } <file_sep>package inheritance; public class Negative implements Function { private Function num; /** * Constructs a new negative function * * @param num */ public Negative(Function num) { this.num = num; } @Override public double evaluate(double x) { return num.evaluate(x) * -1; } @Override public String toString() { return "-" + num.toString(); } } <file_sep>#!/bin/bash cards="/home/dic3jam/Desktop/notebook/2230-SysAdm/4week/test/cards.txt" details="/home/dic3jam/Desktop/notebook/2230-SysAdm/4week/test/details.txt" test="/home/dic3jam/Desktop/notebook/2230-SysAdm/4week/test/" mkdir age{1,2,3} cd "age1" mkdir $(grep -oE "(\w+)\s+age1" "$cards" | cut -d " " -f1 | uniq) cd "../age2" mkdir $(grep -oE "(\w+)\s+age2" "$cards" | cut -d " " -f1 | uniq) cd "../age3" mkdir $(grep -oE "(\w+)\s+age3" "$cards" | cut -d " " -f1 | uniq) x=1 while [ $x -le 77 ] do i=$(awk 'NR=='$x' { print $3 }' "$cards" | tr -d '\n') cd "$i" a=$(awk 'NR=='$x' { print $2 }' "$cards") cd "$a" b=$(awk 'NR=='$x' { print $0 }' "$details" | grep -oE "^\w+\s?\w+") touch "$b" chmod a+w "$b" awk 'NR=='$x' { $1=""; print $0 }' "$details" | sed -e 's/^[\s]*//' > "$b" x=$((x+1)) cd "$test" done <file_sep>#include "jimSort.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> #include <string.h> //global value for size of arrays int arraySize = 0; int main(int argc, char* argv[]) { //set some options for the menus int option = 0; int sortType = 0; //seed the random number generator srand(time(0)); //open text file for writing FILE* fp = fopen("dataWrangle/sortResults.txt", "w"); if(fp == NULL) { printf("Unable to open sortResults.txt"); return(1); } //switch menu for program control can run 1 manual trial or do an auto trial bool quit = true; while(quit) { bool check = true; while(check) { if(option == 0) { printf("\nPlease choose an option:\n 1- Auto\n 2- Manual\n 3- Quit\n"); scanf("%d", &option); if( option > 0 && option < 4 ) check = false; else printf("\nHey guy, options are 1 - 3\n"); } } int trials = 1; bool verify = true; switch(option) { //case 1- run each sort 10 times at increasing array sizes case 1: arraySize = 100; for(int i = 0; i < 10; i++) { sorter(2, 10, arraySize, fp); // arraySize *= 2; } arraySize = 100; for(int i = 0; i < 10; i++) { sorter(1, 10, arraySize, fp); // arraySize *= 2; } break; //case 2 manual- prompt for array size and sort type and number times to execute case 2: while(verify) { printf("\nSort Type 1 for insertion 2 for selection\n"); scanf("%d", &sortType); printf("\nArray size: \n"); scanf("%d", &arraySize); printf("\nTrials: \n"); scanf("%d", &trials); verify = (arraySize > 0 && trials > 0 && (sortType == 1 || sortType == 2)) ? false : true; } sorter(sortType, trials, arraySize, fp); break; //case 3 exit program case 3: quit = false; break; }//end switch option = 0; }//end of while loop menu fclose(fp); return 0; }//end main //create random array at arraySize int* randomize(int arraySize) { int* sortArray = malloc(sizeof(int) * arraySize); for(int i = 0; i < arraySize; i++) sortArray[i] = rand() % 20; return sortArray; } //function for timing double makeTime(clock_t start, clock_t end) { double sortTime = ((double) (end - start)) / CLOCKS_PER_SEC; return sortTime; } //actually performs the operations specified void sorter(int sortType, int trials, int arraySize, FILE* fp) { clock_t start, end; int* sortArray = randomize(arraySize); for(int i = 0; i < trials; i++) { char type = 'n'; if( sortType == 2 ) { start = clock(); selectionSort(sortArray, arraySize); end = clock(); type = 's'; } else if( sortType == 1 ) { start = clock(); insertionSort(sortArray, arraySize); end = clock(); type = 'i'; } double likeForever = makeTime(start, end); fprintf(fp, "%c,%f,%d\n", type, likeForever, arraySize); printf("\n Sort: %c,Performed in: %f,on Array of Size: %d\n",type, likeForever, arraySize); }//end trials loop free(sortArray); } <file_sep>#ifndef TREE_TESTS_H_INCLUDED #define TREE_TESTS_H_INCLUDED #include "bst.h" void test_with_strings(const char*, const char*, const char*); void test_false(const char*, bool); void test_true(const char*, bool); int compare_ints(const void*, const void*); char* int_formatter(const void*); void add_to_null_fails(); void add_null_key_fails(); void add_to_empty_tree_works(); void add_left_works(); void add_right_works(); void search_null_fails(); void search_for_null_key_fails(); void failed_search_fails(); void normal_search_works(); void remove_from_null_fails(); void remove_from_empty_fails(); void remove_null_key_fails(); void remove_missing_key_fails(); void remove_node_with_no_kids(); void remove_node_with_right_child(); void remove_node_with_left_child(); void remove_node_with_two_kids(); void remove_root_works(); void add_tests(); void search_tests(); void delete_tests(); #endif <file_sep>#include <stdio.h> #include <stdlib.h> FILE *fp; char filename[50], buffer[100], ch; int i = 0; void main () { printf("Please provide the filename: "); scanf("%s", filename); printf("You input %s\n\n", filename); if( (fp = fopen(filename, "r")) == NULL ) { fprintf(stderr, "Error opening file."); exit(1); } printf("Copying file\n"); fread(buffer, sizeof(char), 100, fp); /* if(fread(buffer, sizeof(char), 100, fp) != 100) { fprintf(stderr, "Error copying file."); exit(1); }*/ //Print before changes int a=0; for(a=0; a < 100; a++) printf("%c", buffer[a]); printf("\n"); for(i = 0; i < 100; i++) { if(buffer[i] < 123 && buffer[i] > 96) buffer[i] = buffer[i] - 32; } //Print after changes a=0; for(a=0; a < 100; a++) printf("%c", buffer[a]); printf("\n"); fclose(fp); if( (fp = fopen("output.txt", "w")) == NULL) { fprintf(stderr, "Error opening output file."); exit(1); } if (fwrite(buffer, sizeof(char), 100, fp) != 100) { fprintf(stderr, "Error reading to new file."); exit(1); } fclose(fp); } <file_sep>#Bonus Day 2: The C++ Programming Language different set of libraries and routines stdio.h is now iostream.h **cout** sends text to output device. redirect values to it cout << "Hello World!"; cout ENCAPSULATES printing functionality and do not need to specify data types of variables to be printed like printf() add **bool** data type- either true- 1 or false-0 stored in a single byte classes define objects in c++ can declare a variable at any time- can wait to declare variable when ready to use it after declared basic variables will stay in scope until current block ends ex: need a counter for a for loop? just declare it in the for declaration **overloading** a function- use function name more than once must be differences between function prototypes data types OR less inputs OR default values void rectangle(int width = 3, int length = 3); should place values that will probably be defaulted as right as possible **inline functions**- requesting compiler to replace every function call with the literal code of the function- for speed- only good for smaller functions inline long square(long value); **cin**- does opposite of cout and redirects input into a variable cin >> nbr; <file_sep>#include <stdio.h> int main () { int x = 0x10, y = 0xFF; printf("%d\n", (x & y)); printf("%d\n", (x | y)); printf("%d\n", (x ^ y)); } <file_sep>/* Program to calculate the product of two numbers. */ #include <stdio.h> int val1, val2, val3; int product(int x, int y); int main( void ) { /*Get the first number */ printf("Enter a number between 1 and 100: "); scanf("%d", &val1); /*Get the second number */ printf( "Enter another number between 1 and 100: "); scanf("%d", &val2); /*Calculate and display the product */ val3 = product(val1, val2); printf ("%d times %d = %d\n", val1, val2, val3); return 0; } /* Function returns the product of the two values provided */ int product(int x, int y) { return (x * y); } <file_sep># Ch.21 Beyond Physical Memory: Mechanisms ### (should be called swap intro) with a large address space you do not have to worry about if there is room enough in memory for your programs data structures for page to go to swap, OS will need to remember the disk address of a given page normally keeps some of their valid pages in memory, with the rest located in swap space on the disk good memory access summary pg 233: 1. hardware extracts VirtualPageNumber from virtual address 2. checks TLB for a hit, if hit produces physical address if not: 3. if TLB miss hardware locates page table in memory (using page table base register) and looks up PageTableEntry using VPN as index 4. if page is valid and present in physical memory hardware extracts PFN from PTE, installs in TLB, retries instruction may find page NOT present in physical memory, using mechanism of **present bit** **page fault** - accessing a page that is not in physical memory - triggers a trap handler **page fault handler** - OS will need to swap page back into memory PTE for page swapped to disk can now store disk address when I/O completes, OS update page table to mark page as present - remember that while running I/O request, process goes into blocked state so ca nresume other work if memory is full, OS will have to move some pages out, then move the new pages in - **page replacement policy** USUALLY OS has mechanisms to keep some memorey free at all times and do not often use a page fault handler most use a **high watermark and low watermark** IF OS notices there are fewer that low watermark pages available, background thread evicts pages until high watermark pages are available again - usually some kind of swap or page daemon so maybe the page fault handler now just informs the page daemon "hey I need some more pages" and lets it take over so we have achieved the shroud of virtualization so that a process believes it has one contiguous address space <file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign05 - Advanced Web Development</h2> <h2>Research</h2> <!--writeup goes here--> <?php include 'assign05/assign05-writeup.php'?> <h2>tutor.com proof of use</h2> <img src="tutor.png" width="1500" height="500"> <h2>Before & After CODE</h2> <p> Example 1 - 3 I did all the way through the advanced steps. The form will write to an xml then in the second submission when you look up your name it will read from that xml file and print it to the screen. <ul> <li> Before: <a href="assign05/before.php" target="_blank"> Before</a></li> <li> After: <a href="assign05/after.php" target="_blank"> After</a></li> </ul></p> <!-- </ul></p> <p> Example 2 <ul> <li> Before: <a href="" target="_blank"> Before</a></li> <li> After: <a href="" target="_blank"> After</a></li> </ul></p> <p> Example 3 <ul> <li> Before: <a href="" target="_blank"> Before</a></li> <li> After: <a href="" target="_blank"> After</a></li> </ul></p> --> </div> <?php include 'footer.php';?> </body> </html> <file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign02 - Advanced Web Development</h2> <h2>Research</h2> <p>I have used and am very familiar with Eclipse, VSCode, and Vim. I use Eclipse for Java programming, and I love the debugger tools in VSCode (command line debuggers like gdb or pdb do not always offer enough of a visual for me to understand the bug) and sometimes will use VSCode for Python or C projects, but my favorite text editor is Vim. Admittedly I am such a Vim nut that when I am in VSCode or Eclipse I have an extension turned on so I can keep using the Bim key bindings. I do as much of my coding in a terminal with Vim as I can - I find all the gee-wiz gizmos that IDEs have to be distracting. I use a window plexing terminal emulator (called Terminator- like tmux but better) and I have a few Vim plugins for syntactic highlighting. I find my workflow for that to be very efficient. For this class though I believe I will try some more assignments with VSCode. There are some extensions to aid with web development in VSCode that will far exceed my capabilities with a terminal and Vim</p> <p>For Assignment 2 it is to research EDITORS. </p> <p>Link 1: <a href="https://code.visualstudio.com/" target="_blank"> https://code.visualstudio.com/</a></p> <p>Link 2: <a href="https://www.eclipse.org/" target="_blank"> https://www.eclipse.org/</a></p> <p>Link 3: <a href="https://www.vim.org/" target="_blank"> https://www.vim.org/</a></p> <h2>Before & After CODE</h2> <p> Example 1 <ul> <li> Before: <a href="https://jmd06260.classweb.ccv.edu/AdvWeb/assign02/class-before.php" target="_blank"> Classes before</a></li> <li> After: <a href="https://jmd06260.classweb.ccv.edu/AdvWeb/assign02/class-after.php" target="_blank"> Classes after</a></li> </ul></p> <p> Example 2 <ul> <li> Before: <a href="https://jmd06260.classweb.ccv.edu/AdvWeb/assign02/operators-before.php" target="_blank"> Operators before</a></li> <li> After: <a href="https://jmd06260.classweb.ccv.edu/AdvWeb/assign02/operators-after.php" target="_blank"> Operators after</a></li> </ul></p> <p> Example 3 <ul> <li> Before: <a href="https://jmd06260.classweb.ccv.edu/AdvWeb/assign02/print-before.php" target="_blank"> Print before</a></li> <li> After: <a href="https://jmd06260.classweb.ccv.edu/AdvWeb/assign02/print-after.php" target="_blank"> Print after</a></li> </ul></p> </div> <?php include 'footer.php';?> </body> </html> <file_sep>import csv import sys #assign command line arguments if len(sys.argv) > 3 or len(sys.argv) < 1: print("Incorrect command line arguments") exit(1) people = str(sys.argv[1]) seq = str(sys.argv[2]) #import the people try: peopleFile = open(people, "r") csv_reader = csv.reader(peopleFile, delimiter=',') except: print("Unable to open people file") exit(1) peeps = [] for row in csv_reader: peeps.append(row) #print(peeps) #import the dna sequence try: seqFile = open(seq, "r") except: print("Unable to open sequence file") exit(1) #assign the sequence to a string for line in seqFile: sequence = line #begin finding sequences #while return is not -1, creeper starting at first instance of dna seq, then find next instance, if next instance is lenofseq away, increment counter, if not compare to maxcounter, if greater assign to max counter seqCounts = {"AGATC":0,"TTTTTTCT":0,"AATG":0,"TCTAG":0,"GATA":0,"TATC":0,"GAAA":0,"TCTG":0,"AGAT": 0} for x in seqCounts: maxcounter = 0 end = 0 start = 0 end = 0 counter = 0 end = sequence.find(x,start) print(str(end)) if(sequence[end:len(x)] == x): counter = counter + 1 start = end + len(x) print(str(counter)) if(counter >= maxcounter): maxcounter = counter seqCounts[x] = maxcounter print(seqCounts) #close files peopleFile.close() seqFile.close() <file_sep># include <stdio.h> # define MAX 10 int count; int array1[MAX] = {2,4,6,8,10,12,14,16,18,20}; int array2[MAX] = {2,4,6,8,10,12,14,16,18,20}; int sumarray[MAX]; int sumfunction(int array1[], int array2[], int length); int main (void) { sumfunction(array1, array2, MAX); for (count = 0 ; count < MAX ; count++) { printf("\n%d\n", sumarray[count]); } return 0; } int sumfunction( int array1[], int array2[], int length ) { int sum; for (count = 0 ; count < length ; count++) { sumarray[count] = array1[count] + array2[count]; } return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define max 50 int comp(const void *s1, const void *s2); void main () { char *names[max], buffer[max], quit[5] = "quit"; int count; for (count = 0; count < 5; count++) { printf("Please input name. quit to quit: %d:", count+1); scanf("%s", buffer); names[count] = malloc(strlen(buffer)+1); strcpy(names[count], buffer); if (*names[count] == *quit) break; } qsort(names, 5, sizeof(names[0]), comp); for (count=0; count <5; count++) printf("\n%d: %s", count+1, names[count]); } int comp (const void *s1, const void *s2) { return (strcmp(*(char **)s1, *(char **)s2)); } <file_sep>#include "tree_tests.h" int main() { add_tests(); search_tests(); delete_tests(); } <file_sep>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> int main(int argc, char *argv[]) { int parent = (int) getpid(); int scom = fork(); if(scom < 0) { fprintf(stderr, "fork failure\n"); exit(1); } kill(parent, SIGSTOP); if (scom == 0) { //childs path printf("Child says hello, PID: %d\n", (int) getpid()); kill(parent, SIGCONT); } if(scom > 0) { //parents path printf("Parent says goodbye, PID: %d\n", (int) getpid()); } } <file_sep>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main(int argc, char *argv[]) { int parent = (int) getpid(); printf("Start process PID: %d\n", parent); int child1 = fork(); int child2 = fork(); int fildes[2]; if(child1 < 0 || child2 < 0) { fprintf(stderr, "fork failure\n"); exit(1); } else if (child1 == 0) { //child1 path fildes[0] = STDOUT_FILENO; printf("Child 1 says: \n"); } else if (child2 == 0) { //child2 path fildes[1] = STDOUT_FILENO; } else { wait(NULL); pipe(fildes); return 0; } } <file_sep>#include <stdio.h> #include <stdlib.h> char ch, filename[50]; int n; FILE *fp; void main (void) { printf("\nPlease specify the file you would like to count the characters of: "); scanf("%s", filename); if ( (fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "\nError opening file specifed"); exit(1); } while (1) { ch = fgetc(fp); if(feof(fp)) break; if(ch > 31 && ch < 127) n++; } printf("There are %d characters in this file\n", n); fclose(fp); } <file_sep># include <stdio.h> int x; void main () { while ( x < 100 ) { printf("%d\n", x); x += 3; } } <file_sep>FLAG = -o DFLAG = -g -o CC = gcc heapsort: main.c heapsort.h algorithms.h ${CC} ${FLAG} heapsort main.c heapsort.h algorithms.h debug: main.c heapsort.h algorithms.h ${CC} ${DFLAG} debug main.c heapsort.h algorithms.h clean: rm -f heapsort debug *.txt core <file_sep> <?php ini_set('display_errors',1); $servername = "localhost"; $username = "jmd06260"; $password = "<PASSWORD>"; $dbname = "jmd06260_wordpress"; $connect = new mysqli($servername, $username, $password, $dbname); if($connect->connect_error){ die("Could not connect". $connect->connect_error); } echo "Connected to database! Go me!\n"; echo "<br>"; ?> <file_sep>//Insertion sort #include "jimSort.h" void insertionSort(int* sortArray, int arraySize) { int o = 1; while( o < arraySize ) { int i = o; while((i > 0) && (sortArray[i-1] > sortArray[i])) { int tmp = sortArray[i]; sortArray[i] = sortArray[i-1]; sortArray[i-1] = tmp; i--; }//end inner loop o++; }//end outer loop } <file_sep># Ch.8 Scheduling: The Multi-Level Feedback Queue 1. optimize turn around time - done by running shorter jobs first - BUT OS does not known job lengths prior to execution 2. make system feel responsive by optimizng response time question is how can scheduler learn characteristics of running jobs then leverage that info for better scheduling ## MLFQ Basic Rules number of queues each assigned a priority level round robin applied to multiple jobs in particular priority queue Rules -------- 1. if priority(A) > Priority(B), A runs (B does not) 2. if priority(A) == Priority(B), A and B run in RR 3. when a job enters the system, it is placed at the highest priority ## how to change priority 2 extremes of jobs: 1. short-running (frequently relinquish CPU) 2. longer running "CPU-bound" jobs that need a lot of CPU time but response time is not important approximates SJF because: - all jobs start at highest priority - if longer job, will move down priority queues if an interactive job doing a lot of I/O, it will relinquish the CPU before its time slice is complete this kinda creates 2 problems: starvation - if too many interactive jobs consume all of the CPUs time can game the scheduler to consume CPU resources at the right intervals to block other processes one technique to overcome these is the **priority boost** whereby all jobs priority gets raised periodically question is what should that time be? something else to help is better accounting Rules cont -------------- 4. when a job uses up its allotment at a given level (regardless of how many times it has given up the CPU) its priority is reduced 5. after some time period S, move all the jobs in the system to the topmost queue no good answer on how many queues there should be or how big should each time slice be most MLFQs vary time slice across different queues where higher priority have short slices increase as go down some use decaying times some allow user to provide **advice** on priorities <file_sep>#include <stdio.h> #include <time.h> void mergesort(int* array, int innerBound, int outerBound); void merge(int* array, int innerBound, int midIndex, int outerBound); int* genArray(int size); double timer(clock_t begin, clock_t end); <file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign03 - Advanced Web Development</h2> <h2>Research</h2> <!--writeup goes here--> <?php include ?> <h2>Before & After CODE</h2> <p> Example 1 <ul> <li> Before: <a href="" target="_blank"> Before</a></li> <li> After: <a href="" target="_blank"> After</a></li> </ul></p> <p> Example 2 <ul> <li> Before: <a href="" target="_blank"> Before</a></li> <li> After: <a href="" target="_blank"> After</a></li> </ul></p> <p> Example 3 <ul> <li> Before: <a href="" target="_blank"> Before</a></li> <li> After: <a href="" target="_blank"> After</a></li> </ul></p> </div> <?php include 'footer.php';?> </body> </html> <file_sep># Day 10 Working with Characters and Strings if char variable used somewhere a character expected, implemented as character. if used somewhere number expected, interpreted as a number char a,b,c char variales declared char code = 'x' variable code assigned value of x \#define EX 10. char code = EX. const char A = 'Z' 'a' creates literal character constant %c to print character for printing %d of character will return ASCII code want to print extended ASCII characters must use unsigned char **string**- sequence of characters ending with null character so when storing in an array ensure you add array[n+1] for the null character char \*message = "This is a string"; == char message[] = "This is a string"; if do not specify number of subscripts, compiler calculates for you: char string[] = "Alabama"; since end of string marked just need something that POINTS at the beginning using array's name to access strings is method C library expects using array to store a string really only for allocating space \*array = array[] **malloc()**- if program has dynamic memory needs. pass it the amount of memory needed. malloc() will find memory of required size and return address of first byte. return type to pointer type void- compatible all data types. **returns address of first block at return type** char \*str; str = (char \*) malloc(size) ex: (int \*) malloc(50 * sizeof(int)); if you just put malloc(50) it would only allocate 50 bytes ptr = malloc(1)- allocates 1 byte of memory and assigns address of the 1st of 1 bytes to variable ptr. This byte of memory has no name- only pointer can reference. To assign a variable would need: \*ptr = x; Ex: char \*ptr; ptr = malloc(100); if not enough memory is available, malloc returns null (0) if you want to step through the contents of a string with ptr pointing at beginning, need to keep ptr pointed at beginning, so add another variable: p = ptr; for(count = 65 ; count < 91 ; coun++) *p++ = count; **free() towards end of program in order to not hog memory space** in above example notice incremented pointer along with count so pointer moves along puts() really only takes pointers to the string to be displayed. literal string technically a pointer to itself (weird) %s to display a whole string. but must refer to a pointer to the string gets() and scanf() can read from keyboard but need place to put info. create with array declaration or malloc() **gets()**- will read all characters entered until newline (Enter) is pressed. will discard newline and add null character, ending string. then returns pointer to the string. gets a string from standard input device if string has length of 0, null stored in first position ex: while(\*(ptr = gets(Input))) != NULL - will return value stored at pointed to address scanf() also passed a pointer to strings location. beginning is first non whitespace character. runs up to next non whitespace character (not including) if use %s. if use %ns where n is an integer, accepts next n characters or up to next whitespace character whichever comes first scanf() can be passed a pointer, array name or &variable function prototype to return a pointer: char * function(char \*, char \*); ex6 requires you to find length of 2 strings then point at the longer string. creates pointers to strings, then uses strlen() to get lengths in function like exhibited here, then returns the longer with an if condition which is assigned to a pointer <file_sep># Hash Table HW 1+2 ## <NAME> 1. As you approach 100% load in the hash table, linear probing causes insertions to the table to grow and grow until clusters begin to overlap with other clusters. That is why linear probing is only useful for smaller hash tables. Using a pseudorandom function for inserting values will not make look up impossible later as the probe for each hash will follow a predictable route (the pseudo portion of the pseudorandom). 2. a. 0, 2, 4, 6 b. 1, 3, 5 <file_sep># Ch.19 Paging Faster Translations TLBs **TLB** - little cache on CPU of commonly accessed virtual emeory addresses so does not have to go to page table in RAM EVERY time TLB keeping track of frequently accessed PAGES - so if a TLB hit just calculate offset larger page sizes fewer misses spatial (elements in pages packed tightly together) and temporal locality (quick re-referencing of items in time) are the factors of speed here larger caches slower - have to keep small - caches are read from beginning to end everytime - hardware cannot be that cumbersome CISC - hardware handles TLB miss RISC - software handles TLB miss - TLB miss causes hardware exception trap into kernel, handle trap, return from trap - just have to return from trap to start of instruction (so it will replay the instruction with the value returned from the page table lookup that the trap handler is running) - need to ensure not causing infinite chain of TLB misses - several techniques to this software is flexible CISC architecture is hardware driven - large instruction sets RISC architecture is software driven - keep few powerful instructions and abstract into software **TLB entry** VPN | PFN | other bits lots of different information you can include in a TLB entry - valid bit useful for context switches - **flush** TLB on process context switch by turning all valid bits invalid - global bit communicate if translation used in multiple proceses - Address space identifier - 8 bit identifier for processes (like a PID but 8 bits instead of 32) typical TLB have 32, 64, 128 entries and be fully associative - TLB entries not in any particular order every read to TLB reads from start to finish **cache replacement** - how do we handle replacing an old TLB entry? every page table lookup should result in TLB update - trying to increase hit rate couple ways: - least-recently-used - random believe it or not random is pretty good TLBs not so good when process uses many pages - more than will fit into TLB (exceeding **TLB coverage**) BIGGER PAGES!! <file_sep>#include "algorithms.h" int leftChild(int parent) { return (2 * parent) + 1; }//end leftChild int findParent(int index) { return (index - 1) / 2; }//end findParent void siftDown(int* heap, int start, int end) { int p = start; int lefty = leftChild(p); while( lefty <= end ) { int swap = p; if(heap[swap] < heap[lefty]) swap = lefty; if(lefty + 1 <= end && heap[swap] < heap[lefty + 1]) swap = lefty + 1; if(swap == p) break; else { int tmp = heap[p]; heap[p] = heap[swap]; heap[swap] = tmp; } p = swap; lefty = leftChild(p); } }//end siftDown void heapify(int* heap, int count) { int start = findParent(count - 1); while( start >= 0 ) { siftDown(heap, start, count - 1); start--; if((start < 0) && (heap[0] < heap[1] || heap[0] < heap[2])) siftDown(heap, 0, count - 1); } }//end heapify double heapsort(int* array, int sizeOfUnsort) { clock_t start = clock(); heapify(array, sizeOfUnsort); clock_t TIME = clock(); double heapTime = timer(start,TIME); int end = sizeOfUnsort-1; while ( end > 0 ) { int tmp = array[0]; array[0] = array[end]; array[end] = tmp; end--; siftDown(array, 0, end); } return heapTime; }//end heapsort <file_sep># Day 11 Implementing Structures, Unions, and TypeDefs **structure**- collection of one or more variables grouped under a single name. can be of different data types. can hold arrays, pointers, and other structures variable within structure called **member** struct tag { members; } instance1, instance2; **tag** name of structure template, use instances to declare a version of that template **member operator**- ( . ) used to refer to a member of a instance to copy info from one instance to another: instance1 = instance2. same thing as instance1.x = instance2.x; instance1.y = instance2.y if you just define without instance can declare later with: struct tag instancename; Ex: struct time { int hours; int minutes; } time_of_birth = { 8, 45 }; ## using structures that are more complex struct rectable { struct coord topleft; struct coord bottomrt; } mybox; struct coord just x and y previously defined- now describing a shape to change the coordinates of x and y of top left would need to member incept: mybox.topleft.x = 0 mybox.topleft.y = 10 ## structures that contain arrays record.x[2] = 100 record.y[1] = 'x' pointer to first element of array y: record.y ## Arrays of Structures if you already have structure type entry- to declare array of entry structures: struct entry list[1000] list[0] has: list[0].fname list[0].lname list[1] has: list[1].fname list[1].lname .... assign one array element to another: list[1] = list[5] move data between members: strcpy(list[1].phone, list[5].phone); ## Initializing Structures initialize and declare instance: struct sale { struct customer buyer; char item[20]; float amount; } mySale = { "Acme", "left hand widget", 1000.00 }; struct sale 1990[100] { { fill in, for , index[0] } { fill in, for, index[1] } ## Structures and Pointers can use pointers as structure members, can also declare pointers to structures Declare struct data { int *value; } first; Initialize first.value = &cost; ### Creating Pointers to Structures used when passing a structure as an argument to a function 1. struct part \*p_part; 2. struct part gizmo; 3. p_part = \&gizmo; must declare a pointer to the structure tag, then link pointer to a particular instance (*p_part).number = 100; could also use the **indirect membership operator** p_part->member; ## Pointers and Arrays of Structures struct part data[100]; struct part *p_part; p_part = &data[0] OR p_part = data; points at first structure in array of structures can use normal pointer arithmetic to move through array of structures **can pass structures to functions using instance or pointer to structure** if pass pointer to structure as argument, must use -> to access members ## Unions only one member of union can be used at a time. all members of union occupy same address of memory instances can hold one variable type OR another variable type only one member can be initialized at a time pg. 279 listing 11.8 uses the type variable in structure as almost a sub instance to assign information to the union: struct tag { char type; union shared_tag{ char c; char i; } shared; } tag_instance; ## Typedef can use typedef when declaring structure so don't have to always use struct: <file_sep>package week4; import week4.NotFoundException; /* * 2260 OOP * @author <NAME> * Ch.4 Homework */ //4.2 - Frankly it does not seem to matter which loop you choose. I was able to // do the while loop in less lines of code. They both accomplish the same thing though when //one is restricted to using an out of bounds exception to terminate a loop rather than //a logical condition. public class ch4hw { public static int searchFor(int[] a, int x) throws NullPointerException, NotFoundException { /** * @requires: a is sorted * @effects: if a is null throws NullPointerException; else if x is not in a, * throws NotFoundException; else returns i such that a[i] = x. */ if(a == null) throw new NullPointerException(); int i = 0; boolean itsThere = false; for(int b = 0; /*b < a.length*/; b++) { if(a[b] == x) { i = b; itsThere = true; break; } } if(!itsThere) throw new NotFoundException(x + " is not found in the array"); else return i; } public static int searchWhile(int[] a, int x) throws NullPointerException, NotFoundException { /** * @requires: a is sorted * @effects: if a is null throws NullPointerException; else if x is not in a, * throws NotFoundException; else returns i such that a[i] = x. */ if(a == null) throw new NullPointerException(); int i = 0; boolean itsThere = true; int b = 0; while(itsThere) { if(a[b] == x) { i = b; itsThere = false; } b++; } if(!itsThere) throw new NotFoundException(x + " is not found in the array"); else return i; } public static void main(String[] args) { int[] a = {24,56,56,23,67}; int x = 24; int i = 0; try { i = searchFor(a, x); } catch (NullPointerException e) { System.out.println("The array is empty dummy"); } catch (NotFoundException d) { System.out.println(d); } catch (ArrayIndexOutOfBoundsException c) { System.out.println("Gotta catch em all"); return; } System.out.println(x + " is at index " + i); int y = 57; int u = 0; try { u = searchWhile(a, y); } catch (NullPointerException e) { System.out.println("The array is empty dummy"); } catch (NotFoundException d) { System.out.println(d); } catch (ArrayIndexOutOfBoundsException c) { System.out.println("Gotta catch em all"); return; } System.out.println(y + " is at index " + u); } //4.3 - You would want the procedure to throw an exception in this case. If it returned 0, the caller //could mistake that for the sum of the integers in the array. An exception provides better context to //the caller and detail to action upon. //4.4 - static void combine(int[] a, int[] b) throws NullPointerException { /** * @effects: if a or b are null, throws NullPointerException for the respective * empty array; else multiples in place each element of a by the sum of the elements * in b. * * This is a good specification because the calling program can catch for one * exception type that is relevant to both failure cases. This procedure can include * a separate message depending upon which array it found to be null. */ } } <file_sep>//Header files for jimSort #include <time.h> #include <stdio.h> int* randomize(int arraySize); double makeTime(clock_t start, clock_t end); void selectionSort(int* sortArray, int arraySize); void insertionSort(int* sortArray, int arraySize); void sorter(int sortType, int trials, int arraySize, FILE* fp); <file_sep>#! /usr/bin/python3 # comprehend the list - if of certain type, move into its own list def sockMerchant(n, arr): y = 0 for x in range(101): tmp = [y for y in arr if y == x] if len(tmp) > 1: y += len(tmp) // 2 return y test = [67,67,67,67,67,67] print(sockMerchant(6, test)) <file_sep>from quicksort import * def binsearch(arr, q): low = 0 high = len(arr) - 1 while low <= high: mid = (high+low) // 2 if arr[mid] > q: high = mid - 1 elif arr[mid] < q: low = mid + 1 else: return mid return -1 print(binsearch(quicksort(test, 0, (len(test)-1)), 24)) <file_sep> def countingValleys(steps, path): alt = 0 in_val = False val = 0 for x in path: if x == 'D': alt -= 1 if alt < 0: if in_val == False: in_val = True val += 1 elif x == 'U': alt += 1 if alt >= 0: in_val = False # print(f"x {x}, alt {alt}, in_val {in_val}, val {val}") return val test = "DDUUDDUDUUUD" print(countingValleys(len(test), test)) <file_sep>#ifndef OPEN_ADDRESS_H_INCLUDED #define OPEN_ADDRESS_H_INCLUDED #include "record.h" #include <stdio.h> #include <string> /* * struct: HashTable * ---------------------------- * A hash table using open addressing and lazy deletion * N: table size * buckets: array of pointers to records * hash_function: hash function used to find bucket numbers for keys * compare: function for comparing keys. Must obey the following rules: * compare(a, b) < 0 if a < b * compare(a, b) > 0 if a > b * compare(a, b) = 0 if a == b * record_formatter: returns a C string (char*) representation of a record * key_size: size of keys in bytes * value_size: size of values in bytes * */ typedef struct { int N; Record** buckets; size_t (*hash_function)(const void*); int (*compare)(const void*, const void*); char* (*record_formatter)(const void*); size_t key_size; size_t value_size; } HashTable; HashTable* create_table(const int, size_t (const void*), int (const void*, const void*), char* (const void*), const size_t, const size_t); char* table_to_string(const HashTable*); bool insert(HashTable*, const void*, const void*); void* search(const HashTable*, const void*); bool replace(HashTable*, const void*, const void*); bool remove(HashTable*, const void*); // Special helper functions for this table type int find_bucket(const HashTable*, const void*); int find_empty_bucket(const HashTable*, const void*); // Used for lazy deletion Record* const DELETED = (Record*) malloc(sizeof(Record)); #endif <file_sep>#Readability.py import sys import re #Receive the text print("Text: ") try: text = input() except: print("Text only nerd") exit(1) #Parse the text with regex letters = re.findall("\w", text) words = re.findall("\s", text) sentences = re.findall('[!.?]',text) #Apply index index = (0.0588 * (100 * (len(letters)/len(words)))) - (0.296 * (100 * (len(sentences)/len(words)))) - 15.8 index = round(index) #Return the result if (index >= 16): print("Grade 16+") elif (index < 1): print("Before Grade 1") else: print("Grade " + str(index)) <file_sep>package StringPriorityQueue; /** * Represents a priority string consisting of a string and a priority * number - immutable object cannot be modified * * @author <NAME> * */ public class PriorityString { /** The string portion of the priority string*/ private String dastring; /** The priority, must be > 0 */ private int priority; private void repOk() { assert (dastring != null) : "the string cannot be null"; assert (priority > 0) : "priority must be > 0"; } /** * Creates a PriorityString * @param String cannot be null * @param p must be greater than 0 * @throws NullPointerException if string s is null * @throws IllegalArgumentException if p is 0 or less */ public PriorityString(String s, int p) throws NullPointerException, IllegalArgumentException { if(s == null) throw new NullPointerException("String cannot be null silly!"); if(p <= 0) throw new IllegalArgumentException("Priorities must be greater than 0"); this.dastring = s; this.priority = p; repOk(); } /** * Returns the string from this PriorityString * @return the string portion of PriorityString */ public String get_string() { return this.dastring; } /** * Returns the priority of this PriorityString * @return integer value of the priority */ public int get_priority() { return this.priority; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(this.dastring + ", " + this.priority); return builder.toString(); } } <file_sep>#Day 4 Statements, Expressions, and Operators **statement**- complete instruction that directs the computer to carry out some task C compiler is not sensitive to whitespace c compiler does care about whitespace in strings use \\ to break literal string over multiple lines printf("Hello,\\ world!"); place a ; on line by itself creates a null statement block {} = **compound statement** **expression**- anything that evaluates to a numeric value simplest expression consists of a single item- variable, constant etc. **complex expression**- simpler expressions connected by an operator when an expression contains multiple operators, the evaluation of the expression depends on operator precedence an assignment statement is itself an expression. assignment statements should not be nested with other expressions **assignment statement**- variable = expression; expression is evaluated and result is assigned to variable **unary mathematical operators** |increment| ++ |increments the operand by one\\ |decrement| -- | decrements operand by one ++x same as x = x + 1; prefix mode ++x modify operand before used in enclosing statement postfix mode x++ modify operand after used in enclosing statement **binary mathematical operators**- + - * / % use () to modify evaluation order **relational operators**- == > < >= <= != (not equal. if not equal returns a 1) == and != lower in precedence than others relaional operators used to construct **program control statements**- modifies order of statement execution **if statement**- evaluates an expression and directs program execution depending on the result of that evaluation evaluates as true, executed. evaluated as false not executed if ( expression ) { statement1; statement2; else if ( expression 2 ) statement 3; else statement 4; } only need {} if more than one statement ie creating a block will return 1 or 0. any nonzero number will be evaluated as true don't use the != in an if statement containing an else **logical operators**- AND &&, OR ||, NOT ! (true if expression is false) **compound assignment operators**- combines binary mathematical operation with assignment operaion +=, -=, /=, *=, %=. ex: x += 5 - will increase x by 5 and assign that value to x **conditional operator**- only ternary operator. exp1 ? exp2 : exp3 . if exp1 evaluates to be true, then entire expression evaluates to value of exp2. if exp1 evaluates to be false entire expression evaluates to value of exp3. **comma operator**- punctuation but also split into 2 sub expressions- both expressions evaluated, left expression evaluated first, entire expression evaluates to value of the right expression x = (a++ , b++) - assigns value b to x, then increments a then increments b if use single compound if statement expressions evaluated until entire statement evaluates to be false <file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> #include <math.h> #include "mergesort.h" #define SIZE 1000 #define FACTOR 2 #define TRIALS 10 int main() { bool quit = true; while(quit) { char c = 'q'; printf("Perform mergesort starting on array of %d, increasing the array size by a factor of %d, 5 times with %d trials for each size Yes/Quit\n", SIZE, FACTOR, TRIALS); scanf(" %c", &c); if(c == 'y' || c == 'Y') quit = false; else if( c == 'q' || c == 'Q'){ quit = false; exit(0); } else quit = true; } FILE *fp = fopen("results.txt", "w"); if(fp == NULL) { printf("Unable to open a file"); exit(1); } //set a new variable so we can modify file size during execution int testSize = SIZE; for(int i = 0; i < 5; i++) { //generate the random array int* sortArray = genArray(testSize); //run TRIALS number of trials for (int a = 0; a < TRIALS; a++) { clock_t start, end = 0; start = clock(); //it begins mergesort(sortArray, 0, testSize - 1); /*for testing - print for(int i = 0; i < SIZE; i++) { printf("%d\n", sortArray[i]); }*/ end = clock(); //take the time of execution double daTime = timer(start, end); //send to the file the iteration number, the size of the array, and the time the sort took fprintf(fp, "%d,%d,%f\n", a, testSize, daTime); }//end for //free the current array before increasing the size free(sortArray); //increase array size for next testing iteration testSize *= FACTOR; } fclose(fp); return 0; }//end main int* genArray(int testSize) { int *a = (int*) malloc(testSize*sizeof(int)); srand(time(0)); for(int i = 0; i < testSize; i++) { a[i] = rand() % 20; // printf("%d\n", a[i]); } printf("\n\n"); return a; }//end genArray double timer(clock_t begin, clock_t end) { double daTime = ((double) (end - begin)) / CLOCKS_PER_SEC; return daTime; }//end timer void mergesort(int* array, int innerBound, int outerBound) { if(innerBound < outerBound) { int m = floor((innerBound + outerBound) / 2); mergesort(array, innerBound, m); mergesort(array, m + 1, outerBound); merge(array, innerBound, m, outerBound); } }//end mergesort void merge(int* array, int innerBound, int midIndex, int outerBound){ //set bounds for how much of the array goes to the left and right copies int nleft = midIndex - innerBound + 1; int nright = outerBound - midIndex; //create arrays to copy each half of array into int rightArray[nright+1], leftArray[nleft+1]; //copy half of the array into a left and right half for(int r = 0; r < nright; r++) rightArray[r] = array[midIndex + 1 + r]; for(int l = 0; l < nleft; l++) leftArray[l] = array[innerBound + l]; //assign infinity as the final bound in each half for assignment rightArray[nright] = (int) INFINITY; leftArray[nleft] = (int) INFINITY; //create counters for each half of the array int ileft = 0; int iright = 0; //increment across array, compare the half arrays, assign the lower value to array[i] for(int i = innerBound; i < outerBound + 1; i++) { if(leftArray[ileft] <= rightArray[iright]){ array[i] = leftArray[ileft]; ileft++; } else { array[i] = rightArray[iright]; iright++; } } }//end merge <file_sep><!DOCTYPE html> <html> <body> <?php $fav_food = array("Jim"=>"pasta", "Hope"=>"burgers", "Joey"=>"mac and cheese"); foreach($fav_food as $peep => $food) { echo "Person=" . $peep . ", Food=" . $food; echo "<br>"; } ?> </body> </html> <file_sep>def hourglassSum(arr): max_sum = 0 i, j = 0 while j < 3: while i < 3: sum_hrgl = arr[i][j] + arr[i+1][j] + arr[i+2][j] + arr[i+1][j+1] + arr[i][j+2] + arr[i+1][j+2] + arr[i+2][j+2] if(sum_hrgl > max_sum): max_sum = sum_hrgl i += 1 j += 1 return max_sum <file_sep># Day 2 Notes- The Components of a C Program **function**- independent section of program code that performs a certain task and has been assigned a name reference function program can execute code program can send arguments to the function **library functions**- part of C compiler package **user defined functions**- programmer creates 1. **main() function**- main( void ) {} required. braces make up main body of the program. program execution starts first statement main and ends last statement. **must include return statement at end** 2. **\#include**- instructs C compiler to add contents of an include file into program during compilation. include file separate disk file contains info used by program or compiler .h extension **variable**- name assigned to location in memory holds something. must be defined before it can be used. **function prototype**- provides compiler name and arguments of function. appears before function called. **function definition**- contains actual statement of **comments**- // single line comment /* */ multi line comment group of one or more statements in braces is a block <file_sep># Day 13 Advanced Program Control ## Ending Loops Early **break**- placed only in body of for loop, while loop, do...while loop, switch, when encountered execution immediately exits the loop **continue**- " when encountered goes back to beginning of loop to begin next iteration **goto**- unconditional jump instruction. when encountered will jump the program to a location you identify with something like "location1:". Should never use. Target must be in same function ## Infinite Loops will run forever have one of the loop functions evaluate an always true condition such as while (1) or for ( ; ; ) good for when many conditions need to be evaluated avoid if other alternatives void delay ( void) { long x; for ( x=0 ; x < 15000 ; x++) ; } that is good if you want a momentary pause in program and compiler does not contain something like sleep() ## Switch Statement execute different statements based on expression that can have more than 2 values if template matches expression, then that statement and every statement below executed (**why typically use break after every statement**) switch (expression) { case template1: { statement1; break; } case template2: { statement2; break; } default: { defaultStatement; } } also can evaluate multiple templates to the same statement: ... case 1: case 2: case 3: { statement123; break; } ## Exiting the Program can terminate a program at any time by using **exit()** can also specify one or more functions to be executed at termination takes single int argument to indicate success or failure exit(status); 0 means terminated normally, 1 means terminated with some error ## OS System Commands system(command); <file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign07 - Advanced Web Development</h2> <h2>Research</h2> <!--writeup goes here--> <p>So far SQL seems very human friendly and straightforward. Although, I do get the sense that to truly master an understanding of everything that MySQL can do would take a considerable amount of time. PHPMyAdmin also seems easy to use, I just cicked my way the SQL section, and copy pasted the Larry Ullman sql.sql queries into the box and ran it (I did have to take a few things out to get it to run). Looking at what it would take to write all of that information by hand, I can see how an application like PHPMyAdmin can save volums of time.</p> <h2>Before & After CODE</h2> <h3>Intermediate - database connect and display</h3> <?php ini_set('display_errors',1); require 'mysqli_connect.php'; echo "This script is just returning the number of message subjects with the term PHP in them\n"; echo "<br>"; $query1 = "SELECT subject FROM messages"; $r = mysqli_query($connect, $query1); if($r){ echo "Query ran"; } else { echo "Did not run son"; } echo "<br>"; echo $r->num_rows; echo " have been imported successfully!"; $r->free_result(); ?> </div> <?php include 'footer.php';?> </body> </html> <file_sep>#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char *argv[]) { printf("Start process PID: %d\n", (int) getpid()); int x = 100; int scom = fork(); if(scom < 0) { fprintf(stderr, "fork failure\n"); exit(1); } else if (scom == 0) { //childs path printf("Child process PID: %d\n", (int) getpid()); printf("Childs value of x before change: %d\n", x); x = 201; printf("Childs value of x after change: %d\n", x); } else { //parents path printf("Parent process PID: %d\n", (int) getpid()); printf("Parent value of x before change: %d\n", x); x = 101; printf("Parent value of x after change: %d\n", x); } } <file_sep>#CS50 Week 8 Information <file_sep><!DOCTYPE html> <html> <body> <?php $array1 = array(5, "Five"); $array2 = array(10, 10); $array3 = array(10,10,10); $array4 = array(5,5); var_dump($array1 === $array2); var_dump($array2 === $array3); var_dump($array2 === $array4); echo "These will all be false- it seems like the identity operator is looking at the contents of the array, rather than just type checking the contents (cough cough hast table)"; ?> </body> </html><file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign04 - Advanced Web Development</h2> <h2>Research</h2> <!--writeup goes here--> <?php include 'assign04/assign04-writeup.php'?> <h2>Before & After CODE</h2> <p> Example 1 <ul> <li> Before: <a href="assign04/ex1bef.php" target="_blank"> Before</a></li> <li> After: <a href="assign04/ex1aft.php" target="_blank"> After</a></li> </ul></p> <p> Example 2 <ul> <li> Before: <a href="assign04/ex2bef.php" target="_blank"> Before</a></li> <li> After: <a href="assign04/ex2aft.php" target="_blank"> After</a></li> </ul></p> <p> Example 3 <ul> <li> Before: <a href="/assign04/ex3bef.php" target="_blank"> Before</a></li> <li> After: <a href="/assign04/ex3aft.php" target="_blank"> After</a></li> </ul></p> <h3>PHP Info</h3> <br> <?php echo phpinfo(); ?> <br> <h3>MySQL Info</h3> <?php echo "MySQL version on ClassWeb.ccv.edu is: "; echo mysqli_get_server_info($dbc); ?> </div> <?php include 'footer.php';?> </body> </html> <file_sep> <?php require mysqli_connect.php; $query = "CREATE database DB1"; if($conn->query($query) == TRUE) { echo "Good!"; } else { echo "ERROR" . $conn->error; } $conn->close(); ?> <file_sep># include <stdio.h> int x; int main () { for (x = 0 ; x < 100 ; x += 3) { printf("%d\n", x); } return 0; } <file_sep> #Day 14 **STREAMS** **input**- data moved from external location to RAM **stream**-sequence of characters. text or binary streams. text streams organized into lines up to 255 characters long and terminated with newline 5 standard streams: 1. stdin- standard input 2. stdout- standard output 3. stderr- stadard error 4. stdprn- standard printer 5. stdaux- standard auxillary each stream connected to file- intermediate step between stream that program deals with and actual device being used for input or output ## Accepting Keybaord Input character input, line input, formatted input ### Character Input read input from stream one character at a time. some buffered- holds in storage space until you press enter then sends to stdin stream some automatically echo each character as received **getchar()**- obtains next character from stream stdin. provides buffered character input with echo no characters are received until you press enter. each keypress assigned to variable if you choose. only gets 1 **getch()**- unbuffered input without echo. returns each character as soon as key pressed. does not print to screen. only gets 1 buffered character functions translate \\r- carriage return to \\n-newline. unbuffered do not **getche()**- like getch() but echoes **getc() and fgetc()**- don't automatically work with stdin let program specify input stream **fgets()**- reads line of text from an input stream, can specify how output. char \*fgets(char \*str, int n, FILE \*fp); 1. char \*str where stored 2. int n - max characters to input. nothing specified will read until new line, or eof 3. specify input stream ### Formatted input scanf() and fscanf() use [\^*character*] to truncate strings **scanf()**- buffered. pg 351 for gee-wiz modifiers. extra characters can wait in stdin need to use fflush(stdin) to clear ## Controlling Output character output, line output, formatted output **putchar()**- sends single character to stdout. will accept int but will print ascii value of int **fputc()**- int fputc(int c, FILE \*fp) **puts()**- int puts(char \*cp). displays string up to null **printf()**- see pg 363 for gee-wiz modifiers. ## Redirection UNIX redirection < > >> work: redirects standard input. redirect.c > input.txt changes standard input to input.txt redirect.c > test.txt stderr always connected to screen <file_sep># include <stdio.h> float a, b, c, d, e, answer; float average(float a, float b, float c, float d, float e); int main (void) { printf("\nPlease enter the 5 numbers: "); scanf( "%f%f%f%f%f", &a, &b, &c, &d, &e); answer = average(a, b, c, d, e); printf("\nThe answer is %f", answer); return 0; } float average(float a, float b, float c, float d, float e) { return((a+b+c+d+e)/5); } <file_sep>#include <stdio.h> #include <stdlib.h> #include <strings.h> #include <string.h> #include <stdbool.h> #include <ctype.h> #include "dictionary.h" #define DICTIONARY "dictionaries/large" #define N 53 // Represents a node in a hash table typedef struct node { char word[LENGTH + 1]; struct node *next; } node; // Number of buckets in hash table //const unsigned int N = 53; //Variable for storing number of words in dictionary int wordTotal = 0; // Hash table node* table[N]; // Returns true if word is in dictionary else false bool check(const char *word) { int index = hash(word); bool result = false; if( table[index] == NULL ) result = false; else for(node* trav = table[index]; trav != NULL; trav = trav->next) { if( strcasecmp(word, trav->word) == 0 ) { result = true; break; } else result = false; } return result; } // Hashes word to a number unsigned int hash(const char *word) { int hashValue = 0; for(int i = 0; isalpha(word[i]); i++) { int a = (int) word[i] * i; hashValue += a; } hashValue = hashValue % N; return hashValue; } // Loads dictionary into memory, returning true if successful else false bool load(const char *dictionary) { FILE *fp = fopen(dictionary, "r"); if( fp == NULL ) { printf("\nUnable to open dictionary %s", dictionary); return 1; } char* buffer = malloc((sizeof(char)) * (LENGTH+1)); //for(short i = 0; i < (LENGTH+1); i++) // buffer[i] = 0; for(short i = 0; i <= N; i++) table[i] = NULL; while(!feof(fp)) { fscanf(fp, "%s", buffer); if( isalpha(buffer) ) { node* n = malloc(sizeof(node)); if( n == NULL ) { printf("\nUnable to allocate node* n\n"); return 1; } strcpy(n->word, buffer); n->next = NULL; int index = hash(buffer); if( table[index] == NULL ) { table[index] = n; } else { n->next = table[index]; table[index] = n; } wordTotal++; } for(short i = 0; i < (LENGTH+1); i++) buffer[i] = 0; }//end while feof free(buffer); fclose(fp); if( wordTotal > 0 ) return true; else return false; } // Returns number of words in dictionary if loaded else 0 if not yet loaded unsigned int size(void) { return wordTotal; } // Unloads dictionary from memory, returning true if successful else false bool unload(void) { bool success = false; for(int i = 0; i <= N; i++) { if(table[i] == NULL) continue; else { for(node* trav = table[i]; trav != NULL; ){ node* tmp = trav->next; free(trav); trav = tmp; } table[i] = NULL; } } for(int i = 0; i <= N; i++) { if( table[i] == NULL ) { success = true; } else { success = false; break; } } return success; } <file_sep># Algo Week 7 Bucket Sort ## Textbook Countingsort count number items in the array that have each value. then copy each value in order back into the array pass in max value as parameter M - number items in counts array (max_value+1) spends M steps initializing the array N - number number of items in values array spends N steps to count the values in the values array takes N steps to copy back so O(2xN+M) simplified to O(N+M) handles duplication better than quicksort ## Wikipedia Countingsort integer sorting only uses key values instead of comparisons ## textbook Bucketsort also called binsort 1. divide items into buckets 2. use another algorithm to sort buckets or recursively sort buckets 3. concatenate buckets contents back into original array N items in array, use M buckets - expect N / M items per bucket buckets can be any data structure distributing items takes O(N) steps sort buckets O(MxF(N/M)) //F is runtime function of sorting algorithm in total simplifies to O(N). performance really depends upon number of buckets ## Wikipedia Bucketsort could be implemented with comparisons worst case defined by algorithm used to sort buckets average case: O(N) common optimization put buckets back into array then run insertion sort as insertion sort runtime based on how far each element has to go ## Lecture comparison-based algorithms have speed limit of O(nlgn) **countingsort** 1. find smallest and largest elements in array 2. create a counting array with enough room for all possible integers 3. scan through the array and count how many times each number appears adjusting value in counting array accordingly 4. use counting array to reconstruct the sorted version of original array speed: find min and max: traverse array O(n) counting elements traverse again: O(n) assembling sorted array from counting array: O(n) total: O(n) or linear time **bucketsort** - can sort doubles, ints, anything really if using hash function 1. find largest and smallest elements in array 2. create n buckets (same number of elements in array) space buckets evenly 3. scan through array and put elements in buckets 4. sort the buckets - usually done with insertion sort 5. put contents of buckets back into array use arrays for buckets for now if buckets spaced evenly, probability land in bucket is 1/n time: 1. finding min and max: O(n) 2. placing items in buckets: O(n) 3. sorting buckets: -n buckets -nb number elements per bucket -O(nb^2) = (2-1/n) per bucket when using insertion sort -n x O(nb^2) = O(2n-1) which can be reduced to O(n) works best if values evenly distributed slows down when fewer buckets are more full <file_sep>#JimSort- A C program to determine real runtime of Selection and Insertion Sort This program will allow you to run an insertion sort, and or a selection sort, either a specified number of times with a randomized array, or will automatically generate a test for both arrays. Results will be written to a text file called "sortResults.txt" for data processing. <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> char *final; char * concat(char*, char*); void main () { char *a = "Hello"; char *b = "-World!"; final = malloc(sizeof(a)+sizeof(b)); final = concat(a,b); puts(final); free(final); } char * concat(char * a, char * b) { strcpy(final, *a); strcpy(final, *b); return final; } <file_sep>#include <stdio.h> #define MAX 4 struct part { short number; char name[10]; } data[MAX] = {1, "Smith", 2, "Jones", 3, "Adams", 4, "Wilson", }; struct part *p_part; int count; int main (void) { p_part=data; for (count = 0 ; count < MAX ; count++) { printf("At address %p: %d %s\n", p_part, p_part->number, p_part->name); p_part++; } return 0; } <file_sep>package inheritance; /** * Defines a mathematical function of a single variable * @author jeremy * */ public interface Function { /** * Evaluates the function for a particular input variable * @param x * @return the value of the function */ public abstract double evaluate(double x); /** * Prints a representation of the function to the console */ public default void display() { System.out.println(this.toString()); } }<file_sep> long sqr (int x); <file_sep>#CS50 Week 3 Algorithims think of memory of grid of bytes- can create data structures off of that **linear search**- going in a line want to search efficiently **binary search**- must be sorted. start at half then go to half of next half then half of that until reach request *O* big italicized O- "on the order of" n, O(n), on the order of n/2: O(n/2), O(logn) - for how efficient algorithim is as problem gets bigger they converge so really we just say on the order of n or on the order of log n binary search O(log n) greek omega- opposite of O (O is really upper bound) omega is best case or lower bound successful outcome return 0 . no success return 1- just a convention **Structure** typedef struct { string name; string number; } person; person people[4]; people[0].name = "Emma"; people[0].number = "617-555-0100"; **bubble sort**- "bubbled" its way up to the right spot. essentially compares itself to the data to the right repeat n-1 times for i from 0 to n-2 if i'th and i + 1'th elements out of order swap them O(n^2) omega n^2 as well to make more efficient: change repeat n-1 times to repeat until no swaps then omega becomes (n) **selection sort**- identify smallest element of list and move to the left side and evict in place want to be each iteration select next smallest element for i from 0 to n-1 find smallest item between i'h item and last item swap smallest element with i'th item O(n^2) omega O(n^2) **recursion**- implement algorithim, code etc. that calls itself functions can call itself so long as have base case first- point where it stops- could have multiple base cases solves a smaller portion with itself in general, recursive functions can be used to replace loops **merge sort**- if only 1 item- return sort left half of items sort right half of items merge sorted halves (can make a new list) merge sort in each half **RECURSIVELY** process dividing again and again -> logarithim O(n log n) omega O(n log n) <file_sep>package Exam1; public class invalidArraySize extends RuntimeException { public invalidArraySize() { super(); } public invalidArraySize(String s) { super(s); } } <file_sep>def meanderingArray(unsorted): array = sorted(unsorted) i = 0 j = len(array) - 1 out_array = [] for x in range(len(array)): out_array.append(array[j]) out_array.append(array[i]) j -= 1 i += 1 if j == i: out_array.append(array[j]) break elif j < i: break <file_sep># Ch.23 Complete Virutal Memory Systems curse of generality - tasked with general support for a broad class of applications and systems - OS is not likely to support any one installation very well one technique: kernel stays in same spot in virtual memory - each process essentially includes kernel in address space - stays in place upon context switch - base and bounds register for kernel does not change - if kernel given own address space moving data between user applications and kernel would be complicated **demand zeroing** - OS does little work when page added to address space - puts entry in page table marks the page as inaccessible if process reads or writes to the page, a trap into OS takes place. when handling the trap, OS notices this is actually a demand zero page, NOW the OS goes and finds a page, zeros it, and maps it into the process's address space **copy on write** - when OS needs to copy a page from one address space to another, instead of copying it it maps into the target address space and marks it read-only in both address spaces if both address spaces only read the page, no action needed BUT if one wants to write -> trap into OS, which will then actually allocate the page, fill it with the data, and map it to the process address space fork() creates exact copy of address space of caller exec() overlays calling process's address space with that of the soon to be executed program **LINUX** virtual address space consists of a user portion (where user program code, stack, heap, and other parts reside) AND a kernel portion - does not change upon context switch in classic 32bit linux split between user and kernel portions takes place at address 0xC0000000 or 3/4 way through address space and end 0xFFFFFFFF so user is 0x00 through 0xBFFFFFFF - 64 bit similar split just different points kernel has 2 types of kernel virtual addresses: **kernel logical addresses** - what consider normal (maps directly to physical at 0x00000000) - kmalloc - page table, per process kernel stack live here - kernel logical memory CANNOT be swapped to disk if chunk of memory is contiguous in kernel logical space, also contiguous in physical memory - good for operations need contiguous physical memory to work correctly such as I/O via direct memory access **kernel virtual address** - - vmalloc - returns a pointer to a virtually contiguous region of the desired size - usually not contiguous so good for things such as large buffers where large contiguous chunk hard to find x86 provides hardware-managed, multi-level page table structure, with one page table per process OS simply sets up mappings in memory, points a privileged register at the start of the page directory, and hardware handles the rest - OS gets involved at process creation, deletion, and upon context switches for 64bit address sapces - 4 level page table - see pg 270 - 63 - 47 unused - 47- 13 virtual address (36 bits each level 9 bits) - 13 - 0 offset standard 4k page size (thus 12 bit offset) allows for use of multiple page sizes - HUGE pages larger the pages, the fewer the mappings - driver for HUGE pages is better TLB behavior - mmap() or shmget() need for better TLB behavior is becoming more common - added **transparent** HUGE page support - which just means OS automatically looks for chances to allocate HUGE pages but remember, HUGE pages cause internal fragmentation, also not good for swapping to reduce cost of accessing persistent storage, use aggressive **caching** subsystems to keep popular data items in memory linux **page cache** is unified keeping pages in memory from three primary sources **memory-mapped files**, file data, and metadata from devices - keeps track if entries are clean (read but not modified) or dirty (modified) - dirty data periodically written to backing store by background threads (pdflush) linux uses a modified form os 2Q replacement - LRU can be subverted by certain common access patterns 1. when accessed for the first time, a page is placed on one queue- **inactive list** 2. when re-referenced, page is promoted to other queue **active list** 3. periodically moves pages from the bottom of the active list to the inactive list - keeps inactive list to 2/3 of total page cache size - then utilizes an approximation of LRU similar to **clock** replacement to manage these lists **buffer overflow attacks** - bug in target system which lets attacker inject arbitrary data into target's address space - arises bc developer believes input will not be too long for buffer - CHECK SIZE OF USER INPUT PRIOR TO ASSIGNING TO BUFFER attackers can then inject code into the overflow, privilege escalate, and take control defense against the dark arts: - prevent execution of code found within certain regions of address space (within stack) AMDs NX bit (no execute) - prevents execution from any page which has this bit set in its corresponding page table entry **return oriented programming** - lots of code (gadgets in ROP terminology) within programs address space an attacker can overwrite the stack such that the return address in currently executing function points to a desired malicious instruction (or series of instructions) followed by a return instruction defense against the dark arts: - **address space layout randomization (ASLR)** - OS randomizes placement of stack, heap, code - also incorporated into kernel: **kernel address space layout randomization** **speculative execution** - CPU guesses which instructions will be soon executed and starts executing them ahead of time - exploit here is that information to drive prediction is stored in various places - exploits of this: Spectre Meltdown defense against the dark arts: remove as much of the kernel address space from each user process and instead have separate kernel page **kernel page isolation** when switching into kernel now a switch to kernel page table is needed COSTs performance :( <file_sep><?php $servername = "localhost"; $username = "username"; $password = "<PASSWORD>"; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $stmt = $conn->prepare("INSERT INTO ice_cream (flavor, company, rating) VALUES (?, ?, ?)"); $flavor = "strawberry"; $company = "ben&jerrys"; $rating = "10"; $stmt->execute(); $flavor = "vanilla"; $company = "hood"; $rating = "10"; $stmt->execute(); echo "New records created successfully"; $stmt->close(); $conn->close(); ?> <file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign08 - Advanced Web Development</h2> <h2>Research</h2> <!--writeup goes here--> <p>A website is the set of hyperlinked web pages under a single domain name. A web application is software or a program that is accessible using any web browser. Web sites have been around since the first HTML1 page, but web applications are a new growing trend in line with the Software as a Service movement. They are easier to maintain and have fewer compatibility issues, since they are driven by web frameworks designed to work in the popular browsers.</p> <br> <a href="https://www.guru99.com/difference-web-application-website.html#:~:text=Summary%3A,you%20in%20branding%20your%20business."target="_blank">Source</a> <h2>Before & After CODE</h2> <a href="assign08/html/index.php" target="_blank">Message Bord!</a> <h3>Project Outline</h3> <a href="outline.md" target="_blank">Project Outline- Tribe</a> </div> <?php include 'footer.php';?> </body> </html> <file_sep>#include "bst.h" const int STRING_LENGTH = 1024; /* * function: create_tree * ---------------------------- * Creates an empty tree * * data_size: size of keys in bytes * comparator: function for comparing keys. Must obey the following rules: * comparator(a, b) < 0 if a < b * comparator(a, b) > 0 if a > b * comparator(a, b) = 0 if a == b * formatter: function that returns a string representation of keys * * returns: a tree with root = NULL */ Tree* create_tree(const size_t data_size, int (*comparator)(const void*, const void*), char* (*formatter)(const void*)) { // Allocate space for the tree Tree* tree = (Tree*) malloc(sizeof(Tree)); // Initialize the attributes tree->root = NULL; tree->data_size = data_size; tree->compare = comparator; tree->formatter = formatter; // All done! return tree; } /* * function: create_tree_node * ---------------------------- * Creates a tree node and sets its key equal to data * * * returns: A node with: * key = data * parent = NULL * left = NULL * right = NULL */ TreeNode* create_tree_node(const void* data, const size_t data_size) { // Allocate space for the node TreeNode* node = (TreeNode*) malloc(sizeof(TreeNode)); // Set the key node->key = malloc(data_size); memcpy(node->key, data, data_size); // Init pointers to the parents and kids node->parent = NULL; node->left = NULL; node->right = NULL; // All done! return node; } /* * function: tree_as_string * ---------------------------- * Returns a char* representation of the BST * * tree: the tree * */ char* tree_as_string(const Tree* tree) { char* output = (char*) malloc(STRING_LENGTH * sizeof(char)); strcpy(output, "Tree:"); subtree_as_string(tree->root, output, tree->formatter); return output; } /* * function: subtree_as_string * ---------------------------- * Apppends the string representation of the subtree rooted at node to output * node: root of subtree * output: storing the string representation of the whole tree * formatter: converts node's key type to a string * * NB: this doesn't work if the string representation of the tree exceeds * STRING_LENGTH. But fixing it would be annoying and getting tree_delete to * work right took me three hours, so I'm not in the mood to fix this * problem at the moment. */ void subtree_as_string(const TreeNode* node, char* output, char* (*formatter)(const void*)) { if (node != NULL) { if(node->left != NULL){ subtree_as_string(node->left, output, formatter); } if(node->key != NULL){ char* key_as_string = formatter(node->key); sprintf(output,"%s %s", output, key_as_string); free(key_as_string); } else { return; } if(node->right != NULL) subtree_as_string(node->right, output, formatter); } } /* * Function: max_depth * ---------------------------- * Recursively determines the depth of the subtree rooted at a node * * x: node in a tree * * returns: maximum depth of subtree rooted at x * */ int max_depth(const TreeNode* x) { if (x == NULL) { return 0; } else { int lDepth = max_depth(x->left); int rDepth = max_depth(x->right); if (lDepth > rDepth) { return (lDepth + 1); } else { return (rDepth + 1); } } } /* * Function: tree_depth * ---------------------------- * Determines the maximum depth of a tree * * tree: a tree * * returns: maximum depth of tree * */ int tree_depth(const Tree* tree) { if(tree == NULL) return 0; return max_depth(tree->root); } /* * function: tree_insert * ---------------------------- * Inserts a node in to a tree ob/eying the binary search tree property * * tree: tree to add to * data: data to put in new node * */ bool tree_insert(Tree* tree, const void* data) { if(tree == NULL) return false; if(data == NULL) return false; TreeNode* newNode = create_tree_node(data, tree->data_size); TreeNode* x = tree->root; TreeNode* y = NULL; //get to end of tree while(x != NULL) { y = x; if(tree->compare(data, x->key) < 0) { x = x->left; } else { x = x->right; } } //determine if newNode goes to left or right side of current node if(y == NULL) { tree->root = newNode; } else if ( tree->compare(data, y->key) < 0) { newNode->parent = y; y->left = newNode; } else { newNode->parent = y; y->right = newNode; } return true; } /* * function: recursive_search * ---------------------------- * Recursively searches a subtree for a node containing query value * * node: root of the subtree * q: value to find in tree * compare: function for comparing keys. Must obey the following rules: * compare(a, b) < 0 if a < b * compare(a, b) > 0 if a > b * compare(a, b) = 0 if a == b * * returns: a pointer to the node containing the key, NULL if not found */ TreeNode* recursive_search(TreeNode* node, const void* q, int (*compare)(const void*, const void*)) { if(node == NULL) return NULL; if(q == NULL) return NULL; if(compare(node->key, q) > 0) recursive_search(node->left, q, compare); else if(compare(node->key, q) < 0) recursive_search(node->right, q, compare); else if(compare(node->key, q) == 0) return node; else return NULL; } /* * function: search * ---------------------------- * Searches the tree for a query value * * tree: the tree * q: value to find in tree * * returns: true if the key q is present in the tree, false if not */ bool search(const Tree* tree, const void* q) { if(tree == NULL) return false; if(q == NULL) return false; TreeNode* s = recursive_search(tree->root, q, tree->compare); if(s != NULL) return true; else return false; } /* * Function: tree_maximum * ---------------------------- * Finds the node with the maximum key value in the subtree rooted at node * * node: root of a subtree * */ TreeNode* tree_maximum(TreeNode* node) { if (node == NULL) { return NULL; } while (node->right != NULL) { node = node->right; } return node; } /* * Function: transplant * ---------------------------- * Replaces one node with another in a tree * * tree: a tree * u: node to be replaced * v: node to replace with * */ void transplant(Tree* tree, TreeNode* u, TreeNode* v) { if(tree == NULL) return; //assign as root if working with root node if(u->parent == NULL) tree->root = v; //if this is the left node, assign v to left side if(u == u->parent->left) u->parent->left = v; //otherwise this is the right node else u->parent->right = v; if(v != NULL) v->parent = u->parent; node_delete(u); } /* * Function: tree_delete * ---------------------------- * Finds the shallowest node with a given key value and removes it * * tree: a tree * key: key to remove * * returns: true if removal is successful, false otherwise * */ bool tree_delete(Tree* tree, const void* key) { if(tree == NULL) return false; if(key == NULL) return false; if(tree_maximum(tree->root) == 0) return false; TreeNode* foundIt = recursive_search(tree->root, key, tree->compare); if(foundIt == NULL) return false; //if childless if(foundIt->left == NULL && foundIt->right == NULL) { node_delete(foundIt); return true; } //if no left child else if(foundIt->left == NULL) { transplant(tree, foundIt, foundIt->right); return true; } //if no right child else if(foundIt->right == NULL) { transplant(tree, foundIt, foundIt->left); return true; } //if both else { TreeNode* prev = tree_maximum(foundIt->left); foundIt->key = prev->key; transplant(tree, prev, prev->left); return true; } return false; } /* * function: destroy_subtree * ---------------------------- * Destroys all nodes in the subtree rooted at a given node * * node: node in a tree * */ void destroy_subtree(TreeNode* node) { if (node == NULL) return; destroy_subtree(node->left); TreeNode* right = node->right; free(node->key); free(node); destroy_subtree(right); } /* * function: node_delete * ------------------------------ * Destroys the target node with no mercy * * node: the node to eliminate with no prejudice * FOR THE REPUBLIC!! */ void node_delete(TreeNode* node) { if (node == NULL) return; free(node); } /* * function: destroy_tree * ---------------------------- * Destroys all nodes in a tree and the tree itself * * tree: tree to destroy * */ void destroy_tree(Tree* tree) { if (tree == NULL) return; destroy_subtree(tree->root); free(tree); } // COMPARATORS // int comp_doubles(void* a, void* b) { double* ia = (double*) a; double* ib = (double*) b; if(*ia > *ib) { return 1; } else if (*ia < *ib) { return -1; } else { return 0; } }//end comp_doubles int comp_ints(void* a, void* b) { int* ia = (int*) a; int* ib = (int*) b; if(*ia > *ib) { return 1; } else if (*ia < *ib) { return -1; } else { return 0; } }//end comp_ints void* shift(void* a, int i, size_t element_size) { return (void*) ((char*) a + i * element_size); }//end shift <file_sep># Day 17 Manipulating Strings string.h ## String Length strlen() size_t strlen(char *str); size_t unsigned integer used a lot with strings ## Copying Strings must copy source string from its location in memory to memory location of destination string strcpy() copies entire string including null char *strcpy( char *destination, const char *source ); must first allocate storage space for destination string strncpy() specify how many characters to copy char *strncpy(char *destination, const char *source, size_t n); copies at most first n characters of source to destination. if shorter adds nulls, if source longer n characters, no n added non-ansi strdup() similar strcpy() except performs own memory allocation ## Concatenating Strings strcat() appends copy of str2 onto end str1 moving n to end of new string char *strcat(char *str1, const char *str2); strncat() " but lets you specify how many characters of source string to append to destination char *strncat(char *str1, const char *str2, size_t n); str2 contains more than n characters, first n characters appended to end of str1. str2 contains fewer than n characters all of str2 is appended. in either case n added to new end. must allocate enuf space for str1 to hold new string strcpy(str1, " "); copies to empty string consisting of single newline ## Comparing Strings determines whether = or !=. if != one is greater than the other. those determinations made with ASCII codes of the characters. in case letters equivalent alphabetical order- excpet all uppercase less than lowercase strcmp() compares 2 strings character by character int strcmp(const char *str1, const char *str2); return values: <0 str1 is less than str2. 0 str1 equal to str2. >0 str1 greater than str2. strncmp() specified \# number characters int strncmp(const char *str1, const char *str2, size_t n); ## Searching Strings determine whether one string occurs within another string and if so where strchr() finds first occurrence of specified character in a string char *strchr(const char *str, int ch); searches from left to right until character ch is found or terminating null. if ch found, poitner returned. if not NULL returned strrchr() "" except searches string for last occurrence of a specified character in a string char *strrchr(const char *str, int ch); returns pointer to last occurrence of str and NULL if no match strcspn() "" for first occurrence size_t strcspn( const char *str1, const char *str2); not looking str2 but characters it contains. if finds match, returns offset from beginning of str1 where matching character is located. if no match returns value of strlen(str1) strspn() "" returns length of initial segment of str1 that consists entirely of characters found in str2 strpbrk() "" first occurrence of any character contained in another string strstr() searches for first occurrence of one string in another- searches for entire string char *strstr(const char *str1, const char *str2); ## String Conversions not ansi strlwr() upper to lowercase char *strlwr(char *str); strupr() char *strupr(char *str); both return str- ie modify string in place ansi toupper(char *str) and tolower(char *str) ## Misc String Functions not ansi- strrev() reverses order of characters char *strrev(char *str); non ansi- strset() and strnset() changes all characters in str to ch except null char *strnset(char *str, int ch, size_t n); ## String to Number Conversions atoi() converts string to integer int atoi(const char *ptr); long atol(const char *ptr); long long atoll(const char *ptr); double atof ## Character Test Functions ctype.h test characters returning TRUE (nonzero) or FALSE (zero) if character meets certain conditions testing **character value** see chart pg.507 for isxxxx() macros subtracting character '0' from number changes a character number to a real number <file_sep> select title from movies where year >= 2018 order by title desc; <file_sep># Day 6 Basic Program Control **array**- indexed group of data storage locations that have the same name and are distinguished from each other by subscript or index arrays must be declared. type, name , size subscript of array can be another variable **for statement**- executes a block of one or more statements a certain number of times for ( initial ; condition ; increment ) statement; exits loop when condition = 0 can omit init and increment just leave ; for ex: for ( ; condition ; ) (which is basically just a while loop) init can be any valid c expression, can be concatted with commas: for ( ("Sorting..."), x=0 ; condtion ; increment ) ; can be a statement can nest these functions- example of printing box of Xs on pg. 131 **while statement**- executes a block of statements as long as a specified condition is true while (condition) statement; when initialization and updating are required, usually use **for**. when only having condition trying to meet, use **while**. need statements to be executed at least once use **do...while** **do...while**- tests for condition at end of loop rather than beginning. statements are always executed at least once do { statements; }while (condition); <file_sep>package connectfour; import java.util.Collection; import java.util.HashSet; /** * Represents a player in connect four * @author jeremy */ public class Playah extends Player { private int column; /** * Creates a new Playah, hatah * @param name - player's name, never null, never empty, must be unique * @param marker - marker for this player on game board, must be unique, must not be {@link Game#EMPTY} * @throws NullPointerException if name is null * @throws IllegalArgumentException if name is empty or not unique, or if marker is not unique or equal to {@link Game#EMPTY} */ public Playah(String name, char marker) { super(name, marker); this.column = 2; } protected void repOK() { super.repOK(); assert(column < Game.N_COLS); } /** * Chooses a random move like a champ * @param game * @return the column index where the player would like to move * @throws NullPointerException if game is null */ @Override public int chooseMove(Game game) throws NullPointerException { if(game == null) throw new NullPointerException(); int luckyColumn = column; if(game.isValidMove(luckyColumn)){ this.column++; return luckyColumn; } else { int chumpStatus = 0; while(!game.isValidMove(0)) chumpStatus++; repOK(); return chumpStatus; } } } <file_sep># Ch.7 Scheduling scheduling policies = disciplines all processes together usually referred to as workload determining workload critical part of building policies metrics: - **turnaround time** - time at which job completes minus start time - **response time** - time when job arrives in system to first time it is scheduled another metric commonly used is **fairness** with Jain's Fariness Index examples of disciplines: FIFO, shortest job first (SJF), shortest time to completion first (STCF), round robin FIFO problem: convoy effect - heavy process takes too long does not consider short processes round robins run jobs for **time-slice** (or scheduling quantum) - length of time slice must be multiple of timer-interrupt period - if slice too short, context switch will dominate overall performance how to handle I/O? when I/O completes, interrupt is raised and OS runs and moves the process that issued the I/O from blocked back to ready one approach to split up process with multiple I/O requests is to make each "subjob" an independent job to schedule can overlap multiple processes as switches between subjobs to maximize resources inherent trade-off in selecting a scheduling system **multi-level feedback queue** - uses recent past to predict the future <file_sep>#define _GNU_SOURCE #include <time.h> #include <stdio.h> #include <stdlib.h> #include <sched.h> #include <pthread.h> #include <stdbool.h> #define PAGESIZE 4096 double timer(clock_t begin, clock_t end); bool init_array(int* a, int size); int main(int argc, char** argv) { int numpages, trials, jump; clock_t begin, end; cpu_set_t set; double avg_time; FILE *fp = fopen("results.txt", "w"); pthread_t thread = pthread_self(); jump = PAGESIZE / sizeof(int); if(argc < 3) { numpages = 10; trials = 10; } else { numpages = atoi(argv[1]); trials = atoi(argv[2]); } int pager = numpages*jump; int* a = (int*) malloc(pager*sizeof(int)); //establish sched_affinity so runs on only 1 core CPU_ZERO(&set); for(int i = 0; i < 4; i++) CPU_SET(i, &set); pthread_setaffinity_np(thread, sizeof(cpu_set_t), &set); for(int h = 0; h < 10; h++) { numpages += 2; for(int i = 0; i < trials; i++) { for(int j = 0; j < pager; j += jump){ init_array(a, pager); begin = clock(); a[j]++; end = clock(); avg_time += timer(begin, end); } // printf("Trial %d: %.10f s\n", i, (avg_time/pager)); fprintf(fp, "%d,%.10f\n", numpages, (avg_time/pager)); } } free(a); return 0; } double timer(clock_t begin, clock_t end){ return ((double) (end - begin)) / CLOCKS_PER_SEC; } bool init_array(int* a, int size){ for(int i = 0; i < size; i ++) a[i] = 0; return true; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main(int argc, char *argv[]) { printf("Start process PID: %d\n", (int) getpid()); int scom = fork(); if(scom < 0) { fprintf(stderr, "fork failure\n"); exit(1); } else if (scom == 0) { //childs path printf("Child says hi PID: %d\n", (int) getpid()); } else { //parents path int wc = waitpid(scom, NULL, 0); printf("Parent says hi, PID: %d, wait: %d\n", (int) getpid(), wc); } } <file_sep>#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> /* Structure: node * * represets a node in a singly linked list * data: data held by the node * next: pointer to the next node NULL if last element */ typedef struct node { void* data; struct node* next; } node; /* Structure: linkedlist * * Represents a singly linked list * head: first node in the list- if NULL then list is empty */ typedef struct linkedlist { struct node* head; int list_size = 0; } linkedlist; bool add_beginning(linkedlist* list, const void* data, const size_t dataType); node* create_node(linkedlist* list, const void* data, const size_t dataType); linkedlist* create_list(); void remove_node(linkedlist* list, int pos); void destroy(node*); <file_sep># Ch.15 Mechanism: Address Translation idea behind LDE: for the most part, let the program run directly on the hardware OS optimize efficiency and control Applied to memory: ================= - ensures that no application is allowed access to memory but its own - flexibility - programs to be able to use their address space for whatever they would like **hardware based address translation** - changing the virtual addresses provided by the instruction to a physical address **dynamic relocation** - base and bounds registers hold start and end translation of virtual to physical: physical address = virtual address + base dynamic relocation enables address translation **Memory management unit** - part of processor that helps with address translation base and bounds can either hold physical addresses or the size OS must maintain a data structure known one way as a **free list** which knows where all the free memory is dynamic relocation hardware requirements ======================================= - privileged mode - perhaps a single bit processor status word to indicate user or privileged mode - base/bounds registers - ability to translate virtual addresses and check if within bounds - privileged instructions to update base/bounds - privileged instructions to register exception handlers - ability to raise exceptions for context switch: OS must save and restore base/bounds registers example of context switch now with address translation pg 151 exception handlers must be initialized at boot time <file_sep>#include <stdio.h> #include <time.h> int partition(int* sortArray, int innerBound, int outerBound){ int pivot = sortArray[outerBound]; int i = innerBound - 1; for(int j = innerBound; j <= outerBound-1; j++) { if(sortArray[j] < pivot) { i++; int tmp = sortArray[j]; sortArray[j] = sortArray[i]; sortArray[i] = tmp; } } int tmp = sortArray[i+1]; sortArray[i+1] = sortArray[outerBound]; sortArray[outerBound] = tmp; return i + 1; }//end partition void quicksort(int* sortArray, int innerBound, int outerBound){ if(innerBound < outerBound) { int p = partition(sortArray, innerBound, outerBound); quicksort(sortArray, innerBound, p - 1 ); quicksort(sortArray, p + 1, outerBound); } }//end quicksort <file_sep>jimSort: main.c selection.c insertion.c gcc -g -o jimSort main.c selection.c insertion.c jimSort.h <file_sep># Day 19 Exploring the C Function Library ## Mathematical Functions pg 534-536 lists math functions all functions return double for accuracy ## Dealing with Time time.h 2 methods for representing time 1. number seconds elapsed from midnight Jan 1, 1970 time values are stored as type long integers with typedef to time_t and clock_t 2. time broken into components- year mo day using struct tm- see pg 538 but does seconds, minutes, day of week, even flag for daylight savings ###obtaining current time current time on system clock- time_t time(time_t *timeptr); number seconds since 0000 jan 1 1970 so: time_t now; now = time(0); or: time_t now; time_t *ptr_now = &now; time(ptr_now); ### coverting between time representations time since 0000 jan 1 1970 not useful- localtime() represents time as tm struct: struct tm *localtime(time_t *ptr); returns pointer to tm struct- only need to declare a pointer to type tm struct tm overwritten everytime called-if want to capture a time, must declare a separate type tm struct and copy values from that to reverse from tm struct to type time_t value: time_t mktime(struct tm *ntime); back to time since 1970 ###displaying time convert to formatted strings char *asctime(struct tm *ptr); char *ctime(time_t *ptr); ctime type time_t asctime type tm struct both return pointer to static, null terminated 26 character string: Thu Jun 13 19:20:22 2020 for more control over format, use strftime() size_t strftime(char *s, size_t max, char *fmt, struct tm *ptr); takes tm struct pointed to by ptr formats it according to format string fmt, and writes result as null terminated string to memory location pointed to by s. max specifies amount of space at s pg 540 for conversion specifiers for strftime() ###calculating time difference can calculate difference in secs between two times with difftime() double difftime(time_t later, time_t earlier); commonly used calc elapsed time clock() calculates amount of time since program began execution in 1/100 second units clock_t clock(void); ## Error Handling assert.h void assert(int expression); expression anything you want to test- varaible or any C expression if true does nothing- if false displays error message on stderr and aborts execution compiled in debug mode. does not solve compilation errors- rather if program itself is running incorrectly, can sprinkle in assert() to diagnose trouble if NDEBUG is defined- asserts turn off #define NDEBUG ex: believe that problem is variable taking on negative value put something like assert(interest_rate >= 0); after the point you think it is happening ### errno.h and perror() errno.h defines several macros used to define and document runtime errors table 19.2 pg.546 lists error constants in errno.h if nonzero error has occurred only need errno.h defined if you want to use symbolic constants from errno perror() will display a user defined message when a system or library call error occurs or return "no error" void perror(const char *msg); msg points to optional user defined message does not prompt program to take action- COULD have action program takes defined by testing value errno ex of calling errno: printf("errno = %d.\n", errno); ## Searching with bsearch() and qsort() performs binary search of data array looking for array element that matches a key array must be sorted in ascending order must provide comparison function void *bsearch(const void *key, const void *key, const void *base, size_t num, size_t width, int (*cmp)(const void *element1, const void *element2)); key pointer to data item being searched for. base is pointer to first element of array being searched. num number elements in array. width size in bytes of each element. size_t refers to data type returned by the sizeof() operator which is unsigned. sizeof() operator usually used to obtain the values for num and width. cmp is a pointer to comparison function. cmp must: 1. passed pointers to 2 data items 2. returns type int as follows: < 0 Element 1 is less than element 2. 0 Element 1 is equal to element 2. > 0 Element 1 is greater than element 2 return value is type void pointer to first array element that matches the key or null if not found. must cast returned pointer to proper type before using it this returns num, the number of elemetns in the array: sizeof(array)/sizeof(array[0]) starts in middle compares > or < then goes ascending or descending accordingly **qsort**- sorts array into order stdlib.h void qsort(void *base, size_t num, size_t size, int (*cmp)(const void *element1, const void *element2)); no return value pg 551 for examples of using bsearch() and qsort() binary search requires n comparisons to search array of 2^n elements **ALWAYS VALIDATE USER ENTERED DATA** <file_sep>#Day 21 Advanced Compiler Use ## Programming with Multiple Source-Code Files **modular programming**- divide source code for a single program among 2 or more files keep some files with general purpose functions use in other programs like a file that outputs information to screen or takes input from keyboard each source file is called a **module** must have a main module with the main() function. other modules called secondary modules. separate header file associated with each secondary module header files have prototypes for functions in secondary modules, #define directives for symbolic constants and macros, definitons of structures or external variables used in the module secondary modules have general utility functions- things may want to use in other programs. ex: gcc program.c keyboard.c keyboard.h will compile and link those programs, the main function **MUST** be in the first program listed. this will create an executable file with the name of program IF you are recompiling and say keyboard.c was fine and did not need to be recompiled, could simply write: gcc program.c keyboard.obj keyboard.h will use the previously outputted obj file and not go through recompiling keyboard.c again remember to use **extern** for variables want to use across modules if you modify a header file must recompile all modules that use it **make** utility can handle that with a make file and nmake utility ##The C Preprocessor first compiler component that processes your program changes source code based on instructions or preprocessor directives in source code **#define**- creates symbolic constants and creates macros substitution macros = symbolic constants #define text1 text2 replaces every instance of text1 with text2. if text1 found double quotes, no change ###function macros not case sensitive like little functions #define HALFOF(value) ((value)/2) then in code just put HALFOF(x) and will perform mini-function you defined when macro parameter is preceeded by # in substitution string, argument converted into a quoted string when expanded: #define OUT(x) printf(#x) so: OUT(Hello World!) expands to: printf("Hello World!"); **concatenation operator**- joins 2 strings in macro expressions #define CHOP(x) func ## x salad = CHOP(3)(q,w); expanded to: salad = func3 (q,w); compilers have settings so can see what preprocessor doing prior to making object file ### include directive preprocessor reads the specified file and inserts it at the location of the directive angle brackets <> include file in standard directory "" looks for file in current directory ### \#if \#elif \#else \#endif control conditional compilation can be almost any expression that evaluates to a constant cannot use sizeof() typecasts, or float if and endif are required, elif and else are optional if if evaluates to false compiler evaluates in order the conditions associated with each elif if nothing is true else compiled #if DEBUG == 1 debuggin code here #endif **defined()**- tests whether a particular name is defined returns true if yes false if no #if !defined( TRUE ) #define TRUE 1 #endif example of how to use this to not include a header file more than once #if defined (prog_h) #else #define prog_h //header file info goes here #endif **#undef**- removes definition from a name ##Predefined Macros __DATE__, __TIME__, __LINE__, __FILE__ will replace with macros code. date and time will print current time- good to see when file was actually compiled ## using command line arguments add arguments to your main() function: int main(int argc, char *argv[]) { if write so requires filename, and user does not enter, must have way to handle that <file_sep># include <stdio.h> # define SIZE 10 char array1[10] = "abcdefgh"; char array2[10]; char count, *ptr; int copyarray(char array1, char array2); int main (void) { puts(array1); puts("\n=========="); copyarray(*array1, *array2); puts(array2); return 0; } int copyarray(char array1, char array2) { for (count = 0 ; count < 10 ; count++) { *(array1+count) == array2[count]; return 0; } } <file_sep>#Bonus Day 1 Object Oriented Programming Languages **object**- independent and reusable section of software code that can perform a specific task and store specified dta related to that task can also use procedures but emphasize the practice of objects ## Object Oriented Constructs implementation of these features makes a language object oriented: 1. polymorphism 2. encapsulation 3. inheritance **reuse** could be considered fourth- but if implement the 3 key features, reuse automatic **polymorphism**- program is able to adapt automatically ex: listing with 2 functions with same name draw circle 2 sets of inputs- based on inputs program chooses which version to use **encapsulation**- create objects that are self-contained. black boxes- user does not need to know how they work just how to use them if change parameter, function will still work across programs objects will store input **inheritance**- capability to create new objects that expand the characterisitics of existing objects ex: having an object that draws a square, then creating an object that draws a cube by INHERITING some functionality from the square object most common types of programs created with C++: 1. executables- run by OS 2. libraries- routines created to link to other programs being created 3. dynamic linked libraries- reside in memory and be linked to other programs at runtime 4. controls- routines created that can be used in the creation of other programs ##The Java Programming Language Java more inflexible than C to remove complexity, add portability. Java REQUIRES use object oriented concepts- C++ optional java applets or applications not translated all the way to machine code- intermediate step called **bytecode** allows for transfer to different architectures where each one has its own **interpreter called a Java Virtual Machine** java adds packages also called **class libraries** to streamline and simplify reuse of classes (objects) each package defines a separate namespace and a class name needs to be unique within its own namespace **application** full fledged program designed to run on its own **applet**- designed to be distributed over the internet and executed in a browser comprehensive set of libraries to perform functions such as screen display, networkig, internet access etc. <file_sep>linklist: gcc -o linklist linklist.c <file_sep># Jim's Project Outline for tribe.com a community based social media site ## Overview For my final project I want to implement a website from a "bare-metal" server instance, to a hosted website. I have not decided if I will use a CMS or not, I kind of want the challenge of building the LAMP stack, writing and styling all of the pages, and writing the server-side scripts. For System Administration last semester, our final project was to create a server instance and install a LAMP stack with a CMS. This would be a build-off of that. I mostly want to do the extra work so I can show this project off to employers. If the whole self-hosting thing is getting to be too much, then I'll move the website into classweb or hang it off of my Github site. All of the database construction will be based in scripts so moving into classweb will mostly be a file upload. ## Concept This is an idea I have kicked around in my head for awhile. It is essentially my personal solution to the wild wild west of the social media giants such as Twitter and Facebook. Side note before I continue: I am basing the project for this class off of this concept so I can continue to play around with the basic mechanics of how I could possibly do this someday. If my life takes me in that direction of course. There is a lot of ugliness on social media. There are people who have the ability to "fire and forget" with their comments, accusations, fake news sharing. If you think about it did human communities always have this sort of discourse. I am going to say no. An individuals thoughts, feelings, and actions can extend to a global audience when it used to be the other people in the bar, or your Church, your town meeting, or the family dinner table. Saying things that harmed others unfarily had consequences. People shunned other people. If you were a jerk and unfair to someone, there was a vocal and or non-vocal response from your community that you had crossed a line. And it was REAL. Your voice is only 10% of communication. Now until they finish brain-cognitive interfaces, we will always have to deal with that 90% loss when communication happens between screens. I believe that the main thing missing from the social media giants is a sense of COMMUNITY due to the SCALE. There is also this growing trend of the individuals possessing two personalities: who they are on the internet and who they are in the real world. There is a growing discourse here on how the preference toward one or the other is GENERATIONAL, and can explain why none of us born before 1990 can make any sense of Gen X. So if we need more community on the internet how do we do it? Well, humans are already organized into groups IN THE REAL WORLD. Humans are instinctively tribal. Most people in modern life are in multiple tribes. These tribes exist in various states from fully codifed: the club softball team has a roster, to not formalized: the loose group of friends you had in college and all still kinda stay in touch. We do not even realize that we form tribes, but the same instincts that governed our ancestors to band together against the sabertooths are in the Thursday night bowling league's comraderie. So what I aim to do if you could not see it in the rambling, is create a social media site based entirely around groups. You do not get to add anybody in the world as a friend, you do not get to "swipe right" or "swipe left" on meaningless and fake pictures. You create a profile and either join together with at least one other person to found a "tribe" or you get invited to an existing one. When you make a comment or share something you choose the scope of the message. Each tribe will have a members list, a message board, and some kind of mechanism for making group decisions. But maybe that's a later thing because do you have "tribal councils" that call all of the shots, or a system of polling..... OR DO YOU LET THE TRIBAL FOUNDERS CHOOSE? See I have a lot of ideas about how to implement a community-driven social media tool, so I thought I would start here by making it from scratch. TODO find a way to keep Nazis off of it.... (always ruining good things) ## For the pages: Login ===== - conventional login page - validates password starts a session and connects you to your profile page - if you are not a registered member, takes you to the register page Register ======== - form for creating an account - I am keeping this to the most basic of info for now (maybe even just username, password) Cave Wall ======== - your profile. I thought "cave wall" was keeping with the theme - paint it anyway you like! Version 1 its only going to have a profile picture, username, and a list of tribes you are a member of. - if I get time a V1.5 feature would be to have the cave wall painted with your recent activity, and a tool on the cave wall page to post to wherever - inevitably I am seeing these as being a place to colorfully express yourself. You can put as many photos, inspirational quotes, article links on there as you want. Viewing access to those "wall spots" (name subject to revision) should have a privacy scope (set by tribe) and possible the whole cave wall itself Found a Tribe ============ - page running a tribe creation form. I will need to work out the mechanics of how to make it so it takes at least 2 people to create. Tribe ===== - there will be 1 page per tribe. Only by being an invited member to that tribe will you be allowed to link to and view the page - for starters this will just list members and have a message board. Probably a tribe picture Tribe About ========== - separate page for each tribe to say what they are about Tribal Page ========== - tribes can create 1 additional page for whatever they like ## Wrap-Up So I know the assignment calls for 10 pages and I only have 7, but I see that the emphasis here is on the complexity. Now I can create multiple tribes and pages for grading purposes to meet the 10, and just pass you a login to an account I make that is a member of all of the tribes. If possible, I would prefer that so I can focus on the back-end portions that will make this successful and not a bunch of time on fluff. <file_sep># include <stdio.h> int x=1; int main () { while ( x != 0 ) { puts("Enter an even integer value (0 to exit):"); scanf("%d", &x); if ( x % 2 != 0 ) { printf("\n%d is not an even number, please input an even number\n", x); } else{ printf("The value you entered is %d\n", x); } } return 0; } <file_sep><!--For my after portion I created a form that will write the inputted data to an xml file, and upon a button click will go lookup that file and return the contents of it --> <!DOCTYPE HTML> <html> <head></head> <body> <?php include 'form.php';?> </body> </html> <file_sep># DJ's Algorithm HW write-up ![Bahston](map) Graph: NEA -> MFA: 14 NEA -> MOS: 20 MFA -> MOS: 35 MFA -> BHM: 42 MOS -> FPZ: 52 FPZ -> NEA: 21 DJ's [ -1 0 0 1 2 ] So I just used google maps and got the travel times from each point of interest to its neighbors. These times can be drastically different depedning on which mode of travel so I just opted for a car. I belive the results are reasonable as I generally kept the nodes accessible throughout the trials. I ran into an issue where each time I googled the travel time it was different because of traffic. For consistency in representations sake this is the average time between points. <file_sep># include <stdio.h> int x; void main () { do { printf("%d\n",x); x +=3; } while ( x < 100); } <file_sep># include <stdio.h> # include <stdlib.h> # include <time.h> void sleep( int nbr_seconds); int main (void) { int ctr; int wait = 13; printf("Delay for %d seconds\n", wait); printf(">"); for (ctr=1 ; ctr <= wait ; ctr++) { printf("."); fflush(stdout); sleep( (int) 1 ); } printf( "Done!\n"); return 0; } void sleep( int nbr_seconds ) { clock_t goal; goal = ( nbr_seconds * CLOCKS_PER_SEC ) + clock(); while( goal > clock() ) { ; } } <file_sep>#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> //make test typedef struct node { int ID; char* name; struct node *next; } node; node* newNode(int id, char* n); bool searchName(node* h, char* n); void delID(int id, node* h); node* delList(node *h); void displayAll(node* h); int main (void) { node* head = NULL; bool quit = true; int uniqID = 0; while(quit) { short option = 0; printf("1- Create a new linked list\n2- Search by name\n3- Insert a new node to the beginning of the list\n4- Insert a new node at the end of the list\n5- Delete an element by uniqID\n6- Delete the current list\n7- Display all nodes\n8- QUIT\n\n"); scanf("%hd",&option); char* n = malloc(20*sizeof(char)); if( n == NULL ) return 1; switch(option) { //create a new linked list case 1: if( head == NULL ) { printf("\nPlease input the first name: "); scanf("%s",n); node* i = newNode(uniqID, n); head = i; uniqID++; } break; //search by name case 2: printf("\nPlease input the name: "); scanf("%s",n); bool isItThere = searchName(head, n); if ( isItThere ) printf("\nThat name is on the list\n\n"); else printf("\nThat name is not on the list\n\n"); break; //insert a new node at the beginning of the list case 3: if( head == NULL ) { printf("Create a list first"); break; } else { printf("\nWhat is their name?: "); scanf("%s",n); node* i = newNode(uniqID,n); i->next = head; head = i; uniqID++; break; } break; //insert a new node at the end of the list case 4: if( head == NULL ) { printf("Create a list first"); break; } else { printf("\nWhat is their name?: "); scanf("%s",n); node* i = newNode(uniqID,n); node* trav = head; for( node* tmp = trav; tmp != NULL; tmp = tmp->next) if( tmp->next == NULL ) trav = tmp; trav->next = i; uniqID++; } break; //delete an item by uniqID case 5: printf("\nWhat is the ID?: "); int id = 0; scanf("%d",&id); delID(id, head); break; //delete the current list case 6: if( head != NULL ) head = delList(head); printf("TERMINATED!\n\n"); break; //display all nodes case 7: if( head == NULL ) printf("There is no list\n\n"); else displayAll(head); break; //quit case 8: quit = false; if( head != NULL ) head = delList(head); free(n); free(head); break; default: printf("You must input 1 through 8 only\n\n"); }//end switch menu }//end menu while return 0; }//end main node* newNode(int id, char* n) { node* a = malloc(sizeof(node)); a->ID = id; a->name = n; a->next = NULL; return a; } bool searchName(node* h, char* n) { bool existName = false; for( node* trav = h; trav != NULL; trav = trav->next ) { if( strcmp(n, trav->name) == 0 ){ existName = true; break; } else existName = false; } return existName; } //TODO void delID(int id, node* h) { } node* delList(node* h) { while(h != NULL) { node *trav = h->next; free(trav); h = trav; } return h; } void displayAll(node* h) { int i = 0; for( node *trav = h; trav != NULL; trav = trav->next ) { if( trav->next == NULL ) { printf("\n%d: uniqID %d, Name: %s, EOL\n\n", i, trav->ID, trav->name); printf("\nThe list has %d items\n", i); } else{ printf("\n%d: uniqID %d, Name: %s\n", i, trav->ID, trav->name); } i++; } } <file_sep>#include "graph.h" #include <stack> #include <queue> #include <limits.h> #include <iostream> using namespace std; const int INFINITY = INT_MAX; const int NO_PREDECESSOR = -1; /* * Function: min_dist_vertex * ---------------------------- * Helper function for dijkstra. * Finds the vertex in the search queue with the minimum * estimated distance from the source vertex. * * queue: search queue * dist: distance array from Dijkstra's method. dist[i] * is the distance from the source vertex to vertex i * along the lowest-cost path found so far * * returns: the vertex u with the smallest estimated distance to the source Also removes u from queue. * */ int min_dist_vertex(vector<int> &queue, int* dist) { int min_dist = INFINITY; // u will be the index of the vertex in the queue // which is the minimum distance from source int u = -1; // index in search queue of minimum distance vertex int mindex = -1; for (int i = 0; i < queue.size(); i++) { int v = queue[i]; if (dist[v] < min_dist) { min_dist = dist[v]; u = v; mindex = i; } } // Remove u from the queue queue.erase(queue.begin() + mindex); return u; } /* * Function: dijkstra * ---------------------------- * Searches a graph using Dijkstra's algorithm, returning * the predecessor array that will give you the lowest-cost * path from the source node to any other node in the graph * * graph: graph to search * src: index of source vertex to begin search from * * returns: a predecessor array prev. prev[i] yields the index of * vertex i's predecessor in a search begun at a source vertex. * prev[src] is defined to be the constant NO_PREDECESSOR (usually -1) * */ int* dijkstra(Graph* graph, int src) { vector<int> queue; int* prev = (int*) malloc(graph->SIZE * sizeof(int)); int dist[graph->SIZE]; for (int v = 0; v < graph->SIZE; v++) { dist[v] = INFINITY; prev[v] = NO_PREDECESSOR; queue.push_back(v); } dist[src] = 0; while (!queue.empty()) { int u = min_dist_vertex(queue, dist); for (int neighbor : get_neighbors(graph, u)) { int alt = dist[u] + graph->distance[u][neighbor]; if (alt < dist[neighbor]) { dist[neighbor] = alt; prev[neighbor] = u; } } } return prev; } /* * Function: print_path * ---------------------------- * Prints the path from a destination vertex to the source, using the * predecessor array output from a search method * * graph: graph that was searched, used for getting node labels * prev: predecessor array fom a search method. prev[i] yields the index of * vertex i's predecessor in a search begun at a source vertex. * prev[src] is defined to be the constant NO_PREDECESSOR (usually -1) * dst: index of destination vertex to trace back to source * */ void print_path(Graph* graph, int* prev, int dst) { //start at destination //-1 0 0 1 //to get to 3, I went to 1, to get to 1 I came from 0 //3 <- 1 <- 0 //make a stack stack<int> path; int current = dst; while(current != NO_PREDECESSOR) { path.push(current); current = prev[current]; } //will produce 0 1 3 //now when iterate through stack will be in order while(!path.empty()) { int v = path.top(); path.pop(); cout << graph->labels[v] << " -> "; } cout << endl; } /* * Function: dfs * ---------------------------- * Searches a graph using a depth-first strategy * * graph: graph to search * src: index of source vertex to begin search from * * returns: a predecessor array prev. prev[i] yields the index of * vertex i's predecessor in a search begun at a source vertex. * prev[src] is defined to be the constant NO_PREDECESSOR (usually -1) * */ int* dfs(Graph* graph, int src) { bool discovered[graph->SIZE]; int* predecessor = (int*) malloc(graph->SIZE * sizeof(int)); for(int i = 0; i < graph->SIZE; i++) { discovered[i] = false; predecessor[i] = NO_PREDECESSOR; } stack<int> s; s.push(src); while(!s.empty()) { int v = s.top(); s.pop(); if(!discovered[v]) { discovered[v] = true; for(int n : get_neighbors(graph, v)) { s.push(n); if(!discovered[n]) predecessor[n] = v; } } } return predecessor; } /* * Function: bfs * ---------------------------- * Searches a graph using a breadth-first strategy * * graph: graph to search * src: index of source vertex to begin search from * * returns: a predecessor array prev. prev[i] yields the index of * vertex i's predecessor in a search begun at a source vertex. * prev[src] is defined to be the constant NO_PREDECESSOR (usually -1) * */ int* bfs(Graph* graph, int src) { bool discovered[graph->SIZE]; int* predecessor = (int*) malloc(graph->SIZE * sizeof(int)); for(int i = 0; i < graph->SIZE; i++) { discovered[i] = false; predecessor[i] = NO_PREDECESSOR; } queue<int> q; q.push(src); discovered[src] = true; while(!q.empty()) { int v = q.front(); q.pop(); for(int n : get_neighbors(graph, v)) { if(!discovered[n]) { q.push(n); discovered[n] = true; predecessor[n] = v; } } } return predecessor; } int main() { Graph* graph = read_graph_file("boston.dat"); print_graph(graph); /* cout << "BFS\n"; int* bfs_predecessor = bfs(graph, 0); cout << "[ "; for(int i = 0; i < graph->SIZE; i++) { cout << bfs_predecessor[i] << " "; } cout << " ]\n" << endl; cout << "DFS\n"; int* dfs_predecessor = dfs(graph, 0); cout << "[ "; for(int i = 0; i < graph->SIZE; i++) { cout << dfs_predecessor[i] << " "; } cout << " ]\n" << endl; */ cout << "DJ's\n"; int* djs_predecessor = dijkstra(graph, 0); cout << "[ "; for(int i = 0; i < graph->SIZE; i++) { cout << djs_predecessor[i] << " "; } cout << " ]\n" << endl; } <file_sep># Ch.20 Paging: Smaller Tables simple linear page tables are too big and consume too much memory one solution: multiple page sizes problem with big pages: leads to waste within each page -> **internal fragmentation** combine segmentations base and bounds registers with paging - add a base and bounds - not to point to the segment itself but rather hold the physical address of the page table of that segment - in hardware would need base/bounds for code, heap, stack - on context switch these registers must be changed to reflect the location of the page tables of the new processes - bounds register just for value of maximum valid page in the segment now unallocated pages between the stack and heap no longer take up space in a page table (marked as non-valid) if, for instance, have large allocated heap but not using thats wasted space also reintroduce fragmentation - page tables of arbitrary size (multiples of PTEs) **multi-level page table** - turn linear page table into something like a a tree 1. chop up page table into page-sized units, 2. then if entire page of PTEs is invalid, don't allocate that page of the page table at all 3. add a **Page Directory** PD - tell you where a page of the page table is or that entire page table is invalid page directory containes one entry per page of the page table - PDEs - minimum: valid bit and page frame number if PDE is valid, at least one page of that page table is multi-level table only allocates page-table space in proportion to the amount of address space you are using if carefully constructed, each portion of the page table fits neatly within a page , OS can simply grab the next free page when it needs to allocate or grow a page table this is adding a level of indirection aka another step also a $$ Cost $$ - on a TLB miss 2 loads from memory will be required to get the right address translation. PDE -> PTE could also do more than 2 levels so normally have: VPN|offset VPN| |offset PDI|PTI| with multi-level do something like: VPN| | |offset PDI0|PDI1|PTI Page table could easily consume more than one page - what happens if page directory does as well? **inverted page table** - instead of having one page table per system process, keep single page table that has entry for each physical page in thr system even with all of these methods - may just run out of memory. then need to implement a swap system to write some page tables to kernel virtual memory on disk <file_sep># OS3 Ch.2 The Abstraction: The Process **process** - running program **time sharing** - the CPU running on process, stopping it, then running another - promoting the illusion of virtualization **mechanisms** - low level methods or protocols that implement needed piece of functionality **context switch** - stop one process and start another one **machine state** - understand what a program can read or update when it is running - address space - registers program counter stack pointer frame pointer list of files has open policy answers question of **which** process is CPU currently processing common design practice - separate mechanisms from policies ## Process API APIs to manage processes create destroy - forcefully. not normal program exit wait misc control - usually includes suspend (stop for awhile) and resume status ## Process Creation load code and any static variables into memory early or simple OSs program loaded eagerly - loaded completely then run modern/more complex OSs load code as executed lazily OS allocates this memory and gives it to the process, then fills in parameters to main - argc and argv in UNIX systems every program 3 open file descriptors by default - standard input, output and error once loaded, jump to main() through special mechanism, OS transfers control of CPU to newly-created process ## Process States can be in one of 3 states: running ready blocked - not ready to run until some other event takes place (I/O request to disk) process go from ready to running **scheduled** then other way **unscheduled** ## Data Structures 1. process list for all processes that are ready and some additional info to track which process currently running 2. blocked processes 3. register context - hold content of registers for stopped process also **initial** states (what in when being created) **final** state when exited but not yet cleaned up (in UNIX called zombie) when finished parent process will make one final call (wait()) to wait for compeltion of child clean-up <file_sep>#ifndef BST_H_INCLUDED #define BST_H_INCLUDED #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> typedef struct TreeNode TreeNode; typedef struct Tree Tree; /* * struct: TreeNode * ---------------------------- * A node in a tree * * void* key: value of the node * TreeNode* parent: pointer to the node's parent. NULL if this is the root. * TreeNode* left: pointer to the node's left child. NULL if none exists. * TreeNode* right: pointer to the node's right child. NULL if none exists. * */ struct TreeNode { void* key; TreeNode* parent; TreeNode* left; TreeNode* right; }; /* * struct: Tree * ---------------------------- * A Tree (could be a binary search tree or some other type) * * TreeNode* root: pointer to root node of the tree. NULL if tree is empty * data_size: size of keys in bytes * comparator: function for comparing keys. Must obey the following rules: * comparator(a, b) < 0 if a < b * comparator(a, b) > 0 if a > b * comparator(a, b) = 0 if a == b * formatter: function that returns a string representation of keys * */ struct Tree { TreeNode* root; size_t data_size; int (*compare)(const void*, const void*); char* (*formatter)(const void*); }; // CREATION // Tree* create_tree(const size_t, int (const void*, const void*), char* (const void*)); TreeNode* create_tree_node(const void*, const size_t); // DISPLAY // char* tree_as_string(const Tree*); void subtree_as_string(const TreeNode*, char*, char* (const void*)); // DEPTH // int max_depth(const TreeNode*); int tree_depth(const Tree*); // INSERT // bool tree_insert(Tree*, const void*); // SEARCH // TreeNode* recursive_search(TreeNode*, const void*, int (const void*, const void*)); bool search(const Tree*, const void*); TreeNode* tree_maximum(TreeNode*); // DELETE // void transplant(Tree* tree, TreeNode*, TreeNode*); bool tree_delete(Tree*, const void*); void node_delete(TreeNode* node); // DESTROY // void destroy_subtree(TreeNode*); void destroy_tree(Tree*); // COMPARATORS // int comp_doubles(void* a, void* b); int comp_ints(void* a, void* b); void* shift(void* a, int i, size_t element_size); #endif <file_sep>#include "record.h" /* * function: create_record * ---------------------------- * Creates a record ((key, value) pair) for entry into a hash table * * key: entry's key * key_size: size of key in bytes * value: value for entry * value_size: size of value bytes * * returns: a pointer to the record */ Record* create_record(const void* key, const size_t key_size, const void* value, const size_t value_size) { // Allocate memory for the things Record* record = (Record*) malloc(sizeof(Record)); record->key = malloc(key_size); record->value = malloc(value_size); // Copy the things memcpy(record->key, key, key_size); memcpy(record->value, value, value_size); return record; } /* * function: delete_record * ---------------------------- * Frees the memory associated with a record in a table * * record: record to delete */ void delete_record(Record* record) { free(record->key); free(record->value); free(record); } <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> char name[50], mname[25], lname[25], buffer[25]; void main() { printf("Please input your first name: \n"); scanf("%s", buffer); printf("\nPlease input your middle name: \n"); scanf("%s", mname); printf("\nPlease input your last name: \n"); scanf("%s", lname); size_t n = 1, a = 50; strncpy(name, buffer, n); strncpy(buffer, mname, n); strncat(name, buffer, a); strncat(name, lname, a); puts(name); } <file_sep>#!/bin/bash if [ "$1" == "-h" ]; then echo numpages trials fi ./tlb "$1" "$2" ./plot_tlb.py results.txt <file_sep># Dj's Algorithm Notes ## Youtube find shortest path between any 2 vertices in a graph generates list of vertexes, shortest distance from index to each one, previous vertex array lists each step taken for shortest path to dest Packing List: index vertice of where to start destination vertice list of visited vertices list of unvisited vertices (initially all in there) shortest distance from index vertice to N vertex list previous vertex list - keeps track of the path 1. use a visited array and unvisited array. all start in unvisited 2. index to index is 0 and it is its own prev 3. go to each neighbor, A-B is 6 so 6+0 (A-a) = 6, A-D is 2 do 2+0=1 update shortest distancea (if smaller than shortest distance). previous vertice of each neighbor is A 4. then, visit neighbor of A that is smaller, so go to d 5. Ds neighbors are B and E, D-B is 2, d-E is 1. (A-D was 2) D-B would mean 2+2=4, D-E would be 2+1=3, so go to E next and update everything ## Wikipedia shortest path first common variant fixes single node as source, and finds shortest path from source node to all other nodes in the graph - producing shortest path tree could also just return shortest path one time if use min-priority queue for data structure, run in O(Vertices + Edges)log(Vertices) if use array O(Vertices)^2 ### How initial node = starting node distance of node y distance from initial node to Y 1. mark all nodes as unvisited 2. assign every node tentative distance value - 0 for initial, inf for others 3. for current node, calculate all tentative distances for unvisited neighbors through the current node consider newly calculated tentative distance to current assigned value and ex: if current node A is marked with distance 6, and b has 2, distance to B through A will be 6+2=8. if B was previously marked with value >8 change it to 8. otherwise leave it 4. when done considering all unvisited neighbors of current node, mark current node as visited and remove from unvisited set 5. if desintation node has been marked visited OR if smallest tentative distance among nodes in unvisited set is infinity (so no connections) then stop 6. otherwise select unvisited node that is marked with smallest tentative distance, set as new current node and go back to step 3 u and v neighbor nodes create vertex set Q for each vertex v in Graph: dist[v] = INF prev[v] = undefined add v to Q while Q is not empty: u <- vertex in Q with min dist[u] remove u from Q for each neighbor v of u: //only v that are still in Q alt <- dist[u] + length(u,v) if alt < dist[v]: dist[v] <- alt prev[v] <- u return dist[], prev[] ## Class <file_sep>package week4; public class week4class1 { /** * Removes all instances of value in array a * @param a Integer array that is not null * @param value any real number * @return a new array that has removed all instances of value * and has condensed down on itself */ public static int[] removeAll(int[] a, int value) { int[] b = null; for(int i = 0; i < a.length; i++) { int j = 0; if(a[i] != value) { b[j] = a[i]; j++; } else if (a[i] == value) continue; } return b; } /** * Removes all instances of value in array a and replaces with newValue * @param a Integer array that is not null * @param value any real number * @param newValue any real number that will replace all instances of value * @return a new array that has removed all instances of value * and has condensed down on itself */ public static int[] replaceAll(int[] a, int value, int newValue) { return a; } public static void main(String[] args) { int[] a = {1, 2, 3, 5, 6, 6, 6, 7}; int[] b = removeAll(a, 6); System.out.println(b); } } <file_sep>//Selection sort #include "jimSort.h" void selectionSort(int* sortArray, int arraySize) { for(int a = 0; a < arraySize; a++) { int small = sortArray[a]; int smallIndex = a; for(int i = a; i < arraySize; i++) { if( sortArray[i] < small ) { small = sortArray[i]; smallIndex = i; }//end if }//end inner loop int tmp = sortArray[a]; sortArray[a] = sortArray[smallIndex]; sortArray[smallIndex] = tmp; }//end outer loop } <file_sep>### Explain why sorting all the buckets in bucket sort using an O(n2) algorithm like insertion sort results in an O(n) sorting algorithm. If nb is number of elements per bucket, and n is the number of buckets, then the runtime for any individual bucket utilizing insertion sort would be: O(nb^2) The probability of any one element falling into a bucket is 1/n. Extrapolating an expected value from the statistical concept of a binomial distribution we get 2-1/n for nb^2. The variance is 1-1/n. The mean of samples is 1. expected value = variance + (mean)^2 so nb^2 = 2-1/n So now out runtime becomes: n x O(2n-1) which the largest factor in there is n, so it simplifies to O(n) regardless of using an sorting algorithm of O(n^2) runtime. In parlance that I did not have to thoroughly pore over to understand, the buckets are relatively small and the values are evenly distributed (as best as we can get with rand()). Any call to insertion sort does not have to take that many steps to complete its task. <file_sep>#include <time.h> #include <stdlib.h> #include <stdio.h> int* genArray(int testSize) { int *a = (int*) malloc(testSize*sizeof(int)); srand(time(0)); for(int i = 0; i < testSize; i++) { a[i] = rand() % 20; // printf("%d\n", a[i]); } // printf("\n\n"); return a; }//end genArray double timer(clock_t begin, clock_t end) { double daTime = ((double) (end - begin)) / CLOCKS_PER_SEC; return daTime; }//end timer FILE* resultsFile(void) { FILE *fp = fopen("results.txt", "w"); if(fp == NULL) { printf("Unable to open a file"); exit(1); } return fp; }//end resultsFile void printArray(int* array, int size) { printf("Index : Value\n"); for(int i = 0; i < size; i++) { printf(" %d : %d\n", i, array[i]); } printf("\n\n"); }//end printArray <file_sep># Ch.13 The Abstraction: Address Space multiprogramming - multiple processes run at any given time protection is important - do not want one process to be able to access memory of another process ## The Address Space the abstraction of memory is called the **address space** 3 parts to programs address space: **code heap stack** 1. code - the instructions 2. stack - function call chain, allocate variables, pass parameters and return values 3. heap - dynamically allocated, user-managed memory, or statically initialized variables heap at top, stack at bottom - grow in opposite directions multiple threads means space cannot be divided so evenly (each thread will have own stack and heap) all memory addresses that program can "return" are virtual ## Goals of this 1. transparency - OS should implement memory in a way that is invisible to running program 2. efficiency - virtualization should be as efficient as possible (this will need some hardware support) 3. protection - OS should protect one process from another <file_sep># include <stdio.h> int x,y; int stuff[12][10]; int main (void) { for ( x = 0 ; x < 12 ; x++ ) { for ( y = 0 ; y < 10 ; y++ ) { stuff[x][y] = 0; printf("%d,%d : %d\n" , x , y , stuff[x][y]); } } return 0; } <file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign10 - Advanced Web Development</h2> <h2>Research</h2> <!--writeup goes here--> <?php include 'assign10/assign10-writeup.php'?> <a href="assign10/commerce/index.php" target="_blank">Commerce Site</a></li> <h2>Before & After CODE</h2> <p> Example 1 <ul> <li> Before: <a href="assign10/ba/before1.md" target="_blank"> Before</a></li> <li> After: <a href="assign10/ba/after1.md" target="_blank"> After</a></li> </ul></p> <p> Example 2 <ul> <li> Before: <a href="assign10/ba/before2.md" target="_blank"> Before</a></li> <li> After: <a href="assign10/ba/after2.md" target="_blank"> After</a></li> </ul></p> <p> Example 3 <ul> <li> Before: <a href="assign10/ba/before3.md" target="_blank"> Before</a></li> <li> After: <a href="assign10/ba/after3.md" target="_blank"> After</a></li> </ul></p> </div> <?php include 'footer.php';?> </body> </html> <file_sep>#include <stdio.h> float div(float a, float b); float a, b, x; float main(void) { printf("\nPlease input a : "); scanf( "%f" , &a); printf("\nPlease input b: "); scanf( "%f", &b); x = div(a,b); printf("\nThe answer is %f" ,x); return 0; } float div(float a, float b) { if( b==0 ) puts("\nCannot divide by 0!\n"); else { return( a / b ); } } <file_sep>#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char *argv[]) { int scom = fork(); if(scom < 0) { fprintf(stderr, "fork failure\n"); exit(1); } if (scom == 0) { //childs path int i = exec("/bin/ls", ".", (char*) NULL); if(i < 0) exit(1); } else if(scom > 0) { //parents path return 0; } } <file_sep>#include <cs50.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include "valkey.c" #include "encipher.c" int valkey(string key); string encipher(string key, string plaintext); int main(int argc, string argv[]) { string key = argv[1]; if(!(valkey(key)) || argc != 2) { printf("Invalid key emtered- one 26 character string with no repeated characters only\n"); exit(1); } string plaintext = get_string("Please input the plaintext: "); printf("\nPlaintext: %s\n", plaintext); string ciphertext = encipher(key, plaintext); printf("Ciphertext: %s\n", ciphertext); return 0; }//end main <file_sep> 1. 100%. I know it is 100% because we specified 5 instructions each using cpu 100% of time 2. 6 cycles + ioTime. 3. I was wrong it now takes 6 cycles. The schduler calls the io and switches to process 1 to execute those 4 instructions 4. I predict that the switch-on-end flag will make the processor wait until the io request returns and process 0 ends before switching to process 1. Result: That happened 5. switch_on_io causes it to switch to another process when IO initiated making it more efficient 6. Predict: initiate all 3 IO requests, run all the other processes then jump back to IO Result: ran 1 IO request then ran the 3 processes in their entirety then went back and ran the other two System resources are not being effectively utilized 7. Predict: match my 6. prediction Result: runs an IO, runs process until IO request returned then immediately makes the next IO call, then runs processes 8. <file_sep><!doctype html> <html> <body> <?php class fridayNight { public $drink; public $location; public function __construct($drink, $location) { $this->drink = $drink; $this->location = $location; } public function message() { return "This friday I am going to drink" . $this->drink . " " . $this->location . "!"; } } $friday = new fridayNight("BEER!", "...on my couch :("); echo $friday -> message(); echo "<br>"; ?> </body> </html><file_sep>#CS50x Week 2 Arrays "compilation" oversimplification: 1. preprocessing- when have source code with includes <> copies those source codes into file 2. compiling- converts source code to assembly code (not 0s and 1s yet). intermediate step 3. assembling- turn assembly code to machine code for all included files 4. linking- links all of those together into one program the CPU can execute all of this we call compiling **debugging** printf is legit debugger lets you step through code step by step is CS50 add stop signs and use debug50 to run step by step help50 if compile error. debug50 if compiles but not run correctly **array* single quotes necessary for chars to hard code in strings use double quotes (no good reason) array essentially variable stores multiple values **if use more than once, should be a variable const know do not want to change- capitalize by convention const int N = 3; constants ok to put globally \0 all 8 bits in byte written as 0. (terminating null character) CS50 strings data type as array is multidimensional when printing strings printf just iterating through each index and printing if not \0 **command line input** int main(int argc, string argv[]) argc argument count argv[] argument vector argc 1 is program name- everything after corresponds to more words argv[] index corresponds to argc number and captures those arguments by default main returns 0- aka all is well can return more than 0 if something goes wrong <file_sep>#include "linkedlist.h" //basic functions linkedlist* create_list() { linkedlist* list = (linkedlist*) malloc(sizeof(linkedlist*)); list->head = NULL; return list; } node* create_node(linkedlist* list, const void* data, const size_t dataType){ node* newNode = (node*) malloc(sizeof(node)); newNode->data = malloc(dataType); memcpy(newNode->data, data, dataType); list->list_size++; return newNode; } void destroy(node* n) { free(n->data); free(n); } //add functions /* Function: add_beginning * * Adds data to the beginning of the list * list: list to add to * data: data to place in node * dataType: the size of data's datatype * * returns true if operation was successful, false if otherwise */ bool add_beginning(linkedlist* list, const void* data, const size_t dataType) { node* newNode = create_node(list, data, dataType); newNode->next = list->head; list->head = newNode; return true; } void add_end(linkedlist* list, int pos) { } void add_n(linkedlist* list, int pos) { } //removal functions void remove_node(linkedlist* list, int pos){ node* trav = list->head; node* bridge = trav; for(int i = 0; i < pos; i++) { trav = trav->next; if(i != 0) bridge = bridge->next; } bridge->next = trav->next; free(trav); } void remove_beginning(linkedlist* list) { } void remove_end(linkedlist* list) { } //get functions <file_sep># Ch.16 Segmentation just one base/bounds perprocess is wasteful **segmentation** - have base/bounds per local segment of address space - heap, stack, code - each can be placed independently offset based on virtual segmentation- which bytes *in this segment* we are referring to 1. subtract the desired VIRTUAL address from the base VIRTUAL address 2. add the difference to the PHYSICAL base for that segment - which means for a positive growing segment subtract from the physical end of the segment (not the "base") - for a negative growing segment add to the actual base (if address is valid the desired v - v base will be negative, resulting in a valid address) example bc ur dumb: RG seed 0 ARG address space size 1k ARG phys mem size 16k Segment register information: Segment 0 base (grows positive) : 0x00001aea (decimal 6890) Segment 0 limit : 472 Segment 1 base (grows negative) : 0x00001254 (decimal 4692) Segment 1 limit : 450 Virtual Address Trace VA 0: 0x0000020b (decimal: 523) --> SEGMENTATION VIOLATION (SEG1) VA 1: 0x0000019e (decimal: 414) --> VALID in SEG0: 0x00001c88 (decimal: 7304) VA 2: 0x00000322 (decimal: 802) --> VALID in SEG1: 0x00001176 (decimal: 4470) VA 3: 0x00000136 (decimal: 310) --> VALID in SEG0: 0x00001c20 (decimal: 7200) VA 4: 0x000001e8 (decimal: 488) --> SEGMENTATION VIOLATION (SEG0) **NOTE FROM THE HOMEWORK** - your segment 0's base maps to virtual address 0 in the virtual address space - your segment 1's base maps to virtual address n for virtual address space of size n - - so keep track of virtual base/bounds in software?? and physical in hardware? One approach to segmentaion: **explicit** uses the first 2 bits of an address to determine the segment (calculates with logical anding to masks then bitshifting) **implicit** approach - hardware determines segment by noticing how the address was formed - ie: - if instruction fetch then code segment - based off stack pointer, on stack - otherwise heap soo since the stack could grow DOWN we need..... MORE HARDWARE - one approach: keep track of a bit 1 for negative 0 for positive - speaking of that to get a negative offset: 1. subtract the maximum segment size from the requeted virtual offset (bottom bits of address) 2. add that negative offset to PHYSICAL base 3. bounds check based upon absolute value of calculated negative offset coarse-grained or fine-grained segmentation soooo what about a context switch? - add mechanisms to save and restore segment registers - manage free space in memory with a data structure || **external fragmentation** - too many little holes in memory one solution: compact physical memory by rearranging segments - but very costly usually use some kind of algorithmic approach to allocate memory efficiently with the help of the free list - many many ways to slice that cat <file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign12 - Advanced Web Development</h2> <h2>Research</h2> <!--writeup goes here--> <p><a href="https://learning.oreilly.com/library/view/smashing-wordpress-beyond/9781119942719/">Smashing WordPress: Beyond the Blog</a></p> <p><a href="https://learning.oreilly.com/library/view/wordpress-the-missing/9781492074151/">WordPress The Missing Manual</a></p> <h2>Before & After CODE</h2> <p><a href="https://jmd06260.classweb.ccv.edu/wp2/">Second WordPress site</a></p> </div> <?php include 'footer.php';?> </body> </html> <file_sep>#include <stdio.h> #define max 10 int inputs[max]; int a,b,tmp; int sorted[max]; void sortAscend(int inputs[max]); void sortDescend(int inputs[max]); int main () { //Receive Input int a = 0; int sel; for (a = 0; a < max; a++) { printf("\nInput number: %d\n", a); scanf("%d", &inputs[a]); } //Select Ascend or Descend printf("\nWould you like to sort ascending or descending? 1 or 2?:\n"); scanf("%d", &sel); if ( sel == 1){ sortAscend(inputs); } else if ( sel == 2){ sortDescend(inputs); } //Print Sorted List for ( a=0; a < max; a++ ) { printf("%d\n", inputs[a]); } return 0; } void sortDescend(int inputs[max]) { for ( a=0; a < max; ++a) { for (b = a+1; b < max; ++b) { if (inputs[a] > inputs[b]) { tmp = inputs[a]; inputs[a] = inputs[b]; inputs[b] = tmp; } } } } void sortAscend(int inputs[max]) { for ( a=0; a < max; ++a) { for (b = a+1; b < max; ++b) { if (inputs[a] < inputs[b]) { tmp = inputs[a]; inputs[a] = inputs[b]; inputs[b] = tmp; } } } } <file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <limits.h> #define DEFBUCKET 5 /* * Function: display * ---------------------------- * Prints out an integer array in a really nice format. Nice. * * a: pointer to the beginning of an integer array * length: array size * */ void display(int* a, const size_t LENGTH) { printf("[ "); for (int i = 0; i < LENGTH; i++) { printf("%d ", a[i]); } printf("]\n"); } /* * Function: big_rand * ---------------------------- * Hack to get you a bigger range of random ints * */ int big_rand() { if (RAND_MAX < INT_MAX) { return rand() * (RAND_MAX - 1) + rand(); } else { return rand(); } } /* * Function: rand_ints * ---------------------------- * Generates a random array of SIZE integers in the range 0 <= n < MAX * * SIZE: number of elements in array * MAX: upper bound for elements (exclusive) * * returns: pointer to the array * */ int* rand_ints(const int SIZE, const int MAX) { int* a = (int*) malloc(SIZE * sizeof(int)); for (int i = 0; i < SIZE; i++) { a[i] = big_rand() % MAX; } return a; } /* * Function: swap * ---------------------------- * Swaps elements i and j in int[] a * * a: an integer array * i, j: indices to swap * */ void swap(int* a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } /* * Function: insertion_sort * ---------------------------- * Takes an unsorted array and sorts it in ascending order using the insertion * sort algorithm * * a: pointer to the beginning of an integer array * SIZE: size of array * */ void insertion_sort(int* a, int SIZE) { int i = 1; while (i < SIZE) { int j = i; while ((j > 0) && (a[j - 1] > a[j])) { swap(a, j, j - 1); j--; } i++; } } /* * Function: min * ---------------------------- * Finds the smallest element in an array * * a: pointer to the beginning of an integer array * SIZE: size of array * * returns: the smallest element in the array */ int min(int* a, const int SIZE) { int minvalue = INT_MAX; for (int i = 0; i < SIZE; i++) { if (a[i] < minvalue) { minvalue = a[i]; } } return minvalue; } /* * Function: max * ---------------------------- * Finds the largest element in an array * * a: pointer to the beginning of an integer array * SIZE: size of array */ int max(int* a, const int SIZE) { int maxvalue = INT_MIN; for (int i = 0; i < SIZE; i++) { if (a[i] > maxvalue) { maxvalue = a[i]; } } return maxvalue; } /* * Function: bucketsort * ---------------------------- * Takes an unsorted array and sorts it in ascending order using the * bucketsort algorithm * * a: pointer to the beginning of an integer array * SIZE: size of array * */ void bucketsort(int* a, const int SIZE) { //create buckets int smallest = min(a, SIZE); int largest = max(a, SIZE); int bucket_size = (largest - smallest + 1) / SIZE; if(bucket_size == 0) { bucket_size = 1; } const int numBuckets = ((largest - smallest) / bucket_size) + 1; int** bucketArray = (int**) malloc(numBuckets * sizeof(int*)); int* n_in_bucket = (int*) malloc(numBuckets * sizeof(int)); for(int i = 0; i < numBuckets; i++) { bucketArray[i] = (int*) malloc(DEFBUCKET * sizeof(int)); n_in_bucket[i] = 0; } //put array members into buckets for(int i = 0; i < SIZE; i++) { int ibucket = (a[i] - smallest) / bucket_size; if((n_in_bucket[ibucket] % DEFBUCKET) == 0) bucketArray[ibucket] = (int*) realloc(bucketArray[ibucket], (sizeof(int)*(n_in_bucket[ibucket] + DEFBUCKET))); bucketArray[ibucket][n_in_bucket[ibucket]] = a[i]; n_in_bucket[ibucket]++; } //use insertion sort on each bucket for(int i = 0; i < numBuckets; i++) insertion_sort(bucketArray[i], n_in_bucket[i]); //paste sorted members back into array int position = 0; for(int i = 0; i < numBuckets; i++) { for(int j = 0; j < n_in_bucket[i]; j++) { a[position] = bucketArray[i][j]; position++; } } //free memory for(int i = 0; i < numBuckets; i++) free(bucketArray[i]); free(bucketArray); free(n_in_bucket); } int main(void){ srand(time(NULL)); //prove it works int* array = rand_ints(10, 100); display(array, 10); bucketsort(array, 10); display(array, 10); free(array); //test for time int size = 10000; FILE* fp = fopen("results.txt", "w"); clock_t begin, end; double daTime; fprintf(fp, "Array Size, Time\n"); for(int i = 0; i < 5; i++) { for(int j = 0; j < 10; j++) { int* array = rand_ints(size, 1000); begin = clock(); bucketsort(array, size); end = clock(); daTime = ((double) (end - begin)) / CLOCKS_PER_SEC; fprintf(fp, "%d, %f\n", size, daTime); free(array); } size *= 2; } fclose(fp); return 0; } <file_sep>#include "genquicksort.h" int main(void) { //proof I did this correctly double* doubleArray = ranDoubArray(10); printDoubleArray(doubleArray, 10); quicksort(doubleArray, 0, 9, comp_doubles, sizeof(double)); printDoubleArray(doubleArray, 10); free(doubleArray); int* intArray = ranIntArray(10); printIntArray(intArray, 10); quicksort(intArray, 0, 9, comp_ints, sizeof(int)); printIntArray(intArray, 10); free(intArray); //testing times FILE* fp = resultsFile(); int factor = 1; int testSize = 10; clock_t start = 0; clock_t end = 0; fprintf(fp, "Array Type, Array Size, Time\n"); for(int i = 0; i < 5; i++) { int* ranints = ranIntArray(testSize); start = clock(); quicksort(ranints, 0, testSize - 1, comp_ints, sizeof(int)); end = clock(); double daIntTime = timer(start, end); free(ranints); fprintf(fp, "Int, %d, %d, %f\n", i, testSize, daIntTime); printf("Int, %d, %d, %f\n", i, testSize, daIntTime); factor += 2; testSize = testSize * factor; } factor = 1; testSize = 10; start = 0; end = 0; for(int i = 0; i < 5; i++) { double* randoubs = ranDoubArray(testSize); start = clock(); quicksort(randoubs, 0, testSize - 1, comp_doubles, sizeof(double)); end = clock(); double daDoubTime = timer(start, end); free(randoubs); fprintf(fp, "Double, %d, %d, %f\n", i, testSize, daDoubTime); printf("Double, %d, %d, %f\n", i, testSize, daDoubTime); factor += 2; testSize = testSize * factor; } return 0; }//end main <file_sep> #include "calc.h" long sqr(int x) { return ((long)x *x); } <file_sep>package vtc.oop.week7.car; /** * Represents a car that can be driven by burning fuel. * * @author jeremy * */ public class car { /** Number of gallons of gas the tank can hold, must be > 0 */ private final double FUEL_CAPACITY; /** Number of miles that can be driven on a gallon of fuel, must be > 0 */ private final double FUEL_EFFICIENCY; /** Number of miles car has been driven in its lifetime, >= 0 */ private double odometer; /** Number of gallons of fuel in the tank, must be >= 0 and <= {@link FUEL_CAPACITY} */ private double fuelLevel; private void repOK() { assert(FUEL_CAPACITY > 0); assert(FUEL_EFFICIENCY > 0); assert(odometer >= 0); assert(fuelLevel >= 0 && fuelLevel <= FUEL_CAPACITY); } /** * Creates a new car with a full tank of gas * * @param fuelCapacity - maximum number of gallons of fuel tank can hold, must * be > 0 * @param fuelEfficiency - car's fuel efficiency in miles per gallon, must be > * 0 * @param odometer - initial odometer reading in miles, must be >= 0 * @throws IllegalArgumentException if fuel tank capacity or fuel efficiency are * 0 or negative, or if odometer reading is * negative */ public car(double fuelCapacity, double fuelEfficiency, double odometer) throws IllegalArgumentException { if(fuelCapacity <= 0) { throw new IllegalArgumentException("Invalid fuel capacity" + fuelCapacity); } if(fuelEfficiency <= 0) { throw new IllegalArgumentException("Invalid fuel efficiency" + fuelEfficiency); } if(odometer < 0) { throw new IllegalArgumentException("Invalid initial odometer reading" + odometer); } this.FUEL_CAPACITY = fuelCapacity; this.FUEL_EFFICIENCY = fuelEfficiency; this.odometer = odometer; this.fuelLevel = fuelCapacity; repOK(); } /** * Drives the car a given number of miles, burning fuel in the process * * @param nMiles - number of miles to drive, cannot be negative, cannot exceed * the car's range * @throws IllegalArgumentException if the requested number of miles is negative * or exceeds the car's range */ public void drive(double nMiles) throws IllegalArgumentException { if(nMiles < 0) throw new IllegalArgumentException("Invalid distance"); if (nMiles > getRange()) throw new IllegalArgumentException("Too far bro"); odometer = odometer + nMiles; fuelLevel = fuelLevel - (nMiles / FUEL_EFFICIENCY); repOK(); } /** * Fills the car's fuel tank to capacity * * @return {@code true} if any fuel was added to the tank, {@code false} * otherwise */ public boolean refuel() { if(fuelLevel < FUEL_CAPACITY) { fuelLevel = FUEL_CAPACITY; repOK(); return true; } return false; } /** * * @return the number of gallons of fuel left in the tank, >= 0 */ public double getFuelLevel() { return fuelLevel; } /** * @return the number of miles the car can be driven until it runs out of fuel, * >= 0 */ public double getRange() { return fuelLevel*FUEL_EFFICIENCY; } /** * @return how many miles the car has been driven in its lifetime, >= 0 */ public double getOdometerReading() { return odometer; } @Override public String toString() { //Show odometer reading, fuel level / capacity, mpg return String.format("Car: odometer = %.1f, fuel = %.1f / %.1f gal, efficiency = %.1f", odometer, fuelLevel, FUEL_CAPACITY, FUEL_EFFICIENCY); } } <file_sep>#include "heapsort.h" int main(void) { FILE* fp = resultsFile(); fprintf(fp, "Iteration, Test Size, Overall Time, Heapify Time\n"); clock_t begin = 0; clock_t end = 0; int trials = 10; int factor = 2; int testSize = 100; for(int i = 0; i < trials; i++) { int* heap = genArray(testSize); // printArray(heap, testSize); begin = clock(); double heapTime = heapsort(heap, testSize); end = clock(); // printArray(heap, testSize); double daTime = timer(begin, end); fprintf(fp, "%d, %d, %f, %f\n", i, testSize, daTime, heapTime); testSize *= factor; free(heap); } fclose(fp); return 0; }//end main <file_sep># include <stdio.h> double calc(double n1, char op, double n2); void main () { int ctrl = 0; double n1 = 0, n2 = 0; static double output = 0; int op; do { if ( ctrl == 1) { n1 = output;} else{ n1 = 0; printf("\nInput your first number:"); scanf("%lf", &n1); } do { printf("\nInput operation: (1-add, 2- subtract, 3- multiply, 4- divide)\n"); scanf("%d", &op); } while ( op < 5 ); printf("\nInput your second number:"); scanf("%lf", &n2); output = calc(n1, op, n2); printf("\nThe answer is %lf\n", output); printf("Would you like to continue?\n"); printf("1 calc again with last output\n"); printf("2 calc again new\n"); printf("3 quit\n"); scanf("%d", &ctrl); } while (ctrl != 3); } double calc(double n1, char op, double n2) { double answer = 0; switch (op) { case 1: answer= n1 + n2; break; case 2: answer= n1 - n2; break; case 3: answer= n1 * n2; break; case 4: answer= n1 / n2; default: answer = 42; } return answer; } <file_sep><?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign01 - Advanced Web Development</h2> <h2>Research</h2> <p> Hello Everyone! I apologize for being late to the party but I am also a student at VTC and my classes there do not start until next week, so I got a little confused. Nonetheless I am present and ready to get started. I daily drive Linux but I also have access to Windows if need be. I tend to stick in the good zsh terminal so I usually use any tools related to that. I also have access to Microsoft Office products and am pretty familiar with using them. I am a former Army Officer who got out of the Army and (when I started having free time again) discovered a passion for computers and technology. I completed self-study for about a year, then enrolled in VTC's Advanced Software Development Certificate program. I already have a Bachelors degree in Business (kinda useless unless you want to be some flavor of a salesman). As such I know C, Java, Python, HTML/CSS (from web dev 1), SQL, bash scripting, I have dabbled in assembly languages, and even an obscure language called Rockstar. I almost exclusively get my news from Hacker News so I am on there daily. I also watch a LOT of Youtube videos, so I am on there as well. When I took Web Development 1 last summer it was utilized content from w3schools. I have also used w3schools for other concepts as well. I am a pretty quick study in general so I should have no problem picking up what you're putting down. If I do not understand something and cannot find it on Google or in a book, I will send you a message. Thanks, Jim <EMAIL> </p> <h2>Before & After CODE</h2> <p> Example 1 <ul> <li> Before: <a href="https://jmd06260.classweb.ccv.edu/AdvWeb/assign01/FirstPHPScript.php" target="_blank"> https://jmd06260.classweb.ccv.edu/AdvWeb/assign01/FirstPHPScript.php</a></li> <li> After: <a href="https://jmd06260.classweb.ccv.edu/AdvWeb/assign01/FirstPHPScript-after.php" target="_blank"> https://jmd06260.classweb.ccv.edu/AdvWeb/assign01/FirstPHPScript-after.php</a></li> </ul></p> </div> <?php include 'footer.php';?> </body> </html> <file_sep># CS50 Week 0 Introduction computer science is process of solving problems have input want output- CS is inbetween first concept how represent info itself unary notation- counting 1 at a time binary uses powers of 10 2^4 2^2 2 421 000 011 4x0 + 2x1 + 1x1 = 3 create characters by representing with numbers- ASCII unicode superset of ascii for other langauges and emojis represent colors with numbers- mixing RGB each pixel has 3 numbers- tells how much red, green, and blue **algorithim**- the inbetween of the input -> output box. step by step instruction for how to go from input to output problem solving just translating your intuition to something machine understands **functions**- actions what to do **conditions**- branches forks in the road to follow a branch need to ask question **boolean expression**- the question with yes or no answer **loop**- cycle that does something again and again **variables threads** ** ##Scratch circular are varaibles. trapezoids are booleans broadcast puzzle piece sends event- computers can look for events from one program to another can make your own blocks- aka functions or objects build program a piece at a time <file_sep><?php //$_POST = array("name"=>"Jim", "flavor"=>"Chocolate"); foreach ($_POST as $p => $val) echo $p ." => " . $val; $name = $_POST["name"]; $flavor = $_POST["flavor"]; $filename = "CCV_" . $name . ".xml"; if(file_exists($filename)) unlink($filename); //write_icecream($filename, $flavor); new_icecream($filename, $name, $flavor); /*it is ridiculous how hard it is to change the value of 1 tag function write_icecream($filename, $flavmr) { $dom = new DOMDocument('1.0', 'UTF-8'); $dom->formatOutput = true; $dom->load($filename, LIBXML_NOBLANKS); $root = $dom->documentElement; $flavor_old = $root->childNodes(1); $flav = $dom->createElement('flavor', $flavor); $root->replaceChild($flavor_old, $flav); echo '<xmp>' . $dom->saveXML() . '</xmp>'; $dom->save($filename) or die ('Unable to create XML file'); } */ function new_icecream($filename, $name, $flavor) { $dom = new DOMDocument('1.0', 'UTF-8'); $dom->formatOutput = true; $root = $dom->createElement('person'); $dom->appendChild($root); $att1 = $dom->createElement('name', $name); $root->appendChild($att1); $att2 = $dom->createElement('flavor', $flavor); $root->appendChild($att2); echo '<xmp>' . $dom->saveXML() . '</xmp>'; $dom->save($filename) or die ('Unable to create XML file'); } ?> <file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign09 - Advanced Web Development</h2> <h2>Research</h2> <!--writeup goes here--> <p>Larry built up his example very slowly, and spends many pages going over exactly what each block of code is doing. W3Schools just kinda said "well here it is!" without much explanation. At this point in my education, I can do the W3 way (in fact it's easier for me) just because I know how the program is going to run, I just need to see the specific syntax for PHP. If I was just starting out, Larry's book would be a game changer. Especially if I had never been instructed on object oriented programming, or had not spent a lot of time digging through documentation and learning how to do that efficiently.</p> <h2>Ch18 Link</h3> <a href="assign09/index.html" target="_blank">My Ch18 implementation</a> <h2>Before & After CODE</h2> <p> Example 1 <ul> <li> Before: <a href="assign09/before1.md" target="_blank"> Before</a></li> <li> After: <a href="assign09/after1.md" target="_blank"> After</a></li> </ul></p> <p> Example 2 <ul> <li> Before: <a href="assign09/before2.md" target="_blank"> Before</a></li> <li> After: <a href="assign09/after2.md" target="_blank"> After</a></li> </ul></p> <p> Example 3 <ul> <li> Before: <a href="assign09/before3.md" target="_blank"> Before</a></li> <li> After: <a href="assign09/after3.md" target="_blank"> After</a></li> </ul></p> </div> <?php include 'footer.php';?> </body> </html> <file_sep>/* CIS2271 * Midterm * @author <NAME> * * Welcome to Night of the Midterm: a horrifying tale of one Java student's night of survival. * This is a text based mini-game written in Java that demonstrates some of the basics of the language. * It is contained in one class, it has a main menu, an opening sequence, 2 rooms with challenges, and a * closing sequence. * Failure will loop you back to the main menu. Which just consists of the option to play or terminate the * program. * Enjoy! */ import java.util.*; import java.lang.*; import java.util.concurrent.TimeUnit; public class NightMidterm { static int text = 5; //made the time text appears adjustable so I could debug easier static int success = 1; //the main variable for program control static Scanner sc = new Scanner(System.in); //the primary scanner public static void main(String[] args) { System.out.println("|-. -| | --- | \\| (-) -- -| |-- | |- --- / -| | |-| |-- --- "); System.out.println("|.| | '-\\ / -\\ | \\ | |/ -` | '- \\ --| / - \\ |- | --| '- \\/ - \\ "); System.out.println("|.| | | | | --/ | |\\ | | (-| | | | | |- | (-) | -| | |-| | | | --/ "); System.out.println("|-|.|-| |-\\---| |-| \\|-\\--, |-| |-\\--| \\---/|-| \\--|-| |-\\---| "); System.out.println(". |---/ "); System.out.println("--. -- - - - "); System.out.println("|.\\/ (-) --| | |- --- - -- - -- --- "); System.out.println("|.\\/| | |/ -` | --/ -\\ '--| '- ` - \\ "); System.out.println("|.| | | | (-| | || --/ | | | | | | | "); System.out.println("|-|. |-|-\\--,-\\-\\---|-| |-| |-| |-| "); //good idea fairy but I did not want to sink the more than 30 minutes it took to get it to this point do //I just have it continuously loop so you always get asked to exit before exiting. { mainMenu(); //always come back to here bedroom(); //The first room is just a story comment out if in a hurry success = hallway(); //1st challenge room. If you fail you go back to the main menu if (success != 1) continue; success = kitchen(); //if you beat hallway, then you move onto here. Failure returns you to the main menu if (success != 1) continue; backyard(); //just the closing scene. can be commented out if in a hurry } while(true); }//end main public static void mainMenu() //I found it easier to encapsulate the main menu than type it into main { System.out.println("\nWelcome to The Night of the Midterm Please Choose an Option below: "); System.out.printf("Option 1: Start a new game\nOption 2: Exit\n\nPlease input your choice: "); success = sc.nextInt(); if (success != 1) { sc.close(); System.exit(0); } else { System.out.println("Choose your text speed. 3- Fast. 5- Medium. 7-Slow: "); text = sc.nextInt(); } }//end mainMenu public static void bedroom() //First room just story text { System.out.println("It is a dark and stormy night, the wind howls at the apple\ntree now rasping my window with the sound of nails on a chalkboard\n"); delay(text); System.out.println("Sleeping on top of my computer with my screen open to \nmy nowhere-near-done CIS2271 Java Midterm, a puddle of drool pools on my trackpad\n"); delay(text); System.out.println("Sleeping peacefully on the bed, my faithful(?) scroungy \nhound Willy snoozes despite the lightning and hellish wind.\n"); delay(text); System.out.println("Suddenly screeches and crashes can be heard downstairs, \nthe house is bathed in a red light before it washes away.\n A hex symbol appears on the bedroom door\n"); delay(text); System.out.println("Willy, who jumps up in fright, begins to bark, but instead says in \nEnglish \"Whoa whoa whoa go away I am sleeping!\". \nPuzzled even to himself as to how he suddenly gained the power to speak, Willy realizes he has to pee.\n"); delay(text); System.out.println("Willy hops off the bed and begins to poke me gently with his paw\n \"Hey Jim get up I have to pee. You gotta let me out or I will pee all over the house\"\n"); delay(text); System.out.println("I feel the pawing at my shoulder, and rouse from my demonic \nsleep in the groggiest of fogs to see Willy standing by my desk\n"); delay(text); System.out.println("Willy speaks again \"Hey Jim so uh there is definitely something very\n hellish going on downstairs\n now normally I would say (not that I normally say anything) \nlet's sit this one out, but you're going to have to face the demons\n because I need to be let out and if you don't I will pee all over the house.\n"); delay(text); System.out.println("\"Willy you're talking!?!\" I blurt out in astonishment. \n\"What the hell is going on here?\".\n"); delay(text); System.out.println("\"I think that's the problem Jim... hell is in the house.\n I suspect that something to do with the strange noises downstairs\n and the hex symbol on the door... and could explain why I am talking\"\n"); delay(text); System.out.println("I stammer \"So I mean shoot I don't want to go out there, \nthis program was written by guy who has terrible humor,\n are you really going to pee all over the house?\"\n"); delay(text); System.out.println("\"Yes. Now I am going to open the door are you ready for the first demon?\"\n"); delay(text); System.out.println("Fearing the wrath of my wife when Willy pees on the carpet \nmore than the powers of hell,\n I step past my scroungy hound and open the door to the hallway\n\n"); delay(text); }//end bedroom public static int hallway() //face the demon Karen and her multiple choice riddle. { System.out.println("ROOM 1 THE HALLWAY\n"); delay(2); System.out.println("I open the door to hallway and am immediately greeted to\n the smell of pumpkin Yankee Candle\n hex symbols are all over the walls, \nand very low in the background <NAME> is playing.\n"); delay(text); System.out.println("Willy turns to me \"Hey so uh I do not think these demons are \nwhat we were thinking. I think this one is a just a straight stereotype.\"\n"); delay(text); System.out.println("Suddenly a woman steps from around the corner, \nher eyes are glowing but she is wearing Lululemon tights and carrying a Starbucks coffee.\n"); delay(text); System.out.println("\"Who dares challenge me!\" says the woman \n\"I am the mighty demon Karen! If you challenge me you must solve my riddle!\n"); delay(text); System.out.println("Ok let's be real that is pretty funny.\n A demon named Karen? I can't help but chuckle a little bit.\n"); delay(text); System.out.println("\"How dare you laugh at me! Now I will make the riddle that much harder!\"\n"); delay(text); System.out.println("Willy says \"Hey man you wanna give it a rest? \nI would like to not pee on the floor.\"\n"); delay(text); System.out.println("\"Willy chill I got this. Ok Karen I accept you challenge.\" I reply.\n"); delay(text); System.out.println("Karen starts her challenge \"I am tall when I am young, and I am short when I am old. What am I?\"\n"); delay(text); System.out.println("Option 1: A dog\nOption 2: A person\nOption 3: A candle\nOption 4: A lamp\n\n Please input the number of your answer: "); int answer = sc.nextInt(); if ( answer == 3 ) { success = 1; System.out.println("\"Darn you have chosen correctly. My curse is lifted from this room, and you may pass.\"\nHallway Complete!\n\n"); delay(text); } else { success = 0; System.out.println("\"You have chosen incorrectly and you are doomed!\"\n"); delay(text); System.out.println("*Willy pees on floor*\n"); delay(3); } if(success == 0) { System.out.println("GAME OVER"); delay(2); System.out.println("Would you like to continue? 1 - yes. 2- no: "); int cont = sc.nextInt(); if (cont == 1) success = hallway(); } return success; }//end hallway public static int kitchen() //face the demon <NAME> but don't worry he's not here to shoot you. { Random gen = new Random(); System.out.println("ROOM 2 THE KITCHEN\n\n"); delay(3); System.out.println("After defeating Karen, Willy and I wondered what could be next.\nBravely we continued on down the stairs.\n"); delay(text); System.out.println("Luckily the kitchen was right there so the programmer does\n not need to create more rooms.\n"); delay(text); System.out.println("We entered the kitchen to find the counter covered in all different kinds of guns.\nTHe windows were scrolling glyphs like in the matrix\n and AC/DC played softly in the background.\n"); delay(text); System.out.println("A figure dressed entirely in black and sitting in shadow is sitting at the kitchen table\n tossing a knife into the air and catching it perfectly everytime.\nThe knife blade menacingly catches the moon light with each flip,\n We stop dead in our tracks.\n"); delay(text); System.out.println("Willy burps. \"Oh sorry I burp when I am nervous. So who are you supposed to be?\"\n"); delay(text); System.out.println("\"Willy isn't it obvious?\" I chime in. \"That's <NAME>!\nOh my god are you going to shoot us?\"\n"); delay(text); System.out.println("The Boogeyman himself stabs the knife into the table, \nand rises into the light with his hands raised.\n \"Whoa easy gents I won't shoot you if you can guess what number I am thinking.\n"); delay(text); System.out.println("Willy says \"That's the challenge? Oh god I really am going to pee on the floor\nsorry Jim.\n"); delay(text); System.out.println("Keanu continues \"I am thinking of a number between 1 and 10.\nGuess correctly and I will lift my curse\"\n"); delay(text); int keanu = gen.nextInt(10); System.out.println("Please input your guess: "); int guess = sc.nextInt(); System.out.println("\"I guess " + guess + ". I state with confidence\"\n"); //My concatenated string delay(text); if ( guess == keanu ) System.out.printf("\"Wow I was thinking of %d... Well uh I forgot to\n mention there is more to the challenge.\"\n", keanu); else System.out.println("\"Sorry man that's incorrect but good thing that's \nnot the real challenge or else I would go <NAME> on you.\"\n"); delay(text); System.out.println("Keanue continued \"Ya know what is better than guessing numbers \n and my favorite thing in the world?\"\n"); delay(text); System.out.println("Willy can't help himself \"Oh oh is it dogs <NAME>? I saw <NAME> 1\"\n"); delay(text); System.out.println("\"What, no it is not dogs Willy... it's MATH!\"\n"); delay(text); System.out.println("Keanu continues \"Ok one of you pick a number. For satisfying the rubric\n let's make it a double.\"\n"); delay(text); System.out.println("Please input your double: "); double reaves = sc.nextDouble(); System.out.printf("\"Ok so you picked %f, let's call that %d. What is the square root of that to the nearest whole number?\"\n", reaves, (int) reaves ); reaves = Math.sqrt(reaves); double exp = Math.pow(reaves, 3); System.out.printf("Option 1: %f\nOption 2: %d\nOption 3: %d\nOption 4: %f\n\n Please input your answer: ",reaves, (int) reaves, (int) reaves + 1, exp); int answer = sc.nextInt(); if (answer == (int) reaves) { System.out.println("\"Well it would seem that is correct. You may let your dog outside to pee\nMy curse is lifted\"\n"); success = 1; delay(text); } else { System.out.println("\"You have failed this challenge and you may not pass\"\n"); success = 0; delay(text); System.out.println("*Willy pees on floor*\n"); delay(3); } if(success == 0) { System.out.println("GAME OVER"); delay(2); System.out.println("Would you like to continue? 1 - yes. 2- no: "); int cont = sc.nextInt(); if (cont == 1) success = kitchen(); } return success; }//end kitchen public static void backyard() //our closing scene, if our hero succeeds in eradicating the demons, Willy { //gets to pee outside. System.out.println("EPILOGUE"); delay(3); System.out.println("As I open the back door, the storm that was raging in the skies is lifted\nmoonlight shines through the parting clouds."); delay(text); System.out.println("Willy runs rather frantically to his favorite tree\n and relieves himself."); delay(text); System.out.println("I smile as I know that I don't have to clean up dog pee.\n What a great way to end a horrible night."); delay(text); System.out.println("THE END"); delay(3); }//end backyard public static void delay(int seconds)//I found this was a waay easier way to integrate delays. Especially { //because I needed them so much for the story text. try { TimeUnit.SECONDS.sleep(seconds); } catch (InterruptedException e) { e.printStackTrace(); } }//end delay }//end class <file_sep>#include <iostream> #include <vector> #include <stack> #include <queue> using namespace std; int main() { vector<int> v; for (int i = 1; i <=5; i++) { v.push_back(i); } for(int i : v) { cout << v[i] << " "; } cout << endl; queue<int> q; stack<int> s; for(int i = 0; i<5; i++) { q.push(i); s.push(i); } cout << "Queue "; while(!q.empty()) { int value = q.front(); q.pop(); cout << value << " "; } cout << endl; cout << "Stack "; while(!s.empty()) { int value = s.top(); s.pop(); cout << value << " "; } cout << endl; return 0; } <file_sep>#include "open_address_table.h" #include <limits.h> /* * function: create_table * ---------------------------- * Creates a hash table using open addressing and lazy deletion * N: table size * hash_function: hash function used to find bucket numbers for keys * compare: function for comparing keys. Must obey the following rules: * compare(a, b) < 0 if a < b * compare(a, b) > 0 if a > b * compare(a, b) = 0 if a == b * record_formatter: returns a C string (char*) representation of a record * key_size: size of keys in bytes * value_size: size of values in bytes * * returns: a pointer to the table * */ HashTable* create_table(const int N, size_t (*hash_function)(const void*), int (*compare)(const void*, const void*), char* (*record_formatter)(const void*), const size_t key_size, const size_t value_size) { // Allocate space for the table HashTable* table = (HashTable*) malloc(sizeof(HashTable)); // Initialize attributes table->N = N; table->hash_function = hash_function; table->compare = compare; table->record_formatter = record_formatter; table->key_size = key_size; table->value_size = value_size; // Initialize records - this is an array of Records // Initially, all the buckets will be empty table->buckets = (Record**) malloc(N * sizeof(Record*)); for (int i = 0; i < N; i++) { table->buckets[i] = NULL; } return table; } /* * function: table_to_string * ---------------------------- * Provides a string representation of the table * table: the table to return in string form * * returns: a string representation of the table * */ char* table_to_string(const HashTable* table) { char* out = (char*) malloc(2048 * sizeof(char)); sprintf(out, "n\tB[n]\t\n-----------------"); for (int i = 0; i < table->N; i++) { Record* record = table->buckets[i]; char record_as_string[256]; if (record == NULL) { sprintf(record_as_string, "EMPTY"); } else if (record == DELETED) { sprintf(record_as_string, "DELETED"); } else { char* holder = table->record_formatter(record); sprintf(record_as_string, "%s", holder); free(holder); } sprintf(out, "%s\n%d\t%s", out, i, record_as_string); } return out; } /* * function: find_bucket * ---------------------------- * Finds the bucket occupied by the entry with a matching key. DELETED buckets * are treated as occupied. * * table: the table to search * key: key to search for * * returns: the index of the bucket containing the desired key value, * -1 if not found */ int find_bucket(const HashTable* table, const void* key) { int attempts = 0; while(attempts < table->N) { int i = (table->hash_function(key) + attempts) % table->N; if(table->buckets[i] == NULL) return -1; if(table->buckets[i] == DELETED) { attempts++; continue; } if(table->compare(table->buckets[i]->key, key) == 0) return i; attempts++; } return -1; } /* * function: find_empty_bucket * ---------------------------- * Finds next unoccupied bucket in the table. DELETED buckets are treated as * available. Used when inserting a new entry into the table. * table: the table to search * key: key to search for * * returns: the bucket number if thte key is found or -1 if it isn't */ int find_empty_bucket(const HashTable* table, const void* key) { int attempts = 0; while(attempts < table->N) { int i = (table->hash_function(key) + attempts) % table->N; if(table->buckets[i] == NULL || table->buckets[i] == DELETED) return i; attempts++; } return -1; } /* * function: insert * ---------------------------- * Inserts a new entry into the table * table: the table to add to * key: key to add * value: corresponding value * */ bool insert(HashTable* table, const void* key, const void* value) { if(table == NULL) return false; if(key == NULL) return false; if(value == NULL) return false; Record* newNode = create_record(key, table->key_size, value, table->value_size); int i = find_empty_bucket(table, key); if( i != -1 ) { table->buckets[i] = newNode; return true; } else return false; } /* * function: search * ---------------------------- * Searches the table for a particular key and returns the corresponding value * table: the table to search * key: key to search for * * returns: the value or NULL if key is not in table */ void* search(const HashTable* table, const void* key) { if(table == NULL) return NULL; if(key == NULL) return NULL; int i = find_bucket(table, key); if(i == -1) return NULL; else return table->buckets[i]->value; } /* * function: replace * ---------------------------- * Replaces the value of the entry with a given key in the table * table: the table to add to * key: key to add * new_value: new value for key * */ bool replace(HashTable* table, const void* key, const void* new_value) { if(table == NULL) return false; if(key == NULL) return false; if(new_value == NULL) return false; int i = find_bucket(table, key); if(i == -1) return false; else { memcpy(table->buckets[i]->value, new_value, table->value_size); return true; } } /* * function: remove * ---------------------------- * Removes an entry from the table using lazy deletion * table: the table to remove the entry from * key: key of entry to remove * */ bool remove(HashTable* table, const void* key) { if(table == NULL) return false; if(key == NULL) return false; int i = find_bucket(table, key); if(i == -1) return false; else { delete_record(table->buckets[i]); table->buckets[i] = DELETED; return true; } } <file_sep><!DOCTYPE html> <html> <body> <?php echo "Jim's first PHP script!"; ?> </body> </html> <file_sep>#CS50X Week 4 Memory **hexadecimal** 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 0 to 16 in hexadecimal. sooo 20 is 32 30 is 48 RGB FF 00 00 255 red 0 green 0 blue- so lots of red 0x is hex prefix memory addresses are usually represented in hex & is address of operator. %p to print address with printf **pointer**- value of address of \* - go to address int *p = &n DIFFERENT CONTEXT OF \* . this just means this is a pointer to an int pointers will take 64 bit address space modern computers String is char * typedef char *string; used in CS50.h to create strings so instead of string a = "x"; can do char *s = "x"; s[0] and s[1] is really just (s) and (s+1) soo its just adding onto the address 1 sizeof(variable) char *t = malloc(how many bytes) strcpy((pointer string copying to), (string copying from)) opposite malloc **free** hand back memory allocated good practice to free when not using- could memory leak free(t); use address of memory location, pointer etc. when passing inputs to function, function getting copies of inputs loading into memory: program loaded, then global variables then the **heap** - space for malloc calls grows and shrinks as malloc 'd and free 'd **stack** - where local variables go when functions called program loaded into **stack frame** functions get slice above stack frame. so global variables are in one stack or section, the parameter and local variables are in another section when function done, loses memory allocation- main still intact after allocation use pointers to the variables to prevent the loss now function can move to global variables uses this for a simple swap function: function prototype: void swap(&x, &y); function declaration: void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } swaps a with b malloc to heap, functions run on stack **stack overflow** when function calls itself again and again and again **heap overflow** is opposite- too much memory allocation initialize to NULL for pointer if not assigning anything FILE *file = fopen("phonebook.csv", "a); fopen returns pointer to file fprintf() print to a file fprintf(file, "%s, %s", name, number); fclose(file) **CSV** comma separated values really easy to write a program that can write in comma separated data and use excel to see a spreadsheet of info ##Pointers different way to pass data between functions passing variable to function just uses a copy need pointers to modify data in functions- modifying variables in main is different **random access**- just means can access at any point does not have to be sequential **POINTERS ARE NOTHING MORE THAN AN ADDRESS** **dereferencing**- go to pointer to see value at the pointers address for pointer to char pc *pc is the value of the variable dereferencing a null pointer is a segmenation fault int* px, py, pz; will make a pointer called px, and ints py and pz. * is shared. so... int* px, *py, *pz; pointer to any data type is systems's byte width. 32 bit system, 32 bit pointer, 64 bit system, 64 bit address *pk = 35; changing what is at pk ##Dynamic Memory Allocation if do not know how much memory need at compile-time dynam ically allocated memory from heap stack and heap same pool- stack from "bottom to top" heap from "top to bottom" stack for statically allocated memory (variables and such) heap for dynamically allocated memory malloc() from stdlib.h allocates to heap. only argument is how many bytes you want return a pointer to that memory if cannot get memory it will return a null always check for null after malloc must dereference pointer to access contents static int x; dynamic int *px = malloc(sizeof(int)); float stack_array[x]; float* heap_array = malloc(x * sizeof(float)); free(pointer to malloc'd memory) ##Call Stack when call a function, sets aside memory for function to do work. called **stack frames or function frames** more than 1 functions stack frame may exist in memory at any time while multiple frames can be active, only 1 can run at any time frames are arranged in a **stack** frame for most recently called function is on top of the stack when new function called new frame **pushed** onto the stack and becomes active frame when function finishes work, its frame is **popped** off the stack and frame immediately below it becomes active frame. this function picks up where it left off ##File Pointers writing to and from files is means to storing persistent data abstraction of file that C provides is implemented in a data structure known as a FILE using pointer to that FILE\* all in stdio.h fopen() creates the pointer, other file i/o functions work with that pointer FILE* ptr = fopen(<filename>, <operation>); check for null fclose(<file pointer>); read next character in file char ch = fgetc(<file pointer>); pointer must be open for reading "r" will increment across the file- can use to print contents to screen how cat works char ch; while((ch = fgetc(ptr)) != EOF) printf("%c", ch); write or append specified character to file fputc(<character>, <file pointer>); fopen must specify "w" or "a" get any amount of information from file (instead of just 1 character0 fread(<buffer>, <size of chunk>, <qty of chunks>, <file pointer>); <buffer> really need pointer to memory writes from buffer units of size to file depending if FILE ptr is "w" or "a" fwrite(<buffer>, <size of chunk>, <qty of chunks>, ptr); fgets() and fputs() reading writing strings fprintf() write formatted string to file feof() whether read to end of file ferror() tells if error has occurred in working with the file fseek() point to part of file ftel() tells you what byte (position) are at in file <file_sep># Day 7 Fundamentals of Reading and Writing Information **printf()**- first argument is format string, second is name of variable to be printed- called with conversion specifiers %\<characer\> 3 components of format string: literal text. escape sequence (formatting). conversion specifier table of common conversion specifiers pg 149 conversion specifiers pg 153 arguments for conversion specifiers can be any valid C expression **puts()**- displays text online. automatically newlines after text string. puts more efficient on memory than printf() **scanf()**- reads conversion specifiers assigns to variables (using &) **trigraph sequences**- special sequence of characters that will be interpreted to mean someting else. see chart pg 163 <file_sep>#include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> int main(void) { //receive the string string input = get_string("Please input the text: "); int word = 0, letter = 0, sentence = 0; for(int i = 0; i < strlen(input); i++) { if( isalpha(input[i-1]) && (isblank(input[i]) || ispunct(input[i])) ) word++; else if( isalpha(input[i]) ) letter++; else if( ispunct(input[i-1]) || ispunct(input[i]) ) sentence++; //else //printf("Did not read %c", input[i]); // printf("%c, word: %d, letter: %d, sentence: %d\n", input[i], word, letter, sentence); }//end loop //set the variables to the correct condition for the algorithim word = word/100; letter = letter/word; sentence = sentence/word; //Apply the algorithim int index = 0.0588 * letter - 0.296 * sentence - 15.8; //Print the results if (index > 16) printf("Grade 16+\n"); else if (index < 1) printf("Before Grade 1\n"); else printf("Grade %d\n", index); }//end main <file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Assign03 - Advanced Web Development</h2> <h2>Research</h2> <p>I have not used Google's Advanced Search features in almost 10 years as Google has improved to the point that you can almost narrow your search by entering more data into the actual search bar. I find that for 90% of the things I am looking for I can just add more to the search bar and get closer to what I need. I think those advanced search tools are great for filtering by time. Sometimes I find myself looking for something less on the beaten path and I keep running into articles from 3 or more years ago. Since this is Software, that makes most of the information irrelevant. You have to keep modifying the search to get something closer in time. But maybe the advanced search tools would be better.</p> <p>Note: I have redone the whole site as before I had simply copy/pasted the example site. The new content is "nested" from the old but of my own work.</p> <p>Which is why that bar is messed up - I plan to fix that soon!</p> <p>Link 1: <a href="https://support.google.com/websearch/answer/35890?co=GENIE.Platform%3DAndroid&hl=en" target="_blank"> Advanced Search</a></p> <!-- <p>Link 2: <a href="" target="_blank"> link</a></p> <p>Link 3: <a href="https://www.vim.org/" target="_blank"> link</a></p> --> <h2>Before & After CODE</h2> <p> Example 1 <ul> <li> Before: <a href="https://www.w3schools.com/php/phptryit.asp?filename=tryphp_if" target="_blank"> Before</a></li> </ul></p> <p> Example 2 <ul> <li> Before: <a href="https://www.w3schools.com/php/phptryit.asp?filename=tryphp_loop_foreach" target="_blank"> Before</a></li> </ul></p> <p> Example 3 <ul> <li> Before: <a href="https://www.w3schools.com/php/phptryit.asp?filename=tryphp_loop_while" target="_blank"> Before</a></li> </ul></p> <p>Overall After <ul> <li> After: <a href="assign03/array-loops-after.php" target="_blank"> After</a></li> <blockquote> //Not trying to show off here but since my background //is more in strict programming, I thought I would //write a small PHP program to demonstrate arrays, loops //and if/else statements. I also found the foreach loop //to be particularly intriguing and wanted to try exercising it function loopdeloop() { $i = 20; while($i > 0) { $array1 = range(0,$i); foreach($array1 as $value) { $value *= 2; echo $value, ", "; } $i--; echo "<br>"; } } loopdeloop(); return 0; </blockquote> </ul></p> </div> <?php include 'footer.php';?> </body> </html> <file_sep># Ch.6 Limited Direct Execution challenges to time sharing: - performance - control - namely return control of cpu from process to OS ## 6.1 Limited Direct Execution run directly on CPU but limit direct execution protocol w/o limits: OS Program -------------------------------------------------------------- - create entry for process list - allocate memory for program - load program into memory - set up stack with argc/argv - clear registers - execute by jumping to main() - run main() - execute return from main - free memory of process - remove from process list ## 6.2 Problem 1 Restricted Operations sys calls look like C procedure calls - is a procedure call BUT has a trap instruction in it uses agreed upon calling convention with the kernel to put arguments in well known locations (on the stack or CPU registers) ... which is a system-call number and uses that to execute trap instruction trap will return values to calling program - system-calls usually hand-coded in assembly in order to unpack values correctly using trap handlers for allocating resources allows for user modes system calls are layer of security for kernel - that way user programs can still execute privileged operations on resources without compromising kernel user mode and kernel mode hardware keeps the following: instructions to trap into the kernel, return from trap, where trap table resides in memory **trap table** - is built at boot time and keeps record of the instructions for each trap handler (in hardware) system-call numbers are assigned to each system call. the OS, when handling the system call inside the trap handler, examines the number and ensures it is valid soo user code cannot request a specific address to jump to but must request a system call by type - more protection limited direct execution protocol is on pg 53 a secure system must treat user input with great suspicion ## 6.3 Problem 2 Switching between processes if a process is running on the CPU, that means the OS is NOT running **cooperative approach**: OS trusts processes to behave most processes transfer control back to OS by making sys calls cooperative systems usually include a **yield** call to transfer control back applications also transfer control to the OS when they do something illegal - triggers a trap OS usually terminates that process non-cooperative approach brought about by a **timer interrupt** every few milliseconds triggers an interrupt handler that gives the OS control over the CPU again for cooperative systems, best way regain control from infinite process is a reboot during timer interrupt handling, hardware must save current state of program such that a return from trap instruction will be able to resume it enables the **scheduler** to make a decision, which if it does is known as a **context switch** in some way (push to stack, save state in registers) saves current context of current process and SWITCHES into the context of another usually pushes and pulls from the kernel stack **to go from process A to B A's registers pushed onto kernel stack, moves k-stack pointer to use B's kernel stack, return-from-trap by restoring B's registers and then run** while handling the timer interrupt handler the switch() routine will save registers in the proc-struct as well so if there is a switch because of handling a trap from a timer interrupt registers are save in hardware (on k-stack) and software proc-struct see pg. 59 if another timer interrupt happens while in the middle of handling another interrupt.... topic for **concurrency** section **limited direct execution == baby proofing** when int is being processed saves registers to kernel stack. only when performing context switch does it save registers in the software struct of the currently executing process **WHEN USE USER STACK VS KERNEL STACK** kernel stack is used for processing a syscall (to include a timer interrupt) user stack is used when processor in user mode (so on norm until syscall is made) <file_sep> def partition(array, low, high): pi = array[high] i = low - 1 for x in range(low, high): if(array[x] < pi): i += 1 k = array[i] array[i] = array[x] array[x] = k z = array[i+1] array[i+1] = array[high] array[high] = z return i+1 def quicksort(array, low, high): if low < high: p = partition(array, low, high) #lower quicksort(array, low, p-1) #upper quicksort(array, p+1, high) return array test = [4,7,2,1,10,32,1,1,29,74,23,24,67] print(quicksort(test, 0, len(test)-1)) <file_sep>#Day3 Storing Information 2 ways to store values- variables and constants **variable**- data storage location that has a value and can be changed during program execution **constant**- fixed value that can't change ##Variables Variable names: + a-z, A-Z, 0-9, _ + 1st character must be a letter + C is canse sensitive + C keywords cannot be used as variables commonly use lowercase characters in variable names camel notation- InterestRate as opposed to snake notation interest_rate **Numeric Variables**- 2 categories: 1. integer 2. float- more storage space int and short varaibles may be different certain hardware **variable declaration**- *typename varname*; can declare multiple variables of same type on same line ex: int count, number, start; **typedef**- changes typename not varname should always initialize a variable to a known value = not same in programming- x = 12 really means 12 is assigned to x be careful to not initialize a variable outside the allowed range compiler/linker may not catch it! ##Constants ###literal constants value that is typed directly into source code literal constant with a decimal is a floating point constant and is represented by C compiler as a double-precision number floating point constants can also be written in scientific notation + 1.23E2 1.23 times 10 to the 2nd power + 0.85e-4 0.85 times 10 to the -4th power or 0.000085 **integer constants can be written in 3 notations:** 1. constant starting with any digit other than 0 is interpreted as a decimal integer 2. constant starting with digit 0 is interpreted as an octal integer 3. constant starting with 0x or 0X is hexidecimal ###symbolic constants **constant represented by a name (symbol) in program** Ex: const circumfrence = PI * (2 * radius); (PI and radius initialized elsewhere) 2 ways to define: 1. #define 2. const **\#define**- does not need ; at end. can be placed anywhere. only usable "below" where they are written **const**- cannot be modified. ex: const long debt = 120000, float tax_rate = 0.21; **&to call variable in program** **5 rules for allocating size to varaibles:** 1. the size of a char is one byte 2. the size of a short is <= size of int 3. size of int <= size of long 4. size of unsigned = size of int 5. size of float <= size of double <file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> #include <math.h> #include "quicksort.h" #define SIZE 1000 #define FACTOR 2 #define TRIALS 10 int main() { bool quit = true; while(quit) { char c = 'q'; printf("Perform quicksort starting on array of %d, increasing the array size by a factor of %d, 5 times with %d trials for each size Yes/Quit\n", SIZE, FACTOR, TRIALS); scanf(" %c", &c); if(c == 'y' || c == 'Y') quit = false; else if( c == 'q' || c == 'Q'){ quit = false; exit(0); } else quit = true; } FILE *fp = fopen("results.txt", "w"); if(fp == NULL) { printf("Unable to open a file"); exit(1); } //set a new variable so we can modify file size during execution int testSize = SIZE; for(int i = 0; i < 5; i++) { //generate the random array int* sortArray = genArray(testSize); //run TRIALS number of trials for (int a = 0; a < TRIALS; a++) { clock_t start, end = 0; start = clock(); //it begins quicksort(sortArray, 0, testSize - 1); /*for testing - print for(int i = 0; i < testSize; i++) { printf("%d\n", sortArray[i]); }*/ end = clock(); //take the time of execution double daTime = timer(start, end); //send to the file the iteration number, the size of the array, and the time the sort took fprintf(fp, "%d,%d,%f\n", a, testSize, daTime); }//end for //free the current array before increasing the size free(sortArray); //increase array size for next testing iteration testSize *= FACTOR; } fclose(fp); return 0; }//end main int* genArray(int testSize) { int *a = (int*) malloc(testSize*sizeof(int)); srand(time(0)); for(int i = 0; i < testSize; i++) { a[i] = big_rand() % 20; // printf("%d\n", a[i]); } return a; }//end genArray double timer(clock_t begin, clock_t end) { double daTime = ((double) (end - begin)) / CLOCKS_PER_SEC; return daTime; }//end timer void quicksort(int* sortArray, int innerBound, int outerBound){ if(innerBound < outerBound) { int p = partition(sortArray, innerBound, outerBound); quicksort(sortArray, innerBound, p - 1 ); quicksort(sortArray, p + 1, outerBound); } }//end quicksort int partition(int* sortArray, int innerBound, int outerBound){ int pivot = sortArray[outerBound]; int i = innerBound - 1; for(int j = innerBound; j <= outerBound-1; j++) { if(sortArray[j] < pivot) { i++; int tmp = sortArray[j]; sortArray[j] = sortArray[i]; sortArray[i] = tmp; } } int tmp = sortArray[i+1]; sortArray[i+1] = sortArray[outerBound]; sortArray[outerBound] = tmp; return i + 1; }//end partition int big_rand() { return rand() * (rand() + 1) + rand(); } <file_sep> <?php include 'header.php';?> <?php include 'nav.php';?> <div style="padding-left:16px"> <h2>Welcome to <NAME>'s Advanced Web Development 2 Site</h2> <h3>Find my assignments here or feel free to use the snazzy A+ navigation bar</h3> <ul> <li><a href="assign01.php">Week 1</a></li> <li><a href="assign02.php">Week 2</a></li> <li><a href="assign03.php">Week 3</a></li> <li><a href="assign04.php">Week 4</a></li> <li><a href="assign05.php">Week 5</a></li> <li><a href="assign06.php">Week 6</a></li> <li><a href="assign07.php">Week 7</a></li> <li><a href="assign08.php">Week 8</a></li> <li><a href="assign09.php">Week 9</a></li> <li><a href="assign10.php">Week 10</a></li> <li><a href="assign11.php">Week 11</a></li> <li><a href="assign12.php">Week 12</a></li> <!-- <li><a href="assign13.php">Week 13</a></li> <li><a href="assign14.php">Week 14</a></li> <li><a href="assign15.php">Week 15</a></li> --> </ul> <img src="boilerplate2.jpg"> <?php include 'footer.php';?> </div> </body> </html> <file_sep>""" this solution timed out def checkMagazine(magazine, note): for word in note: if word in magazine: magazine.remove(word) continue else: print("No") return print("Yes") """ def checkMagazine(magazine, note): mag_dict = {} for word in magazine: if word in mag_dict: mag_dict[word] += 1 else: mag_dict[word] = 1 for word in note: try: if mag_dict[word] >= 1: mag_dict[word] -= 1 else: print("No") return except KeyError: print("No") return print("Yes") magazine = ["two", "times", "three", "not", "four", "two", "two", "two"] note = ["two", "times", "two", "is", "four"] checkMagazine(magazine, note) <file_sep>#include <time.h> #include <unistd.h> #include <stdio.h> #define RUNS 5 double timer(clock_t, clock_t); int main(int argc, char *argv[]) { double avg_time = 0; for(int i = 0; i < RUNS; i++){ clock_t start = clock(); FILE *test = fopen("test_file", "w"); clock_t end = clock(); avg_time += timer(start, end); fclose(test); } avg_time /= RUNS; printf("Sys-call average: %f\n", avg_time); return 0; } double timer(clock_t start, clock_t end){ return ((double) (end - start)) / CLOCKS_PER_SEC; } <file_sep>def commonChild(s1, s2): comChild = "" for i in range(len(s1)-1): j = 0 l = len(s2) - 1 while((s1[i] != s2[j]) and (j < l)): j += 1 if s1[i] == s2[j]: comChild += s1[i] s2 = s2[j:] j = 0 return len(comChild) a = "HARRY" b = "SALLY" print(commonChild(a,b)) <file_sep> FLAG = -o DFLAG = -g -o CC = gcc mergesort: main.c mergesort.h ${CC} ${FLAG} mergesort main.c mergesort.h debug: main.c mergesort.h ${CC} ${DFLAG} debug main.c mergesort.h clean: rm -f mergesort debug *.txt *.gdb core <file_sep>#include <stdio.h> #include <stdlib.h> #define MAX 1000 void main (void) { char ch; char words[MAX]; int i = 2; printf("1 : "); do { if ( ch == '\n' ) { printf("%d : ", i); i++; } ch = fgetc(stdin); if( ch == EOF ) break; printf("%c", ch); }while (1); } <file_sep>#! /usr/bin/python3 from matplotlib import pyplot import sys import re trial_num = re.compile(r"(\d+),\d.\d+") time = re.compile(r"\d+,(\d.\d+)") trials = [] times = [] # import comma separated list try: inputFile = sys.argv[1] except IndexError: sys.exit(1) except FileNotFoundError: sys.exit(1) readFile = open(inputFile, "r") for line in readFile: trials.append(trial_num.findall(line)[0]) times.append(time.findall(line)[0]) # Plot pyplot.scatter(trials, times) pyplot.show() <file_sep>#include <stdio.h> int main(void) { int* uh_oh = NULL; printf("%d\n", *uh_oh); return 0; } <file_sep>from statistics import median def activityNotifications(expenditure, d): notice = 0 lower = 0 higher = d while higher <= len(expenditure): trail = expenditure[lower:higher-1] today = array[higher] med = 2 * (median(trail)) if today >= med: notice += 1 lower += 1 higher += 1 return notice <file_sep> FLAG = -o DFLAG = -g -o CC = gcc quicksort: main.c quicksort.h ${CC} ${FLAG} quicksort main.c quicksort.h debug: main.c quicksort.h ${CC} ${DFLAG} debug main.c quicksort.h clean: rm quicksort debug *.txt *.gdb core <file_sep>package ch6hw; public class MaxIntSet extends IntSet { private int max = 0; public MaxIntSet() { super(); } @Override public void add(int x) { // If set already contains this number than we do nothing if (this.contains(x)) { return; } // If values is full, double its size if (size == values.length) { int[] oldValues = values; values = new int[2 * size]; for (int i = 0; i < size; i++) { values[i] = oldValues[i]; } } // If larger than anything currently in the set, update max if(x > max) this.max = x; // Add new element values[size] = x; size++; repOK(); } public int getMax() { return this.max; } } <file_sep><?php // this is actually a .html file because it doesn't have any php in it // but for consistancy - because the calling file is a .php file // we usually name all the files .php in case you want to put php code in_array // it won't break any of the links. // ?> <script> function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; } } </script> <div class="topnav" id="myTopnav"> <a href="index.php" class="active">AdvWD</a> <div class="dropdown"> <button class="dropbtn">Assignments <i class="fa fa-caret-down"></i> </button> <div class="dropdown-content"> <a href="assign01.php">Assign01</a> <a href="assign02.php">Assign02</a> <a href="assign03.php">Assign03</a> <a href="assign04.php">Assign04</a> <a href="assign05.php">Assign05</a> <a href="assign06.php">Assign06</a> <a href="assign07.php">Assign07</a> <a href="assign08.php">Assign08</a> <a href="assign09.php">Assign09</a> <a href="assign10.php">Assign10</a> <a href="assign11.php">Assign12</a> <a href="assign12.php">Assign13</a> <a href="assign13.php">Assign14</a> <a href="ProjectOutline.php">Project Outline</a> <a href="Project.php">Final Project</a> </div> </div> <a href="links.php">Links</a> <a href="more.php">More</a> <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">&#9776;</a> </div> <file_sep>import sys import csv """ graph.py Implementation of a simple graph.... in Phierece-thon """ class Node: """ Inputs: String name, List<links> links Returns: Node """ def __init__(self, name, argv): self.name = name self.links = [] for arg in argv: self.links.append(arg) def print_node(self): print(self.name) for l in self.links: print(f"{l.noode}-{l.cost}") class Link: """ Inputs: Int cost, String noode (just the name of the node) Returns: Link """ def __init__(self, noode, cost): self.noode = noode self.cost = int(cost) class graph: """ Inputs: Node root Returns: graph """ def __init__(self, root): self.root = root self.nodes = {} self.nodes[root.name] = root def addNode(self, node): self.nodes[node.name] = node def print_graph(self): self.root.print_node() print("") for x in self.nodes: self.nodes[x].print_node() print("") def build_links(row): links = [] for x in row[::2]: links.append(Link(x, row[row.index(x)+1])) return links """ graph-file schema: Node name,Neighbor1,neighbor1 cost,neighbor2.... """ def read_graph(graph_file): node_num = 0 read_csv = csv.reader(graph_file, delimiter=',') for row in read_csv: if node_num == 0: root = Node(row[0], (build_links(row[1:]))) new_graph = graph(root) else: newNode = Node(row[0], (build_links(row[1:]))) new_graph.addNode(newNode) node_num += 1 print("Graph imported of " + str(node_num) + " nodes") return new_graph def bfs(graph, dest_node): queue = [] visited = [] # cost = 0 queue.insert(0, graph.root) visited.append(graph.root) while len(queue) != 0: check_node = queue[len(queue)-1] queue.remove(check_node) print(f"{check_node.name} ->", end=" ") for link in check_node.links: link_node = graph.nodes[link.noode] if link_node.name == dest_node: print(f"[[{dest_node}]]") continue """ print(f"Cost: {cost}", end=" ") for node in visited: print(f"{node.name} ->", end=" ") cost = 0 print(f"{link_node.name}") continue """ if link_node not in visited: visited.append(link_node) queue.insert(0, link_node) print("") """ Depth-first-search Inputs- graph graph - the graph to search. String dest_node - node to search for Returns- String the path to get to the dest_node, and Int the cumulative cost """ def dfs(graph, dest_node): stack = [] visited = [] # cost = 0 stack.append(graph.root) visited.append(graph.root) while len(stack) != 0: check_node = stack.pop() print(f"{check_node.name} ->", end=" ") for link in check_node.links: link_node = graph.nodes[link.noode] if link_node.name == dest_node: print(f"[[{dest_node}]]") continue """ print(f"Cost: {cost}", end=" ") for node in visited: print(f"{node.name} ->", end=" ") cost = 0 print(f"{link_node.name}") continue """ if link_node not in visited: visited.append(link_node) stack.append(link_node) #cost += link.cost print("") def main(): if len(sys.argv) < 2: print("Gimme something jackass") return graph_file = open(sys.argv[1], "r") the_graph = read_graph(graph_file) the_graph.print_graph() opt = 0 while(opt != 5): opt = int(input("Options:\n1 - add vertice\n2 - BFS\n3 - DFS\n4 - print graph\n5 - quit\n")) if opt == 1: vertice = input("Vertice name: ") links = input("In format node1,weight1,node2,weight2\nLinks: ") links = list(links.split(',')) the_graph.addNode(Node(vertice, (build_links(links)))) elif opt == 2: node_name = input("Node to traverse to:\n") bfs(the_graph, node_name) elif opt == 3: node_name = input("Node to traverse to:\n") dfs(the_graph, node_name) elif opt == 4: the_graph.print_graph() elif opt == 5: sys.exit(0) else: print("1-5 dummy") opt = 0 main() <file_sep># Day 9 Understanding Pointers **pointer**- variable that stores the address of another variable 1. declare a pointer: typename \*ptrname; typename is type of variable pointing to ex: float \*value, percent; pointer nested with variable 2. once declared must point pointer at variable: pointer = &variable & means address of 2 ways to refer to variable that has pointer- 1. rate 2. \*p_rate accessing by using pointer is indirect access or **indirection** \*ptr and var refer to contents of var ptr and &var refer to the address of var each byte of memory has its own address so a multibyte variable occupies several addresses address of variable actually address of lowest byte- variable type tells compiler how many bytes it will occupy ## pointers and arrays array subscripts are really just pointers **array name without brackets is really just pointer to address of first element** array == &data[0] CAN declare pointer and initialize to point at array: int array[100], \*p_array; p_array = array; array elements stored at addresses incremented according to variable type size- access successive elements of array by by sizeof(datatype) ###incrementing pointers when increment pointer by one, automatically increases the pointers value so that it points to the next array element ptr++ to increment ptr +=4 points to 4 array elements ahead decrementing pointer is special case where increment by adding negative number point to first element in array then increment across cannot perform incrementing and decrementing operations on pointer constants (array name w/o brackets is pointer constant) if not careful can increment or decrement beyond array- very dangerous can overwrite other parts of memory (OS? program?) ###pointer ops 1. **assignment**- assign value to a pointer 2. **indirection**- use * operator to get value stored at location 3. **address of**- use & to get address of a pointer. could have pointers to pointers 4. **incrementing**- add integer to pointer in order to point to different memory location 5. **decrementing**- subtract an integer from a pointer to point at different memory location 6. **comparison**- valid with only 2 pointers pointing at same array. ptr1 < ptr2 is true if pointing to lower memory location- can use as a condition must initialize otherwise who the hell knows where it is pointing \*ptr = 12 value 12 assigned to wherever ptr pointed at \*array is array's first element. \*(array + 1) is second element ### passing arrays to functions only way can pass an array to a function is by using a pointer if pass that value to a function function knows the address of the array and can access the array elements using pointer notation can identify last element of array by storing a special value there. OR pass the function the array size as an argument <file_sep>#include "tree_tests.h" /* * Function: test_with_strings * ---------------------------- * runs a test where the expected output is a char* * */ void test_with_strings(const char* test_name, const char* result, const char* expected) { printf("Test: %s... ", test_name); if (strcmp(result, expected) == 0) { printf("passed\n"); } else { printf("FAILED. Expected %s (result %s)\n", expected, result); } } /* * Function: test_false * ---------------------------- * runs a test where the expected output is false * */ void test_false(const char* test_name, bool result) { printf("Test: %s... ", test_name); if (!result) { printf("passed\n"); } else { printf("FAILED.\n"); } } /* * Function: test_false * ---------------------------- * runs a test where the expected output is true * */ void test_true(const char* test_name, bool result) { printf("Test: %s... ", test_name); if (result) { printf("passed\n"); } else { printf("FAILED."); } } /* * Function: compare_ints * ---------------------------- * Compares the data stored at pointers a and b, assuming both addresses store * integers * * a, b: void pointers to integers * * returns: ans < 0 if a < b, ans > 0 if a > b, ans = 0 if a == b * */ int compare_ints(const void* a, const void* b) { return *((int*) a) - *((int*) b); } /* * Function: int_formatter * ---------------------------- * returns a char* representation of the integer stored at a given address * * data: points to an integer * */ char* int_formatter(const void* data) { char* buffer = (char*) malloc(12 * sizeof(char)); sprintf(buffer, "%d", *((int*) data)); return buffer; } Tree* build_small_tree() { int a[] = {8, 5, 12, 3, 7, 18}; Tree* tree = create_tree(sizeof(int), compare_ints, int_formatter); for (int i = 0; i < 6; i++) { tree_insert(tree, &a[i]); } return tree; } Tree* build_bigger_tree() { int a[] = {9, 2, 12, -8, 10, 18, -5, 14, 25, -6, 1}; Tree* tree = create_tree(sizeof(int), compare_ints, int_formatter); for (int i = 0; i < 11; i++) { tree_insert(tree, &a[i]); } return tree; } void add_to_null_fails() { int k = 42; test_false("Can't add to null tree", tree_insert(NULL, &k)); } void add_null_key_fails() { Tree* tree = create_tree(sizeof(int), compare_ints, int_formatter); test_false("Can't add null key", tree_insert(tree, NULL)); } void add_to_empty_tree_works(){ Tree* tree = create_tree(sizeof(int), compare_ints, int_formatter); int x = 42; tree_insert(tree, &x); test_with_strings("Add to empty tree", tree_as_string(tree), "Tree: 42"); } void add_left_works(){ Tree* tree = build_small_tree(); int x = 10; tree_insert(tree, &x); test_with_strings("Add as left child", tree_as_string(tree), "Tree: 3 5 7 8 10 12 18"); } void add_right_works(){ Tree* tree = build_small_tree(); int x = 4; tree_insert(tree, &x); test_with_strings("Add as right child", tree_as_string(tree), "Tree: 3 4 5 7 8 12 18"); } void search_null_fails(){ int k = 42; test_false("Can't search null tree", search(NULL, &k)); } void search_for_null_key_fails(){ Tree* tree = build_small_tree(); test_false("Can't find null key", search(tree, NULL)); } void failed_search_fails(){ Tree* tree = build_small_tree(); int k = 42; test_false("Testing failed search", search(tree, &k)); } void normal_search_works(){ Tree* tree = build_small_tree(); int k = 7; test_true("Testing successful search", search(tree, &k)); } void remove_from_null_fails(){ int k = 42; test_false("Remove from null fails", tree_delete(NULL, &k)); } void remove_null_key_fails(){ Tree* tree = build_small_tree(); test_false("Remove null key fails", tree_delete(tree, NULL)); } void remove_from_empty_fails(){ Tree* tree = create_tree(sizeof(int), compare_ints, int_formatter); int k = 42; test_false("Remove from empty tree fails", tree_delete(tree, &k)); } void remove_missing_key_fails(){ Tree* tree = build_small_tree(); int k = 42; test_false("Remove missing key fails", tree_delete(tree, &k)); } void remove_node_with_no_kids() { Tree* tree = build_bigger_tree(); int k = 10; tree_delete(tree, &k); test_with_strings("Remove childless node", tree_as_string(tree), "Tree: -8 -6 -5 1 2 9 12 14 18 25"); } void remove_node_with_right_child() { Tree* tree = build_bigger_tree(); int k = -8; tree_delete(tree, &k); test_with_strings("Remove node with right child only", tree_as_string(tree), "Tree: -6 -5 1 2 9 10 12 14 18 25"); } void remove_node_with_left_child() { Tree* tree = build_bigger_tree(); int k = 2; tree_delete(tree, &k); test_with_strings("Remove node with left child only", tree_as_string(tree), "Tree: -8 -6 -5 1 9 10 12 14 18 25"); } void remove_node_with_two_kids() { Tree* tree = build_bigger_tree(); int k = 12; tree_delete(tree, &k); test_with_strings("Remove node with two kids", tree_as_string(tree), "Tree: -8 -6 -5 1 2 9 10 14 18 25"); } void remove_root_works() { Tree* tree = build_bigger_tree(); int k = 9; tree_delete(tree, &k); test_with_strings("Remove root", tree_as_string(tree), "Tree: -8 -6 -5 1 2 10 12 14 18 25"); } void add_tests() { add_to_null_fails(); add_null_key_fails(); add_to_empty_tree_works(); add_left_works(); add_right_works(); } void search_tests() { search_null_fails(); search_for_null_key_fails(); failed_search_fails(); normal_search_works(); } void delete_tests() { remove_from_null_fails(); remove_null_key_fails(); remove_from_empty_fails(); remove_missing_key_fails(); remove_node_with_no_kids(); remove_node_with_left_child(); remove_node_with_right_child(); remove_node_with_two_kids(); remove_root_works(); } <file_sep>hashtable: main.cpp open_address_table.cpp open_address_table.h record.cpp record.h table_tests.cpp table_tests.h g++ -g -o hashtable main.cpp open_address_table.cpp open_address_table.h record.cpp record.h table_tests.cpp table_tests.h clean: rm -rf hashtable debug core <file_sep>#CS50 Week 7 SQL def f(item): return item[1] for title, count in sorted(counts.items(), key=f, reverse=True): print(title, count, sep = " | ") .items() returns key and value will print the key with value right next to it each on own line, sorted by the value of the counts f(item) is returning the second part of the counts.items() so in this case the value of the key can also use **lambda**: ... , key=lambda item: item[1], lambda give me a function (never going to use again) "item" input to this function : item[1] return value limited to 1 line **sqlite3** can create new database or open existing at CLI -> sqlite3 favorites.db .mode csv .import "file" .schema select title, count(title) from favorites group by favorites limit 10 - limits to first 10 **relational database** - store data and provide fast access with SQl sqlite3 is a CLI program Create Read Update Delete ** Most frequently used: insert select update delete **Create** create table "table" (column type, ....); SQL 5 main data types integer- smallint, integer, bigint real(decimal) - real, double precision numeric - boolean, date, datetime, numeric(can specify decimal places), time, timestamp text - char(number), varchar(upper and lower bound number), text blob - binary large object - store binary data represent files in binary format functions: avg count distinct max min where at end of query like limit group by order by join select title from favories where title like "%the office%"; % is wildcard to get count of that: select count(title) from .... update favories set title = "The Office" where title like "%office%" delete from table where condition; to delete table drop 'table' **import.py** - importing .tsv file into a sqlite db open("shows3.db", "w").close() #like touching a file db = cs50.SQL("sqlite:///shows3.db") db.execute("create table shows (tconst text, primarytitle text, startyear, genres") #db.execute allows you to execute sql in open db file db = cs50.SQL("sqlite:///shows3.db") with open("titles.basics.tsv", "r") as titles: reader = csv.DictReader(titles, delimiter="\t") for row in reader: if row["titleType"] == "tvSeries" and row ["isAdult"] == "0": blahblah db.execute("insert into shows (tconst, primarytitle, startyear, genres) values(?,?,?,?)", tconst, primarytitle, startyear, genres) **Joins** separate table unique id based on table it came from **join** - select * from shows join genres on shows.id = genres.show_id where... subquery select * from stars where person_id = (select id from people where name = "<NAME>") select title from people join on people.id = stars.person_id join shows on stars.show_id = shows.id where name = "<NAME>" primary key foreign key unique index create index show_index on stars(show_id); indexes are tree like structures for faster searching ##Shorts - SQL char - fixed length string varchar - variable length string up to the specified amount SQLITE groups all the data types into 5 affinities (has all but these are most common) -null -integer -real -text -blob -insert -select -update -delete insert into 'table' ('columns','columns') values ('value1','value2') primary key: auto-increment update 'table' set 'column' = 'value' where 'predicate' delete from 'table' where 'predicate' <file_sep><?php //Not trying to show off here but since my background //is more in strict programming, I thought I would //write a small PHP program to demonstrate arrays, loops //and if/else statements. I also found the foreach loop //to be particularly intriguing and wanted to try exercising it function loopdeloop() { $i = 20; while($i > 0) { $array1 = range(0,$i); foreach($array1 as $value) { $value *= 2; if ($value % 3 == 0) { echo "cat, "; continue; } else { echo $value, ", "; } } $i--; echo "<br>"; } } loopdeloop(); return 0; ?> <file_sep>#include <stdio.h> #define max 10 int inputs[max]; int a,b,tmp; int main () { //Receive Input int a = 0; for (a = 0; a < max; a++) { printf("\nInput number: %d\n", a); scanf("%d", &inputs[a]); } //Apply Sort for ( a=0; a < max; ++a) { for (b = a+1; b < max; ++b) { if (inputs[a] > inputs[b]) { tmp = inputs[a]; inputs[a] = inputs[b]; inputs[b] = tmp; } } } //Print Sorted List for ( a=0; a < max; a++ ) { printf("%d\n", inputs[a]); } return 0; } <file_sep>#include <stdio.h> void main () { int x = 0, y = 0; char array[4][4]; for(x=0;x<5;x++) for(y=0;y<5;y++) array[x][y] = 0; for(x=0;x<5;x++) { printf("\n"); for(y=0;y<5;y++) { if((y%2)) array[x][y] = 'X'; else array[x][y] = '_'; printf("%s", &array[x][y]); } } } <file_sep># how-i-learned This repository showcases some of the work I completed while I was self-taught, and also as a student at Vermont Technical College. ## Summary of this repository: ### Self-Taught Work C-21 - "Teach Yourself C in 21 Days" Well it was more like 24 but at least I taught myself. CS50 - I completed the lectures and labs of the free online series from Harvard but timed out on completing the projects: I had to focus on my actual classes instead. Hackerrank-practice - some of my hackerrank solutions from coding interview training OS3 - Operating Systems : 3 easy pieces code, notes ### VTC Advanced Software Development Certificate and More Java - My first formal programming course. I knew so little just 1 year ago. Algorithms - Algorithms and Data Structures. This course was in C and I did a little bit of C++ at the end. I only included the notable programs. OOP - Object Oriented Programming taught in..... Java WebDev - Web Development 2 - [Website](https://jmd06260.classweb.ccv.edu/AdvWeb/index.php) ProgrammingLanguages - mostly an intro to functional programming with Haskell <file_sep>package ch6hw; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; /** * Represents a first-in first-out (FIFO) queue of integers * @author jeremy * */ public class IntegerQueue implements Collection<Integer> { /** Initial size of queue. */ private final static int INITIAL_SIZE = 8; /** Elements of queue - never null, never empty. */ private Integer[] elements; /** Number of elements in queue and index where next enqueued value should be placed. */ private int size; private void repOK() { assert (elements != null) : "elements cannot be null"; assert (elements.length > 0) : "elements cannot be empty"; assert (size >= 0) : "size (" + size + ") must be >= 0"; assert (size <= elements.length) : "size (" + size + ") must be <= elements.length (" + elements.length + ")"; } /** * Creates an empty queue. */ public IntegerQueue() { clear(); } /** * Adds an element to the end of the queue * @param x * @return {@code true} if the queue was changed by this operation */ public boolean enqueue(Integer x) { if (size == elements.length) { resize(); } elements[size] = x; size++; repOK(); return true; } /** * Resizes the queue so it can hold more elements */ private void resize() { Integer[] old = elements; elements = new Integer[2 * elements.length]; for (int i = 0; i < old.length; i++) { elements[i] = old[i]; } repOK(); } /** * Removes and returns the element from the front of the queue. * * @return the element from the front of the queue. * @throws NoSuchElementException if the queue is empty. */ public Integer dequeue() throws NoSuchElementException { if (size == 0) { throw new NoSuchElementException(); } // Get value at front Integer value = elements[0]; // Mark as empty - necessary for the case where the queue has only one element elements[0] = null; // Shift all elements back for (int i = 1; i < size; i++) { elements[i - 1] = elements[i]; } size--; repOK(); return value; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append('['); for (int i = 0; i < size; i++) { builder.append(elements[i]); if (i < size - 1) { builder.append(", "); } } builder.append(']'); return builder.toString(); } @Override public boolean add(Integer i) { return enqueue(i); } @Override public boolean addAll(Collection<? extends Integer> c) { boolean changed = false; for(Integer i : c) { boolean thisOneAdded = this.add(i); changed = changed || thisOneAdded; } return changed; } @Override public void clear() { elements = new Integer[INITIAL_SIZE]; size = 0; repOK(); } @Override public boolean contains(Object o) { for (Integer i : this) { if (o.equals(i)) { return true; } } return false; } @Override public boolean containsAll(Collection<?> c) { // For every element of c ask if this collection contains that element // If not - then return false // If so - keep checking // If we get all the way through then return true for (Object o : c) { if (!this.contains(o)) { return false; } } return true; } @Override public boolean isEmpty() { return (size == 0); } @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { /** Index of next element to return */ private int next = 0; @Override public boolean hasNext() { return (next < size); } @Override public Integer next() { if (next >= size) { throw new NoSuchElementException(); } return elements[next++]; } }; } /* * If multiple instances of this exist in queue * then the instance closest to the front of the queue * will be removed */ @Override public boolean remove(Object o) { for (int i = 0; i < size; i++) { if (o.equals(elements[i])){ for(int j = i; j < size -1; j++) { elements[j] = elements[j+1]; } size--; repOK(); return true; } } return false; } @Override public boolean removeAll(Collection<?> c) { boolean changed = false; for(Object o : c) { while(this.contains(o)) changed = this.remove(o) || changed; } return changed; } @Override public boolean retainAll(Collection<?> c) { IntegerQueue toRemove = new IntegerQueue(); for(Integer i : this) { if (c.contains(i)) { toRemove.add(i); } } return this.removeAll(toRemove); } @Override public int size() { return size; } @Override public Object[] toArray() { Object[] a = new Object[size]; for(int i = 0; i < size; i++) a[i] = elements[i]; return a; } @Override public <T> T[] toArray(T[] arg0) { // TODO Auto-generated method stub return null; } }<file_sep>def anagram_builder(l, s): new_anagram = "" for w in s: if w in l: new_anagram += w l = l.replace(w, '', 1) return new_anagram def len_check(anagram, l, s): return (len(l) - len(anagram)) + (len(s) - len(anagram)) def makeAnagram(a, b): if len(a) <= len(b): return(len_check(anagram_builder(b,a), b, a)) else: return(len_check(anagram_builder(a,b), a, b)) a = "<KEY>" b = "<KEY>" print(makeAnagram(a, b)) <file_sep># include <stdio.h> int x, y; int array[10]; int array2[10]; int main (void) { for ( x = 0 ; x < 10 ; x++ ) { array[x] = x; printf("array 1 %d: %d\n", x, array[x]); array2[x] = (array[x] +10); printf("array 2 %d: %d\n", x, array2[x]); } return 0; } <file_sep> <?php require mysqli_connect.php; $new_table = "CREATE TABLE table1 ) id INT UNSIGNED AUTO INCREMENT, name VARCHAR(20) NOT NULL, ice_cream VARCHAR(20) NOT NULL, PRIMARY KEY (id) )"; if($conn->query($new_table) == TRUE) { echo "Good!"; } else { echo "ERROR" . $conn->error; } $conn->close(); ?> <file_sep>#Main lecture print("Hello World") python3 "program" "args" no semi-colons. no newlines print does automatically get user input and print to screen: answer = get_string("What is your name?") print("hello," + answer) + or , will concatenate string in print. also adds space print(f"Hello, {answer}") {} interpolate the value inside those. **f is format string** tells interpreter to not print literally, format the value in the {} variables: counter = 0 //thats an int counter = counter + 1 //good counter += 1 //good ++ operator does not exist in python if: if x < y: print("x is less than y") have to use the : and the tab is important python is sensitive to whitespace if want to be in condition, must be indented if blah: thing to do elif: other thing to do else: other thing to do while: while True: print("Hello World") booleans capitalized for: do not map directly to python for i in [0,1,2]: print("cough") [] called list. can grow and shrink easily set i eqaul to 0, cough. set i equal to 1, cough for i in range(3): print("cough'0 range(3) will return list of numbers from 0 up to 3 data types: bool float int str (string) some of those data strcutures from C: range- sequence of numbers list- sequence of mutable values tuple- sequence of immutable values dict- collection of key value pairs (abstract data type implemented with hash table under the hood) set- collection of unique values- will throw away duplicates' not all of them importing: from PIL import Image, ImageFilter functions: words = set() def *name of function*(word): dictionary.py def load(dictionary): file = open(dictionary, "r") for line in file: words.add(line.rstrip("\n")) file.close() return True def check(word): if word.lower() in words: return True else: return False def size(): return len(words) def unload(): return True logic: literallty and , or instead of && || if s.lower() in ["y", "yes"]: print("Agreed") can implement regular expressions use import to pull in other files **traceback**- what went wrong reads line one at a time- so function definitions need to be above "main" code one solution: def main() what main does def function(() what function does ...at end of file main() so define "main" first just remember to actually call main at end. does not need to be called main, just a convention example: def get_positive_int(): while True: n = get_int("Positive Integer: ") if n > 0: break return n **no variable scope** within function so not necessarily accessbile to other functions, but no scope within its own function **input**- receives input from keyboard, but receives string to "cast" age = int(input("What's your age?") no upper bounds for variables- will overflow whole computer **list** scores = [72, 73] scores = [] scores.append(72) scores.append(33) print(f"Average: {sum(scores) / len(scores)}") can grow and shrink- don't think about it iterate over a string (string s) for c in s: print(c, end="") print() **command line arguments** from sys import argv for i in range(len(argv)): print(argv[i]) more pythonic: for arg in argv: print(arg) **exiting function** from sys import exit exit(1) instead of return 1 example: if "EMMA" in names: print("Found") exit(0) print("Not found") exit(1) **dictionary** key-value pair takes input keys, outputs values declaring a dict people = { "EMMA": "617-555-0101", "John": "453-234-5674" } if "EMMA" in people: print(f"Found {people['EMMA']}") returns Emma's number double or single quotes do same thing. here trying to keep interpreter from getting confused **package** == library (use import) **Regular Expressions** define patterns . - any character .\*- 0 or more characters .+ - 1 or more characters ? - optional ^ - start of input $ - end of input import re (str s) if re.search("yes", s): if re.search("yes\y", s): if re.search("y(es)?", s): YES will not work if re.search("y(es)?", s, re.IGNORECASE): **using libraries** like Java object methods: recognizer = speech_recognizer.Recognizer() with speech_recognizer.Microphone() as source: print("Say something") audio = recognizer.listen(source) #Shorts- Python variables declared by initialization only \# for comments code blocks indented ternary operator: letters_only = True if input().isalpha() else False input() native function for getting user input from CLI only while and for loops. no do while for x in range(0, 100, 2): print(x) count from 0 to 100 counting by 2s lists are arrays BUT not fixed in size nums = [] //empty list nums = [x for x in range(500)] use for loop to create list of 500 elements nums.append(5) //adds to end nums.insert(4,5) //insert in 4th position 5 nums[len(nums):] = [5] //could use this to tack a list onto an existing list **tuples**- ordered immutable set of data. useful for associating collections of data (like a struct). order is important list of tuples: presidents = [ ('<NAME>', 1789), ('<NAME>', 1797) ] for prez, year in presidents print("In {1}, {0} took office".format(prez, year)) using . method operator on the string **dictionaries** pizzas = { "cheese":9, "pepperoni":10 } pizzas["bacon"] = 14 #add new key/value pair can easily iterate over a dictionary for pie in pizzas: #pie becomes the keys print(pie) will print all of the keys for pie, price in pizzas.items(): print (price) .items() transforming dictionary into a list str(price) turns price into a string \*\* built in square operator Python is an object-oriented language objects can have own methods defined in the object object.method() define object using class keyword every class needs a constructor every method in class needs "self" (like this os Java) class Student(): def__init__(self, name, id): self.name = name self.id = id def changeID(self, id): self.id = id def print(self): print("{} - {}".format(self.name, self.id)) initialization: jane= Student("Jane", 10) import <module> <file_sep># divide # merge # lolz def mergesort(array): if(len(array) <= 1): return array mid = len(array) // 2 larray = array[:mid] rarray = array[mid:] larray = mergesort(larray) rarray = mergesort(rarray) return merge(larray, rarray) def merge(larray, rarray): i = j = k = 0 out_array = [] while i < len(larray) and j < len(rarray): if larray[i] < rarray[j]: out_array.append(larray[i]) i += 1 else: out_array.append(rarray[j]) j += 1 while i < len(larray): out_array.append(larray[i]) i += 1 while j < len(rarray): out_array.append(rarray[j]) j += 1 return out_array # main test = [98,43,25,104,2,3,4] print(mergesort(test)) <file_sep><?php ini_set('display_errors',1); if($_SERVER["REQUEST_METHOD"] == "POST"){ //if write is set, create save a new xml file with the info if($_POST["write"]){ $name = $_POST["name"]; $flavor = $_POST["flavor"]; } } ?> <h2>Choose your favorite ice cream</h2> <form method="post" action="<?php $_SERVER["PHP_SELF"];?>"> Name: <input type="text" name="name"> Flavor: <input type="radio" id="flavor" name="flavor" value="vanilla">Vanilla <input type="radio" id="flavor" name="flavor" value="chocolate">Chocolate <input type="radio" id="flavor" name="flavor" value="strawberry">Strawberry <!-- <input type="text" id="flavor" name="flavor" value="vanilla">Other --> <input type="submit" name="write" value="write"> </form> <?php echo "<h2>Your Results</h2>"; echo $name; echo "<br>"; echo $flavor; echo "<br>"; ?> <file_sep>def getNumberOfOptions(priceOfJeans, priceOfShoes, priceOfSkirts, priceOfTops, budgeted): list_of_lists = [priceOfJeans, priceOfShoes, priceOfSkirts, priceOfTops] memo = {} lists = sorted(list_of_lists, key=len) for l1 in lists[0]: for l2 in lists[1]: for l3 in lists[2]: for l4 in lists[3]: if (l1,l2,l3,l4) in memo: continue elif l1 + l2 + l3 + l4 > budgeted: continue else: memo[(l1,l2,l3,l4)] = l1 + l2 + l3 + l4 return len(memo) def getNumberOfOptions(priceOfJeans, priceOfShoes, priceOfSkirts, priceOfTops, budgeted): combo = 0 list_of_lists = [priceOfJeans, priceOfShoes, priceOfSkirts, priceOfTops] lists = sorted(list_of_lists, key=len) shorter = [] longer = [] for l1 in lists[0]: for l2 in lists[1]: shorter.append(l1+l2) for l3 in lists[2]: for l4 in lists[3]: longer.append(l3+l4) shorter = sorted(shorter) longer = sorted(longer, reverse=True) for i in range(len(shorter)): for j in range(len(longer)): if shorter[i] + longer[j] < budgeted: combo += len(longer[j:]) return combo <file_sep># Day 18 Getting More from Functions **passing by value**- function is passed a copy of the argument's value 3 steps: 1. argument expression is evaluated 2. result is copied onto the stack, a temporary storage space in memory 3. the function retrieves the argument's value from the stack if a variable is passed as the argument, code in the function cannot modify the value of the variable IF nearly every function will need to modify the data directly, can use global variable otherwise pay attention: variable contents are copied onto stack during execution so function cannot modify original value **passing by reference**- pass a pointer to the argument variable rather than the value of the variable itself limited space on the stack- should not pass large items like structures advantage and disadvantage to pass by reference- may unintentionally change some data COULD just modify by using the function's return value, but that limits you to modifying only a single value ensure prototype and definition understand you will be passing a pointer for calling: prototype void by_ref(int *a, int *b, int *c); definition by_ref(&x, &y, &z); could write a function that retrieves some values by reference and others by value ## Type void Pointers generic pointer that can point to any type of data object most common use is in declaring function parameters could pass type int one time ,type float another etc. can use a typecast to tell function what data type- cannot dereference a pointer until function knows the exact data type void *val; (type *) pval tell it its an int: (int *) pval to derefrence: *(int *) pval could do something like this: void half(void *pval, char type); then integrate into function ## Using Functions that have a Variable number of arguments can write own functions perform like scanf and printf **must include stdarg.h** first declare fixed parameters. then use ellipsis at end of parameter list to indicate that zero or more additional arguments are passed to the function you tell it how many arguments will be passed one of the functions fixed arguments will be used for the additional arguments to create a function that accepts different variable types, must devise method of passing information- like character code w/ switch statement what you need to use for this: va_list a pointer to data type va_start() a macro used to initialize the argument list va_arg() a macro used to retrieve each argument, in turn, from the variable list va_end() macro used to clean up when all arguments have been retrieved must follow these steps: 1. declare a pointer variable of type va_list. usually called arg_ptr 2. call va_start() passing it arg_ptr and **name of last fixed argument** 3. to retrieve each argument call va_arg() passing pointer and data type of next argument. return value is next argument. if receive n arguments, call va_arg() n times to retrieve arguments in order listed in the function call 4. when done call va_end() Example: #include <stdio.h> #include <stdargt.h> float average(int num, ...); int main( void ) { float x; x = average(*numbers*) printf(first average is x) x = average(*second set*) printf(second average is x) } float average(int num, ...) { va_list arg_ptr; int count, total = 0; va_start(arg_ptr, num); for(count = 0; count <num; count++) total += va_arg( arg_ptr, int); va_end(arg_ptr); return ((float)total/num); } returns averages of each list- see pg 525 ## Functions that return a pointer type *func(parameter_list); <file_sep>#include <stdio.h> #include <string.h> int main(void) { char buffer[256]; printf( "Enter your name and press <Enter>:\n"); gets( buffer ); printf( "\nYour name has %ld characters and spaces!", strlen( buffer )); return 0; } <file_sep>/* Name : find_nbr.c * Purpose: This program picks a random number and then * lets the user try to guess it *Returns: Nothing */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define NO 0 #define YES 1 int main( void ) { int guess_value = -1; int number; int nbr_of_guesses; int done = NO; printf("\n\nGetting a Random Number\n"); /*Use the time to seed the random number generator */ srand( (unsigned) time( NULL ) ); number = rand(); printf( "The random number (answer) is: %d", number ); /* cheat */ nbr_of_guesses = 0; while ( done == NO ) { printf("\nPick a number between 0 and %d> ", RAND_MAX); scanf( "%d", &guess_value ); /*Get a number */ nbr_of_guesses++; if ( number == guess_value ) { done = YES; } else if ( number < guess_value ) { printf("\nYou guesses high!"); } else { printf("\nYou guessed low!"); } } printf("\n\nCongratulations! You guessed right in %d Guesses!" , nbr_of_guesses); printf("\n\nThe number was %d\n\n", number); return 0; } <file_sep> <?php $servername = "localhost"; $username = "username"; $password = "<PASSWORD>"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Create database $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $conn->error; } $conn->close(); ?> <file_sep> <!DOCTYPE html> <html> <body> <?php function div($x, $y){} return $x / $y; } echo "5 / 10 = " . div(5,10) . "<br>"; echo "7 / 13 = " . div(7,13) . "<br>"; echo "2 / 4 = " . div(2,4); ?> </body> </html><file_sep>#include <stdio.h> #include <ctype.h> void main () { int var = 1; if ( isalnum(var) > 0 ) { printf("TRUE\n"); } if (isalpha(var) > 0 ) { printf("TRUE\n"); } if (isblank(var) > 0 ) { printf("TRUE\n"); } else if (iscntrl(var) > 0 ) { printf("TRUE\n"); } else if (isdigit(var) > 0 ) { printf("TRUE\n"); } else if (isgraph(var) > 0 ) { printf("TRUE\n"); } else if (islower(var) > 0 ) { printf("TRUE\n"); } else if (isprint(var) > 0 ) { printf("TRUE\n"); } else if (ispunct(var) > 0 ) { printf("TRUE\n"); } else if (isspace(var) > 0 ) { printf("TRUE\n"); } else if (isupper(var) > 0 ) { printf("TRUE\n"); } else if (isxdigit(var) > 0 ) { printf("TRUE\n"); } else { printf("FALSE"); } } <file_sep># Ch.9 Scheduling: Proportional Share proportional share of fair share scheduling instead of optimizing for turnaround or response time, guarantee each job certain percentage of CPU one method: **lottery scheduling** lottery determines which process should get to run next processes that are more important get more chances to win the lottery ## 9.1 Tickets Represent your Share **tickets** - used to represent the share of a resource - % of tickets that a process has represents its share of the system resource in question scheduler must know how many total tickets there are scheduler then picks a "winning ticket" - if process A holds ticket 0 to 74 and process B has 75 to 99, then random number generator picks a winning ticket - so A has more chances to win leads to probabilistic correctness in meeting desires proportion, but not guarantee - gets better longer jobs run ## 9.2 Ticket Mechanisms provides a number of mechanisms to manipulate tickets in useful ways one way: **ticket currency** - allows user with a set of tickets to allocate tickets among their own jobs - aka virtualize a set of a global ticket number to each user, then convert that back to a global value when actually processing it another mechanism: **ticket transfer** - with transfers, a process can temporarily hand off its ticekts to another process **ticket inflation** - process can temporarily raise or lower the number of tickets it owns inflation can be applied in an environment where a group of processes trusts one another ## 9.3 Implementation lottery is simple scheduling decision code iterates through each processes tickets, adds them to a counter when matches the randomly generated value, runs that process currently pointing at may be best to keep data stucture of processes sorted - ensures less iterations over structure ## 9.4 An Example would like to jobs started at same time with same tickets and same run time to finish at same time - but not always the case with randomness to quantify this, use a **unfairness metric** first job completed divided by time second job completes - so as jobs finish closer together, unfairness approaches 1 when job lengths are not that long, unfairness can be quite severe ## 9.5 all this says is problem with anything not CFS is how to assign tickets? ## 9.6 Why not deterministic **stride scheduling** - each job in system has a **stride** which is inverse in proportion to the number of tickets a process has so if use some arbitrary large value like 10,000, and process has 50, thats 50/10,000 the stride would be 10,000/50 or 200 every time a process runs, increment a counter for it (called **pass value**) by its stride to track its global process then run the process with lowest value next **by its stride to track its global process** have to have some global state for fairness ## 9.7 The Linux Completely Fair Scheduler (CFS) fair share scheduling in a very scalable way spend very little CPU cycles making scheduling decisions to divide CPU utilization evenly among all competing processes does so with counting based technique: **virtual runtime** (vruntime) as each process runs it accumulates vruntime in basic case, vruntime increases at same rate CFS will pick the process with the lowest vruntime to run next soooo how does the scheduler know when to stop the currently running process and start the next one? - tension: if CFS switches too often fairness is increased, but at the cost of performance (too much context switching) if switches less often, performance is increased but at the cost of near term fairness CFS manages this tension throught various control parameters: 1. **sched-latency** CFS uses this value to determine how long one process should run before considering a switch - effectively determines time slice on per job basis / dynamically - typical value is 48 ms CFS divides sched_latency by number of processes running on the CPU to determine the time slice for a process - so overtime the CFS is COMPLETELY fair what if!? too many processes running? - wouldn't the time slices be too small? sets: 2. **min-granularity** - usually 6ms - the lowest a time slice can go 3. **Weighting (Niceness)** - also adds process priority users can set - the **nice** level of a process - can be anywhere from - 20 to + 19 - negative numbers are better static const int prio_to_weight[40] is an int array with all of the possible weights that nice draws from (pg 97) formula for computing effective time slice based on sched_latency and factoring in niceness: time_slice(k) = weight(k)/ (sumnation of as n goes from 0 to n-1)weight(k) * sched__latency formula for vruntime becomes: for process i vruntime(i) = vruntime(i) + weight(0) / weight(i) * runtime(i) CSF uses a red-black tree - a type of balanced tree that maintains consistent tree depth - to make scheduler find next job as quickly as possible - only keeps track of running ( or runnable) jobs - if process goes to sleep from I/O or waiting on network then removed from CFS red-black tree - jobs are ordered in the tree by vruntime - insertion and deletion O(logn) when a job sleeps and wakes up its vruntime is set to the minimum value found in the tree (prevents process sitting behind because vruntime not updating with call from taking over CPU) CFS like weighted round-robin with dynamic time slices still not answered: - jobs that sleep frequently are not treated fairly - initial ticket/priority assignment <file_sep># ch.5 Process API exec() fork() wait() ## fork() creates a new process exact copy of calling process child does not start at main() but at same location parent called fork() child gets own address space/other resources fork() returns to parent int PID, child receives 0 not deterministic as to whether parent or child process executes first ## wait() call after fork, parent will WAIT until child process completes ## exec() run program different than calling program transforms currently running program into different program loads code and static data from executable and overwrites the current process data heap, stack, other parts memory space re-initialized almost as if calling program never existed successful call to exec() never returns ## why? can run code AFTER call to fork() can run code BEFORE call to exec() - alter environment about to be run how shell works (as example): 1. finds executable 2. calls fork() to create child of shell to run command 3. some variant of exec() in that child to run it 4. then calls wait() 5. when child completes, shell returns from eait() then ready to accept prompt ex: wc p1.c > results.txt before calling exec() for wc shell closes standard output file and opens results.txt pipe() output of one process connected to in-kernal pipe (aka queue) and input of another process is connected to same pipe ## process control kill() sends signals to a process ctrl-c SIGINT. interrupt. normally kills process ctrl-z SIGSTP. stop. pauses process can also send to whole process group process should use signal() to "catch" various signals ensuring a partciluar system call is delivered to a process it will suspend execution and run a particular piece of code in response <file_sep># Day 15 Pointers: Beyond the Basics **pointer to pointer**- variable whose value is the address of a pointer int myVar = 12; int *ptr = &myVar; int **ptr2ptr = &ptr; use double indirection operator when accessing pointed to varaible: **ptr2ptr = 12; assigns value of 12 to myVar most common use is for arrays of pointers ## Pointers and Multi-Dimensional Arrays review: int multi[2][4] 1. multi contains 2 elements 2. each of these 2 elements contains 4 elements 3. each of the 4 elements is a type int **ARRAY OF ARRAYS** **name of multidimensional array is a pointer to first array element** multi[0] would be pointer to multi[0][0] or first element of multidimensional array the array name followed by n pairs of brackets evaluates as array data (data stored in the specified array element) array name followed by fewer than n pairs of brackets evaluates as pointer to an array element sizeof(multi) = 32 sizeof(multi[0] = 16 sizeof(multi[0][0]) = 4 to access data at multi[0][0]: multi[0][0] *multi[0] **multi **array with n dimensions has elements that are arrays of n-1 dimensions** to declare a pointer to an element of multi (can point to 4 element integer array): int (*ptr)[4] to point at first element of multi: prt = multi; use typecast (ex:(int \*)) when handling pouinters to pointers of arrays ## Working with Arrays of Pointers most common use of array of pointers with strings start of string indicated by poitner to first character by declaring and initializing an array of pointers to type char can access and manipulate large number of strings using pointer array review: string must have space allocated for it. whether at compilation at declaration or at runtime with malloc() declare an array of 10 pointers to type char: char *message[10]; char *message[10] = { "one" , "two" , "three" } allocates 10 element array named message- each pointer to type char allocates space in memory for the three strings. each with terminating null character initializes array indexes point at first character of each string much easier to pass array of pointers to function then pass several strings. when pass that array to a function passing a pointer (array name) to a pointer (first array element) review: malloc() returns a pointer int (*b)[12]; //pointer to array of 12 integers int *c[12]; // array of 12 pointers to integers ## Working with Pointers to Functions when program runs, code for each function loaded into memory starting at specific address- pointer to function holds starting address- entry point more flexible way of calling a function type (*ptr_to_func)(parameter_list) must be declared but also initialized to point float square(float x); //prototpye float (*ptr)(float x); //pointer declaration float square(float x); //function definition ptr = square //initialize ptr to square answer = ptr(x) //call function using pointer **function name without () is pointer to function** but that is a constant and cannot be changed- why the pointers are useful declare a pointer to a function that takes no arguments and returns a character: char (\*func)(); declare a function returns a pointer to a character char \*func() # Linked Lists pg416 single linked lists contained in a structure- add pointers to structure links to other instances to generate linking last element in list identified by pointer assigned value of NULL instance1 -> instance2 -> instance3 -> NULL create HEAD pointer as intermediate step add an element to beginning of list 1. create instance of structure, allocating memory space malloc() 2. set next pointer of new element to the current value of the head pointer 3. make the head pointer point to the new element adding an element to the end of the list 1. create instance of structure, allocating memory space malloc() 2. set the next pointer in the last element to point to the new element (whose address is returned by malloc()) 3. set the next pointer in the new element to NULL to signal that i it is the last item in the list adding an element to the middle of the list 1. in the list, locate the exisitng element that the new elementi will be placed after- marker element 2. create an instance of your structure, allocating memory malloc() 3. set the next pointer of the marker element to point to the new element whose address is returned by malloc() 4. set the next pointer of the new element that the marker element used to point to deleting element from a list 1. to delete the first element set the head pointer to point toi the second element in the list 2. to delete the last element set the next pointer of the next-to-lasti element to NULL 3. to delete any other element set the next pointer of the element before i the one being delete to point to the element after the one being deleted <file_sep> string encipher(string key, string plaintext) { //string key = "<KEY>"; //string plaintext = "hElLo, wORLd"; int len = strlen(plaintext)+1; char ciphertext[len]; for(int u = 65, l = 97, a = 0; a < 26; u++, l++, a++ ) { for (int i = 0; i < len -1 ; i++) { if ( ispunct(plaintext[i]) || isspace(plaintext[i]) ) { ciphertext[i] = plaintext[i]; continue; } if ( plaintext[i] == u ) ciphertext[i] = toupper(key[a]); if ( plaintext[i] == l ) ciphertext[i] = tolower(key[a]); } } string conv = ciphertext; //printf("%s\n", conv); return conv; }//end encipher<file_sep>#include <stdio.h> #include <stdlib.h> #define MAX 100 #define YES 1 #define NO 0 struct record { char fname[16]; char lname[21]; char phone[10]; long income; int month; int day; int year; }; struct record list[MAX]; int last_entry = 0; int main(void); void get_data(void); void display_report(void); int continue_function(void); void clear_kb(void); int main( void ) { int cont = YES; int ch; while( cont == YES) { printf( "\n"); printf( "\n MENU"); printf( "\n ======\n"); printf( "\n1. Enter names"); printf( "\n2. Print report"); printf( "\n3. Quit"); printf( "\n\nEnter Selection ==> "); ch = getchar(); fflush(stdin); switch( ch ) { case '1':get_data(); break; case '2':display_report(); break; case '3':printf("\n\nThank you for using this program!\n"); cont = NO; break; default: printf("\n\nInvalid choice, Please select 1 to 3!"); break; } } return 0; } void get_data(void) { int cont; for( cont = YES; last_entry < MAX && cont ==YES; last_entry++ ) { printf("\n\nEnter information for Person %d.", last_entry+1); printf("\n\nEnter first name: "); fgets(stdin, list[last_entry].fname); printf("\n\nEnter last name: "); fgets(stdin, list[last_entry].lname); printf("\nEnter phone in 123-4567 format: "); fgets(stdin, list[last_entry].phone); printf("\nEnter Yearly Income (whole dollars): "); scanf("%ld", &list[last_entry].income); printf("\nEnter Birthday: "); do { printf("\n\tMonth (0 - 12): "); scanf("%d", &list[last_entry].month); }while ( list[last_entry].month < 0 || list[last_entry].month > 12); do { printf("\n\tDay (0-31): "); scanf("%d", &list[last_entry].day); }while ( list[last_entry].day < 0 || list[last_entry].day > 31); do { printf("\n\tYear (1800 - 2020): "); scanf("%d", &list[last_entry].year); }while ( list[last_entry].year != 0 && (list[last_entry].year < 1800 || list[last_entry].year > 2020)); cont = continue_function(); } if( last_entry == MAX) printf("\n\nMaximum Number of Names has been entered!\n"); } void display_report() { long month_total = 0, grand_total = 0; int x,y; fprintf(stdout, "\n\n"); fprintf(stdout, "\n REPORT"); fprintf(stdout, "\n ========"); for( x = 0; x <= 12; x++) { month_total = 0; for( y = 0; y < last_entry; y++) { if( list[y].month == x ) { fprintf(stdout, "\n\t%s %s %s %ld", list[y].fname, list[y].lname, list[y].phone,list[y].income); month_total += list[y].income; } } fprintf(stdout, "\nTotal for month %d is %ld",x,month_total); grand_total += month_total; } fprintf(stdout, "\n\nReport totals:"); fprintf(stdout, "\nTotal Income is %ld", grand_total); fprintf(stdout, "\nAverage Income is %ld", grand_total/last_entry); fprintf(stdout, "\n\n* * * End of Report * * *"); } int continue_function( void ) { int ch; printf("\n\nDo you wish to continue? Y(es)/N(o): "); fflush(stdin); ch = getchar(); while( ch != 'n' && ch != 'N' && ch != 'y' && ch!= 'Y' ) { printf("\n%C is invalid!", ch); printf("\n\nPlease enter \'N\' to Quit or \'Y\' to Continue: "); fflush(stdin); ch = getchar(); } clear_kb(); if(ch == 'n' || ch == 'N') return (NO); else return (YES); } void clear_kb(void) { char junk[80]; fgets(stdin, junk); }
505f5da76ebc9be0394ceede7b0c17ed30c90017
[ "SQL", "Markdown", "Makefile", "Java", "Python", "PHP", "C", "C++", "Shell" ]
238
Makefile
dic3jam/how-i-learned
0383f677f5330dd3cfaa5cebd7883bc878915fa7
c70a712a78f4baca4332d3b497da94600fc237eb
refs/heads/master
<file_sep>from Rbac_utils.Rbac_ready_functions import rbac_utils from cbas.cbas_base import CBASBaseTest from remote.remote_util import RemoteMachineShellConnection class CBASError: errors = [ # Error codes starting with 2XXXX { "id": "user_unauthorized", "msg": ["Unauthorized user"], "code": 20000, "query": "select count(*) from ds" }, { "id": "user_permission", "msg": ["User must have permission (cluster.bucket[default].analytics!manage)"], "code": 20001, "query": "drop dataset ds" }, # Error codes starting with 21XXX { "id": "invalid_duration", "msg": ['Invalid duration "tos"'], "code": 21000, "query": "select sleep(count(*), 2000) from ds" },{ "id": "unknown_duration", "msg": ['Unknown duration unit M'], "code": 21001, "query": "select sleep(count(*), 2000) from ds" }, { "id": "request_timeout", "msg": ["Request timed out and will be cancelled"], "code": 21002, "query": "select sleep(count(*), 2000) from ds" }, { "id": "unsupported_multiple_statements", "msg": ["Unsupported multiple statements."], "code": 21003, "query": "create dataset ds1 on default;connect link Local" }, # Error codes starting with 22XXX { "id": "bucket_uuid_change", "msg": ["Connect link failed", "Default.Local.default", "Bucket UUID has changed"], "code": 22001, "query": "connect link Local" }, { "id": "connect_link_fail", "msg": ["Connect link failed", "Default.Local.default", "Bucket (default) does not exist"], "code": 22001, "query": "connect link Local" }, { "id": "max_writable_datasets", "msg": ["Maximum number of active writable datasets (8) exceeded"], "code": 22001, "query": "connect link Local" }, # Error codes starting with 23XXX { "id": "dataverse_drop_link_connected", "msg": ["Dataverse Default cannot be dropped while link Local is connected"], "code": 23005, "query": "drop dataverse custom" }, { "id": "create_dataset_link_connected", "msg": ["Dataset cannot be created because the bucket default is connected"], "code": 23006, "query": "create dataset ds1 on default" }, { "id": "drop_dataset_link_connected", "msg": ["Dataset cannot be dropped because the bucket", "is connected", '"bucket" : "default"'], "code": 23022, "query": "drop dataset ds" }, # Error codes starting with 24XXX { "id": "syntax_error", "msg": ["Syntax error:", "select count(*) for ds1;", "Encountered \"for\""], "code": 24000, "query": "select count(*) for ds1" }, { "id": "compilation_error", "msg": ["Compilation error: count is a SQL-92 aggregate function. The SQL++ core aggregate function array_count could potentially express the intent"], "code": 24001, "query": "select count(*) ds1" }, { "id": "index_on_type", "msg": ["Cannot index field [click] on type date. Supported types: bigint, double, string"], "code": 24002, "query": "create index idx on ds(click:date)" }, { "id": "cb_bucket_does_not_exist", "msg": ["Bucket (default1) does not exist"], "code": 24003, "query": "create dataset ds1 on default1" }, { "id": "create_dataset_that_exist", "msg": ["A dataset with name ds already exists"], "code": 24005, "query": "create dataset ds on default" }, { "id": "drop_local_not_exist", "msg": ["Link Default.Local1 does not exist"], "code": 24006, "query": "drop link Local1" }, { "id": "drop_local_link", "msg": ["Local link cannot be dropped"], "code": 24007, "query": "drop link Local" }, { "id": "type_mismatch", "msg": ["Type mismatch: function contains expects its 2nd input parameter to be of type string, but the actual input type is bigint"], "code": 24011, "query": 'SELECT CONTAINS("N1QL is awesome", 123) as n1ql' }, { "id": "dataverse_not_found", "msg": ["Cannot find dataverse with name custom"], "code": 24034, "query": 'use custom;' }, { "id": "dataset_not_found", "msg": ["Cannot find dataset ds1 in dataverse Default nor an alias with name ds1!"], "code": 24045, "query": 'select * from ds1' }, { "id": "index_name_already_exist", "msg": ["An index with this name sec_idx already exists"], "code": 24048, "query": "create index sec_idx on ds(name:string)" }, # Error codes starting with 25XXX ] def __init__(self, error_id): self.error_id = error_id def get_error(self): for error in self.errors: if error['id'] == self.error_id: return error return None class CBASErrorValidator(CBASBaseTest): def setUp(self): super(CBASErrorValidator, self).setUp() self.log.info("Read input param") self.error_id = self.input.param('error_id', None) self.error_response = CBASError(self.error_id).get_error() self.log.info("Test to validate error response :\ %s" % self.error_response) self.log.info("Create connection") self.cbas_util.createConn(self.cb_bucket_name) def create_dataset_connect_link(self): self.log.info("Create dataset on the CBAS") self.cbas_util.create_dataset_on_bucket(self.cb_bucket_name, self.cbas_dataset_name) self.log.info("Connect to Local link") self.cbas_util.connect_link() def validate_error_response(self, status, errors, expected_errors, expected_error_code): if errors is None: self.fail("Query did not fail. No error code and message to validate") for expected_error in expected_errors: self.assertTrue(self.cbas_util.validate_error_in_response(status, errors, expected_error, expected_error_code), msg="Mismatch. Refer logs for actual and expected error code/msg") """ cbas.cbas_error_codes.CBASErrorValidator.test_error_response_for_error_id,default_bucket=True,cb_bucket_name=default,cbas_bucket_name=cbas,cbas_dataset_name=ds,error_id=<passed from conf file> """ def test_error_response_for_error_id(self): self.log.info("Create dataset and connect link") self.create_dataset_connect_link() status, _, errors, _, _ = self.cbas_util.execute_statement_on_cbas_util(self.error_response["query"]) self.validate_error_response(status, errors, self.error_response["msg"], self.error_response["code"]) """ test_error_response_for_analytics_timeout,default_bucket=True,cb_bucket_name=default,cbas_bucket_name=cbas,cbas_dataset_name=ds,error_id=query_timeout """ def test_error_response_for_analytics_timeout(self): self.log.info("Create dataset and connect link") self.create_dataset_connect_link() self.log.info("Read time unit and time out value from test params") time_out = self.input.param('time_out', 1) time_unit = self.input.param('time_unit', "s") status, _, errors, _, _ = self.cbas_util.execute_statement_on_cbas_util(self.error_response["query"], analytics_timeout=time_out, time_out_unit=time_unit) self.validate_error_response(status, errors, self.error_response["msg"], self.error_response["code"]) """ test_error_response_create_index_with_index_name_already_exist,default_bucket=True,cb_bucket_name=default,cbas_bucket_name=cbas,cbas_dataset_name=ds,error_id=create_index_with_index_name_already_exist """ def test_error_response_create_index_with_index_name_already_exist(self): self.log.info("Create dataset and connect link") self.create_dataset_connect_link() self.log.info("Disconnect Local link") self.assertTrue(self.cbas_util.disconnect_from_bucket(), msg="Failed to disconnect connected bucket") self.log.info("Create a secondary index") self.assertTrue(self.cbas_util.execute_statement_on_cbas_util(self.error_response["query"]), msg="Failed to create secondary index") self.log.info("Verify creating a secondary index fails with expected error codes") status, _, errors, _, _ = self.cbas_util.execute_statement_on_cbas_util(self.error_response["query"]) self.validate_error_response(status, errors, self.error_response["msg"], self.error_response["code"]) """ test_error_response_user_permissions,default_bucket=True,cb_bucket_name=default,cbas_bucket_name=cbas,cbas_dataset_name=ds,error_id=user_permission """ def test_error_response_user_permissions(self): self.log.info("Create dataset and connect link") self.create_dataset_connect_link() self.log.info("Create a user with analytics reader role") rbac_util = rbac_utils(self.master) rbac_util._create_user_and_grant_role("reader_admin", "analytics_reader") status, _, errors, _, _ = self.cbas_util.execute_statement_on_cbas_util(self.error_response["query"], username="reader_admin", password="<PASSWORD>") self.validate_error_response(status, errors, self.error_response["msg"], self.error_response["code"]) """ test_error_response_user_unauthorized,default_bucket=True,cb_bucket_name=default,cbas_bucket_name=cbas,cbas_dataset_name=ds,error_id=user_unauthorized """ def test_error_response_user_unauthorized(self): self.log.info("Create dataset and connect link") self.create_dataset_connect_link() self.log.info("Create remote connection and execute cbas query using curl") cbas_url = "http://{0}:{1}/analytics/service".format(self.cbas_node.ip, 8095) shell = RemoteMachineShellConnection(self.cbas_node) output, _ = shell.execute_command("curl -X POST {0} -u {1}:{2}".format(cbas_url, "Administrator", "pass")) self.assertTrue(self.error_response["msg"][0] in output[3], msg="Error message mismatch") self.assertTrue(str(self.error_response["code"]) in output[2], msg="Error code mismatch") """ test_error_response_max_writable_dataset_exceeded,default_bucket=True,cb_bucket_name=default,cbas_bucket_name=cbas,cbas_dataset_name=ds,error_id=max_writable_datasets """ def test_error_response_max_writable_dataset_exceeded(self): self.log.info("Create dataset and connect link") self.create_dataset_connect_link() self.log.info("Disconnect Local link") self.assertTrue(self.cbas_util.disconnect_from_bucket(), msg="Failed to disconnect Local link") self.log.info("Create 8 more datasets on CBAS bucket") for i in range(1, 9): self.assertTrue(self.cbas_util.create_dataset_on_bucket(self.cb_bucket_name, self.cbas_dataset_name + str(i)), msg="Create dataset %s failed" % self.cbas_dataset_name + str(i)) self.log.info("Connect back Local link and verify error response for max dataset exceeded") status, _, errors, _, _ = self.cbas_util.execute_statement_on_cbas_util(self.error_response["query"]) self.validate_error_response(status, errors, self.error_response["msg"], self.error_response["code"]) """ test_error_response_for_cbas_node_unstable,default_bucket=True,cb_bucket_name=default,cbas_bucket_name=cbas,cbas_dataset_name=ds,error_id=unstable_cbas_node """ def test_error_response_for_cbas_node_unstable(self): self.log.info("Create dataset and connect link") self.create_dataset_connect_link() status, _, errors, _, _ = self.cbas_util.execute_statement_on_cbas_util(self.error_response["query"]) self.validate_error_response(status, errors, self.error_response["msg"], self.error_response["code"]) """ test_error_response_for_bucket_uuid_change,default_bucket=True,cb_bucket_name=default,cbas_bucket_name=cbas,cbas_dataset_name=ds,error_id=bucket_uuid_change """ def test_error_response_for_bucket_uuid_change(self): self.log.info("Create dataset and connect link") self.create_dataset_connect_link() self.log.info("Disconnect link") self.cbas_util.disconnect_link() self.log.info("Delete KV bucket") self.delete_bucket_or_assert(serverInfo=self.master) self.log.info("Recreate KV bucket") self.create_default_bucket() status, _, errors, _, _ = self.cbas_util.execute_statement_on_cbas_util(self.error_response["query"]) self.validate_error_response(status, errors, self.error_response["msg"], self.error_response["code"]) """ test_error_response_for_connect_link_failed,default_bucket=True,cb_bucket_name=default,cbas_bucket_name=cbas,cbas_dataset_name=ds,error_id=connect_link_fail """ def test_error_response_for_connect_link_failed(self): self.log.info("Create dataset and connect link") self.create_dataset_connect_link() self.log.info("Delete KV bucket") self.delete_bucket_or_assert(serverInfo=self.master) status, _, errors, _, _ = self.cbas_util.execute_statement_on_cbas_util(self.error_response["query"]) self.validate_error_response(status, errors, self.error_response["msg"], self.error_response["code"]) """ test_error_response_drop_dataverse_link_connected,default_bucket=True,cb_bucket_name=default,cbas_bucket_name=cbas,cbas_dataset_name=ds,error_id=dataverse_drop_link_connected """ def test_error_response_drop_dataverse_link_connected(self): self.log.info("Create dataverse") status, metrics, _, cbas_result, _ = self.cbas_util.execute_statement_on_cbas_util("create dataverse custom") self.assertEquals(status, "success", msg="Create dataverse query failed") self.log.info("Use dataverse") status, metrics, _, cbas_result, _ = self.cbas_util.execute_statement_on_cbas_util("use custom") self.assertEquals(status, "success", msg="Use dataverse query failed") self.log.info("Create dataset and connect link") self.create_dataset_connect_link() status, _, errors, _, _ = self.cbas_util.execute_statement_on_cbas_util(self.error_response["query"]) self.validate_error_response(status, errors, self.error_response["msg"], self.error_response["code"]) def tearDown(self): super(CBASErrorValidator, self).tearDown() <file_sep>[global] username:root password:<PASSWORD> index_port:9102 n1ql_port:8093 data_path:/data/dta index_path=/data/idx cbas_path:['/data/d1','/data/d2','/data/d3','/data/d4','/data/d5','/data/d6'] [membase] rest_username:Administrator rest_password:<PASSWORD> [servers] 1:_1 2:_2 3:_3 4:_4 5:_5 6:_6 7:_7 8:_8 9:_9 10:_10 [_1] ip:172.23.96.18 port:8091 services:kv [_2] ip:172.23.96.207 port:8091 services:n1ql,index [_3] ip:172.23.96.209 port:8091 services:kv [_4] ip:172.23.96.210 port:8091 services:kv [_5] ip:172.23.96.212 port:8091 services:cbas [_6] ip:172.23.96.48 port:8091 services:cbas [_7] ip:172.23.96.14 port:8091 services:cbas [_8] ip:172.23.96.214 port:8091 services:cbas [_9] ip:172.23.96.254 port:8091 services:kv [_10] ip:172.23.96.122 port:8091 services:kv
1ecf7118d68d43bb54894771fddb9930a690a6b6
[ "Python", "INI" ]
2
Python
ritalrw/Jython
7e2d316b3f6be4533040308c83dfa52f34894d92
5929d55bd0154521ad1a8375940deacfbbc624a6
refs/heads/master
<repo_name>mvines/silk-camera-facedetect<file_sep>/index.js 'use strict'; const log = require('silk-alog'); const Camera = require('silk-camera').default; const path = require('path'); const FACE_CASCADE = path.join(__dirname, 'haarcascade_frontalface_alt.xml'); require('./device').init(); let camera = new Camera(); camera.init() .then(() => { log.info('camera initialized'); camera.startRecording(); }); let busy = false; camera.on('frame', (when, image) => { if (busy) { // If the previous haar cascade is still running, skip this frame return; } if (image.width() < 1 || image.height() < 1) throw new Error('Image has no size'); busy = true; image.detectObject(FACE_CASCADE, {}, (err, faces) => { busy = false; if (err) throw err; if (faces.length === 0) { log.info('No faces detected'); } else { log.info(faces.length + ' faces detected'); for (let i = 0; i < faces.length; i++) { const face = faces[i]; image.ellipse(face.x + face.width / 2, face.y + face.height / 2, face.width / 2, face.height / 2); } const filename = '/data/faces.png'; image.save(filename); log.info('Saved ' + filename); } }); }); <file_sep>/README.md # silk-camera-facedetect Demo of basic face detection using Silk # Usage 1. Flash the Kenzo device with the latest Silk platform 2. `silk run` this program 3. When the face is detected, the camera frame will be saved to `/data/faces.png` on device. Use `adb pull /data/faces.png` to retrieve it
a120faee893b8ef8bb762a328a986bcd537112de
[ "JavaScript", "Markdown" ]
2
JavaScript
mvines/silk-camera-facedetect
62212a315e5a99fe5253aa78676c3c3fde5d9329
7e881e77c4f6b03f003c2804e24586516fe3a289
refs/heads/master
<repo_name>nicmr/sensor-tiles<file_sep>/README.md # sensor-tiles ![](https://github.com/nicmr/sensor-tiles/workflows/Build%20and%20Test/badge.svg) [![npm version](https://img.shields.io/npm/v/@gwenmohr/sensor-tiles-js)](https://www.npmjs.com/@gwenmohr/sensor-tiles-js) Algorithms for our geographical data visualization project that maps and interpolates sensor data onto a 2D tile matrix. Written in Purescript, targeting Javascript. ## How to call from javascript ### Installing with npm Install the package as a dependency with npm ```shell npm install --save-dev @gwenmohr/sensor-tiles-js ``` Now you have the choice between two ways of calling the library. ### A: JS wrapper (Recommended) To allow for idiomatic multi-parameter calls from javascript to our purescript code, we've written a javascript wrapper. It will also deep freeze all returned objects, making them completely immutable. ```js var Tiles = require ('@gwenmohr/sensor-tiles-js'); // ... let w = 4; let h = 6; let tile_matrix = Tiles.init(w,h); // frozen let sensor_x = 2; let sensor_y = 3; let sensor_value = 2.5 let with_sensor = Tiles.insertSensor(sensor_x, sensor_y, sensor_value, tile_matrix); // frozen console.log(with_sensor); ``` ### B: Direct calls (Not recommended) The compiled purescript code can also be called directly. Some precautions have to be taken to prevent possible errors in that case. #### Immutability You should treat all objects returned by the Tiles module as immutable if you plan to eventually pass them back to another function exposed by the module. Immutability on the javascript side can be achieved by using the shallow freeze `Object.freeze()` or an appropriate deep freeze function. Read more about freezing objects and how to spin up a deep freeze function in the [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze). If you don't freeze the objects and mutate them manually, you risk breaking them. #### Curried By default, the exposed purescript functions are compiled to curried javascript functions, i.e. function parameters have to be applied one by one. ```js var Tiles = require ('@gwenmohr/sensor-tiles-js'); // curried functions are available under the PS (purescript) object var TilesPS = Tiles.PS; // ... let w = 4; let h = 6; let tile_matrix = TilesPS.init(w)(h); Object.freeze(tile_matrix) let sensor_x = 2; let sensor_y = 3; let sensor_value = 2.5 let with_sensor = TilesPS.insertSensor(sensor_x)(sensor_y)(sensor_value)(tile_matrix); Object.freeze(tile_matrix) console.log(with_sensor); ``` ## Developers: How to build ```shell # using your globally installed `spago` and `purs` spago build # using the recommended version of `spago` and `purs` from the npm dependencies # run once npm install # run each build, (up to 50% faster than npm install) npm run-script install ``` <file_sep>/TilesWrapper.js var PS = require ('./TilesPS.js'); /** Generates a two-dimensional matrix of tiles without any sensors. * @param { number } x - The horizontal size of the matrix * @param { number } x - The vertical size of the matrix */ function init (x,y) { return deepFreeze(PS.init(x)(y)); } /** Inserts a sensor into the tile matrix. * @param { Number } x - The x coordinate of the sensor * @param { Number } y - The y coordinate of the sensor * @param { Number } value - The value of the sensor * @param { TileMatrix } matrix - The tile matrix the sensor should be inserted in */ function insertSensor(x, y, value, matrix) { return deepFreeze(PS.insertSensor(x)(y)(value)(matrix)); } /** Creates a `MapBound`. Required for initiating a coordinate matrix * @param { Number } north * @param { Number } south * @param { Number } west * @param { Number } east */ function createMapBounds(north, south, west, east) { return deepFreeze(PS.createMapBounds(north)(south)(west)(east)); } /** Inserts a sensor into the coordinate matrix and returns the resulting matrix * @param { MapBounds } mapbounds - MapBounds returned by `createMapBounds` * @param { int } cellcount - desired cellcount. Has to be a natural number */ function initCoordMatrix(mapbounds, cellcount) { return deepFreeze(PS.initCoordMatrix(mapbounds)(cellcount)); } /** Creates `CoordSensor` at the specified coordinates * @param { Number } latitude * @param { Number } longitude * @param { Number } value */ function createCoordSensor(latitude, longitude, value) { return deepFreeze(PS.createCoordSensor(latitude)(longitude)(value)); } /** Inserts a sensor into the coordinate matrix and returns the resulting matrix * @param { CoordSensor } coordSensor - A sensor returned by `createCoordSensor` * @param { CoordMatrix } coordMatrix - A matrix returned by `initCoordMatrix` */ function insertCoordSensor(coordSensor, coordMatrix) { return deepFreeze(PS.insertCoordSensor(coordSensor)(coordMatrix)); } /** Inserts many sensors and returns the resulting matrix * @param { Array CoordSensor } coordSensors - An array of sensors created by `createCoordSensor` * @param { CoordMatrix } coordMatrix - A matrix returned by `initCoordMatrix` */ function insertManyCoordSensors(sensorArray, coordMatrix) { return deepFreeze(PS.insertManyCoordSensors(sensorArray)(coordMatrix)); } // -- deepFreeze snippet by Mozilla, public domain under (CC0) // -- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze function deepFreeze(object) { // Retrieve the property names defined on object var propNames = Object.getOwnPropertyNames(object); // Freeze properties before freezing self for (let name of propNames) { let value = object[name]; object[name] = value && typeof value === "object" ? deepFreeze(value) : value; } return Object.freeze(object); } // -- end of deepFreeze snippet module.exports = { init, insertSensor, PS, createMapBounds, createCoordSensor, insertCoordSensor, initCoordMatrix, insertManyCoordSensors }
b5bb19337bfa9c8051765e2bc9494060db5d7349
[ "Markdown", "JavaScript" ]
2
Markdown
nicmr/sensor-tiles
3f1944d53489e453ac7e3877c765894286fc4115
b9b0ce4d38fd86fb50ed79fd990b775faca4e006
refs/heads/master
<repo_name>dungeon2567/edgedb<file_sep>/docs/edgeql/functions/setagg.rst .. _ref_eql_functions_setagg: ========== Aggregates ========== :index: set aggregate .. eql:function:: std::count(s: SET OF anytype) -> int64 :index: aggregate Return the number of elements in a set. .. code-block:: edgeql-repl db> SELECT count({2, 3, 5}); {3} db> SELECT count(User); # number of User objects in db {4} .. eql:function:: std::sum(s: SET OF anyreal) -> anyreal :index: aggregate Return the sum of the set of numbers. The numbers have to be either :eql:type:`anyreal` or any type that can be cast into it, such as :eql:type:`float64` or :eql:type:`int64`. .. code-block:: edgeql-repl db> SELECT sum({2, 3, 5}); {10} db> SELECT sum({0.2, 0.3, 0.5}); {1.0} Here's a list of aggregate functions covered in other sections: * :eql:func:`array_agg` <file_sep>/edb/server2/backend/__init__.py # # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # 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. # import weakref from edb.lang.common import taskgroup from edb.server2 import pgcon from edb.server2 import procpool from . import compiler from .dbview import DatabaseIndex __all__ = ('DatabaseIndex', 'BackendManager') class Backend: def __init__(self, pgcon, compiler): self._pgcon = pgcon self._compiler = compiler @property def pgcon(self): return self._pgcon @property def compiler(self): return self._compiler async def close(self): self._pgcon.terminate() self._compiler.close() class BackendManager: def __init__(self, *, pgaddr, runstate_dir, data_dir): self._pgaddr = pgaddr self._runstate_dir = runstate_dir self._data_dir = data_dir self._backends = weakref.WeakSet() self._compiler_manager = None async def start(self): self._compiler_manager = await procpool.create_manager( runstate_dir=self._runstate_dir, name='edgedb-compiler', worker_cls=compiler.Compiler, worker_args=(dict(host=self._pgaddr), self._data_dir)) async def stop(self): # TODO: Make a graceful version of this. try: async with taskgroup.TaskGroup() as g: for backend in self._backends: g.create_task(backend.close()) finally: await self._compiler_manager.stop() async def new_backend(self, *, dbname: str, dbver: int): try: compiler = None async with taskgroup.TaskGroup() as g: new_pgcon = g.create_task( pgcon.connect(self._pgaddr, dbname)) compiler = await self._compiler_manager.spawn_worker() g.create_task( compiler.call('connect', dbname, dbver)) except Exception: try: if compiler is not None: compiler.close() finally: if (new_pgcon.done() and not new_pgcon.cancelled() and not new_pgcon.exception()): con = new_pgcon.result() con.abort() raise backend = Backend(new_pgcon.result(), compiler) self._backends.add(backend) return backend <file_sep>/edb/server2/backend/dbstate.py # # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # 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. # import dataclasses import enum import time import typing import immutables from edb.lang.schema import schema as s_schema class TxAction(enum.IntEnum): START = 1 COMMIT = 2 ROLLBACK = 3 class BaseQuery: pass @dataclasses.dataclass(frozen=True) class Query(BaseQuery): sql: bytes sql_hash: bytes out_type_data: bytes out_type_id: bytes in_type_data: bytes in_type_id: bytes @dataclasses.dataclass(frozen=True) class SimpleQuery(BaseQuery): sql: bytes @dataclasses.dataclass(frozen=True) class SessionStateQuery(BaseQuery): sess_set_modaliases: typing.Mapping[typing.Optional[str], str] = None sess_reset_modaliases: typing.Set[typing.Optional[str]] = None sess_set_config: typing.Mapping[str, typing.Union[str, bool]] = None sess_reset_config: typing.Set[str] = None @dataclasses.dataclass(frozen=True) class DDLQuery(BaseQuery): sql: bytes @dataclasses.dataclass(frozen=True) class TxControlQuery(BaseQuery): sql: bytes action: TxAction ############################# @dataclasses.dataclass class QueryUnit: dbver: int txid: typing.Optional[int] sql: bytes = b'' sql_hash: bytes = b'' has_ddl: bool = False commits_tx: bool = False rollbacks_tx: bool = False starts_tx: bool = False out_type_data: bytes = b'' out_type_id: bytes = b'' in_type_data: bytes = b'' in_type_id: bytes = b'' config: typing.Optional[immutables.Map] = None modaliases: typing.Optional[immutables.Map] = None def is_preparable(self): """Answers the question: can this query be prepared and cached?""" prep = bool(self.sql and self.sql_hash and self.out_type_data) assert not prep or (not self.config and not self.modaliases and not self.has_ddl and not self.commits_tx and not self.rollbacks_tx and not self.starts_tx) return prep ############################# @dataclasses.dataclass class TransactionState: name: str schema: s_schema.Schema modaliases: immutables.Map config: immutables.Map class Transaction: def __init__(self, schema: s_schema.Schema, modaliases: immutables.Map, config: immutables.Map, *, implicit=True): self._id = time.monotonic_ns() self._implicit = implicit self._stack = [] self._stack.append( TransactionState( name=None, schema=schema, modaliases=modaliases, config=config)) @property def id(self): return self._id def is_implicit(self): return self._implicit def make_explicit(self): if self._implicit: self._implicit = False else: raise RuntimeError('already in explicit transaction') def make_savepoint(self, name: str): self._stack.append( TransactionState( name=name, schema=self.get_schema(), modaliases=self.get_modaliases(), config=self.get_config())) def restore_savepoint(self, name: str): new_stack = self._stack.copy() while new_stack: last_state = new_stack.pop() if last_state.name == name: self._stack = new_stack return raise RuntimeError(f'there is no {name!r} savepoint') def get_schema(self) -> s_schema.Schema: return self._stack[-1].schema def get_modaliases(self) -> immutables.Map: return self._stack[-1].modaliases def get_config(self) -> immutables.Map: return self._stack[-1].config def update_schema(self, new_schema: s_schema.Schema): self._stack[-1].schema = new_schema def update_modaliases(self, new_modaliases: immutables.Map): self._stack[-1].modaliases = new_modaliases def update_config(self, new_config: immutables.Map): self._stack[-1].config = new_config class CompilerConnectionState: def __init__(self, dbver: int, schema: s_schema.Schema, modaliases: immutables.Map, config: immutables.Map): self._dbver = dbver self._schema = schema self._modaliases = modaliases self._config = config self._init_current_tx() def _init_current_tx(self): self._current_tx = Transaction( self._schema, self._modaliases, self._config) @property def dbver(self): return self._dbver def current_tx(self) -> Transaction: return self._current_tx def start_tx(self): if self._current_tx.is_implicit(): self._current_tx.make_explicit() else: raise RuntimeError('already in transaction') def rollback_tx(self): if self._current_tx.is_implicit(): raise RuntimeError('cannot rollback: not in transaction') self._init_current_tx() def commit_tx(self): if self._current_tx.is_implicit(): raise RuntimeError('cannot commit: not in transaction') self._schema = self._current_tx.get_schema() self._modaliases = self._current_tx.get_modaliases() self._config = self._current_tx.get_config() self._init_current_tx() <file_sep>/docs/edgeql/functions/string.rst .. _ref_eql_functions_string: String ====== .. eql:function:: std::lower(string: str) -> str Return a lowercase copy of the input string. .. code-block:: edgeql-repl db> SELECT lower('Some Fancy Title'); {'some fancy title'} .. eql:function:: std::str_to_json(string: str) -> json :index: json parse loads Return JSON value represented by the input string. This is the reverse of :eql:func:`json_to_str`. .. code-block:: edgeql-repl db> SELECT str_to_json('[1, "foo", null]'); {[1, 'foo', None]} db> SELECT str_to_json('{"hello": "world"}'); {{hello: 'world'}} .. eql:function:: std::re_match(pattern: str, \ string: str) -> array<str> :index: regex regexp regular Find the first regular expression match in a string. Given an input string and a regular expression string find the first match for the regular expression within the string. Return the match, each match represented by an :eql:type:`array\<str\>` of matched groups. .. code-block:: edgeql-repl db> SELECT std::re_match(r'\w{4}ql', 'I ❤️ edgeql'); {['edgeql']} .. eql:function:: std::re_match_all(pattern: str, \ string: str) -> SET OF array<str> :index: regex regexp regular Find all regular expression matches in a string. Given an input string and a regular expression string repeatedly match the regular expression within the string. Return the set of all matches, each match represented by an :eql:type:`array\<str\>` of matched groups. .. code-block:: edgeql-repl db> SELECT std::re_match_all(r'a\w+', 'an abstract concept'); {['an'], ['abstract']} .. eql:function:: std::re_replace(pattern: str, repl: str, \ string: str, \ NAMED ONLY flags: str='') \ -> str :index: regex regexp regular replace Replace matching substrings in a given string. Given an input string and a regular expression string replace matching substrings with the replacement string. Optional :ref:`flag <string_regexp_flags>` argument can be used to specify additional regular expression flags. Return the string resulting from substring replacement. .. code-block:: edgeql-repl db> SELECT std::re_replace(r'l', r'L', 'Hello World', flags := 'g'); {'HeLLo WorLd'} .. eql:function:: std::re_test(pattern: str, string: str) -> bool :index: regex regexp regular match Test if a regular expression has a match in a string. Given an input string and a regular expression string test whether there is a match for the regular expression within the string. Return ``True`` if there is a match, ``False`` otherwise. .. code-block:: edgeql-repl db> SELECT std::re_test(r'a', 'abc'); {True} Regular Expressions ------------------- EdgeDB supports Regular expressions (REs), as defined in POSIX 1003.2. They come in two forms: BRE (basic RE) and ERE (extended RE). In addition to that EdgeDB supports certain common extensions to the POSIX standard commonly known as ARE (advanced RE). More details about BRE, ERE, and ARE support can be found in `PostgreSQL documentation`_. .. _`PostgreSQL documentation`: https://www.postgresql.org/docs/10/static/ functions-matching.html#POSIX-SYNTAX-DETAILS For convenience, here's a table outlining the different options accepted as the ``flag`` argument to various regular expression functions: .. _string_regexp_flags: Option Flags ^^^^^^^^^^^^ ====== ================================================================== Option Description ====== ================================================================== ``b`` rest of RE is a BRE ``c`` case-sensitive matching (overrides operator type) ``e`` rest of RE is an ERE ``i`` case-insensitive matching (overrides operator type) ``m`` historical synonym for n ``n`` newline-sensitive matching ``p`` partial newline-sensitive matching ``q`` rest of RE is a literal ("quoted") string, all ordinary characters ``s`` non-newline-sensitive matching (default) ``t`` tight syntax (default) ``w`` inverse partial newline-sensitive ("weird") matching ``x`` expanded syntax ignoring white-space characters ====== ================================================================== <file_sep>/edb/lang/edgeql/compiler/inference/cardinality.py # # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # 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. # import functools import typing from edb import errors from edb.lang.edgeql import functypes as ql_ft from edb.lang.schema import objtypes as s_objtypes from edb.lang.schema import pointers as s_pointers from edb.lang.schema import schema as s_schema from edb.lang.schema import sources as s_sources from edb.lang.ir import ast as irast ONE = irast.Cardinality.ONE MANY = irast.Cardinality.MANY def _get_set_scope( ir_set: irast.Set, scope_tree: irast.ScopeTreeNode) -> irast.ScopeTreeNode: new_scope = None if ir_set.path_scope_id: new_scope = scope_tree.root.find_by_unique_id(ir_set.path_scope_id) if new_scope is None: new_scope = scope_tree return new_scope def _max_cardinality(args): if all(a == ONE for a in args): return ONE else: return MANY def _common_cardinality(args, scope_tree, schema): return _max_cardinality( infer_cardinality(a, scope_tree, schema) for a in args) @functools.singledispatch def _infer_cardinality(ir, scope_tree, schema): raise ValueError(f'infer_cardinality: cannot handle {ir!r}') @_infer_cardinality.register(type(None)) def __infer_none(ir, scope_tree, schema): # Here for debugging purposes. raise ValueError('invalid infer_cardinality(None, schema) call') @_infer_cardinality.register(irast.Statement) def __infer_statement(ir, scope_tree, schema): return infer_cardinality(ir.expr, scope_tree, schema) @_infer_cardinality.register(irast.EmptySet) def __infer_emptyset(ir, scope_tree, schema): return ONE @_infer_cardinality.register(irast.TypeRef) def __infer_typeref(ir, scope_tree, schema): return ONE @_infer_cardinality.register(irast.Set) def __infer_set(ir, scope_tree, schema): parent_fence = scope_tree.parent_fence if parent_fence is not None: if scope_tree.namespaces: path_id = ir.path_id.strip_namespace(scope_tree.namespaces) else: path_id = ir.path_id if parent_fence.is_visible(path_id): return ONE if ir.rptr is not None: if ir.rptr.ptrcls.singular(schema, ir.rptr.direction): new_scope = _get_set_scope(ir, scope_tree) return infer_cardinality(ir.rptr.source, new_scope, schema) else: return MANY elif ir.expr is not None: new_scope = _get_set_scope(ir, scope_tree) return infer_cardinality(ir.expr, new_scope, schema) else: return MANY @_infer_cardinality.register(irast.OperatorCall) @_infer_cardinality.register(irast.FunctionCall) def __infer_func_call(ir, scope_tree, schema): # the cardinality of the function call depends on the cardinality # of non-SET_OF arguments AND the cardinality of the function # return value SET_OF = ql_ft.TypeModifier.SET_OF if ir.typemod is ql_ft.TypeModifier.SET_OF: return MANY else: # assume that the call is valid and the signature has been matched args = [] # process positional args for arg, typemod in zip(ir.args, ir.params_typemods): if typemod is not SET_OF: args.append(arg) if args: return _common_cardinality(args, scope_tree, schema) else: return ONE @_infer_cardinality.register(irast.BaseConstant) @_infer_cardinality.register(irast.Parameter) def __infer_const_or_param(ir, scope_tree, schema): return ONE @_infer_cardinality.register(irast.Coalesce) def __infer_coalesce(ir, scope_tree, schema): return _common_cardinality([ir.left, ir.right], scope_tree, schema) @_infer_cardinality.register(irast.SetOp) def __infer_setop(ir, scope_tree, schema): if ir.op == 'UNION': if not ir.exclusive: # Exclusive UNIONs are generated from IF ELSE expressions. result = MANY else: result = _common_cardinality( [ir.left, ir.right], scope_tree, schema) else: result = infer_cardinality(ir.left, scope_tree, schema) return result @_infer_cardinality.register(irast.TypeCheckOp) def __infer_typecheckop(ir, scope_tree, schema): return infer_cardinality(ir.left, scope_tree, schema) @_infer_cardinality.register(irast.IfElseExpr) def __infer_ifelse(ir, scope_tree, schema): return _common_cardinality([ir.if_expr, ir.else_expr, ir.condition], scope_tree, schema) @_infer_cardinality.register(irast.TypeCast) def __infer_typecast(ir, scope_tree, schema): return infer_cardinality(ir.expr, scope_tree, schema) def _is_ptr_or_self_ref( ir_expr: irast.Base, srccls: s_sources.Source, schema: s_schema.Schema) -> bool: if not isinstance(ir_expr, irast.Set): return False else: ir_set = ir_expr return ( isinstance(srccls, s_objtypes.ObjectType) and ir_set.expr is None and (ir_set.stype == srccls or ( ir_set.rptr is not None and srccls.getptr( schema, ir_set.rptr.ptrcls.get_shortname(schema).name) is not None )) ) def _extract_filters( result_set: irast.Set, ir_set: irast.Set, scope_tree: typing.Set[irast.PathId], schema: s_schema.Schema) -> typing.Sequence[s_pointers.Pointer]: scope_tree = _get_set_scope(ir_set, scope_tree) ptr_filters = [] expr = ir_set.expr if isinstance(expr, irast.OperatorCall): if expr.func_shortname == 'std::=': left, right = expr.args op_card = _common_cardinality( [left, right], scope_tree, schema) if op_card == MANY: pass elif _is_ptr_or_self_ref(left, result_set.stype, schema): if infer_cardinality(right, scope_tree, schema) == ONE: if left.stype == result_set.stype: ptr_filters.append(left.stype.getptr(schema, 'id')) else: ptr_filters.append(left.rptr.ptrcls) elif _is_ptr_or_self_ref(right, result_set.stype, schema): if infer_cardinality(left, scope_tree, schema) == ONE: if right.stype == result_set.stype: ptr_filters.append(right.stype.getptr(schema, 'id')) else: ptr_filters.append(right.rptr.ptrcls) elif expr.func_shortname == 'std::AND': left, right = expr.args ptr_filters.extend( _extract_filters(result_set, left, scope_tree, schema)) ptr_filters.extend( _extract_filters(result_set, right, scope_tree, schema)) return ptr_filters def _analyse_filter_clause( result_set: irast.Set, filter_clause: irast.Set, scope_tree: typing.Set[irast.PathId], schema: s_schema.Schema) -> irast.Cardinality: filtered_ptrs = _extract_filters(result_set, filter_clause, scope_tree, schema) if filtered_ptrs: exclusive_constr = schema.get('std::exclusive') for ptr in filtered_ptrs: is_unique = ( ptr.is_id_pointer(schema) or any(c.issubclass(schema, exclusive_constr) for c in ptr.get_constraints(schema).objects(schema)) ) if is_unique: # Bingo, got an equality filter on a link with a # unique constraint return ONE return MANY def _infer_stmt_cardinality( result_set: irast.Set, filter_clause: typing.Optional[irast.Set], scope_tree: typing.Set[irast.PathId], schema: s_schema.Schema) -> irast.Cardinality: result_card = infer_cardinality(result_set, scope_tree, schema) if result_card == ONE or filter_clause is None: return result_card return _analyse_filter_clause( result_set, filter_clause, scope_tree, schema) @_infer_cardinality.register(irast.SelectStmt) def __infer_select_stmt(ir, scope_tree, schema): if ir.cardinality: return ir.cardinality else: if (ir.limit is not None and isinstance(ir.limit.expr, irast.IntegerConstant) and ir.limit.expr.value == '1'): # Explicit LIMIT 1 clause. stmt_card = ONE else: stmt_card = _infer_stmt_cardinality( ir.result, ir.where, scope_tree, schema) if ir.iterator_stmt: iter_card = infer_cardinality(ir.iterator_stmt, scope_tree, schema) stmt_card = _max_cardinality((stmt_card, iter_card)) return stmt_card @_infer_cardinality.register(irast.InsertStmt) def __infer_insert_stmt(ir, scope_tree, schema): if ir.cardinality: return ir.cardinality else: if ir.iterator_stmt: return infer_cardinality(ir.iterator_stmt, scope_tree, schema) else: # INSERT without a FOR is always a singleton. return ONE @_infer_cardinality.register(irast.UpdateStmt) @_infer_cardinality.register(irast.DeleteStmt) def __infer_update_delete_stmt(ir, scope_tree, schema): if ir.cardinality: return ir.cardinality else: stmt_card = _infer_stmt_cardinality( ir.subject, ir.where, scope_tree, schema) if ir.iterator_stmt: iter_card = infer_cardinality(ir.iterator_stmt, scope_tree, schema) stmt_card = _max_cardinality((stmt_card, iter_card)) return stmt_card @_infer_cardinality.register(irast.Stmt) def __infer_stmt(ir, scope_tree, schema): if ir.cardinality: return ir.cardinality else: return infer_cardinality(ir.result, scope_tree, schema) @_infer_cardinality.register(irast.SliceIndirection) def __infer_slice(ir, scope_tree, schema): # slice indirection cardinality depends on the cardinality of # the base expression and the slice index expressions args = [ir.expr] if ir.start is not None: args.append(ir.start) if ir.stop is not None: args.append(ir.stop) return _common_cardinality(args, scope_tree, schema) @_infer_cardinality.register(irast.IndexIndirection) def __infer_index(ir, scope_tree, schema): # index indirection cardinality depends on both the cardinality of # the base expression and the index expression return _common_cardinality([ir.expr, ir.index], scope_tree, schema) @_infer_cardinality.register(irast.Array) def __infer_array(ir, scope_tree, schema): return _common_cardinality(ir.elements, scope_tree, schema) @_infer_cardinality.register(irast.Tuple) def __infer_tuple(ir, scope_tree, schema): return _common_cardinality( [el.val for el in ir.elements], scope_tree, schema) @_infer_cardinality.register(irast.TupleIndirection) def __infer_tuple_indirection(ir, scope_tree, schema): # the cardinality of the tuple indirection is the same as the # cardinality of the underlying tuple return infer_cardinality(ir.expr, scope_tree, schema) def infer_cardinality(ir, scope_tree, schema): try: return ir._inferred_cardinality_[scope_tree] except (AttributeError, KeyError): pass result = _infer_cardinality(ir, scope_tree, schema) if result not in {ONE, MANY}: raise errors.QueryError( 'could not determine the cardinality of ' 'set produced by expression', context=ir.context) try: cache = ir._inferred_cardinality_ except AttributeError: cache = ir._inferred_cardinality_ = {} cache[scope_tree] = result return result <file_sep>/docs/edgeql/functions/array.rst .. _ref_eql_functions_array: ===== Array ===== .. eql:function:: std::array_agg(s: SET OF anytype) -> array<anytype> :index: aggregate array set Return the array made from all of the input set elements. The ordering of the input set will be preserved if specified. .. code-block:: edgeql-repl db> SELECT array_agg({2, 3, 5}); {[2, 3, 5]} db> SELECT array_agg(User.name ORDER BY User.name); {['Alice', 'Bob', 'Joe', 'Sam']} .. eql:function:: std::array_contains(array: array<anytype>, \ value: anytype) -> bool Return ``TRUE`` if the array contains the specified element. .. code-block:: edgeql-repl db> SELECT array_contains([2, 3, 5], 2); {True} db> SELECT array_contains(['foo', 'bar'], 'baz'); {False} .. eql:function:: std::array_enumerate(array: array<anytype>) -> \ SET OF tuple<anytype, int64> :index: enumerate index array Return a set of tuples of the form ``(element, index)``. Return a set of tuples where the first element is an array value and the second element is the index of that value for all values in the array. .. note:: The ordering of the returned set is not guaranteed. .. code-block:: edgeql-repl db> SELECT array_enumerate([2, 3, 5]); {(3, 1), (2, 0), (5, 2)} .. eql:function:: std::array_get(array: array<anytype>, \ index: int64, \ NAMED ONLY default: anytype = {} \ ) -> OPTIONAL anytype :index: array access get Return the element of the *array* at the specified *index*. If the *index* is out of array bounds, the *default* or ``{}`` is returned. This works the same as :ref:`array element referencing operator<ref_eql_expr_array_elref>` except that if the index is outside array boundaries an empty set of the array element type is returned instead of raising an exception. .. code-block:: edgeql-repl db> SELECT array_get([2, 3, 5], 1); {3} db> SELECT array_get([2, 3, 5], 100); {} db> SELECT array_get([2, 3, 5], 100, default := 42); {42} .. eql:function:: std::array_unpack(array: array<anytype>) -> SET OF anytype :index: set array unpack Return array elements as a set. .. note:: The ordering of the returned set is not guaranteed. .. code-block:: edgeql-repl db> SELECT array_unpack([2, 3, 5]); {3, 2, 5} <file_sep>/edb/server2/backend/dbview.py # # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # 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. # import time import typing import immutables from edb.server import defines from edb.lang.common import lru from . import dbstate __all__ = ('DatabaseIndex', 'DatabaseConnectionView') class Database: # Global LRU cache of compiled anonymous queries _eql_to_compiled: typing.Mapping[bytes, dbstate.QueryUnit] def __init__(self, name): self._name = name self._dbver = time.monotonic_ns() self._eql_to_compiled = lru.LRUMapping( maxsize=defines._MAX_QUERIES_CACHE) def _signal_ddl(self): self._dbver = time.monotonic_ns() # Advance the version self._invalidate_caches() def _invalidate_caches(self): self._eql_to_compiled.clear() def _cache_compiled_query(self, eql: bytes, json_mode: bool, compiled: dbstate.QueryUnit): assert compiled.is_preparable() key = (eql, json_mode) existing = self._eql_to_compiled.get(key) if existing is not None and existing.dbver > compiled.dbver: # We already have a cached query for a more recent DB version. return self._eql_to_compiled[key] = compiled def _new_view(self, *, user): return DatabaseConnectionView(self, user=user) class DatabaseConnectionView: _eql_to_compiled: typing.Mapping[bytes, dbstate.QueryUnit] def __init__(self, db: Database, *, user): self._db = db self._user = user self._config = immutables.Map() self._modaliases = immutables.Map({None: 'default'}) # Whenever we are in a transaction that had executed a # DDL command, we use this cache for compiled queries. self._eql_to_compiled = lru.LRUMapping( maxsize=defines._MAX_QUERIES_CACHE) self._new_tx_state() def _invalidate_local_cache(self): self._eql_to_compiled.clear() def _new_tx_state(self): self._txid = None self._in_tx = False self._in_tx_with_ddl = False self._tx_error = False def rollback(self): self._new_tx_state() @property def config(self): return self._config @property def modaliases(self): return self._modaliases @property def txid(self): return self._txid @property def in_tx(self): return self._in_tx @property def user(self): return self._user @property def dbver(self): return self._db._dbver @property def dbname(self): return self._db._name def cache_compiled_query(self, eql: bytes, json_mode: bool, compiled: dbstate.QueryUnit): if self._in_tx_with_ddl: self._eql_to_compiled[(eql, json_mode)] = compiled else: self._db._cache_compiled_query(eql, json_mode, compiled) def lookup_compiled_query( self, eql: bytes, json_mode: bool) -> typing.Optional[dbstate.QueryUnit]: compiled: dbstate.QueryUnit key = (<KEY> if self._in_tx_with_ddl: compiled = self._eql_to_compiled.get(key) else: compiled = self._db._eql_to_compiled.get(key) if compiled is not None and compiled.dbver != self.dbver: compiled = None return compiled def tx_error(self): if self._in_tx: self._tx_error = True def start(self, qu: dbstate.QueryUnit): self._txid = qu.txid if qu.starts_tx: self._in_tx = True if qu.has_ddl: self._in_tx_with_ddl def on_error(self, qu: dbstate.QueryUnit): self.tx_error() def on_success(self, qu: dbstate.QueryUnit): if not self._in_tx and qu.has_ddl: self._db._signal_ddl() if qu.commits_tx: assert self._in_tx if self._in_tx_with_ddl: self._db._signal_ddl() self._new_tx_state() elif qu.rollbacks_tx: assert self._in_tx self._new_tx_state() if qu.config: self._config = qu.config if qu.modaliases: self._modaliases = qu.modaliases class DatabaseIndex: def __init__(self): self._dbs = {} def new_view(self, dbname: str, *, user: str) -> DatabaseConnectionView: try: db = self._dbs[dbname] except KeyError: db = Database(dbname) self._dbs[dbname] = db return db._new_view(user=user) <file_sep>/Makefile .PHONY: docs SPHINXOPTS:="-W -n" docs: find docs -name '*.rst' | xargs touch $(MAKE) -C docs html SPHINXOPTS=$(SPHINXOPTS) BUILDDIR="../build" <file_sep>/tests/test_server_procpool.py # # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # 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. # import asyncio import os import signal import tempfile import uvloop from edb.server import _testbase as tb from edb.server2 import procpool from edb.lang.common import taskgroup class MyExc(Exception): pass class Worker: def __init__(self, o): self._o = o self._i = 0 async def test1(self, t): self._i += 1 await asyncio.sleep(t) return self._i async def test2(self): return self._o async def test3(self): 1 / 0 async def test4(self): e = MyExc() e.special = 'spam' raise e async def test5(self): class WillCrashPickle(Exception): pass raise WillCrashPickle class TestProcPool(tb.TestCase): @classmethod def setUpClass(cls): asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) super().setUpClass() @classmethod def tearDownClass(cls): try: super().tearDownClass() finally: asyncio.set_event_loop_policy(None) def setUp(self): self._dir = tempfile.TemporaryDirectory() self.runstate_dir = self._dir.name def tearDown(self): self._dir.cleanup() self._dir = None async def test_procpool_1(self): pool = await procpool.create_pool( max_capacity=1, min_capacity=1, runstate_dir=self.runstate_dir, worker_cls=Worker, worker_args=([123],), name='test_procpool_1') try: i1 = asyncio.create_task(pool.call('test1', 0.1)) i2 = asyncio.create_task(pool.call('test1', 0.05)) i1 = await i1 i2 = await i2 self.assertEqual(i1, 1) self.assertEqual(i2, 2) finally: await pool.stop() async def test_procpool_2(self): pool = await procpool.create_pool( max_capacity=5, min_capacity=5, runstate_dir=self.runstate_dir, worker_cls=Worker, worker_args=([123],), name='test_procpool_2') try: tasks = [] for i in range(20): tasks.append(asyncio.create_task(pool.call('test1', 0.1))) await asyncio.gather(*tasks) finally: await pool.stop() results = [t.result() for t in tasks] self.assertEqual(results, [ 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4 ]) async def test_procpool_3(self): pool = await procpool.create_pool( max_capacity=5, min_capacity=5, runstate_dir=self.runstate_dir, worker_cls=Worker, worker_args=([123],), name='test_procpool_3') try: r = await pool.call('test2') finally: await pool.stop() self.assertEqual(r, [123]) async def test_procpool_4(self): pool = await procpool.create_pool( max_capacity=1, min_capacity=1, runstate_dir=self.runstate_dir, worker_cls=Worker, worker_args=([123],), name='test_procpool_4') try: with self.assertRaises(ZeroDivisionError): await pool.call('test3') self.assertEqual(await pool.call('test1', 0.1), 1) with self.assertRaises(ZeroDivisionError): await pool.call('test3') self.assertEqual(await pool.call('test1', 0.1), 2) finally: await pool.stop() async def test_procpool_5(self): pool = await procpool.create_pool( max_capacity=1, min_capacity=1, runstate_dir=self.runstate_dir, worker_cls=Worker, worker_args=([123],), name='test_procpool_5') try: t1 = asyncio.create_task(pool.call('test3')) t2 = asyncio.create_task(pool.call('test1', 0.1)) t3 = asyncio.create_task(pool.call('test3')) t4 = asyncio.create_task(pool.call('test1', 0.1)) await asyncio.gather(t1, t2, t3, t4, return_exceptions=True) with self.assertRaises(ZeroDivisionError): await t1 with self.assertRaises(ZeroDivisionError): await t3 self.assertEqual(t2.result(), 1) self.assertEqual(t4.result(), 2) finally: await pool.stop() async def test_procpool_6(self): pool = await procpool.create_pool( max_capacity=1, min_capacity=1, runstate_dir=self.runstate_dir, worker_cls=Worker, worker_args=([123],), name='test_procpool_6') try: with self.assertRaises(MyExc) as e: await pool.call('test4') self.assertEqual(e.exception.special, 'spam') finally: await pool.stop() async def test_procpool_7(self): pool = await procpool.create_pool( max_capacity=1, min_capacity=1, runstate_dir=self.runstate_dir, worker_cls=Worker, worker_args=([123],), name='test_procpool_7') try: with self.assertRaisesRegex(RuntimeError, 'pickle local object'): await pool.call('test5') self.assertEqual(await pool.call('test1', 0.1), 1) finally: await pool.stop() async def test_procpool_8(self): pool = await procpool.create_pool( max_capacity=1, min_capacity=1, runstate_dir=self.runstate_dir, worker_cls=Worker, worker_args=([123],), name='test_procpool_8') worker = next(pool.manager.iter_workers()) pid = worker.get_pid() try: t = asyncio.create_task(pool.call('test1', 10)) await asyncio.sleep(0.1) os.kill(pid, signal.SIGTERM) with self.assertRaisesRegex(ConnectionError, 'lost connection to the worker'): await t self.assertEqual(await pool.call('test1', 0.1), 1) finally: await pool.stop() async def test_procpool_9(self): pool = await procpool.create_pool( max_capacity=10, min_capacity=1, gc_interval=0.01, runstate_dir=self.runstate_dir, worker_cls=Worker, worker_args=([123],), name='test_procpool_9') try: async with taskgroup.TaskGroup() as g: for _ in range(100): g.create_task(pool.call('test1', 0.1)) await asyncio.sleep(1) await pool.call('test1', 0.1) finally: await pool.stop() async def test_procpool_10(self): pool = await procpool.create_pool( max_capacity=10, min_capacity=2, gc_interval=0.01, runstate_dir=self.runstate_dir, worker_cls=Worker, worker_args=([123],), name='test_procpool_10') manager = pool.manager try: async with taskgroup.TaskGroup() as g: for _ in range(100): g.create_task(pool.call('test1', 0.1)) await asyncio.sleep(0.5) self.assertEqual(manager._stats_spawned, 10) self.assertEqual(manager._stats_killed, 8) w1 = await pool.acquire() w2 = await pool.acquire() w3 = await pool.acquire() await asyncio.sleep(0.5) self.assertEqual(manager._stats_spawned, 11) self.assertEqual(manager._stats_killed, 8) await w1.call('test1', 0.1) await w2.call('test1', 0.1) await w3.call('test1', 0.1) self.assertEqual(manager._stats_spawned, 11) self.assertEqual(manager._stats_killed, 8) finally: await pool.stop() self.assertEqual(manager._stats_spawned, 11) self.assertEqual(manager._stats_killed, 11) <file_sep>/edb/lang/edgeql/compiler/expr.py # # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # 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. # """EdgeQL non-statement expression compilation functions.""" import typing from edb import errors from edb.lang.edgeql import functypes as ft from edb.lang.ir import ast as irast from edb.lang.ir import staeval as ireval from edb.lang.ir import utils as irutils from edb.lang.schema import abc as s_abc from edb.lang.schema import objtypes as s_objtypes from edb.lang.schema import pointers as s_pointers from edb.lang.edgeql import ast as qlast from . import astutils from . import cast from . import context from . import dispatch from . import inference from . import pathctx from . import setgen from . import schemactx from . import stmtctx from . import typegen from . import func # NOQA @dispatch.compile.register(qlast._Optional) def compile__Optional( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Set: result = setgen.ensure_set( dispatch.compile(expr.expr, ctx=ctx), ctx=ctx) pathctx.register_set_in_scope(result, ctx=ctx) pathctx.mark_path_as_optional(result.path_id, ctx=ctx) return result @dispatch.compile.register(qlast.Path) def compile_Path( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Set: return setgen.compile_path(expr, ctx=ctx) @dispatch.compile.register(qlast.BinOp) def compile_BinOp( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Set: if expr.op == 'UNION': op_node = compile_set_op(expr, ctx=ctx) else: op_node = func.compile_operator( expr, op_name=expr.op, qlargs=[expr.left, expr.right], ctx=ctx) folded = try_fold_binop(op_node.expr, ctx=ctx) if folded is not None: return folded return setgen.ensure_set(op_node, ctx=ctx) @dispatch.compile.register(qlast.IsOp) def compile_IsOp( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Set: op_node = compile_type_check_op(expr, ctx=ctx) return setgen.ensure_set(op_node, ctx=ctx) @dispatch.compile.register(qlast.Parameter) def compile_Parameter( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Set: if ctx.func is not None: raise errors.QueryError( f'"$parameters" cannot be used in functions', context=expr.context) pt = ctx.env.query_parameters.get(expr.name) return setgen.ensure_set( irast.Parameter(stype=pt, name=expr.name), ctx=ctx) @dispatch.compile.register(qlast.DetachedExpr) def compile_DetachedExpr( expr: qlast.DetachedExpr, *, ctx: context.ContextLevel): with ctx.detached() as subctx: return dispatch.compile(expr.expr, ctx=subctx) @dispatch.compile.register(qlast.Set) def compile_Set( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Base: if expr.elements: if len(expr.elements) == 1: # From the scope perspective, single-element set # literals are equivalent to a binary UNION with # an empty set, not to the element. with ctx.newscope(fenced=True) as scopectx: ir_set = dispatch.compile(expr.elements[0], ctx=scopectx) return setgen.scoped_set(ir_set, ctx=scopectx) else: elements = flatten_set(expr) # a set literal is just sugar for a UNION op = 'UNION' bigunion = qlast.BinOp( left=elements[0], right=elements[1], op=op ) for el in elements[2:]: bigunion = qlast.BinOp( left=bigunion, right=el, op=op ) return dispatch.compile(bigunion, ctx=ctx) else: return irutils.new_empty_set(ctx.env.schema, alias=ctx.aliases.get('e')) @dispatch.compile.register(qlast.BaseConstant) def compile_BaseConstant( expr: qlast.BaseConstant, *, ctx: context.ContextLevel) -> irast.Base: value = expr.value if isinstance(expr, qlast.StringConstant): std_type = 'std::str' node_cls = irast.StringConstant elif isinstance(expr, qlast.RawStringConstant): std_type = 'std::str' node_cls = irast.RawStringConstant elif isinstance(expr, qlast.IntegerConstant): int_value = int(expr.value) if expr.is_negative: int_value = -int_value value = f'-{value}' # If integer value is out of int64 bounds, use decimal if -2 ** 63 <= int_value < 2 ** 63: std_type = 'std::int64' else: std_type = 'std::decimal' node_cls = irast.IntegerConstant elif isinstance(expr, qlast.FloatConstant): if expr.is_negative: value = f'-{value}' std_type = 'std::float64' node_cls = irast.FloatConstant elif isinstance(expr, qlast.BooleanConstant): std_type = 'std::bool' node_cls = irast.BooleanConstant elif isinstance(expr, qlast.BytesConstant): std_type = 'std::bytes' node_cls = irast.BytesConstant else: raise RuntimeError(f'unexpected constant type: {type(expr)}') ct = ctx.env.schema.get(std_type) return setgen.generated_set(node_cls(value=value, stype=ct), ctx=ctx) def try_fold_binop( opcall: irast.OperatorCall, *, ctx: context.ContextLevel) -> typing.Optional[irast.Set]: try: const = ireval.evaluate(opcall, schema=ctx.env.schema) except ireval.UnsupportedExpressionError: anyreal = ctx.env.schema.get('std::anyreal') if (opcall.func_shortname in ('std::+', 'std::*') and opcall.operator_kind is ft.OperatorKind.INFIX and all(a.stype.issubclass(ctx.env.schema, anyreal) for a in opcall.args)): return try_fold_associative_binop(opcall, ctx=ctx) else: return setgen.ensure_set(const, ctx=ctx) def try_fold_associative_binop( opcall: irast.OperatorCall, *, ctx: context.ContextLevel) -> typing.Optional[irast.Set]: # Let's check if we have (CONST + (OTHER_CONST + X)) # tree, which can be optimized to ((CONST + OTHER_CONST) + X) op = opcall.func_shortname my_const = opcall.args[0] other_binop = opcall.args[1] folded = None if isinstance(other_binop.expr, irast.BaseConstant): my_const, other_binop = other_binop, my_const if (isinstance(my_const.expr, irast.BaseConstant) and isinstance(other_binop.expr, irast.OperatorCall) and other_binop.expr.func_shortname == op and other_binop.expr.operator_kind is ft.OperatorKind.INFIX): other_const = other_binop.expr.args[0] other_binop_node = other_binop.expr.args[1] if isinstance(other_binop_node.expr, irast.BaseConstant): other_binop_node, other_const = \ other_const, other_binop_node if isinstance(other_const.expr, irast.BaseConstant): try: new_const = ireval.evaluate( irast.OperatorCall( args=[other_const, my_const], func_shortname=op, func_polymorphic=opcall.func_polymorphic, func_sql_function=opcall.func_sql_function, sql_operator=opcall.sql_operator, force_return_cast=opcall.force_return_cast, operator_kind=opcall.operator_kind, params_typemods=opcall.params_typemods, context=opcall.context, stype=opcall.stype, typemod=opcall.typemod, ), schema=ctx.env.schema, ) except ireval.UnsupportedExpressionError: pass else: folded_binop = irast.OperatorCall( args=[ setgen.ensure_set(new_const, ctx=ctx), other_binop_node ], func_shortname=op, func_polymorphic=opcall.func_polymorphic, func_sql_function=opcall.func_sql_function, sql_operator=opcall.sql_operator, force_return_cast=opcall.force_return_cast, operator_kind=opcall.operator_kind, params_typemods=opcall.params_typemods, context=opcall.context, stype=opcall.stype, typemod=opcall.typemod, ) folded = setgen.ensure_set(folded_binop, ctx=ctx) return folded @dispatch.compile.register(qlast.TupleElement) def compile_TupleElement( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Base: name = expr.name.name if expr.name.module: name = f'{expr.name.module}::{name}' val = setgen.ensure_set(dispatch.compile(expr.val, ctx=ctx), ctx=ctx) element = irast.TupleElement( name=name, val=val, ) return element @dispatch.compile.register(qlast.NamedTuple) def compile_NamedTuple( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Base: elements = [dispatch.compile(e, ctx=ctx) for e in expr.elements] tup = astutils.make_tuple(elements, named=True, ctx=ctx) return setgen.generated_set(tup, ctx=ctx) @dispatch.compile.register(qlast.Tuple) def compile_Tuple( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Base: elements = [] for i, el in enumerate(expr.elements): element = irast.TupleElement( name=str(i), val=dispatch.compile(el, ctx=ctx) ) elements.append(element) tup = astutils.make_tuple(elements, named=False, ctx=ctx) return setgen.generated_set(tup, ctx=ctx) @dispatch.compile.register(qlast.Array) def compile_Array( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Base: elements = [dispatch.compile(e, ctx=ctx) for e in expr.elements] # check that none of the elements are themselves arrays for el, expr_el in zip(elements, expr.elements): if isinstance(inference.infer_type(el, ctx.env), s_abc.Array): raise errors.QueryError( f'nested arrays are not supported', context=expr_el.context) return setgen.generated_set( astutils.make_array(elements, ctx=ctx), ctx=ctx) @dispatch.compile.register(qlast.IfElse) def compile_IfElse( expr: qlast.IfElse, *, ctx: context.ContextLevel) -> irast.Base: condition = setgen.ensure_set( dispatch.compile(expr.condition, ctx=ctx), ctx=ctx) ql_if_expr = expr.if_expr ql_else_expr = expr.else_expr with ctx.newscope(fenced=True) as scopectx: if_expr = setgen.scoped_set( dispatch.compile(ql_if_expr, ctx=scopectx), ctx=scopectx) with ctx.newscope(fenced=True) as scopectx: else_expr = setgen.scoped_set( dispatch.compile(ql_else_expr, ctx=scopectx), ctx=scopectx) if_expr_type = inference.infer_type(if_expr, ctx.env) else_expr_type = inference.infer_type(else_expr, ctx.env) cond_expr_type = inference.infer_type(condition, ctx.env) # make sure that the condition is actually boolean bool_t = ctx.env.schema.get('std::bool') if not cond_expr_type.issubclass(ctx.env.schema, bool_t): raise errors.QueryError( 'if/else condition must be of type {}, got: {}'.format( bool_t.get_displayname(ctx.env.schema), cond_expr_type.get_displayname(ctx.env.schema)), context=expr.context) result = if_expr_type.find_common_implicitly_castable_type( else_expr_type, schema=ctx.env.schema) if result is None: raise errors.QueryError( 'if/else clauses must be of related types, got: {}/{}'.format( if_expr_type.get_displayname(ctx.env.schema), else_expr_type.get_displayname(ctx.env.schema)), context=expr.context) ifelse = irast.IfElseExpr( if_expr=if_expr, else_expr=else_expr, condition=condition) stmtctx.get_expr_cardinality_later( target=ifelse, field='if_expr_card', irexpr=if_expr, ctx=ctx) stmtctx.get_expr_cardinality_later( target=ifelse, field='else_expr_card', irexpr=else_expr, ctx=ctx) return setgen.generated_set( ifelse, ctx=ctx ) @dispatch.compile.register(qlast.UnaryOp) def compile_UnaryOp( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Set: result = func.compile_operator( expr, op_name=expr.op, qlargs=[expr.operand], ctx=ctx) try: result = ireval.evaluate(result, schema=ctx.env.schema) except ireval.UnsupportedExpressionError: pass return setgen.generated_set(result, ctx=ctx) @dispatch.compile.register(qlast.Coalesce) def compile_Coalesce( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Base: if all(isinstance(a, qlast.Set) and not a.elements for a in expr.args): return irutils.new_empty_set(ctx.env.schema, alias=ctx.aliases.get('e')) # Due to the construction of relgen, the (unfenced) subscope # below is necessary to shield LHS paths from the outer query # to prevent path binding which may break OPTIONAL. with ctx.newscope() as newctx: leftmost_arg = larg = setgen.ensure_set( dispatch.compile(expr.args[0], ctx=newctx), ctx=newctx) for rarg_ql in expr.args[1:]: with newctx.new() as nestedscopectx: with nestedscopectx.newscope(fenced=True) as fencectx: rarg = setgen.scoped_set( dispatch.compile(rarg_ql, ctx=fencectx), force_reassign=True, ctx=fencectx) coalesce = irast.Coalesce(left=larg, right=rarg) larg = setgen.generated_set(coalesce, ctx=nestedscopectx) stmtctx.get_expr_cardinality_later( target=coalesce, field='right_card', irexpr=rarg, ctx=ctx) # Make sure any empty set types are properly resolved # before entering them into the scope tree. inference.infer_type(larg, env=ctx.env) pathctx.register_set_in_scope(leftmost_arg, ctx=ctx) pathctx.mark_path_as_optional(leftmost_arg.path_id, ctx=ctx) pathctx.assign_set_scope(leftmost_arg, newctx.path_scope, ctx=ctx) return larg @dispatch.compile.register(qlast.TypeCast) def compile_TypeCast( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Base: target_typeref = typegen.ql_typeref_to_ir_typeref(expr.type, ctx=ctx) if (isinstance(expr.expr, qlast.Array) and not expr.expr.elements and target_typeref.maintype == 'array'): ir_expr = irast.Array() elif isinstance(expr.expr, qlast.Parameter): pt = typegen.ql_typeref_to_type(expr.type, ctx=ctx) param_name = expr.expr.name if param_name not in ctx.env.query_parameters: if ctx.env.query_parameters: first_key: str = next(iter(ctx.env.query_parameters)) if first_key.isdecimal(): if not param_name.isdecimal(): raise errors.QueryError( f'expected a positional argument', context=expr.expr.context) else: if param_name.isdecimal(): raise errors.QueryError( f'expected a named argument', context=expr.expr.context) ctx.env.query_parameters[param_name] = pt else: param_first_type = ctx.env.query_parameters[param_name] if not param_first_type.explicitly_castable_to(pt, ctx.env.schema): raise errors.QueryError( f'cannot cast ' f'{param_first_type.get_displayname(ctx.env.schema)} to ' f'{pt.get_displayname(ctx.env.schema)}', context=expr.expr.context) param = irast.Parameter( stype=pt, name=param_name, context=expr.expr.context) return setgen.ensure_set(param, ctx=ctx) else: with ctx.new() as subctx: # We use "exposed" mode in case this is a type of a cast # that wants view shapes, e.g. a std::json cast. We do # this wholesale to support tuple and array casts without # having to analyze the target type (which is cumbersome # in QL AST). subctx.expr_exposed = True ir_expr = dispatch.compile(expr.expr, ctx=subctx) new_stype = typegen.ql_typeref_to_type(expr.type, ctx=ctx) return cast.compile_cast( ir_expr, new_stype, ctx=ctx, srcctx=expr.expr.context) @dispatch.compile.register(qlast.TypeFilter) def compile_TypeFilter( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Base: # Expr[IS Type] expressions. with ctx.new() as scopectx: arg = setgen.ensure_set( dispatch.compile(expr.expr, ctx=scopectx), ctx=scopectx) arg_type = inference.infer_type(arg, ctx.env) if not isinstance(arg_type, s_objtypes.ObjectType): raise errors.QueryError( f'invalid type filter operand: ' f'{arg_type.get_displayname(ctx.env.schema)} ' f'is not an object type', context=expr.expr.context) typ = schemactx.get_schema_type(expr.type.maintype, ctx=ctx) if not isinstance(typ, s_objtypes.ObjectType): raise errors.QueryError( f'invalid type filter operand: ' f'{typ.get_displayname(ctx.env.schema)} is not an object type', context=expr.type.context) return setgen.class_indirection_set(arg, typ, optional=False, ctx=ctx) @dispatch.compile.register(qlast.Indirection) def compile_Indirection( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Base: node = dispatch.compile(expr.arg, ctx=ctx) for indirection_el in expr.indirection: if isinstance(indirection_el, qlast.Index): idx = dispatch.compile(indirection_el.index, ctx=ctx) idx.context = indirection_el.index.context node = irast.IndexIndirection(expr=node, index=idx, context=expr.context) elif isinstance(indirection_el, qlast.Slice): if indirection_el.start: start = dispatch.compile(indirection_el.start, ctx=ctx) else: start = None if indirection_el.stop: stop = dispatch.compile(indirection_el.stop, ctx=ctx) else: stop = None node = irast.SliceIndirection( expr=node, start=start, stop=stop) else: raise ValueError('unexpected indirection node: ' '{!r}'.format(indirection_el)) return setgen.ensure_set(node, ctx=ctx) def compile_type_check_op( expr: qlast.IsOp, *, ctx: context.ContextLevel) -> irast.TypeCheckOp: # <Expr> IS <TypeExpr> left = dispatch.compile(expr.left, ctx=ctx) ltype = inference.infer_type(left, ctx.env) left = setgen.ptr_step_set( left, source=ltype, ptr_name='__type__', direction=s_pointers.PointerDirection.Outbound, source_context=expr.context, ctx=ctx) pathctx.register_set_in_scope(left, ctx=ctx) right = typegen.ql_typeref_to_ir_typeref(expr.right, ctx=ctx) return irast.TypeCheckOp(left=left, right=right, op=expr.op) def compile_set_op( expr: qlast.BinOp, *, ctx: context.ContextLevel) -> irast.Set: with ctx.newscope(fenced=True) as scopectx: left = setgen.scoped_set( dispatch.compile(expr.left, ctx=scopectx), ctx=scopectx) with ctx.newscope(fenced=True) as scopectx: right = setgen.scoped_set( dispatch.compile(expr.right, ctx=scopectx), ctx=scopectx) left_type = inference.infer_type(left, ctx.env) right_type = inference.infer_type(right, ctx.env) if left_type != right_type and isinstance(left_type, s_abc.Collection): common_type = left_type.find_common_implicitly_castable_type( right_type, ctx.env.schema) if common_type is None: raise errors.QueryError( f'could not determine type of a set', context=expr.context) if left_type != common_type: left = cast.compile_cast( left, common_type, ctx=ctx, srcctx=expr.context) if right_type != common_type: right = cast.compile_cast( right, common_type, ctx=ctx, srcctx=expr.context) setop = irast.SetOp(left=left, right=right, op=expr.op) stmtctx.get_expr_cardinality_later( target=setop, field='left_card', irexpr=left, ctx=ctx) stmtctx.get_expr_cardinality_later( target=setop, field='right_card', irexpr=right, ctx=ctx) return setgen.ensure_set(setop, ctx=ctx) def flatten_set(expr: qlast.Set) -> typing.List[qlast.Expr]: elements = [] for el in expr.elements: if isinstance(el, qlast.Set): elements.extend(flatten_set(el)) else: elements.append(el) return elements <file_sep>/edb/server/pgsql/backend.py # # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # 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. # import collections import logging import pathlib import pickle import re import uuid from edb import errors from edb.lang.common import context as parser_context from edb.lang.common import debug from edb.lang.common import devmode from edb.lang.common import exceptions from edb.lang import edgeql from edb.lang.schema import delta as sd from edb.lang.schema import abc as s_abc from edb.lang.schema import database as s_db from edb.lang.schema import ddl as s_ddl from edb.lang.schema import deltas as s_deltas from edb.lang.schema import schema as s_schema from edb.lang.schema import std as s_std from edb.server import query as backend_query from edb.server.pgsql import dbops from edb.server.pgsql import delta as delta_cmds from . import common from . import compiler from . import intromech from . import types from .common import quote_ident as qi CACHE_SRC_DIRS = s_std.CACHE_SRC_DIRS + ( (pathlib.Path(__file__).parent, '.py'), ) class Query(backend_query.Query): def __init__( self, *, text, argmap, argument_types, output_desc=None, output_format=None): self.text = text self.argmap = argmap self.argument_types = collections.OrderedDict((k, argument_types[k]) for k in argmap if k in argument_types) self.output_desc = output_desc self.output_format = output_format class TypeDescriptor: def __init__(self, type_id, schema_type, subtypes, element_names): self.type_id = type_id self.schema_type = schema_type self.subtypes = subtypes self.element_names = element_names self.cardinality = '1' class OutputDescriptor: def __init__(self, type_desc, tuple_registry): self.type_desc = type_desc self.tuple_registry = tuple_registry class Backend: std_schema = None def __init__(self, connection, data_dir): self.schema = None self.modaliases = {None: 'default'} self.testmode = False self._intro_mech = intromech.IntrospectionMech(connection) self.connection = connection self.data_dir = pathlib.Path(data_dir) self.dev_mode = devmode.is_in_dev_mode() self.transactions = [] async def getschema(self): if self.schema is None: cls = type(self) if cls.std_schema is None: with open(self.data_dir / 'stdschema.pickle', 'rb') as f: try: cls.std_schema = pickle.load(f) except Exception as e: raise RuntimeError( 'could not load std schema pickle') from e self.schema = await self._intro_mech.readschema( schema=cls.std_schema, exclude_modules=s_schema.STD_MODULES) return self.schema def create_context(self, cmds=None, stdmode=None): context = sd.CommandContext() context.testmode = self.testmode if stdmode is not None: context.stdmode = stdmode return context def adapt_delta(self, delta): return delta_cmds.CommandMeta.adapt(delta) def process_delta(self, delta, schema, *, stdmode=None): """Adapt and process the delta command.""" if debug.flags.delta_plan: debug.header('Delta Plan') debug.dump(delta, schema=schema) delta = self.adapt_delta(delta) context = self.create_context(delta_cmds, stdmode) schema, _ = delta.apply(schema, context) if debug.flags.delta_pgsql_plan: debug.header('PgSQL Delta Plan') debug.dump(delta, schema=schema) return schema, delta async def run_delta_command(self, delta_cmd): schema = self.schema context = self.create_context() result = None if isinstance(delta_cmd, s_deltas.CreateDelta): delta = None else: delta = schema.get(delta_cmd.classname) with context(s_deltas.DeltaCommandContext(schema, delta_cmd, delta)): if isinstance(delta_cmd, s_deltas.CommitDelta): ddl_plan = sd.DeltaRoot() ddl_plan.update(delta.get_commands(schema)) await self.run_ddl_command(ddl_plan) elif isinstance(delta_cmd, s_deltas.GetDelta): result = s_ddl.ddl_text_from_delta(schema, delta) elif isinstance(delta_cmd, s_deltas.CreateDelta): self.schema, _ = delta_cmd.apply(schema, context) else: raise RuntimeError( f'unexpected delta command: {delta_cmd!r}') return result async def _execute_ddl(self, sql_text): try: if debug.flags.delta_execute: debug.header('Delta Script') debug.dump_code(sql_text, lexer='sql') await self.connection.execute(sql_text) except Exception as e: position = getattr(e, 'position', None) internal_position = getattr(e, 'internal_position', None) context = getattr(e, 'context', '') if context: pl_func_line = re.search( r'^PL/pgSQL function inline_code_block line (\d+).*', context, re.M) if pl_func_line: pl_func_line = int(pl_func_line.group(1)) else: pl_func_line = None point = None if position is not None: position = int(position) point = parser_context.SourcePoint( None, None, position) text = e.query if text is None: # Parse errors text = sql_text elif internal_position is not None: internal_position = int(internal_position) point = parser_context.SourcePoint( None, None, internal_position) text = e.internal_query elif pl_func_line: point = parser_context.SourcePoint( pl_func_line, None, None ) text = sql_text if point is not None: context = parser_context.ParserContext( 'query', text, start=point, end=point) exceptions.replace_context(e, context) raise async def _load_std(self): schema = s_schema.Schema() current_block = None std_texts = [] for modname in s_schema.STD_LIB + ['stdgraphql']: std_texts.append(s_std.get_std_module_text(modname)) ddl_text = '\n'.join(std_texts) for ddl_cmd in edgeql.parse_block(ddl_text): delta_command = s_ddl.delta_from_ddl( ddl_cmd, schema=schema, modaliases={None: 'std'}, stdmode=True) if debug.flags.delta_plan_input: debug.header('Delta Plan Input') debug.dump(delta_command) # Do a dry-run on test_schema to canonicalize # the schema delta-commands. test_schema = schema context = self.create_context(stdmode=True) canonical_delta = delta_command.copy() canonical_delta.apply(test_schema, context=context) # Apply and adapt delta, build native delta plan, which # will also update the schema. schema, plan = self.process_delta(canonical_delta, schema, stdmode=True) if isinstance(plan, (s_db.CreateDatabase, s_db.DropDatabase)): if (current_block is not None and not isinstance(current_block, dbops.SQLBlock)): raise errors.QueryError( 'cannot mix DATABASE commands with regular DDL ' 'commands in a single block') if current_block is None: current_block = dbops.SQLBlock() else: if (current_block is not None and not isinstance(current_block, dbops.PLTopBlock)): raise errors.QueryError( 'cannot mix DATABASE commands with regular DDL ' 'commands in a single block') if current_block is None: current_block = dbops.PLTopBlock() plan.generate(current_block) sql_text = current_block.to_string() return schema, sql_text async def run_std_bootstrap(self): cache_hit = False sql_text = None cluster_schema_cache = self.data_dir / 'stdschema.pickle' if self.dev_mode: schema_cache = 'backend-stdschema.pickle' script_cache = 'backend-stdinitsql.pickle' src_hash = devmode.hash_dirs(CACHE_SRC_DIRS) sql_text = devmode.read_dev_mode_cache(src_hash, script_cache) if sql_text is not None: schema = devmode.read_dev_mode_cache(src_hash, schema_cache) if sql_text is None or schema is None: schema, sql_text = await self._load_std() else: cache_hit = True await self._execute_ddl(sql_text) self.schema = schema if not cache_hit and self.dev_mode: devmode.write_dev_mode_cache(schema, src_hash, schema_cache) devmode.write_dev_mode_cache(sql_text, src_hash, script_cache) with open(cluster_schema_cache, 'wb') as f: pickle.dump(schema, file=f, protocol=pickle.HIGHEST_PROTOCOL) async def run_ddl_command(self, ddl_plan): schema = self.schema if debug.flags.delta_plan_input: debug.header('Delta Plan Input') debug.dump(ddl_plan) # Do a dry-run on test_schema to canonicalize # the schema delta-commands. test_schema = schema context = self.create_context() canonical_ddl_plan = ddl_plan.copy() canonical_ddl_plan.apply(test_schema, context=context) # Apply and adapt delta, build native delta plan, which # will also update the schema. schema, plan = self.process_delta(canonical_ddl_plan, schema) context = self.create_context(delta_cmds) if isinstance(plan, (s_db.CreateDatabase, s_db.DropDatabase)): block = dbops.SQLBlock() else: block = dbops.PLTopBlock() plan.generate(block) ql_text = block.to_string() await self._execute_ddl(ql_text) self.schema = schema async def exec_session_state_cmd(self, cmd): for alias, module in cmd.modaliases.items(): self.modaliases[alias] = module.get_name(self.schema) self.testmode = cmd.testmode def _get_collection_type_id(self, coll_type, subtypes, element_names): subtypes = (f"{st.type_id}-{st.cardinality}" for st in subtypes) string_id = f'{coll_type}\x00{":".join(subtypes)}' if element_names: string_id += f'\x00{":".join(element_names)}' return uuid.uuid5(types.TYPE_ID_NAMESPACE, string_id) def _get_union_type_id(self, schema, union_type): base_type_id = ','.join( str(c.id) for c in union_type.children(schema)) return uuid.uuid5(types.TYPE_ID_NAMESPACE, base_type_id) def _describe_type(self, schema, t, view_shapes, _tuples): mt = t.material_type(schema) is_tuple = False if isinstance(t, s_abc.Collection): subtypes = [self._describe_type(schema, st, view_shapes, _tuples) for st in t.get_subtypes()] if isinstance(t, s_abc.Tuple) and t.named: element_names = list(t.element_types.keys()) else: element_names = None type_id = self._get_collection_type_id(t.schema_name, subtypes, element_names) is_tuple = True elif view_shapes.get(t): # This is a view if mt.get_is_virtual(schema): base_type_id = self._get_union_type_id(schema, mt) else: base_type_id = mt.id subtypes = [] element_names = [] for ptr in view_shapes[t]: subdesc = self._describe_type( schema, ptr.get_target(schema), view_shapes, _tuples) subdesc.cardinality = ( '1' if ptr.singular(schema) else '*' ) subtypes.append(subdesc) element_names.append(ptr.get_shortname(schema).name) t_rptr = t.get_rptr(schema) if t_rptr is not None: # There are link properties in the mix for ptr in view_shapes[t_rptr]: subdesc = self._describe_type( schema, ptr.get_target(schema), view_shapes, _tuples) subdesc.cardinality = ( '1' if ptr.singular(schema) else '*' ) subtypes.append(subdesc) element_names.append(ptr.get_shortname(schema).name) type_id = self._get_collection_type_id(base_type_id, subtypes, element_names) is_tuple = True else: # This is a regular type subtypes = None element_names = None type_id = mt.id type_desc = TypeDescriptor( type_id=type_id, schema_type=mt, subtypes=subtypes, element_names=element_names) if is_tuple: _tuples[type_id] = type_desc return type_desc def compile(self, query_ir, context=None, *, output_format=None, timer=None): tuples = {} type_desc = self._describe_type( query_ir.schema, query_ir.stype, query_ir.view_shapes, tuples) output_desc = OutputDescriptor( type_desc=type_desc, tuple_registry=tuples) sql_text, argmap = compiler.compile_ir_to_sql( query_ir, schema=query_ir.schema, output_format=output_format, timer=timer) argtypes = {} for k, v in query_ir.params.items(): argtypes[k] = v return Query( text=sql_text, argmap=argmap, argument_types=argtypes, output_desc=output_desc, output_format=output_format) async def compile_migration( self, cmd: s_deltas.CreateDelta) -> s_deltas.CreateDelta: declarations = cmd.get_attribute_value('target') if not declarations: return cmd return s_ddl.compile_migration(cmd, self.std_schema, self.schema) async def translate_pg_error(self, query, error): return await self._intro_mech.translate_pg_error( self.schema, query, error) async def start_transaction(self): tx = self.connection.transaction() self.transactions.append((tx, self.schema)) await tx.start() async def commit_transaction(self): if not self.transactions: raise errors.TransactionError( 'there is no transaction in progress') transaction, _ = self.transactions.pop() await transaction.commit() async def rollback_transaction(self): if not self.transactions: raise errors.TransactionError( 'there is no transaction in progress') transaction, self.schema = self.transactions.pop() await transaction.rollback() async def open_database(pgconn, data_dir, *, bootstrap=False): bk = Backend(pgconn, data_dir) pgconn.add_log_listener(pg_log_listener) if not bootstrap: schema = await bk.getschema() stdschema = common.get_backend_name(schema, schema.get('std')) await pgconn.execute( f'SET search_path = edgedb, {qi(stdschema)}') else: bk.schema = s_schema.Schema() return bk logger = logging.getLogger('edb.backend') def pg_log_listener(conn, msg): if msg.severity_en == 'WARNING': level = logging.WARNING else: level = logging.DEBUG logger.log(level, msg.message) <file_sep>/docs/edgeql/operators/json.rst .. _ref_eql_operators_json: ==== JSON ==== JSON in EdgeDB is one of the :ref:`scalar types <ref_datamodel_scalar_types>`. This scalar doesn't have its own literal and instead can be obtained by casting a value into :eql:type:`json` or by using :eql:func:`str_to_json`: .. code-block:: edgeql-repl db> SELECT str_to_json('{"hello": "world"}'); {{hello: 'world'}} db> SELECT <json>'hello world'; {'hello world'} Anything in EdgeDB can be cast into :eql:type:`json`: .. code-block:: edgeql-repl db> SELECT <json>2018; {2018} db> SELECT <json>current_date(); {'2018-10-18'} db> SELECT <json>( ... SELECT schema::Object { ... name, ... timestamp := current_date() ... } ... FILTER .name = 'std::bool'); {{name: 'std::bool', timestamp: '2018-10-18'}} JSON values can also be cast back into scalars. This casting is symmetrical meaning that if a scalar can be cast into JSON, only that particular JSON type can be cast back into that scalar: - JSON *string* can be cast into :eql:type:`str` - JSON *number* can be cast into any of the :ref:`numeric types <ref_datamodel_scalars_numeric>` - JSON *boolean* can be cast into :eql:type:`bool` - JSON *null* is special since it can be cast into an ``{}`` of any type - JSON *array* can be cast into any valid EdgeDB array, so it must be homogeneous, and must not contain *null* - JSON *object* can be cast into a valid EdgeDB named tuple, but it must not contain *null* The contents of JSON *objects* and *arrays* can also be accessed via ``[]``: .. code-block:: edgeql-repl db> SELECT str_to_json('[1, "a", null]')[1]; {'a'} db> SELECT str_to_json('[1, "a", null]')[-1]; {None} db> SELECT j := <json>(schema::Object { ... name, ... timestamp := current_date() ... }) ... FILTER j['name'] = <json>'std::bool'; {{name: 'std::bool', timestamp: '2018-10-18'}} <file_sep>/edb/server2/backend/compiler.py # # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # 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. # import collections import hashlib import pathlib import pickle import typing import asyncpg import immutables from edb import errors from edb.server import defines from edb.server.pgsql import compiler as pg_compiler from edb.server.pgsql import intromech from edb.lang import edgeql from edb.lang import graphql from edb.lang.common import debug from edb.lang.edgeql import ast as qlast from edb.lang.edgeql import compiler as ql_compiler from edb.lang.edgeql import quote as ql_quote from edb.lang.ir import staeval as ireval from edb.lang.schema import database as s_db from edb.lang.schema import ddl as s_ddl from edb.lang.schema import delta as s_delta from edb.lang.schema import deltas as s_deltas from edb.lang.schema import schema as s_schema from edb.lang.schema import types as s_types from edb.server.pgsql import delta as pg_delta from edb.server.pgsql import dbops as pg_dbops from . import config from . import dbstate from . import errormech from . import sertypes class CompilerDatabaseState(typing.NamedTuple): dbver: int con_args: dict schema: s_schema.Schema class CompileContext(typing.NamedTuple): state: dbstate.CompilerConnectionState output_format: pg_compiler.OutputFormat single_query_mode: bool legacy_mode: bool graphql_mode: bool EMPTY_MAP = immutables.Map() class Compiler: _connect_args: dict _dbname: typing.Optional[str] _cached_db: typing.Optional[CompilerDatabaseState] def __init__(self, connect_args: dict, data_dir: str): self._connect_args = connect_args self._data_dir = pathlib.Path(data_dir) self._dbname = None self._cached_db = None self._cached_std_schema = None self._current_db_state = None async def _get_database(self, dbver: int) -> CompilerDatabaseState: if self._cached_db is not None and self._cached_db.dbver == dbver: return self._cached_db self._cached_db = None con_args = self._connect_args.copy() con_args['user'] = defines.EDGEDB_SUPERUSER con_args['database'] = self._dbname con = await asyncpg.connect(**con_args) try: im = intromech.IntrospectionMech(con) schema = await im.readschema( schema=self._get_std_schema(), exclude_modules=s_schema.STD_MODULES) db = CompilerDatabaseState( dbver=dbver, con_args=con_args, schema=schema) self._cached_db = db return db finally: await con.close() def _get_std_schema(self): if self._cached_std_schema is not None: return self._cached_std_schema with open(self._data_dir / 'stdschema.pickle', 'rb') as f: try: self._cached_std_schema = pickle.load(f) except Exception as e: raise RuntimeError( 'could not load std schema pickle') from e return self._cached_std_schema def _hash_sql(self, sql: bytes, **kwargs: bytes): h = hashlib.sha1(sql) for param, val in kwargs.items(): h.update(param.encode('latin1')) h.update(val) return h.hexdigest().encode('latin1') def _new_delta_context(self, ctx: CompileContext): current_tx = ctx.state.current_tx() config = current_tx.get_config() context = s_delta.CommandContext() context.testmode = bool(config.get('__internal_testmode')) return context def _process_delta(self, ctx: CompileContext, delta, schema): """Adapt and process the delta command.""" if debug.flags.delta_plan: debug.header('Delta Plan') debug.dump(delta, schema=schema) delta = pg_delta.CommandMeta.adapt(delta) context = self._new_delta_context(ctx) schema, _ = delta.apply(schema, context) if debug.flags.delta_pgsql_plan: debug.header('PgSQL Delta Plan') debug.dump(delta, schema=schema) return schema, delta def _compile_ql_query( self, ctx: CompileContext, ql: qlast.Base) -> dbstate.BaseQuery: current_tx = ctx.state.current_tx() ir = ql_compiler.compile_ast_to_ir( ql, schema=current_tx.get_schema(), modaliases=current_tx.get_modaliases(), implicit_id_in_shapes=False) sql_text, argmap = pg_compiler.compile_ir_to_sql( ir, schema=ir.schema, pretty=debug.flags.edgeql_compile, output_format=ctx.output_format) sql_bytes = sql_text.encode(defines.EDGEDB_ENCODING) if ctx.single_query_mode or ctx.legacy_mode: if ctx.output_format is pg_compiler.OutputFormat.NATIVE: out_type_data, out_type_id = sertypes.TypeSerializer.describe( ir.schema, ir.expr.stype, ir.view_shapes) else: out_type_data, out_type_id = \ sertypes.TypeSerializer.describe_json() if ir.params: subtypes = [None] * len(ir.params) first_param_name = next(iter(ir.params)) if first_param_name.isdecimal(): named = False for param_name, param_type in ir.params.items(): subtypes[int(param_name)] = (param_name, param_type) else: named = True for param_name, param_type in ir.params.items(): subtypes[argmap[param_name] - 1] = ( param_name, param_type ) params_type = s_types.Tuple.create( ir.schema, element_types=collections.OrderedDict(subtypes), named=named) else: params_type = s_types.Tuple.create( ir.schema, element_types={}, named=False) in_type_data, in_type_id = sertypes.TypeSerializer.describe( ir.schema, params_type, {}) sql_hash = self._hash_sql( sql_bytes, mode=str(ctx.output_format).encode()) return dbstate.Query( sql=sql_bytes, sql_hash=sql_hash, in_type_id=in_type_id.bytes, in_type_data=in_type_data, out_type_id=out_type_id.bytes, out_type_data=out_type_data, ) else: if ir.params: raise errors.QueryError( 'queries compiled in script mode cannot accept parameters') return dbstate.SimpleQuery(sql=sql_bytes) def _compile_and_apply_delta_command( self, ctx: CompileContext, cmd) -> dbstate.BaseQuery: current_tx = ctx.state.current_tx() schema = current_tx.get_schema() context = self._new_delta_context(ctx) if isinstance(cmd, s_deltas.CreateDelta): delta = None else: delta = schema.get(cmd.classname) with context(s_deltas.DeltaCommandContext(schema, cmd, delta)): if isinstance(cmd, s_deltas.CommitDelta): ddl_plan = s_delta.DeltaRoot() ddl_plan.update(delta.get_commands(schema)) return self._compile_and_apply_ddl_command(ctx, ddl_plan) elif isinstance(cmd, s_deltas.GetDelta): delta_ql = s_ddl.ddl_text_from_delta(schema, delta) query_ql = qlast.SelectQuery( result=qlast.StringConstant( quote="'", value=ql_quote.escape_string(delta_ql))) return self._compile_ql_query(ctx, query_ql) elif isinstance(cmd, s_deltas.CreateDelta): schema, _ = cmd.apply(schema, context) current_tx.update_schema(schema) return dbstate.DDLQuery(sql=b'') else: raise RuntimeError(f'unexpected delta command: {cmd!r}') def _compile_and_apply_ddl_command(self, ctx: CompileContext, cmd): current_tx = ctx.state.current_tx() schema = current_tx.get_schema() if debug.flags.delta_plan_input: debug.header('Delta Plan Input') debug.dump(cmd) # Do a dry-run on test_schema to canonicalize # the schema delta-commands. test_schema = schema context = self._new_delta_context(ctx) cmd.apply(test_schema, context=context) # Apply and adapt delta, build native delta plan, which # will also update the schema. schema, plan = self._process_delta(ctx, cmd, schema) if isinstance(plan, (s_db.CreateDatabase, s_db.DropDatabase)): block = pg_dbops.SQLBlock() else: block = pg_dbops.PLTopBlock() plan.generate(block) sql = block.to_string().encode('utf-8') current_tx.update_schema(schema) return dbstate.DDLQuery(sql=sql) def _compile_command( self, ctx: CompileContext, cmd) -> dbstate.BaseQuery: if isinstance(cmd, s_deltas.DeltaCommand): return self._compile_and_apply_delta_command(ctx, cmd) elif isinstance(cmd, s_delta.Command): return self._compile_and_apply_ddl_command(ctx, cmd) else: raise RuntimeError(f'unexpected plan {cmd!r}') def _compile_ql_ddl(self, ctx: CompileContext, ql: qlast.DDL): current_tx = ctx.state.current_tx() schema = current_tx.get_schema() cmd = s_ddl.delta_from_ddl( ql, schema=schema, modaliases=current_tx.get_modaliases(), testmode=bool(current_tx.get_config().get('__internal_testmode'))) return self._compile_command(ctx, cmd) def _compile_ql_migration(self, ctx: CompileContext, ql: typing.Union[qlast.Database, qlast.Delta]): current_tx = ctx.state.current_tx() schema = current_tx.get_schema() cmd = s_ddl.cmd_from_ddl( ql, schema=schema, modaliases=current_tx.get_modaliases(), testmode=bool(current_tx.get_config().get('__internal_testmode'))) if (isinstance(ql, qlast.CreateDelta) and cmd.get_attribute_value('target')): cmd = s_ddl.compile_migration( cmd, self._get_std_schema(), current_tx.get_schema()) return self._compile_command(ctx, cmd) def _compile_ql_transaction( self, ctx: CompileContext, ql: qlast.Transaction) -> dbstate.Query: if isinstance(ql, qlast.StartTransaction): ctx.state.start_tx() sql = b'START TRANSACTION;' action = dbstate.TxAction.START elif isinstance(ql, qlast.CommitTransaction): ctx.state.commit_tx() sql = b'COMMIT;' action = dbstate.TxAction.COMMIT elif isinstance(ql, qlast.RollbackTransaction): ctx.state.rollback_tx() sql = b'ROLLBACK;' action = dbstate.TxAction.ROLLBACK else: raise ValueError(f'expecting transaction node, got {ql!r}') return dbstate.TxControlQuery(sql=sql, action=action) def _compile_ql_sess_state(self, ctx: CompileContext, ql: qlast.SetSessionState): current_tx = ctx.state.current_tx() schema = current_tx.get_schema() aliases = {} config_vals = {} for item in ql.items: if isinstance(item, qlast.SessionSettingModuleDecl): try: schema.get(item.module) except errors.InvalidReferenceError: raise errors.UnknownModuleError( f'module {item.module!r} does not exist') from None aliases[item.alias] = item.module elif isinstance(item, qlast.SessionSettingConfigDecl): name = item.alias try: desc = config.configs[name] except KeyError: raise errors.ConfigurationError( f'invalid SET expression: ' f'unknown CONFIG setting {name!r}') try: val_ir = ql_compiler.compile_ast_fragment_to_ir( item.expr, schema=schema) val = ireval.evaluate_to_python_val( val_ir.expr, schema=schema) except ireval.StaticEvaluationError: raise RuntimeError('invalid SET expression') else: if not isinstance(val, desc.type): dispname = val_ir.stype.get_displayname(schema) raise errors.ConfigurationError( f'expected a {desc.type.__name__} value, ' f'got {dispname!r}') else: config_vals[name] = val else: raise RuntimeError( f'unsupported SET command type {type(item)!r}') aliases = immutables.Map(aliases) config_vals = immutables.Map(config_vals) if aliases: ctx.state.current_tx().update_modaliases( ctx.state.current_tx().get_modaliases().update(aliases)) if config_vals: ctx.state.current_tx().update_config( ctx.state.current_tx().get_config().update(config_vals)) return dbstate.SessionStateQuery( sess_set_modaliases=aliases, sess_set_config=config_vals) def _compile_dispatch_ql(self, ctx: CompileContext, ql: qlast.Base): if isinstance(ql, (qlast.Database, qlast.Delta)): return self._compile_ql_migration(ctx, ql) elif isinstance(ql, qlast.DDL): return self._compile_ql_ddl(ctx, ql) elif isinstance(ql, qlast.Transaction): return self._compile_ql_transaction(ctx, ql) elif isinstance(ql, qlast.SetSessionState): return self._compile_ql_sess_state(ctx, ql) else: return self._compile_ql_query(ctx, ql) def _compile(self, *, ctx: CompileContext, eql: bytes) -> typing.List[dbstate.QueryUnit]: eql = eql.decode() if ctx.graphql_mode: eql = graphql.translate( ctx.state.current_tx().get_schema(), eql, variables={}) + ';' statements = edgeql.parse_block(eql) if ctx.single_query_mode and len(statements) > 1: raise errors.ProtocolError( f'expected one statement, got {len(statements)}') units = [] unit = None txid = None if not ctx.state.current_tx().is_implicit(): txid = ctx.state.current_tx().id for stmt in statements: comp: dbstate.BaseQuery = self._compile_dispatch_ql(ctx, stmt) if ctx.legacy_mode and unit is not None: units.append(unit) unit = None if unit is None: unit = dbstate.QueryUnit(txid=txid, dbver=ctx.state.dbver) if isinstance(comp, dbstate.Query): if ctx.single_query_mode or ctx.legacy_mode: unit.sql = comp.sql unit.sql_hash = comp.sql_hash unit.out_type_data = comp.out_type_data unit.out_type_id = comp.out_type_id unit.in_type_data = comp.in_type_data unit.in_type_id = comp.in_type_id else: unit.sql += comp.sql elif isinstance(comp, dbstate.SimpleQuery): unit.sql += comp.sql elif isinstance(comp, dbstate.DDLQuery): unit.sql += comp.sql unit.has_ddl = True elif isinstance(comp, dbstate.TxControlQuery): unit.sql += comp.sql if comp.action == dbstate.TxAction.START: unit.starts_tx = True unit.txid = txid = ctx.state.current_tx().id else: if comp.action == dbstate.TxAction.COMMIT: unit.commits_tx = True else: unit.rollbacks_tx = True units.append(unit) unit = None elif isinstance(comp, dbstate.SessionStateQuery): unit.config = ctx.state.current_tx().get_config() unit.modaliases = ctx.state.current_tx().get_modaliases() else: raise RuntimeError('unknown compile state') if unit is not None: units.append(unit) return units async def _ctx_new_con_state(self, *, dbver: int, json_mode: bool, single_query_mode: bool, modaliases, config, legacy_mode: bool, graphql_mode: bool=False): assert isinstance(modaliases, immutables.Map) assert isinstance(config, immutables.Map) db = await self._get_database(dbver) self._current_db_state = dbstate.CompilerConnectionState( dbver, db.schema, modaliases, config) state = self._current_db_state if json_mode: of = pg_compiler.OutputFormat.JSON else: of = pg_compiler.OutputFormat.NATIVE ctx = CompileContext( state=state, output_format=of, single_query_mode=single_query_mode, legacy_mode=legacy_mode, graphql_mode=graphql_mode) return ctx async def _ctx_from_con_state(self, *, txid: int, json_mode: bool, single_query_mode: bool, legacy_mode: bool, graphql_mode: bool=False): if (self._current_db_state is None or self._current_db_state.current_tx().id != txid): self._current_db_state = None raise RuntimeError( f'failed to lookup transaction with id={txid}') state = self._current_db_state if json_mode: of = pg_compiler.OutputFormat.JSON else: of = pg_compiler.OutputFormat.NATIVE ctx = CompileContext( state=state, output_format=of, single_query_mode=single_query_mode, legacy_mode=legacy_mode, graphql_mode=graphql_mode) return ctx # API async def connect(self, dbname: str, dbver: int) -> CompilerDatabaseState: self._dbname = dbname self._cached_db = None await self._get_database(dbver) async def compile_eql( self, dbver: int, eql: bytes, sess_modaliases: immutables.Map, sess_config: immutables.Map, json_mode: bool) -> dbstate.QueryUnit: ctx = await self._ctx_new_con_state( dbver=dbver, json_mode=json_mode, single_query_mode=True, modaliases=sess_modaliases, config=sess_config, legacy_mode=False) units = self._compile(ctx=ctx, eql=eql) assert len(units) == 1 return units[0] async def compile_eql_in_tx( self, txid: int, eql: bytes, json_mode: bool) -> dbstate.QueryUnit: ctx = await self._ctx_from_con_state( txid=txid, json_mode=json_mode, single_query_mode=True, legacy_mode=False) units = self._compile(ctx=ctx, eql=eql) assert len(units) == 1 return units[0] async def compile_eql_script( self, dbver: int, eql: bytes, sess_modaliases: immutables.Map, sess_config: immutables.Map, json_mode: bool, legacy_mode: bool, graphql_mode: bool) -> typing.List[dbstate.QueryUnit]: ctx = await self._ctx_new_con_state( dbver=dbver, json_mode=json_mode, single_query_mode=False, modaliases=sess_modaliases, config=sess_config, legacy_mode=legacy_mode, graphql_mode=graphql_mode) return self._compile(ctx=ctx, eql=eql) async def compile_eql_script_in_tx( self, txid: int, eql: bytes, json_mode: bool, legacy_mode: bool, graphql_mode: bool) -> typing.List[dbstate.QueryUnit]: ctx = await self._ctx_from_con_state( txid=txid, json_mode=json_mode, single_query_mode=False, legacy_mode=legacy_mode, graphql_mode=graphql_mode) return self._compile(ctx=ctx, eql=eql) async def interpret_backend_error(self, dbver, fields): db = await self._get_database(dbver) return errormech.interpret_backend_error(db.schema, fields) <file_sep>/docs/edgeql/functions/generic.rst .. _ref_eql_functions_generic: ======= Generic ======= This section describes mathematical functions provided by EdgeDB. .. eql:function:: std::len(value: anytype) -> int64 :index: length count array A polymorphic function to calculate a "length" of its first argument. Return the number of characters in a :eql:type:`str`, or the number of bytes in :eql:type:`bytes`, or the number of elements in an :eql:type:`array`. .. code-block:: edgeql-repl db> SELECT len('foo'); {3} db> SELECT len([2, 5, 7]); {3} .. eql:function:: std::random() -> float64 Return a pseudo-random number in the range ``0.0 <= x < 1.0``. .. code-block:: edgeql-repl db> SELECT std::random(); {0.62649393780157} .. eql:function:: std::uuid_generate_v1mc() -> uuid Return a version 1 UUID. The algorithm uses a random multicast MAC address instead of the real MAC address of the computer. .. code-block:: edgeql-repl db> SELECT std::uuid_generate_v1mc(); {'1893e2b6-57ce-11e8-8005-13d4be166783'} <file_sep>/edb/lang/edgeql/compiler/setgen.py # # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # 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. # """EdgeQL set compilation functions.""" import contextlib import copy import typing from edb import errors from edb.lang.common import parsing from edb.lang.ir import ast as irast from edb.lang.ir import utils as irutils from edb.lang.schema import abc as s_abc from edb.lang.schema import expr as s_expr from edb.lang.schema import links as s_links from edb.lang.schema import name as s_name from edb.lang.schema import nodes as s_nodes from edb.lang.schema import objtypes as s_objtypes from edb.lang.schema import pointers as s_pointers from edb.lang.schema import sources as s_sources from edb.lang.schema import types as s_types from edb.lang.schema import utils as s_utils from edb.lang.edgeql import ast as qlast from edb.lang.edgeql import parser as qlparser from . import astutils from . import context from . import dispatch from . import inference from . import pathctx from . import schemactx from . import stmtctx from . import typegen PtrDir = s_pointers.PointerDirection def new_set(*, ctx: context.ContextLevel, **kwargs) -> irast.Set: """Create a new ir.Set instance with given attributes. Absolutely all ir.Set instances must be created using this constructor. """ ir_set = irast.Set(**kwargs) ctx.all_sets.append(ir_set) return ir_set def new_set_from_set( ir_set: irast.Set, *, preserve_scope_ns: bool=False, path_id: typing.Optional[irast.PathId]=None, stype: typing.Optional[s_types.Type]=None, ctx: context.ContextLevel) -> irast.Set: """Create a new ir.Set from another ir.Set. The new Set inherits source Set's scope, schema item, expression, and, if *preserve_scope_ns* is set, path_id. If *preserve_scope_ns* is False, the new Set's path_id will be namespaced with the currently active scope namespace. """ if path_id is None: path_id = ir_set.path_id if not preserve_scope_ns: path_id = path_id.merge_namespace(ctx.path_id_namespace) if stype is None: stype = ir_set.stype result = new_set( path_id=path_id, path_scope_id=ir_set.path_scope_id, stype=stype, expr=ir_set.expr, ctx=ctx ) result.rptr = ir_set.rptr return result def compile_path(expr: qlast.Path, *, ctx: context.ContextLevel) -> irast.Set: """Create an ir.Set representing the given EdgeQL path expression.""" anchors = ctx.anchors path_tip = None if expr.partial: if ctx.partial_path_prefix is not None: path_tip = ctx.partial_path_prefix else: raise errors.QueryError( 'could not resolve partial path ', context=expr.context) extra_scopes = {} computables = [] path_sets = [] for i, step in enumerate(expr.steps): if isinstance(step, qlast.Source): # 'self' can only appear as the starting path label # syntactically and is a known anchor path_tip = anchors[step.__class__] elif isinstance(step, qlast.Subject): # '__subject__' can only appear as the starting path label # syntactically and is a known anchor path_tip = anchors[step.__class__] elif isinstance(step, qlast.ObjectRef): if i > 0: raise RuntimeError( 'unexpected ObjectRef as a non-first path item') refnode = None if not step.module and step.name not in ctx.aliased_views: # Check if the starting path label is a known anchor refnode = anchors.get(step.name) if refnode is not None: path_tip = new_set_from_set( refnode, preserve_scope_ns=True, ctx=ctx) else: stype = schemactx.get_schema_type( step, item_types=(s_objtypes.ObjectType,), ctx=ctx) if (stype.get_view_type(ctx.env.schema) is not None and stype.get_name(ctx.env.schema) not in ctx.view_nodes): # This is a schema-level view, as opposed to # a WITH-block or inline alias view. stype = stmtctx.declare_view_from_schema(stype, ctx=ctx) path_tip = class_set(stype, ctx=ctx) view_set = ctx.view_sets.get(stype) if view_set is not None: path_tip = new_set_from_set(view_set, ctx=ctx) path_scope = ctx.path_scope_map.get(view_set) extra_scopes[path_tip] = path_scope.copy() view_scls = ctx.class_view_overrides.get( stype.get_name(ctx.env.schema)) if view_scls is not None: path_tip.stype = view_scls elif isinstance(step, qlast.Ptr): # Pointer traversal step ptr_expr = step ptr_target = None direction = (ptr_expr.direction or s_pointers.PointerDirection.Outbound) if ptr_expr.target: # ... link [IS Target] ptr_target = schemactx.get_schema_type( ptr_expr.target.maintype, ctx=ctx) if not isinstance(ptr_target, s_objtypes.ObjectType): raise errors.QueryError( f'invalid type filter operand: ' f'{ptr_target.get_name(ctx.env.schema)} ' f'is not an object type', context=ptr_expr.target.context) ptr_name = ptr_expr.ptr.name if ptr_expr.type == 'property': # Link property reference; the source is the # link immediately preceding this step in the path. source = path_tip.rptr.ptrcls else: source = path_tip.stype with ctx.newscope(fenced=True, temporary=True) as subctx: if isinstance(source, s_abc.Tuple): path_tip = tuple_indirection_set( path_tip, source=source, ptr_name=ptr_name, source_context=step.context, ctx=subctx) else: path_tip = ptr_step_set( path_tip, source=source, ptr_name=ptr_name, direction=direction, ptr_target=ptr_target, ignore_computable=True, source_context=step.context, ctx=subctx) ptrcls = path_tip.rptr.ptrcls if _is_computable_ptr(ptrcls, ctx=ctx): computables.append(path_tip) else: # Arbitrary expression if i > 0: raise RuntimeError( 'unexpected expression as a non-first path item') with ctx.newscope(fenced=True, temporary=True) as subctx: path_tip = ensure_set( dispatch.compile(step, ctx=subctx), ctx=subctx) if path_tip.path_id.is_type_indirection_path(ctx.env.schema): scope_set = path_tip.rptr.source else: scope_set = path_tip extra_scopes[scope_set] = subctx.path_scope for key_path_id in path_tip.path_id.iter_weak_namespace_prefixes(): mapped = ctx.view_map.get(key_path_id) if mapped is not None: path_tip = new_set( path_id=mapped.path_id, stype=path_tip.stype, expr=mapped.expr, rptr=mapped.rptr, ctx=ctx) break path_sets.append(path_tip) path_tip.context = expr.context pathctx.register_set_in_scope(path_tip, ctx=ctx) for ir_set in computables: scope = ctx.path_scope.find_descendant(ir_set.path_id) if scope is None: # The path is already in the scope, no point # in recompiling the computable expression. continue with ctx.new() as subctx: subctx.path_scope = scope comp_ir_set = computable_ptr_set(ir_set.rptr, ctx=subctx) i = path_sets.index(ir_set) if i != len(path_sets) - 1: path_sets[i + 1].rptr.source = comp_ir_set else: path_tip = comp_ir_set path_sets[i] = comp_ir_set for ir_set, scope in extra_scopes.items(): node = ctx.path_scope.find_descendant(ir_set.path_id) if node is None: # The path portion not being a descendant means # that is is already present in the scope above us, # along with the view scope. continue fuse_scope_branch(ir_set, node, scope, ctx=ctx) if ir_set.path_scope_id is None: pathctx.assign_set_scope(ir_set, node, ctx=ctx) return path_tip def fuse_scope_branch( ir_set: irast.Set, parent: irast.ScopeTreeNode, branch: irast.ScopeTreeNode, *, ctx: context.ContextLevel) -> None: if parent.path_id is None: parent.attach_subtree(branch) else: if branch.path_id is None and len(branch.children) == 1: target_branch = next(iter(branch.children)) else: target_branch = branch if parent.path_id == target_branch.path_id: new_root = irast.new_scope_tree() for child in tuple(target_branch.children): new_root.attach_child(child) parent.attach_subtree(new_root) else: parent.attach_subtree(branch) def ptr_step_set( path_tip: irast.Set, *, source: s_sources.Source, ptr_name: str, direction: PtrDir, ptr_target: typing.Optional[s_nodes.Node]=None, source_context: parsing.ParserContext, ignore_computable: bool=False, ctx: context.ContextLevel) -> irast.Set: ptrcls = resolve_ptr( source, ptr_name, direction, target=ptr_target, source_context=source_context, ctx=ctx) target = ptrcls.get_far_endpoint(ctx.env.schema, direction) path_tip = extend_path( path_tip, ptrcls, direction, target, ignore_computable=ignore_computable, ctx=ctx) if ptr_target is not None and target != ptr_target: path_tip = class_indirection_set( path_tip, ptr_target, optional=False, ctx=ctx) return path_tip def resolve_ptr( near_endpoint: s_sources.Source, pointer_name: str, direction: s_pointers.PointerDirection, target: typing.Optional[s_nodes.Node]=None, *, source_context: typing.Optional[parsing.ParserContext]=None, ctx: context.ContextLevel) -> s_pointers.Pointer: ptr = None if isinstance(near_endpoint, s_sources.Source): ctx.env.schema, ptr = near_endpoint.resolve_pointer( ctx.env.schema, pointer_name, direction=direction, look_in_children=False, include_inherited=True, far_endpoint=target) if ptr is None: if isinstance(near_endpoint, s_links.Link): msg = (f'{near_endpoint.get_displayname(ctx.env.schema)} ' f'has no property {pointer_name!r}') if target: msg += f'of type {target.get_name(ctx.env.schema)!r}' elif direction == s_pointers.PointerDirection.Outbound: msg = (f'{near_endpoint.get_displayname(ctx.env.schema)} ' f'has no link or property {pointer_name!r}') if target: msg += f'of type {target.get_name(ctx.env.schema)!r}' else: nep_name = near_endpoint.get_displayname(ctx.env.schema) path = f'{nep_name}.{direction}{pointer_name}' if target: path += f'[IS {target.get_displayname(ctx.env.schema)}]' msg = f'{path!r} does not resolve to any known path' err = errors.InvalidReferenceError(msg, context=source_context) if direction == s_pointers.PointerDirection.Outbound: near_enpoint_pointers = near_endpoint.get_pointers( ctx.env.schema) s_utils.enrich_schema_lookup_error( err, pointer_name, modaliases=ctx.modaliases, item_types=(s_pointers.Pointer,), collection=near_enpoint_pointers.objects(ctx.env.schema), schema=ctx.env.schema ) raise err else: if direction == s_pointers.PointerDirection.Outbound: bptr = schemactx.get_schema_ptr(pointer_name, ctx=ctx) schema_cls = ctx.env.schema.get('schema::ScalarType') if bptr.get_shortname(ctx.env.schema) == 'std::__type__': ctx.env.schema, ptr = bptr.derive( ctx.env.schema, near_endpoint, schema_cls) if ptr is None: # Reference to a property on non-object msg = 'invalid property reference on a primitive type expression' raise errors.InvalidReferenceError(msg, context=source_context) return ptr def extend_path( source_set: irast.Set, ptrcls: s_pointers.Pointer, direction: PtrDir=PtrDir.Outbound, target: typing.Optional[s_nodes.Node]=None, *, ignore_computable: bool=False, force_computable: bool=False, unnest_fence: bool=False, same_computable_scope: bool=False, ctx: context.ContextLevel) -> irast.Set: """Return a Set node representing the new path tip.""" if ptrcls.is_link_property(ctx.env.schema): src_path_id = source_set.path_id.ptr_path() else: if direction != s_pointers.PointerDirection.Inbound: source = ptrcls.get_near_endpoint(ctx.env.schema, direction) if not source_set.stype.issubclass(ctx.env.schema, source): # Polymorphic link reference source_set = class_indirection_set( source_set, source, optional=True, ctx=ctx) src_path_id = source_set.path_id if target is None: target = ptrcls.get_far_endpoint(ctx.env.schema, direction) path_id = src_path_id.extend(ptrcls, direction, target, ns=ctx.path_id_namespace, schema=ctx.env.schema) target_set = new_set(stype=target, path_id=path_id, ctx=ctx) ptr = irast.Pointer( source=source_set, target=target_set, ptrcls=ptrcls, direction=direction ) target_set.rptr = ptr if (not ignore_computable and _is_computable_ptr( ptrcls, force_computable=force_computable, ctx=ctx)): target_set = computable_ptr_set( ptr, unnest_fence=unnest_fence, same_computable_scope=same_computable_scope, ctx=ctx) return target_set def _is_computable_ptr( ptrcls, *, force_computable: bool=False, ctx: context.ContextLevel) -> bool: try: qlexpr = ctx.source_map[ptrcls][0] except KeyError: pass else: return qlexpr is not None if ptrcls.is_pure_computable(ctx.env.schema): return True if force_computable and ptrcls.get_default(ctx.env.schema) is not None: return True def tuple_indirection_set( path_tip: irast.Set, *, source: s_sources.Source, ptr_name: str, source_context: parsing.ParserContext, ctx: context.ContextLevel) -> irast.Set: el_name = ptr_name el_norm_name = source.normalize_index(ctx.env.schema, el_name) el_type = source.get_subtype(ctx.env.schema, el_name) path_id = irutils.tuple_indirection_path_id( path_tip.path_id, el_norm_name, el_type, schema=ctx.env.schema) expr = irast.TupleIndirection( expr=path_tip, name=el_norm_name, path_id=path_id, context=source_context) return generated_set(expr, ctx=ctx) def class_indirection_set( source_set: irast.Set, target_scls: s_nodes.Node, *, optional: bool, ctx: context.ContextLevel) -> irast.Set: poly_set = new_set(stype=target_scls, ctx=ctx) rptr = source_set.rptr if (rptr is not None and not rptr.ptrcls.singular(ctx.env.schema, rptr.direction)): cardinality = irast.Cardinality.MANY else: cardinality = irast.Cardinality.ONE poly_set.path_id = irutils.type_indirection_path_id( source_set.path_id, target_scls, optional=optional, cardinality=cardinality, schema=ctx.env.schema) ptr = irast.Pointer( source=source_set, target=poly_set, ptrcls=poly_set.path_id.rptr(), direction=poly_set.path_id.rptr_dir() ) poly_set.rptr = ptr return poly_set def class_set( stype: s_nodes.Node, *, path_id: typing.Optional[irast.PathId]=None, ctx: context.ContextLevel) -> irast.Set: if path_id is None: path_id = pathctx.get_path_id(stype, ctx=ctx) return new_set(path_id=path_id, stype=stype, ctx=ctx) def generated_set( expr: irast.Base, path_id: typing.Optional[irast.PathId]=None, *, typehint: typing.Optional[s_types.Type]=None, ctx: context.ContextLevel) -> irast.Set: if typehint is not None: ql_typeref = s_utils.typeref_to_ast(ctx.env.schema, typehint) ir_typeref = typegen.ql_typeref_to_ir_typeref(ql_typeref, ctx=ctx) else: ir_typeref = None alias = ctx.aliases.get('expr') return new_expression_set( expr, path_id, alias=alias, typehint=ir_typeref, ctx=ctx) def get_expression_path_id( t: s_types.Type, alias: str, *, ctx: context.ContextLevel) -> irast.PathId: typename = s_name.Name(module='__expr__', name=alias) return pathctx.get_path_id(t, typename=typename, ctx=ctx) def new_expression_set( ir_expr, path_id=None, alias=None, typehint: typing.Optional[irast.TypeRef]=None, *, ctx: context.ContextLevel) -> irast.Set: if typehint is not None and irutils.is_empty(ir_expr): ir_expr.stype = typehint result_type = inference.infer_type(ir_expr, ctx.env) if path_id is None: path_id = getattr(ir_expr, 'path_id', None) if not path_id: if alias is None: raise ValueError('either path_id or alias are required') path_id = get_expression_path_id(result_type, alias, ctx=ctx) return new_set( path_id=path_id, stype=result_type, expr=ir_expr, context=ir_expr.context, ctx=ctx ) def scoped_set( expr: irast.Base, *, typehint: typing.Optional[s_types.Type]=None, path_id: typing.Optional[irast.PathId]=None, force_reassign: bool=False, ctx: context.ContextLevel) -> irast.Set: if not isinstance(expr, irast.Set): ir_set = generated_set(expr, typehint=typehint, path_id=path_id, ctx=ctx) pathctx.assign_set_scope(ir_set, ctx.path_scope, ctx=ctx) else: if typehint is not None: ir_set = ensure_set(expr, typehint=typehint, path_id=path_id, ctx=ctx) else: ir_set = expr if ir_set.path_scope_id is None or force_reassign: if ctx.path_scope.find_child(ir_set.path_id) and path_id is None: # Protect from scope recursion in the common case by # wrapping the set into a subquery. ir_set = generated_set( ensure_stmt(ir_set, ctx=ctx), typehint=typehint, ctx=ctx) pathctx.assign_set_scope(ir_set, ctx.path_scope, ctx=ctx) return ir_set def ensure_set( expr: irast.Base, *, typehint: typing.Optional[s_types.Type]=None, path_id: typing.Optional[irast.PathId]=None, ctx: context.ContextLevel) -> irast.Set: if not isinstance(expr, irast.Set): expr = generated_set(expr, typehint=typehint, path_id=path_id, ctx=ctx) if (isinstance(expr, irast.EmptySet) and expr.stype is None and typehint is not None): inference.amend_empty_set_type(expr, typehint, schema=ctx.env.schema) if (typehint is not None and not expr.stype.implicitly_castable_to(typehint, ctx.env.schema)): raise errors.QueryError( f'expecting expression of type ' f'{typehint.get_name(ctx.env.schema)}, ' f'got {expr.stype.get_name(ctx.env.schema)}', context=expr.context ) return expr def ensure_stmt(expr: irast.Base, *, ctx: context.ContextLevel) -> irast.Stmt: if not isinstance(expr, irast.Stmt): expr = irast.SelectStmt( result=ensure_set(expr, ctx=ctx), implicit_wrapper=True, ) return expr def computable_ptr_set( rptr: irast.Pointer, *, unnest_fence: bool=False, same_computable_scope: bool=False, ctx: context.ContextLevel) -> irast.Set: """Return ir.Set for a pointer defined as a computable.""" ptrcls = rptr.ptrcls source_set = rptr.source source_scls = source_set.stype # process_view() may generate computable pointer expressions # in the form "self.linkname". To prevent infinite recursion, # self must resolve to the parent type of the view NOT the view # type itself. Similarly, when resolving computable link properties # make sure that we use rptr.ptrcls.derived_from. if source_scls.is_view(ctx.env.schema): source_set = new_set_from_set( source_set, preserve_scope_ns=True, ctx=ctx) source_set.stype = source_scls.peel_view(ctx.env.schema) source_set.shape = [] if source_set.rptr is not None: schema = ctx.env.schema derived_from = source_set.rptr.ptrcls.get_derived_from(schema) if (derived_from is not None and not derived_from.generic(schema) and derived_from.get_derived_from(schema) is not None and ptrcls.is_link_property(schema)): source_set.rptr.ptrcls = derived_from try: qlexpr, qlctx, inner_source_path_id, path_id_ns = \ ctx.source_map[ptrcls] except KeyError: ptrcls_default = ptrcls.get_default(ctx.env.schema) if not ptrcls_default: ptrcls_sn = ptrcls.get_shortname(ctx.env.schema) raise ValueError( f'{ptrcls_sn!r} is not a computable pointer') if isinstance(ptrcls_default, s_expr.ExpressionText): qlexpr = astutils.ensure_qlstmt(qlparser.parse(ptrcls_default)) else: qlexpr = qlast.BaseConstant.from_python(ptrcls_default) qlctx = None inner_source_path_id = None path_id_ns = None if qlctx is None: # Schema-level computable, completely detached context newctx = ctx.detached else: newctx = _get_computable_ctx( rptr=rptr, source=source_set, source_scls=source_scls, inner_source_path_id=inner_source_path_id, path_id_ns=path_id_ns, same_scope=same_computable_scope, qlctx=qlctx, ctx=ctx) if ptrcls.is_link_property(ctx.env.schema): source_path_id = rptr.source.path_id.ptr_path() else: source_path_id = rptr.target.path_id.src_path() path_id = source_path_id.extend( ptrcls, s_pointers.PointerDirection.Outbound, ptrcls.get_target(ctx.env.schema), ns=ctx.path_id_namespace, schema=ctx.env.schema) with newctx() as subctx: subctx.view_scls = ptrcls.get_target(ctx.env.schema) subctx.view_rptr = context.ViewRPtr( source_scls, ptrcls=ptrcls, rptr=rptr) subctx.anchors[qlast.Source] = source_set subctx.empty_result_type_hint = ptrcls.get_target(ctx.env.schema) if isinstance(qlexpr, qlast.Statement) and unnest_fence: subctx.stmt_metadata[qlexpr] = context.StatementMetadata( is_unnest_fence=True) comp_ir_set = dispatch.compile(qlexpr, ctx=subctx) if ptrcls in ctx.pending_cardinality: comp_ir_set_copy = copy.copy(comp_ir_set) specified_card, source_ctx = ctx.pending_cardinality[ptrcls] stmtctx.get_pointer_cardinality_later( ptrcls=ptrcls, irexpr=comp_ir_set_copy, specified_card=specified_card, source_ctx=source_ctx, ctx=ctx) def _check_cardinality(ctx): if ptrcls.singular(ctx.env.schema): stmtctx.enforce_singleton_now(comp_ir_set_copy, ctx=ctx) stmtctx.at_stmt_fini(_check_cardinality, ctx=ctx) comp_ir_set.stype = ptrcls.get_target(ctx.env.schema) comp_ir_set.path_id = path_id comp_ir_set.rptr = rptr rptr.target = comp_ir_set return comp_ir_set def _get_computable_ctx( *, rptr: irast.Pointer, source: irast.Set, source_scls: s_nodes.Node, inner_source_path_id: irast.PathId, path_id_ns: typing.Optional[irast.WeakNamespace], same_scope: bool, qlctx: context.ContextLevel, ctx: context.ContextLevel) -> typing.ContextManager: @contextlib.contextmanager def newctx(): with ctx.new() as subctx: subctx.class_view_overrides = {} subctx.partial_path_prefix = None subctx.modaliases = qlctx.modaliases.copy() subctx.aliased_views = qlctx.aliased_views.new_child() if source_scls.is_view(ctx.env.schema): scls_name = source.stype.get_name(ctx.env.schema) subctx.aliased_views[scls_name] = None subctx.source_map = qlctx.source_map.copy() subctx.view_nodes = qlctx.view_nodes.copy() subctx.view_sets = qlctx.view_sets.copy() subctx.view_map = qlctx.view_map.new_child() source_scope = pathctx.get_set_scope(rptr.source, ctx=ctx) if source_scope and source_scope.namespaces: subctx.path_id_namespace |= source_scope.namespaces if path_id_ns is not None: subctx.path_id_namespace |= {path_id_ns} subctx.pending_stmt_own_path_id_namespace = { irast.WeakNamespace(ctx.aliases.get('ns')), } if path_id_ns is not None and same_scope: subctx.pending_stmt_own_path_id_namespace.add(path_id_ns) subns = subctx.pending_stmt_full_path_id_namespace = \ set(subctx.pending_stmt_own_path_id_namespace) self_view = ctx.view_sets.get(source.stype) if self_view: if self_view.path_id.namespace: subns.update(self_view.path_id.namespace) inner_path_id = self_view.path_id.merge_namespace( subctx.path_id_namespace | subns) else: if source.path_id.namespace: subns.update(source.path_id.namespace) if inner_source_path_id is not None: # The path id recorded in the source map may # contain namespaces referring to a temporary # scope subtree used by `process_view()`. # Since we recompile the computable expression # using the current path id namespace, the # original source path id needs to be fixed. inner_path_id = inner_source_path_id \ .strip_namespace(qlctx.path_id_namespace) \ .merge_namespace(subctx.path_id_namespace) else: inner_path_id = pathctx.get_path_id( source.stype, ctx=subctx) inner_path_id = inner_path_id.merge_namespace(subns) remapped_source = new_set_from_set(rptr.source, ctx=ctx) remapped_source.rptr = rptr.source.rptr subctx.view_map[inner_path_id] = remapped_source yield subctx return newctx <file_sep>/edb/lang/schema/expr.py # # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # 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. # from edb.lang.common import typed class ExpressionText(str): pass class ExpressionList(typed.FrozenTypedList, type=ExpressionText): @classmethod def merge_values(cls, target, sources, field_name, *, schema): result = target.get_explicit_field_value(schema, field_name, None) for source in sources: theirs = source.get_explicit_field_value(schema, field_name, None) if theirs: if result is None: result = theirs[:] else: result.extend(theirs) return result <file_sep>/edb/lang/ir/ast.py # # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # 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. # import typing from edb.lang.common.exceptions import EdgeDBError from edb.lang.common import ast, compiler, parsing from edb.lang.schema import modules as s_modules from edb.lang.schema import name as sn from edb.lang.schema import objects as so from edb.lang.schema import pointers as s_pointers from edb.lang.schema import schema as s_schema from edb.lang.schema import types as s_types from edb.lang.edgeql import ast as qlast from edb.lang.edgeql import functypes as ft from .pathid import PathId, WeakNamespace # noqa from .scopetree import InvalidScopeConfiguration, ScopeTreeNode # noqa def new_scope_tree(): return ScopeTreeNode(fenced=True) Cardinality = qlast.Cardinality class ASTError(EdgeDBError): pass class Base(ast.AST): __ast_hidden__ = {'context'} context: parsing.ParserContext def __repr__(self): return ( f'<ir.{self.__class__.__name__} at 0x{id(self):x}>' ) class Pointer(Base): source: Base target: Base ptrcls: s_pointers.PointerLike direction: s_pointers.PointerDirection anchor: typing.Union[str, ast.MetaAST] show_as_anchor: typing.Union[str, ast.MetaAST] @property def is_inbound(self): return self.direction == s_pointers.PointerDirection.Inbound class BaseTypeRef(Base): name: str class TypeRef(BaseTypeRef): maintype: str subtypes: typing.List[BaseTypeRef] class AnyTypeRef(BaseTypeRef): pass class AnyTupleRef(BaseTypeRef): pass class Set(Base): path_id: PathId path_scope_id: int stype: s_types.Type source: Base view_source: Base expr: Base rptr: Pointer anchor: typing.Union[str, ast.MetaAST] show_as_anchor: typing.Union[str, ast.MetaAST] shape: typing.List[Base] def __repr__(self): return \ f'<ir.Set \'{self.path_id or self.stype.id}\' at 0x{id(self):x}>' class Command(Base): pass class Statement(Command): expr: Set views: typing.Dict[sn.Name, s_types.Type] params: typing.Dict[str, s_types.Type] cardinality: Cardinality stype: s_types.Type view_shapes: typing.Dict[so.Object, typing.List[s_pointers.Pointer]] schema: s_schema.Schema scope_tree: ScopeTreeNode scope_map: typing.Dict[Set, str] source_map: typing.Dict[s_pointers.Pointer, typing.Tuple[qlast.Expr, compiler.ContextLevel, PathId, typing.Optional[WeakNamespace]]] class Expr(Base): pass class EmptySet(Set): pass class BaseConstant(Expr): value: str stype: s_types.Type def __init__(self, *args, stype, **kwargs): super().__init__(*args, stype=stype, **kwargs) if self.stype is None: raise ValueError('cannot create irast.Constant without a type') if self.value is None: raise ValueError('cannot create irast.Constant without a value') class StringConstant(BaseConstant): pass class RawStringConstant(BaseConstant): pass class IntegerConstant(BaseConstant): pass class FloatConstant(BaseConstant): pass class BooleanConstant(BaseConstant): pass class BytesConstant(BaseConstant): pass class Parameter(Base): name: str stype: s_types.Type class TupleElement(Base): name: str val: Base class Tuple(Expr): named: bool = False elements: typing.List[TupleElement] stype: s_types.Type class Array(Expr): elements: typing.List[Base] stype: s_types.Type class SetOp(Expr): left: Set right: Set op: str exclusive: bool = False left_card: Cardinality right_card: Cardinality class TypeCheckOp(Expr): left: Set right: typing.Union[BaseTypeRef, Array] op: str class IfElseExpr(Expr): condition: Set if_expr: Set else_expr: Set if_expr_card: Cardinality else_expr_card: Cardinality class Coalesce(Base): left: Set right: Set right_card: Cardinality class SortExpr(Base): expr: Base direction: str nones_order: qlast.NonesOrder class Call(Expr): """Operator or a function call.""" # Bound callable has polymorphic parameters and # a polymorphic return type. func_polymorphic: bool # Bound callable's name. func_shortname: sn.Name # If the bound callable is a "FROM SQL" callable, this # attribute will be set to the name of the SQL function. func_sql_function: typing.Optional[str] # Whether the return value of the function should be # explicitly cast into the declared function return type. force_return_cast: bool # Bound arguments. args: typing.List[Base] # Typemods of parameters. This list corresponds to ".args" # (so `zip(args, params_typemods)` is valid.) params_typemods: typing.List[ft.TypeModifier] # Return type and typemod. In bodies of polymorphic functions # the return type can be polymorphic; in queries the return # type will be a concrete schema type. stype: s_types.Type typemod: ft.TypeModifier class FunctionCall(Call): # initial value needed for aggregate function calls to correctly # handle empty set func_initial_value: Base # True if the bound function has a variadic parameter and # there are no arguments that are bound to it. has_empty_variadic: bool = False # Set to the type of the variadic parameter of the bound function # (or None, if the function has no variadic parameters.) variadic_param_type: typing.Optional[s_types.Type] class OperatorCall(Call): # The kind of the bound operator (INFIX, PREFIX, etc.). operator_kind: ft.OperatorKind # If this operator maps directly onto an SQL operator, this # will contain the operator name, and, optionally, backend # operand types. sql_operator: typing.Optional[typing.Tuple[str, ...]] = None class TupleIndirection(Expr): expr: Base name: str path_id: PathId class IndexIndirection(Expr): expr: Base index: Base class SliceIndirection(Expr): expr: Base start: Base stop: Base step: Base class TypeCast(Expr): """<Type>Expr""" expr: Base cast_name: str from_type: BaseTypeRef to_type: BaseTypeRef sql_function: str sql_cast: bool sql_expr: bool class Stmt(Base): name: str result: Base cardinality: Cardinality parent_stmt: Base iterator_stmt: Base class SelectStmt(Stmt): where: Base orderby: typing.List[SortExpr] offset: Base limit: Base implicit_wrapper: bool = False class GroupStmt(Stmt): subject: Base groupby: typing.List[Base] result: SelectStmt group_path_id: PathId class MutatingStmt(Stmt): subject: Set class InsertStmt(MutatingStmt): pass class UpdateStmt(MutatingStmt): where: Base class DeleteStmt(MutatingStmt): where: Base class SessionStateCmd(Command): modaliases: typing.Dict[typing.Optional[str], s_modules.Module] testmode: bool <file_sep>/edb/lang/ir/utils.py # # This source file is part of the EdgeDB open source project. # # Copyright 2015-present MagicStack Inc. and the EdgeDB authors. # # 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. # import json import typing from edb import errors from edb.lang.common import ast from edb.lang.edgeql import functypes as ft from edb.lang.schema import abc as s_abc from edb.lang.schema import objtypes as s_objtypes from edb.lang.schema import name as s_name from edb.lang.schema import pointers as s_pointers from edb.lang.schema import pseudo as s_pseudo from edb.lang.schema import schema as s_schema from edb.lang.schema import sources as s_sources # NOQA from edb.lang.schema import types as s_types # NOQA from . import ast as irast def get_source_references(ir): result = set() flt = lambda n: isinstance(n, irast.Set) and n.expr is None ir_sets = ast.find_children(ir, flt) for ir_set in ir_sets: result.add(ir_set.stype) return result def get_terminal_references(ir): result = set() parents = set() flt = lambda n: isinstance(n, irast.Set) and n.expr is None ir_sets = ast.find_children(ir, flt) for ir_set in ir_sets: result.add(ir_set) if ir_set.rptr: parents.add(ir_set.rptr.source) return result - parents def get_variables(ir): result = set() flt = lambda n: isinstance(n, irast.Parameter) result.update(ast.find_children(ir, flt)) return result def is_const(ir): flt = lambda n: isinstance(n, irast.Set) and n.expr is None ir_sets = ast.find_children(ir, flt) variables = get_variables(ir) return not ir_sets and not variables def is_set_membership_expr(ir): return ( isinstance(ir, irast.OperatorCall) and ir.operator_kind is ft.OperatorKind.INFIX and ir.func_shortname in {'std::IN', 'std::NOT IN'} ) def is_distinct_expr(ir): return ( isinstance(ir, irast.OperatorCall) and ir.operator_kind is ft.OperatorKind.PREFIX and ir.func_shortname == 'std::DISTINCT' ) def is_exists_expr(ir): return ( isinstance(ir, irast.OperatorCall) and ir.operator_kind is ft.OperatorKind.PREFIX and ir.func_shortname == 'std::EXISTS' ) def is_empty_array_expr(ir): return ( isinstance(ir, irast.Array) and not ir.elements ) def is_untyped_empty_array_expr(ir): return ( is_empty_array_expr(ir) and (ir.stype is None or ir.stype.contains_any()) ) def get_id_path_id( path_id: irast.PathId, *, schema: s_schema.Schema) -> irast.PathId: """For PathId representing an object, return (PathId).(std::id).""" source: s_sources.Source = path_id.target assert isinstance(source, s_objtypes.ObjectType) return path_id.extend( source.getptr(schema, 'id'), s_pointers.PointerDirection.Outbound, schema.get('std::uuid'), schema=schema) def get_subquery_shape(ir_expr): if (isinstance(ir_expr, irast.Set) and isinstance(ir_expr.expr, irast.Stmt) and isinstance(ir_expr.expr.result, irast.Set)): result = ir_expr.expr.result if result.shape: return result elif is_view_set(result): return get_subquery_shape(result) elif ir_expr.view_source is not None: return get_subquery_shape(ir_expr.view_source) else: return None def is_empty(ir_expr): return ( isinstance(ir_expr, irast.EmptySet) or (isinstance(ir_expr, irast.Array) and not ir_expr.elements) or (isinstance(ir_expr, irast.Set) and is_empty(ir_expr.expr)) ) def is_view_set(ir_expr): return ( isinstance(ir_expr, irast.Set) and (isinstance(ir_expr.expr, irast.SelectStmt) and isinstance(ir_expr.expr.result, irast.Set)) or ir_expr.view_source is not None ) def is_subquery_set(ir_expr): return ( isinstance(ir_expr, irast.Set) and isinstance(ir_expr.expr, irast.Stmt) ) def is_scalar_view_set(ir_expr, *, schema: s_schema.Schema): return ( isinstance(ir_expr, irast.Set) and len(ir_expr.path_id) == 1 and ir_expr.path_id.is_scalar_path() and ir_expr.path_id.target.is_view(schema) ) def is_inner_view_reference(ir_expr): return ( isinstance(ir_expr, irast.Set) and ir_expr.view_source is not None ) def is_simple_path(ir_expr): return ( isinstance(ir_expr, irast.Set) and ir_expr.expr is None and (ir_expr.rptr is None or is_simple_path(ir_expr.rptr.source)) ) def is_implicit_wrapper(ir_expr): return ( isinstance(ir_expr, irast.SelectStmt) and ir_expr.implicit_wrapper ) def unwrap_set(ir_set): if is_implicit_wrapper(ir_set.expr): return ir_set.expr.result else: return ir_set def wrap_stmt_set(ir_set): if is_subquery_set(ir_set): src_stmt = ir_set.expr elif is_inner_view_reference(ir_set): src_stmt = ir_set.view_source.expr else: raise ValueError('expecting subquery IR set or a view reference') stmt = irast.SelectStmt( result=ir_set, path_scope=src_stmt.path_scope, specific_path_scope=src_stmt.specific_path_scope ) return stmt def new_empty_set(schema, *, stype=None, alias): if stype is None: path_id_scls = s_pseudo.Any.create() else: path_id_scls = stype typename = s_name.Name(module='__expr__', name=alias) path_id = irast.PathId.from_type(schema, path_id_scls, typename=typename) return irast.EmptySet(path_id=path_id, stype=stype) class TupleIndirectionLink(s_pointers.PointerLike): """A Link-alike that can be used in tuple indirection path ids.""" def __init__(self, element_name): self._name = s_name.Name(module='__tuple__', name=str(element_name)) def __hash__(self): return hash((self.__class__, self._name)) def __eq__(self, other): if not isinstance(other, self.__class__): return False return self._name == other._name def get_shortname(self, schema): return self._name def get_name(self, schema): return self._name def get_path_id_name(self, schema): return self._name def is_link_property(self, schema): return False def generic(self, schema): return False def get_source(self, schema): return None def singular(self, schema, direction=s_pointers.PointerDirection.Outbound) -> bool: return True def scalar(self): return self._target.is_scalar() def is_pure_computable(self, schema): return False def tuple_indirection_path_id(tuple_path_id, element_name, element_type, *, schema): return tuple_path_id.extend( TupleIndirectionLink(element_name), s_pointers.PointerDirection.Outbound, element_type, schema=schema ) class TypeIndirectionLink(s_pointers.PointerLike): """A Link-alike that can be used in type indirection path ids.""" def __init__(self, source, target, *, optional, cardinality): name = 'optindirection' if optional else 'indirection' self._name = s_name.Name(module='__type__', name=name) self._source = source self._target = target self._cardinality = cardinality self._optional = optional def get_name(self, schema): return self._name def get_shortname(self, schema): return self._name def get_path_id_name(self, schema): return self._name def is_link_property(self, schema): return False def generic(self, schema): return False def get_source(self, schema): return self._source def get_target(self, schema): return self._target def get_cardinality(self, schema): return self._cardinality def singular(self, schema, direction=s_pointers.PointerDirection.Outbound) -> bool: if direction is s_pointers.PointerDirection.Outbound: return self.get_cardinality(schema) is irast.Cardinality.ONE else: return True def scalar(self): return self._target.is_scalar() def is_pure_computable(self, schema): return False def type_indirection_path_id(path_id, target_type, *, optional: bool, cardinality: irast.Cardinality, schema): return path_id.extend( TypeIndirectionLink(path_id.target, target_type, optional=optional, cardinality=cardinality), s_pointers.PointerDirection.Outbound, target_type, schema=schema ) def get_source_context_as_json( expr: irast.Base, exctype=errors.InternalServerError) -> typing.Optional[str]: if expr.context: details = json.dumps({ 'line': expr.context.start.line, 'column': expr.context.start.column, 'name': expr.context.name, 'code': exctype.get_code(), }) else: details = None return details def typeref_to_type(schema, typeref: irast.TypeRef) -> s_types.Type: if typeref.subtypes: coll = s_types.Collection.get_class(typeref.maintype) result = coll.from_subtypes( schema, [typeref_to_type(schema, t) for t in typeref.subtypes]) else: result = schema.get(typeref.maintype) return result def type_to_typeref(schema, t: s_types.Type, *, _name=None) -> irast.TypeRef: if t.is_anytuple(): result = irast.AnyTupleRef() elif t.is_any(): result = irast.AnyTypeRef() elif not isinstance(t, s_abc.Collection): result = irast.TypeRef( name=_name, maintype=t.get_name(schema), ) elif isinstance(t, s_abc.Tuple) and t.named: result = irast.TypeRef( name=_name, maintype=t.schema_name, subtypes=[ type_to_typeref(schema, st, _name=sn) for sn, st in t.element_types.items() ] ) else: result = irast.TypeRef( name=_name, maintype=t.schema_name, subtypes=[ type_to_typeref(schema, st) for st in t.get_subtypes() ] ) return result <file_sep>/edb/lang/edgeql/compiler/cast.py # # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # 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. # """EdgeQL compiler routines for type casts.""" import typing from edb import errors from edb.lang.common import parsing from edb.lang.ir import ast as irast from edb.lang.ir import utils as irutils from edb.lang.schema import casts as s_casts from edb.lang.schema import functions as s_func from edb.lang.schema import types as s_types from edb.lang.edgeql import functypes as ft from . import astutils from . import context from . import inference from . import polyres from . import setgen from . import viewgen def compile_cast( ir_expr: irast.Base, new_stype: s_types.Type, *, srcctx: parsing.ParserContext, ctx: context.ContextLevel) -> irast.OperatorCall: if isinstance(ir_expr, irast.EmptySet): # For the common case of casting an empty set, we simply # generate a new EmptySet node of the requested type. return irutils.new_empty_set(ctx.env.schema, stype=new_stype, alias=ir_expr.path_id.target_name.name) elif irutils.is_untyped_empty_array_expr(ir_expr): # Ditto for empty arrays. return setgen.generated_set( irast.Array(elements=[], stype=new_stype), ctx=ctx) ir_set = setgen.ensure_set(ir_expr, ctx=ctx) orig_stype = ir_set.stype if orig_stype == new_stype: return ir_set elif orig_stype.is_object_type() and new_stype.is_object_type(): # Object types cannot be cast between themselves, # as cast is a _constructor_ operation, and the only # valid way to construct an object is to INSERT it. raise errors.QueryError( f'cannot cast object type ' f'{orig_stype.get_displayname(ctx.env.schema)!r} ' f'to {new_stype.get_displayname(ctx.env.schema)!r}, use ' f'`...[IS {new_stype.get_displayname(ctx.env.schema)}]` instead', context=srcctx) if isinstance(ir_set.expr, irast.Array): return _cast_array_literal( ir_set, orig_stype, new_stype, srcctx=srcctx, ctx=ctx) elif orig_stype.is_tuple(): return _cast_tuple( ir_set, orig_stype, new_stype, srcctx=srcctx, ctx=ctx) elif orig_stype.issubclass(ctx.env.schema, new_stype): # The new type is a supertype of the old type, # and is always a wider domain, so we simply reassign # the stype. return _inheritance_cast_to_ir( ir_set, orig_stype, new_stype, ctx=ctx) elif new_stype.issubclass(ctx.env.schema, orig_stype): # The new type is a subtype, so may potentially have # a more restrictive domain, generate a cast call. return _inheritance_cast_to_ir( ir_set, orig_stype, new_stype, ctx=ctx) elif orig_stype.is_array(): return _cast_array( ir_set, orig_stype, new_stype, srcctx=srcctx, ctx=ctx) else: json_t = ctx.env.schema.get('std::json') if (new_stype.issubclass(ctx.env.schema, json_t) and ir_set.path_id.is_objtype_path()): # JSON casts of objects are special: we want the full shape # and not just an identity. viewgen.compile_view_shapes(ir_set, ctx=ctx) return _compile_cast( ir_expr, orig_stype, new_stype, srcctx=srcctx, ctx=ctx) def _compile_cast( ir_expr: irast.Base, orig_stype: s_types.Type, new_stype: s_types.Type, *, srcctx: parsing.ParserContext, ctx: context.ContextLevel) -> irast.Set: ir_set = setgen.ensure_set(ir_expr, ctx=ctx) cast = _find_cast(orig_stype, new_stype, srcctx=srcctx, ctx=ctx) if cast is None: raise errors.QueryError( f'cannot cast ' f'{orig_stype.get_displayname(ctx.env.schema)!r} to ' f'{new_stype.get_displayname(ctx.env.schema)!r}', context=srcctx or ir_set.context) return _cast_to_ir(ir_set, cast, orig_stype, new_stype, ctx=ctx) def _cast_to_ir( ir_set: irast.Set, cast: s_casts.Cast, orig_stype: s_types.Type, new_stype: s_types.Type, *, ctx: context.ContextLevel) -> irast.Set: orig_typeref = irutils.type_to_typeref(ctx.env.schema, orig_stype) new_typeref = irutils.type_to_typeref(ctx.env.schema, new_stype) cast_ir = irast.TypeCast( expr=ir_set, from_type=orig_typeref, to_type=new_typeref, cast_name=cast.get_name(ctx.env.schema), sql_function=cast.get_from_function(ctx.env.schema), sql_cast=cast.get_from_cast(ctx.env.schema), sql_expr=bool(cast.get_code(ctx.env.schema)), ) return setgen.ensure_set(cast_ir, ctx=ctx) def _inheritance_cast_to_ir( ir_set: irast.Set, orig_stype: s_types.Type, new_stype: s_types.Type, *, ctx: context.ContextLevel) -> irast.Set: orig_typeref = irutils.type_to_typeref(ctx.env.schema, orig_stype) new_typeref = irutils.type_to_typeref(ctx.env.schema, new_stype) cast_ir = irast.TypeCast( expr=ir_set, from_type=orig_typeref, to_type=new_typeref, cast_name=None, sql_function=None, sql_cast=True, sql_expr=False, ) return setgen.ensure_set(cast_ir, ctx=ctx) class CastParamListWrapper(list): def find_named_only(self, schema): return {} def find_variadic(self, schema): return None def has_polymorphic(self, schema): return False class CastCallableWrapper: # A wrapper around a cast object to make it quack like a callable # for the purposes of polymorphic resolution. def __init__(self, cast): self._cast = cast def has_inlined_defaults(self, schema): return False def get_params(self, schema): from_type_param = s_func.ParameterDesc( num=0, name='val', type=self._cast.get_from_type(schema), typemod=ft.TypeModifier.SINGLETON, kind=ft.ParameterKind.POSITIONAL, default=None, ) to_type_param = s_func.ParameterDesc( num=0, name='_', type=self._cast.get_to_type(schema), typemod=ft.TypeModifier.SINGLETON, kind=ft.ParameterKind.POSITIONAL, default=None, ) return CastParamListWrapper([from_type_param, to_type_param]) def get_return_type(self, schema): return self._cast.get_to_type(schema) def _find_cast( orig_stype: s_types.Type, new_stype: s_types.Type, *, srcctx: parsing.ParserContext, ctx: context.ContextLevel) -> typing.Optional[s_casts.Cast]: casts = ctx.env.schema.get_casts_to_type(new_stype) if not casts: return None args = [ (orig_stype, None), (new_stype, None), ] matched = polyres.find_callable( (CastCallableWrapper(c) for c in casts), args=args, kwargs={}, ctx=ctx) if len(matched) == 1: return matched[0].func._cast elif len(matched) > 1: raise errors.QueryError( f'cannot unambiguously cast ' f'{orig_stype.get_displayname(ctx.env.schema)!r} ' f'to {new_stype.get_displayname(ctx.env.schema)!r}', context=srcctx) else: return None def _cast_tuple( ir_set: irast.Base, orig_stype: s_types.Type, new_stype: s_types.Type, *, srcctx: parsing.ParserContext, ctx: context.ContextLevel) -> irast.Base: direct_cast = _find_cast(orig_stype, new_stype, srcctx=srcctx, ctx=ctx) if direct_cast is not None: # Direct casting to non-tuple involves casting each tuple # element and also keeping the cast around the whole tuple. # This is to trigger the downstream logic of casting # objects (in elements of the tuple). elements = [] for i, n in enumerate(orig_stype.element_types): val = setgen.generated_set( irast.TupleIndirection( expr=ir_set, name=n ), ctx=ctx ) val.path_id = irutils.tuple_indirection_path_id( ir_set.path_id, n, orig_stype.element_types[n], schema=ctx.env.schema) val_type = inference.infer_type(val, ctx.env) # Element cast val = compile_cast(val, new_stype, ctx=ctx, srcctx=srcctx) elements.append(irast.TupleElement(name=n, val=val)) new_tuple = setgen.ensure_set( astutils.make_tuple(elements, named=orig_stype.named, ctx=ctx), ctx=ctx ) return _cast_to_ir( new_tuple, direct_cast, orig_stype, new_stype, ctx=ctx) if not new_stype.is_tuple(): raise errors.QueryError( f'cannot cast {orig_stype.get_displayname(ctx.env.schema)!r} ' f'to {new_stype.get_displayname(ctx.env.schema)!r}', context=srcctx) if len(orig_stype.element_types) != len(new_stype.element_types): raise errors.QueryError( f'cannot cast {orig_stype.get_displayname(ctx.env.schema)!r} ' f'to {new_stype.get_displayname(ctx.env.schema)!r}: ', f'the number of elements is not the same', context=srcctx) # For tuple-to-tuple casts we generate a new tuple # to simplify things on sqlgen side. new_names = list(new_stype.element_types) elements = [] for i, n in enumerate(orig_stype.element_types): val = setgen.generated_set( irast.TupleIndirection( expr=ir_set, name=n ), ctx=ctx ) val.path_id = irutils.tuple_indirection_path_id( ir_set.path_id, n, orig_stype.element_types[n], schema=ctx.env.schema) val_type = inference.infer_type(val, ctx.env) new_el_name = new_names[i] new_subtypes = list(new_stype.get_subtypes()) if val_type != new_stype.element_types[new_el_name]: # Element cast val = compile_cast( val, new_subtypes[i], ctx=ctx, srcctx=srcctx) elements.append(irast.TupleElement(name=new_el_name, val=val)) return setgen.ensure_set(astutils.make_tuple( named=new_stype.named, elements=elements, ctx=ctx), ctx=ctx) def _cast_array( ir_set: irast.Set, orig_stype: s_types.Type, new_stype: s_types.Type, *, srcctx: parsing.ParserContext, ctx: context.ContextLevel) -> irast.Base: direct_cast = _find_cast(orig_stype, new_stype, srcctx=srcctx, ctx=ctx) if direct_cast is None: if not new_stype.is_array(): raise errors.QueryError( f'cannot cast {orig_stype.get_displayname(ctx.env.schema)!r} ' f'to {new_stype.get_displayname(ctx.env.schema)!r}', context=srcctx) el_type = new_stype.get_subtypes()[0] else: el_type = new_stype orig_el_type = orig_stype.get_subtypes()[0] el_cast = _find_cast(orig_el_type, el_type, srcctx=srcctx, ctx=ctx) if el_cast is None: raise errors.QueryError( f'cannot cast {orig_stype.get_displayname(ctx.env.schema)!r} ' f'to {new_stype.get_displayname(ctx.env.schema)!r}', context=srcctx) from None if el_cast.get_from_cast(ctx.env.schema): # Simple cast return _cast_to_ir( ir_set, direct_cast, orig_stype, new_stype, ctx=ctx) else: # Functional cast, need to apply element-wise. raise errors.QueryError( f'cannot cast {orig_stype.get_displayname(ctx.env.schema)!r} ' f'to {new_stype.get_displayname(ctx.env.schema)!r}: ' f'non-trivial array casts are not implemented', context=srcctx) from None def _cast_array_literal( ir_set: irast.Set, orig_stype: s_types.Type, new_stype: s_types.Type, *, srcctx: parsing.ParserContext, ctx: context.ContextLevel) -> irast.Base: orig_typeref = irutils.type_to_typeref(ctx.env.schema, orig_stype) new_typeref = irutils.type_to_typeref(ctx.env.schema, new_stype) direct_cast = _find_cast(orig_stype, new_stype, srcctx=srcctx, ctx=ctx) if direct_cast is None: if not new_stype.is_array(): raise errors.QueryError( f'cannot cast {orig_stype.get_displayname(ctx.env.schema)!r} ' f'to {new_stype.get_displayname(ctx.env.schema)!r}', context=srcctx) from None el_type = new_stype.get_subtypes()[0] else: el_type = new_stype casted_els = [] for el in ir_set.expr.elements: el = compile_cast(el, el_type, ctx=ctx, srcctx=srcctx) casted_els.append(el) new_array = setgen.generated_set( irast.Array(elements=casted_els, stype=orig_stype), ctx=ctx) if direct_cast is not None: return _cast_to_ir( new_array, direct_cast, orig_stype, new_stype, ctx=ctx) else: cast_ir = irast.TypeCast( expr=new_array, from_type=orig_typeref, to_type=new_typeref, sql_cast=True, ) return setgen.ensure_set(cast_ir, ctx=ctx) <file_sep>/edb/lang/edgeql/compiler/func.py # # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # 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. # """EdgeQL compiler routines for function calls and operators.""" import typing from edb import errors from edb.lang.ir import ast as irast from edb.lang.ir import utils as irutils from edb.lang.schema import name as sn from edb.lang.schema import types as s_types from edb.lang.edgeql import ast as qlast from edb.lang.edgeql import functypes as ft from edb.lang.edgeql import parser as qlparser from . import astutils from . import cast from . import context from . import dispatch from . import inference from . import pathctx from . import polyres from . import setgen from . import typegen @dispatch.compile.register(qlast.FunctionCall) def compile_FunctionCall( expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Base: env = ctx.env if isinstance(expr.func, str): if ctx.func is not None: ctx_func_params = ctx.func.get_params(env.schema) if ctx_func_params.get_by_name(env.schema, expr.func): raise errors.QueryError( f'parameter `{expr.func}` is not callable', context=expr.context) funcname = expr.func else: funcname = sn.Name(expr.func[1], expr.func[0]) funcs = env.schema.get_functions(funcname, module_aliases=ctx.modaliases) if funcs is None: raise errors.QueryError( f'could not resolve function name {funcname}', context=expr.context) args, kwargs = compile_call_args(expr, funcname, ctx=ctx) matched = polyres.find_callable(funcs, args=args, kwargs=kwargs, ctx=ctx) if not matched: raise errors.QueryError( f'could not find a function variant {funcname}', context=expr.context) elif len(matched) > 1: raise errors.QueryError( f'function {funcname} is not unique', context=expr.context) else: matched_call = matched[0] args, params_typemods = finalize_args(matched_call, ctx=ctx) matched_func_params = matched_call.func.get_params(env.schema) variadic_param = matched_func_params.find_variadic(env.schema) variadic_param_type = None if variadic_param is not None: variadic_param_type = variadic_param.get_type(env.schema) matched_func_ret_type = matched_call.func.get_return_type(env.schema) is_polymorphic = ( any(p.get_type(env.schema).is_polymorphic(env.schema) for p in matched_func_params.objects(env.schema)) and matched_func_ret_type.is_polymorphic(env.schema) ) matched_func_initial_value = matched_call.func.get_initial_value( env.schema) func = matched_call.func node = irast.FunctionCall( args=args, func_shortname=func.get_shortname(env.schema), func_polymorphic=is_polymorphic, func_sql_function=func.get_from_function(env.schema), force_return_cast=func.get_force_return_cast(env.schema), params_typemods=params_typemods, context=expr.context, stype=matched_call.return_type, typemod=matched_call.func.get_return_typemod(env.schema), has_empty_variadic=matched_call.has_empty_variadic, variadic_param_type=variadic_param_type, ) if matched_func_initial_value is not None: rtype = inference.infer_type(node, env=ctx.env) iv_ql = qlast.TypeCast( expr=qlparser.parse_fragment(matched_func_initial_value), type=typegen.type_to_ql_typeref(rtype, ctx=ctx) ) node.func_initial_value = dispatch.compile(iv_ql, ctx=ctx) return setgen.ensure_set(node, typehint=matched_call.return_type, ctx=ctx) def compile_operator( qlexpr: qlast.Base, op_name: str, qlargs: typing.List[qlast.Base], *, ctx: context.ContextLevel) -> irast.OperatorCall: env = ctx.env opers = env.schema.get_operators(op_name, module_aliases=ctx.modaliases) if opers is None: raise errors.QueryError( f'no operator matches the given name and argument types', context=qlexpr.context) args = [] for ai, qlarg in enumerate(qlargs): with ctx.newscope(fenced=True) as fencectx: # We put on a SET OF fence preemptively in case this is # a SET OF arg, which we don't know yet due to polymorphic # matching. We will remove it if necessary in `finalize_args()`. arg_ir = setgen.ensure_set( dispatch.compile(qlarg, ctx=fencectx), ctx=fencectx) arg_ir = setgen.scoped_set( setgen.ensure_stmt(arg_ir, ctx=fencectx), ctx=fencectx) arg_type = inference.infer_type(arg_ir, ctx.env) if arg_type is None: raise errors.QueryError( f'could not resolve the type of operand ' f'#{ai} of {op_name}', context=qlarg.context) args.append((arg_type, arg_ir)) matched = polyres.find_callable(opers, args=args, kwargs={}, ctx=ctx) if len(matched) == 1: matched_call = matched[0] else: if len(args) == 2: ltype = args[0][0].material_type(env.schema) rtype = args[1][0].material_type(env.schema) types = ( f'{ltype.get_displayname(env.schema)!r} and ' f'{rtype.get_displayname(env.schema)!r}') else: types = ', '.join( repr( a[0].material_type(env.schema).get_displayname(env.schema) ) for a in args ) if not matched: raise errors.QueryError( f'operator {str(op_name)!r} cannot be applied to ' f'operands of type {types}', context=qlexpr.context) elif len(matched) > 1: detail = ', '.join( f'`{m.func.get_display_signature(ctx.env.schema)}`' for m in matched ) raise errors.QueryError( f'operator {str(op_name)!r} is ambiguous for ' f'operands of type {types}', hint=f'Possible variants: {detail}.', context=qlexpr.context) args, params_typemods = finalize_args(matched_call, ctx=ctx) oper = matched_call.func matched_params = oper.get_params(env.schema) matched_ret_type = oper.get_return_type(env.schema) is_polymorphic = ( any(p.get_type(env.schema).is_polymorphic(env.schema) for p in matched_params.objects(env.schema)) and matched_ret_type.is_polymorphic(env.schema) ) in_polymorphic_func = ( ctx.func is not None and ctx.func.get_params(env.schema).has_polymorphic(env.schema) ) from_op = oper.get_from_operator(env.schema) if (from_op is not None and oper.get_code(env.schema) is None and oper.get_from_function(env.schema) is None and not in_polymorphic_func): sql_operator = tuple(from_op) else: sql_operator = None node = irast.OperatorCall( args=args, func_shortname=oper.get_shortname(env.schema), func_polymorphic=is_polymorphic, func_sql_function=oper.get_from_function(env.schema), sql_operator=sql_operator, force_return_cast=oper.get_force_return_cast(env.schema), operator_kind=oper.get_operator_kind(env.schema), params_typemods=params_typemods, context=qlexpr.context, stype=matched_call.return_type, typemod=oper.get_return_typemod(env.schema), ) return setgen.ensure_set(node, typehint=matched_call.return_type, ctx=ctx) def compile_call_arg(arg: qlast.FuncArg, *, ctx: context.ContextLevel) -> irast.Base: arg_ql = arg.arg if arg.sort or arg.filter: arg_ql = astutils.ensure_qlstmt(arg_ql) if arg.filter: arg_ql.where = astutils.extend_qlbinop(arg_ql.where, arg.filter) if arg.sort: arg_ql.orderby = arg.sort + arg_ql.orderby with ctx.newscope(fenced=True) as fencectx: # We put on a SET OF fence preemptively in case this is # a SET OF arg, which we don't know yet due to polymorphic # matching. We will remove it if necessary in `finalize_args()`. arg_ir = setgen.ensure_set( dispatch.compile(arg_ql, ctx=fencectx), ctx=fencectx) return setgen.scoped_set( setgen.ensure_stmt(arg_ir, ctx=fencectx), ctx=fencectx) def compile_call_args( expr: qlast.FunctionCall, funcname: sn.Name, *, ctx: context.ContextLevel) \ -> typing.Tuple[ typing.List[typing.Tuple[s_types.Type, irast.Base]], typing.Dict[str, typing.Tuple[s_types.Type, irast.Base]]]: args = [] kwargs = {} for ai, arg in enumerate(expr.args): arg_ir = compile_call_arg(arg, ctx=ctx) arg_type = inference.infer_type(arg_ir, ctx.env) if arg_type is None: raise errors.QueryError( f'could not resolve the type of positional argument ' f'#{ai} of function {funcname}', context=arg.context) args.append((arg_type, arg_ir)) for aname, arg in expr.kwargs.items(): arg_ir = compile_call_arg(arg, ctx=ctx) arg_type = inference.infer_type(arg_ir, ctx.env) if arg_type is None: raise errors.QueryError( f'could not resolve the type of named argument ' f'${aname} of function {funcname}', context=arg.context) kwargs[aname] = (arg_type, arg_ir) return args, kwargs def finalize_args(bound_call: polyres.BoundCall, *, ctx: context.ContextLevel) -> typing.List[irast.Base]: args = [] typemods = [] for barg in bound_call.args: param = barg.param arg = barg.val if param is None: # defaults bitmask args.append(arg) typemods.append(ft.TypeModifier.SINGLETON) continue param_mod = param.get_typemod(ctx.env.schema) typemods.append(param_mod) if param_mod is not ft.TypeModifier.SET_OF: arg_scope = pathctx.get_set_scope(arg, ctx=ctx) param_shortname = param.get_shortname(ctx.env.schema) if arg_scope is not None: arg_scope.collapse() pathctx.assign_set_scope(arg, None, ctx=ctx) # Arg was wrapped for scope fencing purposes, # but that fence has been removed above, so unwrap it. arg = irutils.unwrap_set(arg) if (param_mod is ft.TypeModifier.OPTIONAL or param_shortname in bound_call.null_args): pathctx.register_set_in_scope(arg, ctx=ctx) pathctx.mark_path_as_optional(arg.path_id, ctx=ctx) paramtype = param.get_type(ctx.env.schema) param_kind = param.get_kind(ctx.env.schema) if param_kind is ft.ParameterKind.VARIADIC: # For variadic params, paramtype would be array<T>, # and we need T to cast the arguments. paramtype = list(paramtype.get_subtypes())[0] if (not barg.valtype.issubclass(ctx.env.schema, paramtype) and not paramtype.is_polymorphic(ctx.env.schema)): # The callable form was chosen via an implicit cast, # cast the arguments so that the backend has no # wiggle room to apply its own (potentially different) # casting. arg = cast.compile_cast( arg, paramtype, srcctx=None, ctx=ctx) args.append(arg) return args, typemods <file_sep>/edb/server/pgsql/errormech.py # # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # 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. # import collections import json import re import uuid import asyncpg from edb import errors from edb.lang.schema import name as sn from edb.lang.schema import objtypes as s_objtypes from . import common class ErrorMech: error_res = { asyncpg.IntegrityConstraintViolationError: collections.OrderedDict(( ('cardinality', re.compile(r'^.*".*_cardinality_idx".*$')), ('link_target', re.compile(r'^.*link target constraint$')), ('constraint', re.compile(r'^.*;schemaconstr(?:#\d+)?".*$')), ('id', re.compile(r'^.*"(?:\w+)_data_pkey".*$')), ('link_target_del', re.compile(r'^.*link target policy$')), )) } @classmethod async def _interpret_db_error( cls, schema, intro_mech, constr_mech, err): if isinstance(err, asyncpg.NotNullViolationError): source_name = pointer_name = None if err.schema_name and err.table_name: tabname = (err.schema_name, err.table_name) source = common.get_object_from_backend_name( schema, s_objtypes.ObjectType, tabname) source_name = source.get_displayname(schema) if err.column_name: pointer_name = err.column_name if pointer_name is not None: pname = f'{source_name}.{pointer_name}' return errors.MissingRequiredError( 'missing value for required property {}'.format(pname), source_name=source_name, pointer_name=pointer_name) else: return errors.InternalServerError(err.message) elif isinstance(err, asyncpg.IntegrityConstraintViolationError): source = pointer = None for ecls, eres in cls.error_res.items(): if isinstance(err, ecls): break else: eres = {} for type, ere in eres.items(): m = ere.match(err.message) if m: error_type = type break else: return errors.InternalServerError(err.message) if error_type == 'cardinality': err = 'cardinality violation' errcls = errors.CardinalityViolationError return errcls(err, source=source, pointer=pointer) elif error_type == 'link_target': if err.detail: try: detail = json.loads(err.detail) except ValueError: detail = None if detail is not None: srcname = detail.get('source') ptrname = detail.get('pointer') target = detail.get('target') expected = detail.get('expected') if srcname and ptrname: srcname = sn.Name(srcname) ptrname = sn.Name(ptrname) lname = '{}.{}'.format(srcname, ptrname.name) else: lname = '' msg = 'invalid target for link {!r}: {!r} (' \ 'expecting {!r})'.format(lname, target, ' or '.join(expected)) else: msg = 'invalid target for link' return errors.UnknownLinkError(msg) elif error_type == 'link_target_del': return errors.ConstraintViolationError( err.message, detail=err.detail) elif error_type == 'constraint': if err.constraint_name is None: return errors.InternalServerError(err.message) constraint_id, _, _ = err.constraint_name.rpartition(';') try: constraint_id = uuid.UUID(constraint_id) except ValueError: return errors.InternalServerError(err.message) constraint = schema.get_by_id(constraint_id) return errors.ConstraintViolationError( constraint.format_error_message(schema)) elif error_type == 'id': msg = 'unique link constraint violation' errcls = errors.ConstraintViolationError return errcls(msg=msg) else: return errors.InternalServerError(err.message)
0ec43a20a03e7b1ed88e4bbc11e647691f918f86
[ "Python", "Makefile", "reStructuredText" ]
21
reStructuredText
dungeon2567/edgedb
f5bbd3bc6599faad320f7821d771b56396a1fb9a
1d34d7ec9f571de6a0e56ac79bae9da3c36e752c
refs/heads/master
<file_sep>const express = require('express'); const router = express.Router(); // Controllers const authController = require('../controllers/auth'); // Loga o usuario router.post('/login', authController.login); // Registra uma usuário novo router.post('/register', authController.register); module.exports = router; <file_sep>import React, { Component } from 'react'; import {View, Text, Image, StyleSheet} from 'react-native'; export default class Publi extends Component{ render(){ return( <View> <Image style={styles.imagePubli} souce={{uri: this.props.data.file}} /> <Text style={styles.nomePubli}>{this.props.data.title}</Text> </View> ) } } const styles = StyleSheet.create({ container:{ }, nomePubli:{ fontSize: 18, }, imagePubli:{ width: 110, height: 150, }, });<file_sep># FiscalizeGuanambi Para rodar o projeto é bem simples Basta instalar o nodeJs e as bibliotecas do react native Instalar o expo no site - expo.io o próximo é jogar um npm instal no terminal para instalar todos os repositórios usados no projeto e por último só rodar o expo start no terminal e o projeto já vai rodar <file_sep>const express = require('express'); const cors = require('cors'); const app = express(); // Configurações iniciais app.use(cors()); app.use(express.json()); app.use(express.urlencoded({ extended: true })); // Rotas const authRoutes = require('./routes/auth'); const claimsRoutes = require('./routes/claims'); app.use('/auth', authRoutes); app.use('/claims', claimsRoutes); // Tratamento de error app.use((req, res, next) => { const erro = new Error('Route not found.'); erro.status = 404; next(erro); }); app.use((error, req, res) => { res.status(error.status || 500); return res.send({ error: { mensage: error.message, status: error.status } }); }); module.exports = app; <file_sep>export default [ { title: 'Dia Que meu carro capotou', place: 'To nem aí', image: 'https://diariodonordeste.verdesmares.com.br/image/contentid/policy:1.3029307:1609794989/acidente.jpg?f=16x9&h=720&q=0.8&w=1280&$p$f$h$q$w=5e5fab2', autor: 'thauan.a', }, { title: '<NAME>', place: 'paris', image: 'https://f7j8i5n9.stackpathcdn.com/wp-content/uploads/2016/04/Paris.jpg', autor: 'thauan.a', }, ]; <file_sep>import React, { useState, useEffect } from "react"; import { Modal, StyleSheet, View, Pressable } from "react-native"; import { Text } from 'galio-framework'; import * as ImagePicker from 'expo-image-picker'; function ImagePickerModal({ modalVisible, onClose, onSetClaimsData }) { useEffect(() => { (async () => { if (Platform.OS !== 'web') { const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (status !== 'granted') { alert('Desculpe, precisamos de permissões da câmera para fazer isso funcionar!'); } } })(); }, []); async function choseGalery() { let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [4, 3], quality: 1, base64: true }); if (!result.cancelled) { let prefix; let ext; if (result.fileName) { [prefix, ext] = result.fileName; ext = ext.toLowerCase() === 'heic' ? 'jpg' : ext; } else { prefix = new Date().getTime(); ext = 'jpg' } const data = { type: result.type, name: `${prefix}`, ext, file: result.base64 } onSetClaimsData(data); onClose(); } } return ( <Modal visible={modalVisible} animationType="slide" transparent={true} onRequestClose={() => onClose()} > <View style={styles.centeredView}> <View style={styles.modalView}> <Pressable style={styles.modalButtons} onPress={() => choseGalery()} > <Text style={styles.modalButtonsText}>Selecionar da galeria</Text> </Pressable> </View> </View> </Modal> ) } const styles = StyleSheet.create({ centeredView: { flex: 1, justifyContent: "center", alignItems: "center", marginTop: 22 }, modalView: { margin: 20, backgroundColor: "white", borderRadius: 4, padding: 35, shadowColor: "#000", shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.25, shadowRadius: 4, elevation: 5 }, modalButtons: { width: '100%' }, modalButtonsText: { fontSize: 16, fontWeight: '600', }, divider: { marginVertical: 20, borderWidth: 1, borderColor: '#cecece' } }); export default ImagePickerModal;<file_sep>import React from 'react'; import { ImageBackground, Image, StyleSheet, StatusBar, Dimensions, Platform } from 'react-native'; import { Block, Button, Text, theme, Input } from 'galio-framework'; import { LinearGradient } from 'expo-linear-gradient'; import Constants from 'expo-constants'; const { height, width } = Dimensions.get('screen'); import { Images, materialTheme } from '../constants/'; import { HeaderHeight } from "../constants/utils"; export default class Pro extends React.Component { constructor(props){ super(props); this.state = { detalhes:'', } } calcular = () => { console.log(this.state.detalhes); } render() { const { navigation } = this.props; return ( <Block flex style={styles.container}> <Block flex> <Block> <Text color="#000" size={30}>Cadastrar post</Text> <Text size={20} color='#000'> Dê mais detalhes </Text> <Input name="detalhes" onChangeText={(text) => this.setState({detalhes:text})} right color="black" placeholder="Descrição" /> <Button shadowless style={styles.button} color={materialTheme.COLORS.BUTTON_COLOR} onPress={() => { this.calcular(); navigation.navigate('Addimg')}} //onPress={() => navigation.navigate('LocalPost')} > AVANÇAR </Button> </Block> </Block> </Block> ); } } const styles = StyleSheet.create({ container: { flex: 1, padding: 10, paddingTop: Constants.statusBarHeight + 10, marginHorizontal: 10, backgroundColor: "#F5F5F5", marginTop: Platform.OS === 'android' ? -HeaderHeight : 0, }, button: { width: width - theme.SIZES.BASE * 4, height: theme.SIZES.BASE * 3, shadowRadius: 0, shadowOpacity: 0, }, }); <file_sep>import React from 'react'; import { Pressable, View, StyleSheet, Dimensions } from 'react-native'; import { Button, Text, Input, } from 'galio-framework'; import { materialTheme } from '../constants/'; import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; import { useState } from 'react'; import ImagePickerModal from '../components/ImagePicker'; import { Alert } from 'react-native'; import API from '../services/api' export default function Pro({ navigation }) { const [claimsData, setClaimsData] = useState({}); const [step, setStep] = useState(0) const [showImagePicker, setShowImagePicker] = useState(false); const [loading, setLoading] = useState(false); function handleSubmitStep1() { setLoading(true); validateFields(); } function validateFields() { const { title, description, file } = claimsData; if (!title || !description || !file) { Alert.alert("Oops!", "Campos inválidos, preencha todos os campos."); setLoading(false) return } nextStep(); } function nextStep() { setLoading(false); setStep(1) } function handleSubmitStep2() { setLoading(true); validateFields2(); } function validateFields2() { const { address } = claimsData; if (!address) { Alert.alert("Oops!", "Campos inválidos, preencha todos os campos."); setLoading(false) return } mountData(); } function mountData() { const { file, ...rest } = claimsData; const newData = { ...rest, media: file} saveClaim(newData); } function saveClaim(data) { API.post('/claims/create', data) .then(({data}) => { if (!data.success) { Alert.alert("Oops!", data.message); setLoading(false); return } Alert.alert( "Sucesso!", 'Reclamação criada com sucesso', [{}, { text: "OK", onPress: () => { setClaimsData({}); setStep(0); setLoading(false); }}]); }) .catch(() => { Alert.alert("Oops!", 'Houve uma falhada inesperada, contate o suporte.'); setLoading(false) }); } return ( <> <View style={styles.container}> {step === 0 && ( <> <View> <Text color="#000" size={30}>Cadastrar post</Text> </View> <View style={{ marginTop: 16 }}> <Text size={20} color='#000'>Dê um titulo</Text> <Input color="black" placeholder="Titulo" onChangeText={title => setClaimsData({ ...claimsData, title })} /> </View> <View style={{ marginTop: 16 }}> <Text size={20} color='#000'>Dê mais detalhes</Text> <Input color="black" placeholder="Descrição" onChangeText={description => setClaimsData({ ...claimsData, description })} /> </View> <Pressable style={styles.uploadImage} onPress={() => setShowImagePicker(true)} > <Text style={styles.uploadImageText}> {claimsData.file ? 'Arquivo enviado' : 'Escolha um bom arquivo'} </Text> </Pressable> <View style={{ marginTop: 25 }}> <Button style={styles.button} color={materialTheme.COLORS.BUTTON_COLOR} shadowless onPress={() => handleSubmitStep1()} > {loading ? 'Aguarde...' : 'Avançar'} </Button> </View> </> )} {step === 1 && ( <> <Text size={20} color='#000' style={{ marginBottom: 16 }}> Qual a localização? </Text> <GooglePlacesAutocomplete query={{ key: '<KEY>', language: 'cs', components: 'country:br' }} onFail={(error) => console.error(error)} onPress={(data, details = null) => { setClaimsData({ ...claimsData, address: data.description }) }} /> <Button style={styles.button} color={materialTheme.COLORS.BUTTON_COLOR} shadowless disabled={loading} onPress={() => handleSubmitStep2()} > {loading ? 'Aguarde...' : 'Salvar'} </Button> </> )} </View> <ImagePickerModal modalVisible={showImagePicker} onClose={() => setShowImagePicker(false)} onSetClaimsData={(file) => setClaimsData({ ...claimsData, file })} /> </> ); } const styles = StyleSheet.create({ container: { flex: 1, paddingHorizontal: 16, paddingVertical: 30, backgroundColor: "#F5F5F5", }, button: { width: '100%', margin: 0, }, uploadImage: { width: '100%', height: 50, marginTop: 16, padding: 8, alignItems: 'center', justifyContent: 'center', borderStyle: 'dashed', borderWidth: 1, borderColor: '#000', borderRadius: 6 }, uploadImageText: { fontSize: 16, fontWeight: '700' } });<file_sep>// Keys const serviceAccount = require('../keys/serviceAccountKey.json'); // JWT const jwt = require('jsonwebtoken'); // Utils const NodeRSA = require('node-rsa'); /** * Validar sessão do usuário * */ exports.validateSession = async (req, res, next) => { init(); function init() { validateHeader(); } function validateHeader() { const { authorization } = req.headers; if (!authorization) { return res .status(200) .send({ success: false, message: 'Nenhum token fornecido' }); } const token = authorization.split('Bearer ')[1].trim(); validateSession(token); } function validateSession(token) { const publicKey = new NodeRSA() .importKey(serviceAccount.private_key, 'pkcs8-private-pem') .exportKey('pkcs8-public-pem'); jwt.verify(token, publicKey, { algorithms: ['RS256'] }, err => { if (err) { return res .status(200) .send({ success: false, message: 'Sessão inválida' }); } next(); }); } }; <file_sep>const functions = require('firebase-functions'); // API const app = require('./src/index'); module.exports = { api: functions.https.onRequest(app) }; <file_sep>// Firebase const firebase = require('../config/firebase'); const db = firebase.db(); const bucket = firebase.storage().bucket(); // Validações const { Validator } = require('node-input-validator'); // Utils const { v4: uuidv4 } = require('uuid'); /** * Busca as reclamações * */ exports.search = async (req, res) => { init(); function init() { getClaims(); } function getClaims() { const collectionsRef = db.collection('claims'); collectionsRef .get() .then(querySnapshot => { if (querySnapshot.empty) { return res.status(200).send({ success: false, message: 'Nenhuma reclamação encontrada.' }); } const claims = []; querySnapshot.forEach(doc => { claims.push({ ...doc.data(), id: doc.id }); }); return res .status(200) .send({ success: true, data: { claims: claims } }); }) .catch(error => { return res .status(200) .send({ success: false, message: error.message || error }); }); } }; /** * Busca as reclamações * */ exports.searchById = async (req, res) => { init(); function init() { validateFields(); } function validateFields() { const { params } = req; const validator = new Validator(params, { id: 'required|string' }); validator .check() .then(matched => { if (!matched) { const { errors } = validator; return res .status(200) .send({ success: false, message: 'Campos inválidos!', errors }); } getClaimById(params.id); }) .catch(error => { return res .status(200) .send({ success: false, message: error.message || error }); }); } function getClaimById(docId) { const docRef = db.collection('claims').doc(docId); docRef .get() .then(doc => { const claimData = { ...doc.data(), id: doc.id }; return res.status(200).send({ success: true, data: claimData }); }) .catch(error => { return res .status(200) .send({ success: false, message: error.message || error }); }); } }; /** * Cria uma nova reclamação * */ exports.create = async (req, res) => { init(); function init() { validateFields(); } function validateFields() { const validator = new Validator(req.body, { address: 'required|string', title: 'required|string', description: 'required|string', media: 'required|object' }); validator .check() .then(matched => { if (!matched) { const { errors } = validator; return res .status(200) .send({ success: false, message: 'Campos inválidos!', errors }); } generateDocId(); }) .catch(error => { return res .status(200) .send({ success: false, message: error.message || error }); }); } function generateDocId() { const docId = db.collection('claims').doc().id; req.body.docId = docId; handleUploadMedias(); } async function handleUploadMedias() { const { media, docId } = req.body; const downloadUrl = await uploadMediasBucket(media, docId); media.file = downloadUrl; mountData(); } async function uploadMediasBucket(media, docId) { const { file: base64EncodedImageString, name, ext } = media; const uuid = uuidv4(); const fileName = `claims/${docId}/${name}.${ext}`; const imageBuffer = Buffer.from(base64EncodedImageString, 'base64'); const file = bucket.file(fileName); const url = file.save( imageBuffer, { metadata: { metadata: { firebaseStorageDownloadTokens: uuid } } }, error => { if (error) { return ''; } return `https://firebasestorage.googleapis.com/v0/b/${ bucket.name }/o/${encodeURIComponent(fileName)}?alt=media&token=${uuid}`; } ); return url; } function mountData() { const { docId, title, description, ...rest } = req.body; const newData = { ...rest, personalData: { createdAt: firebase.db.Timestamp.fromDate(new Date()), title, description } }; saveClaimsDB(newData, docId); } function saveClaimsDB(claimData, docId) { const docRef = db.collection('claims').doc(docId); docRef .set(claimData) .then(() => { return res.status(200).send({ success: true, data: claimData }); }) .catch(error => { return res .status(200) .send({ success: false, message: error.message || error }); }); } }; /** * Apaga uma reclamação * */ exports.delete = async (req, res) => { init(); function init() { validateFields(); } function validateFields() { const { params } = req; const validator = new Validator(params, { id: 'required|string' }); validator .check() .then(matched => { if (!matched) { const { errors } = validator; return res .status(200) .send({ success: false, message: 'Campos inválidos!', errors }); } deleteClaim(params.id); }) .catch(error => { return res .status(200) .send({ success: false, message: error.message || error }); }); } function deleteClaim(docId) { const docRef = db.collection('claims').doc(docId); docRef .delete() .then(() => { return res .status(200) .send({ success: true, message: 'Reclamação excluída com sucesso' }); }) .catch(error => { return res .status(200) .send({ success: false, message: error.message || error }); }); } };
5857fd295bae1b6929d6bb9c49923fd24120b92b
[ "JavaScript", "Markdown" ]
11
JavaScript
thauan312/FiscalizeGuanambi
b7befcfbb288b3d47287ba0f27676cfa55a6e956
5f4b9a21e88f4ac820a2ce2531806a41a074c58e
refs/heads/master
<file_sep>//importing api's const express = require('express') const Users = require('./routes/usersRoute') const Auth = require('./routes/authRoute') const Contact = require('./routes/contactRoute') const Blogs = require('./routes/blogRoute') const Notification = require('./routes/notifications') const Projects = require('./routes/projectRoute') const Requests = require('./routes/requestRoute') const payments = require('./routes/paymentRoute') // const Dashboard = require('./routes/dashboardRoute') module.exports = function(app){ //look for dependency //Middlware app.use(express.json()) app.use('/api/users',Users) app.use('/api/auth',Auth) app.use('/api/contact',Contact) // app.use('/api/dashboard',Dashboard) app.use('/api/notifications',Notification) app.use('/api/blogs',Blogs) app.use('/api/projects',Projects) app.use('/api/requests',Requests) app.use('/api/payments',payments) // app.use(error) }<file_sep>const mongoose = require("mongoose"); const PaymentsSchema = new mongoose.Schema({ user:{ firstname:{type:String,default : null}, lastname:{type:String,default : null}, email:{type:String,default : null}, city:{type:String,default : null}, zip_code:{type:String,default : null} }, charge_id: { type: String }, payload: { type: String }, amount: { type: String }, status: { type: String }, type: { type: String }, method:{ type:String } }); PaymentsSchema.set('timestamps', true) module.exports = Payments = mongoose.model("Payments", PaymentsSchema)<file_sep>// const bcrypt = require("bcrypt"); // const { check, validationResult } = require("express-validator"); // const moment = require("moment"); // const _ = require("lodash"); // const { baseUrl } = require("../utils/url"); // //models // //services // const { sendEmail } = require("../service/email"); // const UserModel = require("../models/User.model"); // // const deliveryModel = require("../models/delivery.model"); // exports.SALES_ANALYITICS = async (req, res) => { // const { year } = req.query; // let year1 = year ? year : new Date().getFullYear(); // try { // const dates = [ // new Date(year1, 0), // new Date(year1, 1), // new Date(year1, 2), // new Date(year1, 3), // new Date(year1, 4), // new Date(year1, 5), // new Date(year1, 6), // new Date(year1, 7), // new Date(year1, 8), // new Date(year1, 9), // new Date(year1, 10), // new Date(year1, 11), // ]; // let data = []; // let countData = []; // await Promise.all( // dates.map(async (date, index) => { // let from = moment(date).startOf("month").toDate(); // let to = moment(date).endOf("month").toDate(); // const uploadHour = { createdAt: { $gte: from, $lte: to } }; // let total_requests = await asyncRunner(uploadHour); // // console.log(total_requests); // data.push({ // count: total_requests[0].length > 0 ? total_requests[0][0].count : 0, // month: index, // }); // }) // ); // data = data.sort((a, b) => a.month - b.month); // data.map((item) => countData.push(item.count)); // // console.log(countData) // await res.status(200).json(countData); // } catch (err) { // res.status(500).json({ error: err.message }); // } // }; // function asyncRunner(uploadHour) { // return Promise.all([test(uploadHour)]); // } // function test(uploadHour) { // // let totalusers = await // return new Promise((resolve, reject) => { // resolve( // deliveryModel.aggregate([ // { // $match: { // ...uploadHour, // }, // }, // { // $group: { // _id: null, // count: { $sum: 1 }, // }, // }, // ]) // ); // }); // } // exports.GET_TOTAL_STATS = async (req, res) => { // try { // const total_users = await UserModel.find({ // isAdmin: false, // }).countDocuments(); // const total_deliveries = await deliveryModel.find().countDocuments(); // let data = { // total_users: total_users, // total_deliveries: total_deliveries, // }; // return res.json({ totalstats: data }); // } catch (err) { // console.log(err); // res.status(500).json({ // message: "Internal Server Error", // }); // } // }; // // console.log(countryWiseOrder) // let data = {} // let mapData = countryWiseOrder.map(item=> // data[item.doc.countryCode] = 0 // ) // const organizationOrderPerMonth = await orderModel.aggregate( [ // { $group: { _id: "$organization", "doc":{"$first":"$$ROOT"}, total_order: { $sum: 1 }, // total_qrcodes: {$sum :'$no_of_qr_codes'}, // total_scanned: {$sum :'$scan_count'} // // "doc":{"$first":"$$ROOT"}, // // "$replaceRoot":{"newRoot":"$doc"} // } // }, // // {"$replaceRoot":{"newRoot":"$doc"}}, // { $project: { _id: 0 , total_order:1,total_qrcodes:1,total_scanned:1 } } // ] ) // console.log(organizationOrderPerMonth) // return res.json({totalstats:totalstats?totalstats[0]:null,totalorganizations:totalorganizations?totalorganizations[0]:null,countryWiseOrder:countryWiseOrder,mapData: mapData?data:[]}) // } catch (err) { // console.log(err); // res.status(500).json({ // message: "Internal Server Error", // }); // } // }; <file_sep>const express = require("express"); const router = express.Router(); const { check, validationResult } = require("express-validator"); const auth = require("../middleware/authMiddleware"); const admin = require("../middleware/adminMiddleware"); const projectController = require("../controllers/projectController"); //create new Project router.post( "/create", [ auth, admin, [ check("title", "title is required").not().isEmpty(), check("type", "type is required").not().isEmpty(), check("description", "description is required").not().isEmpty(), ], ], projectController.CREATE_PROJECT ); // get all projects router.get("/", projectController.GET_PROJECTS); // getProejctBYID router.get("/:project_id", projectController.GET_PROJECT_BY_ID); // router.post("/edit", projectController.EDIT_BLOG); module.exports = router; <file_sep>const express = require("express"); const { check } = require("express-validator"); const auth = require("../middleware/authMiddleware"); const paymentController = require("../controllers/paymentController"); const router = express.Router(); router.post( "/pay", [ // auth, [ check("first_name", "first_name is required").not().isEmpty(), check("lastname", "lastname is required").not().isEmpty(), check("email", "email is required").not().isEmpty(), check("city", "city is required").not().isEmpty(), check("zip_code", "zip_code is required").not().isEmpty(), check("payment_method", "payment_method is required").not().isEmpty(), check("charges", " charges is required").not().isEmpty(), check("card_number", "card_number is required").not().isEmpty(), check("card_expiry", "card_expiry is required").not().isEmpty(), check("card_cvv", "card_cvv is required").not().isEmpty(), ], ], paymentController.DONATE ); router.get( "/mysubscription", [ auth, ], paymentController.MY_SUBSCRIPTION ); module.exports = router<file_sep>const express = require("express"); const bcrypt = require("bcrypt"); const _ = require("lodash"); const fs = require("fs"); var path = require("path"); const { baseUrl } = require("../utils/url"); // const { CreateNotification } = require('../utils/Notification') const { check, validationResult } = require("express-validator"); const config = require("config"); const moment = require("moment"); //model const User = require("../models/User.model"); var isBase64 = require("is-base64"); const { GET_IMAGE_PATH } = require("../helper/helper"); const e = require("express"); exports.Register = async (req, res) => { try { // console.log(req.body); // console.log(req.files); // let image = req.files let error = []; const errors = validationResult(req); const url = baseUrl(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } // if user duplicated let user = await User.findOne({ email: req.body.email.toLowerCase() }); if (user) { error.push({ message: "User already registered" }); return res.status(400).json({ errors: error }); } //if password doesnot match if (req.body.password !== req.body.confirmpassword) { error.push({ message: "confirm password doesnot match" }); return res.status(400).json({ errors: error }); } let pathName = "uploads/images/abc.jpg"; const salt = await bcrypt.genSalt(10); //decode the base 4 image if (req.files.image) { let image = req.files.image ? req.files.image : ""; pathName = await GET_IMAGE_PATH(image); console.log(pathName); } // } //create new user user = new User({ firstname: req.body.firstname, lastname: req.body.lastname, email: req.body.email.toLowerCase(), image: pathName, phone_no: req.body.phone_no ? req.body.phone_no : null, }); //hash passoword user.password = <PASSWORD>.hashSync(req.body.password, salt); const token = await user.generateAuthToken(); await user.save(); const notification = { notificationType: "Admin", notifiableId: null, title: "New User Created", body: "New User has been Registered", payload: { type: "users", id: user._id, }, }; // CreateNotification(notification) user.image = `${url}${user.image}`; res.status(200).json({ message: "Registration Success, please login to proceed", token: token, createdUser: user, // data: JSON.stringify(response1.data) }); } catch (error) { res.status(500).json({ error: error.message, }); } }; exports.GetUsers = async (req, res) => { const { page, limit, selection, fieldname, order, from, to, keyword } = req.query; const currentpage = page ? parseInt(page, 10) : 1; const per_page = limit ? parseInt(limit, 10) : 5; const CurrentField = fieldname ? fieldname : "createdAt"; const currentOrder = order ? parseInt(order, 10) : -1; let offset = (currentpage - 1) * per_page; const sort = {}; sort[CurrentField] = currentOrder; // return res.json(sort) const currentSelection = selection ? { status: selection } : {}; //date filter // let Datefilter = from && to ? // { createdAt: { $gte: moment(from).startOf('day').toDate(), $lte: moment(to).endOf('day').toDate() } } // : {} let Datefilter = ""; if (from && to) { Datefilter = from && to ? { createdAt: { $gte: moment(from).startOf("day").toDate(), $lte: moment(to).endOf("day").toDate(), }, } : {}; console.log("fromto", Datefilter); } else if (from) { console.log("from"); Datefilter = from ? { createdAt: { $gte: moment(from).startOf("day").toDate(), $lte: moment(new Date()).endOf("day").toDate(), }, } : {}; console.log("from", Datefilter); } else if (to) { console.log.apply("to"); Datefilter = to ? { createdAt: { $lte: moment(to).endOf("day").toDate() } } : {}; console.log("to", Datefilter); } const search = keyword ? { $or: [ { firstname: { $regex: `${keyword}`, $options: "i" } }, { lastname: { $regex: `${keyword}`, $options: "i" } }, { email: { $regex: `${keyword}`, $options: "i" } }, ], } : {}; // console.log(Datefilter) try { let users = await User.find({ ...currentSelection, ...Datefilter, ...search, isAdmin: false, }) .limit(per_page) .skip(offset) .sort(sort); // console.log(users) if (!users.length) { return res.status(400).json({ message: "no user exist" }); } const url = baseUrl(req); users.forEach((user) => (user.image = `${url}${user.image}`)); let Totalcount = await User.find({ ...currentSelection, ...Datefilter, ...search, isAdmin: false, }).countDocuments(); const paginate = { currentPage: currentpage, perPage: per_page, total: Math.ceil(Totalcount / per_page), to: offset, data: users, }; res.status(200).json(paginate); } catch (error) { res.status(500).json({ error: error.message }); } }; exports.EditProfile = async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { res.status(400).json({ errors: errors.array() }); } const { firstname, lastname, city, country, phone_no, image, state, zip_code, address, } = req.body; try { let user = await User.findOne({ _id: req.user._id }); // console.log(user) if (!user) { return res.status(400).json({ message: "no User Found" }); } user.firstname = firstname; (user.lastname = lastname), (user.city = city ? city : user.city), (user.country = country ? country : user.country), (user.state = state ? state : user.state), (user.zip_code = zip_code ? zip_code : user.zip_code), (user.address = address ? address : user.address); user.phone_no = phone_no ? phone_no : user.phone_no; if (req.files.image) { let imagePath = req.files.image ? req.files.image : ""; pathName = await GET_IMAGE_PATH(imagePath); // console.log(pathName); user.image = pathName } else{ user.image = user.image; } await user.save(); const url = baseUrl(req); user.image = `${url}${user.image}`; const resuser = user; res.status(200).json({ message: "Profile Updated Successfully", user: resuser, }); } catch (err) { const errors = []; errors.push({ message: err.message }); res.status(500).json({ errors: errors }); } }; exports.GetCurrentUser = async (req, res) => { try { let user = await User.findOne({ _id: req.user._id }).lean(); // console.log(user) if (!user) { return res.status(400).json({ message: "User doesnot exist" }); } const url = baseUrl(req); user.image = `${url}${user.image}`; // const reviews = await Review.find({luggerUser:req.user._id}).lean() // let totalRating = 0 // let length =reviews.length // for(let i =0;i<reviews.length;i++){ // totalRating = totalRating + reviews[i].rating // } // let Average = totalRating/length // user.AverageRating = Average res.status(200).json({ user: _.pick(user, [ "_id", "firstname", "lastname", "email", "image", "averageRating", "city", "country", "state", "zip_code", "address", "phone_no", ]), }); } catch (error) { res.status(500).json({ error: error.message }); } }; exports.GetUserById = async (req, res) => { let user_id = req.params.user_id; try { const user = await User.findOne({ _id: user_id, }); if (!user) return res.status(400).json({ message: "User Detail not found" }); const url = baseUrl(req); user.image = `${url}${user.image}`; return res.json(user); } catch (err) { console.error(err.message); return res.status(500).json({ error: err.message }); } }; exports.ApproveAndBlockUser = async (req, res) => { const { status } = req.params; // console.log(status) try { let user = await User.findOne({ _id: req.body.userId }); // console.log(user) if (!user) { return res.status(400).json({ message: "no user exist " }); } if (status == 1 && user.status == 1) { return res.json({ message: "This user is already active " }); } else if (status == 0 && user.status == 0) { return res.json({ message: "This user is already blocked" }); } if (user.status == 0 && status == 1) { user.status = status; await user.save(); return res.status(200).json({ message: "User is Active" }); } if (user.status == 1 && status == 0) { user.status = status; await user.save(); return res.status(200).json({ message: "User is blocked" }); } else { return res.status(200).json({ message: "Invalid status" }); } } catch (error) { // console.error(error.message); res.status(500).json({ error: error.message }); } }; exports.UploadProfilePicture = async (req, res) => { try { let image = req.files.image ? req.files.image : ""; let pathName = await GET_IMAGE_PATH(image); const url = baseUrl(req); res.status(200).json({ image: pathName, imagepreview: `${url}${pathName}`, }); } catch (error) { res.status(500).json({ error: error.message, }); } }; exports.Update_User = async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { res.status(400).json({ errors: errors.array() }); } const { firstname, lastname, city, country, state, zip_code, address, phone_no, } = req.body; try { let user = await User.findOne({ _id: req.params.userId }); // console.log(user) if (!user) { return res.status(400).json({ message: "no User Found" }); } user.firstname = firstname; (user.lastname = lastname), (user.city = city ? city : user.city), (user.country = country ? country : user.country), (user.state = state ? state : user.state), (user.zip_code = zip_code ? zip_code : user.zip_code), (user.address = address ? address : user.address); user.phone_no = phone_no ? phone_no : user.phone_no; await user.save(); const url = baseUrl(req); user.image = `${url}${user.image}`; const resuser = user; res.status(200).json({ message: "User Profile Updated Successfully", user: resuser, }); } catch (err) { const errors = []; errors.push({ message: err.message }); res.status(500).json({ errors: errors }); } }; <file_sep>const express = require("express"); const app = express(); const path = require("path"); const port = process.env.PORT || 5000; const connectDB = require("./config/db"); const engines = require("consolidate"); var cors = require("cors"); const helmet = require("helmet"); const xss = require("xss-clean"); const mongoSanitize = require("express-mongo-sanitize"); const compression = require("compression"); var multipart = require('connect-multiparty'); const AdminBro = require("admin-bro"); const AdminBroExpress = require("@admin-bro/express"); const AdminBroMongoose = require("@admin-bro/mongoose"); const mongoose = require("mongoose"); const Blog = require('./models/blog.model') const Contact = require('./models/contact.model') const Project = require('./models/project.model') const Request = require('./models/requests.model') const User = require('./models/User.model') const Admin = require("./models/Admin"); const config = require('config') const db = config.get("MongoURI"); const runServer = async () => { // Mongoolia // Admin Bro AdminBro.registerAdapter(AdminBroMongoose); let adminBro = null; const connection = await mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true, }); adminBro = new AdminBro({ databases: [connection], rootPath: "/admin", resources: [ { resource: Blog, options: {}, }, { resource: Contact, options: {}, }, { resource: Project, options: {}, }, { resource: Request, options: { properties: { status: { availableValues: [ { value: 'ACCEPTED', label: 'ACCEPTED' }, { value: 'REJECTED', label: 'REJECTED' }, ] } } }, }, { resource: User, options: {}, }, { resource: Admin, options: {}, }, ], branding: { companyName: "All Lives Matter Admin", }, }); require("dotenv").config(); var fs = require("fs"); //db connection app.use(function (req, res, next) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE"); res.setHeader("Access-Control-Allow-Headers", "*"); next(); }); const router = AdminBroExpress.buildAuthenticatedRouter(adminBro, { authenticate: async (email, password) => { const admin = await Admin.findOne({ email }).select("+password"); if (admin) { console.log(admin); const isMatch = await admin.matchPassword(password); return isMatch; } return false; }, cookiePassword: "<PASSWORD>", }); // const router = AdminBroExpress.buildRouter(adminBro) app.use(adminBro.options.rootPath, router); app.use(multipart()); app.use(helmet()); app.use(xss()); app.use(mongoSanitize()); // gzip compression app.use(compression()); app.use(cors()); app.options("*", cors()); app.use(express.json({ limit: "50mb" })); require("./routes")(app); app.get("/", (req, res) => { res.send("All lives Matter Running"); }); app.get("/uploads/images/:name", (req, res) => { // const myURL = new URL(req.url) // console.log(myURL.host); res.sendFile(path.join(__dirname, `./uploads/images/${req.params.name}`)); }); app.listen(port, () => { console.log(`Server is running at the port ${port}`); }); } connectDB(); runServer() <file_sep> const _ = require("lodash"); const fs = require("fs"); var path = require("path"); const { baseUrl } = require("../utils/url"); const { validationResult } = require("express-validator"); //model const blogModel = require("../models/blog.model"); const moment = require("moment"); var isBase64 = require("is-base64"); const { GET_IMAGE_PATH } = require("../helper/helper"); const requestModel = require("../models/requests.model"); const requestsModel = require("../models/requests.model"); const { SendPushNotification } = require("../utils/Notification"); const { sendRequestEmail } = require("../service/email"); exports.CREATE_REQUEST = async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } // console.log(req.body); const { project, partner_type, description, firstname, lastname, email , gender, occupation, phone_no, message , } = req.body; // console.log(image) try { // const requests = await requestModel.find(); // if (requests.length) // return res.json({ message: 'You have already sent Request on this Project' }); let request = new requestModel({ // user: req.user._id, project:project?project:null, partner_type:partner_type, description:description?description:null, firstname:firstname?firstname:null, lastname: lastname?lastname:null, email : email ?email:null, gender: gender?gender:null, occupation:occupation?occupation:null, phone_no: phone_no?phone_no:null, message : message ?message:null, }); await request.save(); await sendRequestEmail(request) return res.status(200).json({ code: 200, message: 'Your request has been sent', request:request }); } catch (error) { console.error(error.message); res.status(500).json({ error: error.message }); } } exports.GET_ALL_REQUESTS = async (req, res) => { try { const { page, limit, selection, fieldname, order, from, to, keyword } = req.query; const currentpage = page ? parseInt(page, 10) : 1; const per_page = limit ? parseInt(limit, 10) : 5; const CurrentField = fieldname ? fieldname : "createdAt"; const currentOrder = order ? parseInt(order, 10) : -1; let offset = (currentpage - 1) * per_page; const sort = {}; sort[CurrentField] = currentOrder; // return res.json(sort) let Datefilter = ""; if (from && to) { Datefilter = from && to ? { createdAt: { $gte: moment(from).startOf("day").toDate(), $lte: moment(to).endOf("day").toDate(), }, } : {}; console.log("fromto", Datefilter); } else if (from) { console.log("from"); Datefilter = from ? { createdAt: { $gte: moment(from).startOf("day").toDate(), $lte: moment(new Date()).endOf("day").toDate(), }, } : {}; console.log("from", Datefilter); } else if (to) { console.log.apply("to"); Datefilter = to ? { createdAt: { $lte: moment(to).endOf("day").toDate() } } : {}; console.log("to", Datefilter); } const search = keyword ? { $or: [ { firstname: { $regex: `${keyword}`, $options: "i" } }, { lastname: { $regex: `${keyword}`, $options: "i" } }, { email: { $regex: `${keyword}`, $options: "i" } }, ], } : {}; let requests = await requestModel.find({ ...Datefilter, ...search, }).populate( 'user', [ 'firstname', 'lastname', 'email', 'image' ] ).populate({ path :'project'}) .limit(per_page) .skip(offset) .sort(sort); // console.log(users) if (!requests.length) { return res .status(400) .json({ msg: 'no request found' }); } const url = baseUrl(req); var unique = []; // var distinct = []; // for( let i = 0; i < requests.length; i++ ){ // if( !unique[requests[i].user.image]){ // requests[i].user.image = `${url}${requests[i].user.image}` // unique[requests[i].user.image] = 1; // } // } let Totalcount = await requestModel.find({ ...Datefilter, ...search, }).countDocuments(); const paginate = { currentPage: currentpage, perPage: per_page, total: Math.ceil(Totalcount / per_page), to: offset, data: requests, }; res.status(200).json(paginate); } catch (error) { console.error(error.message); res.status(500).send('server Error'); } } exports.GET_REQUEST_BY_ID = async (req, res) => { let request_id = req.params.request_id; try { const request = await requestsModel.findOne({ _id: request_id, }).populate('project') if (!request) return res.status(400).json({ message: "request Detail not found" }); return res.json(request); } catch (err) { console.error(err.message); return res.status(500).json({ error: err.message }); } }; exports.UPDATE_REQUEST_STATUS = async (req, res) => { try { let request = await requestModel.findOne({ _id: req.body.request_id }) if (!request) return res.status(400).json({ msg: 'Request doesnot exist ' }); if (req.params.status == 1 && request.status == "ACCEPTED") { return res.json({ "message": 'You have already Approved this request' }); } if (req.params.status == 2 && request.status == "REJECTED") { return res.json({ message: 'You have already Rejected this request' }); } if (req.params.status == 1 && request.status == "PENDING" ) { request.status = "ACCEPTED"; await request.save(); // console.log("request",request) const data = { notifiableId: request.user, title: "Request Accepted", notificationType: "Request", body: "Request has been Accepted", payload: { "type": "MyRequest", "id": request._id } } const resp = SendPushNotification(data) console.log(resp) return res.status(200).json({ message: 'You request has been approved' }); } else if (req.params.status == 2 && request.status == "PENDING") { request.status = "REJECTED"; await request.save(); const data = { notifiableId: request.user, title: "Request Rejected", notificationType: "Request", body: "Request has been Rejected", payload: { "type": "MyRequest", "id": request._id } } const resp = SendPushNotification(data) console.log(resp) return res.status(200).json({ message: 'you request has been rejected' }); } else{ return res.status(500).json({ message: 'Invalid status' }) } } catch (error) { console.error(error.message); res.status(500).send(error.message); } }<file_sep>const express = require("express"); const router = express.Router(); const Notification = require("../models/notifications.model"); const { check, validationResult } = require("express-validator"); const axios = require("axios"); const FCM = require("fcm-node"); const config = require("config"); const auth = require("../middleware/authMiddleware"); const admin = require("../middleware/adminMiddleware"); const Session = require("../models/session.model"); const checkObjectId = require("../middleware/checkobjectId"); const { SendPushNotification } = require("../utils/Notification"); const notificationsModel = require("../models/notifications.model"); //set the route path and initialize the API router.get("/admin", [auth, admin], async (req, res) => { try { console.log(req.query); const { page, limit } = req.query; let currentpage = page ? parseInt(page, 10) : 1; // console.log(currentpage) let per_page = limit ? parseInt(limit, 10) : 5; // console.log(limit) let offset = (currentpage - 1) * per_page; let notifications = await Notification.find({ notificationType: "Admin", isread: false, }) .populate("notifiableId", ["id", "email"]) .limit(per_page) .skip(offset) .lean() .sort({ createdAt: -1 }); if (!notifications.length) { return res.status(400).json({ message: "no notification exist" }); } // let content =await Notification.updateMany( // {notificationType:"Admin"}, // { // $set: {is_read:true} // }) // console.log(content) let Totalcount = await Notification.find({ notificationType: "Admin", isread: false, }) .populate("notifiableId", ["id", "email"]) .count(); const paginate = { currentPage: currentpage, perPage: per_page, total: Math.ceil(Totalcount / per_page), to: offset, totalCount: Totalcount, data: notifications, }; return res.json(paginate); } catch (error) { res.status(500).json({ error: error.message }); } }); router.get("/count", [auth], async (req, res) => { try { let Totalcount = await Notification.find({ notifiableId: req.user._id, isread: false, }) .populate("notifiableId", ["id", "email"]) .count(); return res.json({ total_count: Totalcount }); } catch (error) { res.status(500).json({ error: error.message }); } }); router.get("/", auth, async (req, res) => { try { console.log(req.query); const { page, limit } = req.query; let currentpage = page ? parseInt(page, 10) : 1; console.log(currentpage); let per_page = limit ? parseInt(limit, 10) : 5; console.log(limit); let offset = (currentpage - 1) * per_page; let notifications = await Notification.find({ notifiableId: req.user._id }) .populate("notifiableId", ["id", "email"]) .limit(per_page) .skip(offset) .lean() .sort({ createdAt: -1 }); if (!notifications.length) { return res.status(400).json({ message: "no notification exist" }); } let Totalcount = await Notification.find({ notifiableId: req.user._id }) .populate("notifiableId", ["id", "email"]) .count(); const paginate = { currentPage: currentpage, perPage: per_page, total: Math.ceil(Totalcount / per_page), to: offset, data: notifications, }; return res.json(paginate); } catch (error) { res.status(500).json({ error: error.message }); } }); //update router.post("/update", auth, async (req, res) => { try { let notification = await notificationsModel.updateMany( { _id: { $in: req.body.notificationIds } }, { $set: { isread: true }, } ); res.status(200).json(notification); } catch (error) { res.status(500).json({ error: error.message }); } }); router.get("/:id", auth, async (req, res) => { try { const notification = await Notification.findById(req.params.id); notification.isread = true; await notification.save(); await res.status(201).json({ message: "Notification Marked as Read", }); } catch (err) { res.status(500).json({ message: err.toString(), }); } }); module.exports = router; <file_sep>var fs = require("fs"); var path= require('path') exports.GET_IMAGE_PATH = async function (image) { try { const match = ["image/png", "image/jpeg","image/jpg"]; let r = Math.random().toString(36).substring(7) if (match.indexOf(image.type) === -1) { throw new Error('invalid image type') } pathName = `uploads/images/${r+""+image.originalFilename.replace(/\s/g, "" ) }`; // let pathName = `uploads/files/images/${image.originalFilename.replace( // /\s/g, // "" // )}`; let stream = await fs.readFileSync(image.path); await fs.writeFileSync(path.join(__dirname, `../${pathName}`), stream); console.log("ImageURl",pathName) // clean it and return return pathName; } catch (error) { throw error } }; <file_sep>const express = require("express"); const router = express.Router(); const { check, validationResult } = require("express-validator"); const auth = require("../middleware/authMiddleware"); const admin = require("../middleware/adminMiddleware"); const BlogsController = require("../controllers/blogController"); // get all Blogs router.get("/", BlogsController.GET_BLOGS); // getBlogBYID router.get("/:blog_id", BlogsController.GET_BLOG_BY_ID); //create new Blog router.post( "/create", [ auth, admin, [ check("title", "title is required").not().isEmpty(), check("description", "description is required").not().isEmpty(), ], ], BlogsController.CREATE_BLOG ); // router.post("/edit", BlogsController.EDIT_BLOG); module.exports = router; <file_sep> const _ = require("lodash"); const fs = require("fs"); var path = require("path"); const { baseUrl } = require("../utils/url"); const { validationResult } = require("express-validator"); //model const blogModel = require("../models/blog.model"); const moment = require("moment"); var isBase64 = require("is-base64"); const { GET_IMAGE_PATH } = require("../helper/helper"); const projectModel = require("../models/project.model"); // const cloudinary = require('cloudinary') // cloudinary.config({ // cloud_name: 'all-lives-matter', // api_key: '844554439773792', // api_secret: '<KEY>' // }); exports.CREATE_PROJECT = async (req, res, next) => { try { let error = []; const errors = validationResult(req); const url = baseUrl(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { title, description,type,image } = req.body; // if service already exist let project = await projectModel.findOne({ title,type }); if (project) { error.push({ message: "Project already Exist" }); return res.status(400).json({ errors: error }); } // let pathName = ""; // // console.log(req.files) // var cloudinaryResult = null // if (req.files.image) { // pathName = await GET_IMAGE_PATH(req.files.image); // } // const result = await cloudinary.uploader.upload(pathName) project = new projectModel({ title: title, description: description, type:type, image:image, }); await project.save(); res.status(200).json({ message: "Project Created Successfully", }); } catch (error) { res.status(500).json({ error: error.message, }); } }; exports.GET_PROJECTS = async (req, res) => { const { page, limit, selection, fieldname, order, from, to, keyword } = req.query; const currentpage = page ? parseInt(page, 10) : 1; const per_page = limit ? parseInt(limit, 10) : 3; const CurrentField = fieldname ? fieldname : "createdAt"; const currentOrder = order ? parseInt(order, 10) : -1; let offset = (currentpage - 1) * per_page; const sort = {}; sort[CurrentField] = currentOrder; // return res.json(sort) const currentSelection = selection ? selection : 1; // const categoryFilter = category?{category:category}:{} let Datefilter = ""; if (from && to) { Datefilter = from && to ? { createdAt: { $gte: moment(from).startOf("day").toDate(), $lte: moment(to).endOf("day").toDate(), }, } : {}; console.log("fromto", Datefilter); } else if (from) { console.log("from"); Datefilter = from ? { createdAt: { $gte: moment(from).startOf("day").toDate(), $lte: moment(new Date()).endOf("day").toDate(), }, } : {}; console.log("from", Datefilter); } else if (to) { console.log.apply("to"); Datefilter = to ? { createdAt: { $lte: moment(to).endOf("day").toDate() } } : {}; console.log("to", Datefilter); } const search = keyword ? { $or: [{ title: { $regex: `${keyword}`, $options: "i" } }], } : {}; // return res.json(sort) console.log(search); try { let projects = await projectModel .find({ ...Datefilter,...search }) .limit(per_page ? per_page : null) .skip(offset) .sort(sort); const Totalcount = await projectModel.find({ ...Datefilter,...search}).countDocuments(); const paginate = { currentPage: currentpage, perPage: per_page, total: Math.ceil(Totalcount / per_page), to: offset, data: projects, }; res.status(200).json(paginate); } catch (error) { res.status(500).json({ error: error.message }); } }; exports.GET_PROJECT_BY_ID = async (req, res) => { let project_id = req.params.project_id; try { const project = await projectModel.findOne({ _id: project_id, }) if (!project) return res.status(400).json({ message: "Project Detail not found" }); // const url = baseUrl(req); // project.image = `${url}${project.image}`; return res.json(project); } catch (err) { console.error(err.message); return res.status(500).json({ error: err.message }); } }; <file_sep>const express = require("express"); const { baseUrl } = require("../utils/url"); const { CreateNotification, SendPushNotification, } = require("../utils/Notification"); const { check, validationResult } = require("express-validator"); const config = require("config"); //model const paymentModel = require("../models/payment.model") const moment = require("moment"); const { sendRequestEmail } = require("../service/email"); const stripe = require("stripe")("sk_test_RG4EfYiSTOT8IxuNxbeMeDiy"); exports.DONATE = async (req, res) => { try { let { first_name, last_name, email, city, zip_code, charges, payment_method, card_number, card_expiry, card_cvv, } = req.body; let charge = ""; let m = card_expiry.split("/"); let cardNumber = card_number; let token = await stripe.tokens.create({ card: { number: cardNumber, exp_month: m[0], exp_year: m[1], cvc: card_cvv, }, }); if (token.error) { // throw new Error (token.error); return res.status(400).json({ message: token.error }); } charge = await stripe.charges.create({ amount: charges, description: "All live Matters", currency: "usd", source: token.id, }); const paymentLog = new paymentModel({ first_name: first_name, last_name: last_name, email: email, city: city, zip_code: zip_code, charge_id: charge.id ? charge.id : null, amount: charges, type: payment_method, status: charge.id ? "paid" : "unpaid", }); await paymentLog.save(); await sendRequestEmail(paymentLog,"DONATION") res.status(200).json({ msg: "Donation SuccessFul !" }); } catch (err) { throw err; } }; exports.MY_SUBSCRIPTION = async (req,res)=>{ try { let error =[] let subscription = await paymentModel.findOne({ user: req.user._id}).populate('user').populate('package') if (!subscription) { error.push({ message: "No subscription Exist" }) return res.status(400).json({ errors: error }) } res.status(200).json( subscription ); } catch (err) { const errors = []; errors.push({ message: err.message }); res.status(500).json({ errors: errors }); } }<file_sep>const express = require('express'); const router = express.Router(); const bcrypt = require('bcrypt') const { check, validationResult } = require('express-validator') const moment = require("moment"); const _ = require('lodash') const { baseUrl } = require('../utils/url'); //middleware const auth = require('../middleware/authMiddleware') const User = require('../models/User.model') //models const Token = require('../models/Token.model') const Session = require('../models/session.model') //services const { sendEmail } = require('../service/email') const Controller = require('../controllers/authController') moment().format(); //@route Get api/auth //@desc Test route //access Public router.get('/', auth,Controller.LoadUser) //@route Post api/login //@desc Test route //access Public router.post('/login', [check('email', 'Email is required').isEmail(), check('password', 'password <PASSWORD>').exists(),], Controller.Login); router.post( '/login/admin', [ check('email', 'Email is required').isEmail(), check( 'password', '<PASSWORD>' ).exists(), ], async (req, res) => { let error = [] const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } try { let { email, password } = req.body; email = email.toLowerCase() //see if user exists let user = await User.findOne({ email: email, isAdmin: true }); if (!user) { error.push({ message: "Invalid Credentials" }) return res.status(400).json({ errors: error }); } const validpassword = await bcrypt.compare(password, user.password) if (!validpassword) { error.push({ message: "Invalid Credentials" }) return res.status(400).json({ errors: error }); } const token = user.generateAuthToken() let session = await Session.findOne({ user: user.id }); // console.log(session) // if (session) { // session.token = token, // session.status = true, // session.deviceId = req.body.deviceId // } else { session = new Session({ token: token, user: user.id, status: true, deviceId: req.body.deviceId, deviceType: req.body.deviceType }) // } await session.save() res.status(200).json({ "message": "Log in Successfull", "token": token }) } catch (err) { const errors = [] errors.push({ message: err.message }) res.status(500).json({ errors: errors }); } //return json webtoken } ); //Post /api/auth/forgot //access public router.post("/forgot", check('email', 'Email is required').isEmail(), Controller.ForgotPassword) //post /api/auth/verifyCode/ //access private router.post("/verifycode", check('resetCode', 'Code is Required'), Controller.VerifyCode); //post /api/auth/reset/ //access private router.post("/reset/:token", [ check('newpassword', 'newpassword is required').not().isEmpty(), check('confirmpassword', 'confirmpassword is required').not().isEmpty()], Controller.ResetPassword); //post /api/auth/changepassword //access private router.post( '/changepassword', [auth, [ check('currentpassword', 'current Password is required').not().isEmpty(), check('newpassword', 'New Password is required').not().isEmpty(), check('confirmpassword', 'Confirm password is required').not().isEmpty() ]], Controller.ChangePassword ); router.get('/logout', auth, Controller.Logout) module.exports = router<file_sep>const mongoose = require('mongoose'); const user = require('./User.model') const projectSchema = new mongoose.Schema({ title: { type:String, required:true }, type:{ type:String, required:true }, description:{ type:String, required:true }, status: { type:Boolean, default:true }, image:{ type:String, default:null } }); projectSchema.set('timestamps',true) module.exports= project = mongoose.model('project', projectSchema);
0d15928611f965c2e2c2a4a0b9126ce7cbda91b7
[ "JavaScript" ]
15
JavaScript
satiwankumar/LIVE_MATTERS
029f398cf1c862a2b4fbe82789cf1167b5cd2d1b
b5b1a6013f4e5723576e328ce0897f2f2ea01adc
refs/heads/master
<repo_name>matara/faker_api_app<file_sep>/test/interfaces/web_test.rb require 'test_helper' require 'rack_test_helper' describe app do let(:web_host) { 'test.domain.com' } before do env('HTTP_HOST', web_host) end describe 'main page' do before do get '/' end it 'render main page' do expect(last_response.status).must_equal 200 end it 'render text' do expect(last_response.body).must_equal 'API interface for https:://github.com/stympy/faker gem' end end describe '#faker endpoint' do describe 'when no params present' do it 'Address.state' do get '/faker/address/state' assert_includes Faker::Base.fetch_all('address.state'), response_json['data'].first expect_faker_response('Faker::Address', 'state') end it 'return Address.state' do get '/faker/internet/domain_suffix' assert_includes Faker::Base.fetch_all('internet.domain_suffix'), response_json['data'].first expect_faker_response('Faker::Internet', 'domain_suffix') end after do expect(response_json['data'].size).must_equal(1) end end describe 'when count params present' do before do @count = rand(2..5) end it 'return array of data' do get '/faker/food/ingredient?count=' + @count.to_s indredients = Faker::Base.fetch_all('food.ingredients') response_json['data'].each do |indredient| assert_includes indredients, indredient end expect_faker_response('Faker::Food', 'ingredient') end after do expect(response_json['data'].size).must_equal(@count) expect(response_json['data'].uniq.size).must_equal(@count) end end describe 'when undefined words' do it 'with undefined module' do get '/faker/blabla/ingredient' end it 'with undefined method' do get '/faker/Food/blabla' end after do expect(last_response.status).must_equal 200 expect(last_response.headers['Content-Type']).must_equal 'application/json' expect(response_json['data']).must_equal([]) expect(response_json['module']).must_equal('') expect(response_json['method']).must_equal('') end end it 'when module plural' do get '/faker/friend/character' expect_faker_response('Faker::Friends', 'character', skip_data_empty: true) get '/faker/friend/characters' expect_faker_response('Faker::Friends', 'character', skip_data_empty: true) get '/faker/friends/character' expect_faker_response('Faker::Friends', 'character', skip_data_empty: true) get '/faker/friends/characters' expect_faker_response('Faker::Friends', 'character', skip_data_empty: true) end it 'when module singular' do get '/faker/food/ingredient' expect_faker_response('Faker::Food', 'ingredient', skip_data_empty: true) get '/faker/food/ingredients' expect_faker_response('Faker::Food', 'ingredient', skip_data_empty: true) get '/faker/foods/ingredient' expect_faker_response('Faker::Food', 'ingredient', skip_data_empty: true) get '/faker/foods/ingredients' expect_faker_response('Faker::Food', 'ingredient', skip_data_empty: true) end def expect_faker_response(mod = nil, method = nil, opt = {}) expect(last_response.status).must_equal 200 expect(last_response.headers['Content-Type']).must_equal 'application/json' expect(response_json['data']).wont_be_empty unless opt[:skip_data_empty] expect(response_json['data'].class).must_equal(Array) expect(response_json['module']).must_equal(mod) if mod expect(response_json['method']).must_equal(method) if method end end def response_json JSON.parse(last_response.body) end end <file_sep>/test/rack_test_helper.rb # Rack::Test ENV['RACK_ENV'] = 'test' require 'interfaces/web' def app Sinatra::Application end require 'rack/test' include Rack::Test::Methods <file_sep>/test/test_helper.rb # Minitest require 'minitest/autorun' require 'minitest/hooks/default' <file_sep>/config.ru $:.unshift File.expand_path('src') require 'interfaces/web' run Sinatra::Application <file_sep>/Gemfile # frozen_string_literal: true source 'https://rubygems.org' # automation gem 'rake' # web interface gem 'sinatra' gem 'sinatra-contrib' gem 'faker' gem 'activesupport' group :development do gem 'shotgun' end group :test do gem 'minitest' gem 'minitest-hooks' gem 'rack-test' end <file_sep>/src/interfaces/web.rb require 'sinatra' require 'sinatra/json' require 'faker' require 'active_support' def error_resp status 200 content_type :json { module: '', method: '', data: [] }.to_json end get '/?' do 'API interface for https:://github.com/stympy/faker gem' end get '/faker/*?' do begin content_type :json possible_class, possible_method = params[:splat].first.split('/') clazz = faker_class_for(possible_class) method = faker_method_for(clazz, possible_method) data = faker_data_times(clazz, method, params[:count] ? params[:count].to_i : 1) { module: clazz, method: method, data: data }.to_json rescue error_resp end end def faker_class_for(possible_class) if possible_class =~ /s$/ begin Object.const_get(['Faker', possible_class.capitalize].join('::')) rescue Object.const_get(['Faker', possible_class.gsub(/s$/, '').capitalize].join('::')) end else begin Object.const_get(['Faker', possible_class.gsub(/s$/, '').capitalize].join('::')) rescue Object.const_get(['Faker', (possible_class + 's').capitalize].join('::')) end end end def faker_method_for(clazz, method) return method if clazz.respond_to?(method) method.gsub(/s$/, '') end def faker_data_times(clazz, method, count) count = 1 if count < 1 count.times.map { clazz.send(method) } end
64515eaef44ff42b3967f6b4c26e2e8673b3d74b
[ "Ruby" ]
6
Ruby
matara/faker_api_app
14dbe6580e6861f48907dc39f3ebeeed364e0e2b
5cf1d2103db29b03c8c910153b899fbf5984b7da
refs/heads/master
<repo_name>xiaochuankk123/python-spider<file_sep>/test/test.py import pyautogui import time import random def moveAndClick(x,y,*timeout): #随机常量 #x,y随机距离 randomSize=random.uniform(0, 20) #鼠标移动时间 mouseMoveSecs=random.uniform(0, 0.1) #点击次数 clickTimes=random.randint(4,8) #间隔 secs=random.uniform(0.3,0.8) print('时间打印:', clickTimes, mouseMoveSecs, randomSize) time.sleep(secs) pyautogui.moveTo(x+randomSize, y+randomSize, mouseMoveSecs) pyautogui.click(clicks=clickTimes) def yuhun(): while(True): #开始战斗按钮: moveAndClick(x=1759,y=428) time.sleep(60+random.uniform(1,2)) #等60秒,点点点 moveAndClick(x=1560,y=70) moveAndClick(x=1560,y=570) time.sleep(1+random.uniform(1,2)) moveAndClick(x=1560,y=70) moveAndClick(x=1560,y=570) time.sleep(1+random.uniform(1,2)) moveAndClick(x=1560,y=70) moveAndClick(x=1560,y=570) time.sleep(1+random.uniform(1,2)) moveAndClick(x=1560,y=70) moveAndClick(x=1560,y=570) time.sleep(10+random.uniform(1,2)) yuhun()
e132f40177110f4c89b2b9f581a5233132929dc9
[ "Python" ]
1
Python
xiaochuankk123/python-spider
25a2bf3a2bff05e0031d1640783907ef4f5ff534
ae45ac6f1314ba0fc1d6d69101cefe9a8a3cb38f
refs/heads/master
<repo_name>Spanfile/DHCP-UI<file_sep>/dhcp-ui-frontend/src/common/config/IHostsConfig.ts import { ICommonConfig, IConfigCollection } from "common/config/ICommonConfig"; import { IOptionsConfig } from "common/config/IOptionsConfig"; export type IHostsConfig = IConfigCollection<IHostConfig>; export default interface IHostConfig extends ICommonConfig<ICommonHostConfig> { options: IOptionsConfig; } export interface ICommonHostConfig { hostname: string; hardware: string; fixedAddress: string; ddnsHostname: string; } <file_sep>/dhcp-ui-backend/src/dhcp-ui.py import eventlet eventlet.monkey_patch(select=False) from subprocess import Popen, PIPE from flask import Flask, jsonify, request, abort from flask_cors import CORS from lease_parser import Parser from flask_socketio import SocketIO, send, emit from watcher import Watcher from blinker import Namespace, NamedSignal signals = Namespace() app = Flask(__name__) app.config.from_envvar("DHCPUI_SETTINGS") CORS(app) socketio_logs = app.config["SOCKETIO_DEBUG_LOGS"] socketio = SocketIO(app, logger=socketio_logs, engineio_logger=socketio_logs) leases_changed: NamedSignal = signals.signal("leases_changed") watcher = Watcher(app.config["DHCP_LEASES"], leases_changed) parser = Parser(app.config["DHCP_LEASES"]) @app.route("/detectdhcpserver") def hello_world(): return jsonify( { "serviceName": "isc-dhcp-server", "configDir": "/etc/dhcp/", "logFile": "/var/log/dhcp", "logInJournal": False, "leaseFile": "/var/lib/dhcp.leases", } ) @app.route("/leases") def leases(): leases = [lease.get_serializable() for lease in parser.get_leases()] return jsonify(leases) @app.route("/generatednssec", methods=["GET", "POST"]) def generate_dnssec(): if request.method == "GET": available = False reason = "" p = Popen(["which", "tsig-keygen"], stdin=PIPE, stdout=PIPE, stderr=PIPE) output, _ = p.communicate() if p.returncode != 0: reason = "tsig-keygen executable not found" else: available = True return jsonify({"available": available, "reason": reason}) elif request.method == "POST": algorithm = request.get_json()["algorithm"] p = Popen( ["tsig-keygen", "-a", algorithm, "generated"], stdin=PIPE, stdout=PIPE, stderr=PIPE, ) output, err = p.communicate() if p.returncode != 0: abort(400) else: output = output.decode("utf-8") args = output.split() secret = args[args.index("secret") + 1].strip('";') return jsonify({"secret": secret}) @app.route("/generateconfig", methods=["POST"]) def generate_config(): config = request.get_json() print(config) return "Hello!" @leases_changed.connect_via(watcher) def handle_leases_changed(sender): print("leases changed") socketio.emit( "leases", [lease.get_serializable() for lease in parser.get_leases()], namespace="/leases", ) if __name__ == "__main__": socketio.run(app, host="0.0.0.0") <file_sep>/dhcp-ui-frontend/src/common/config/ddns/IDDNSZone.ts import { IConfigCollection } from "common/config/ICommonConfig"; export type IDDNSZones = IConfigCollection<IDDNSZone>; export interface IDDNSZone { domain: string; primary: string; key: string; } <file_sep>/dhcp-ui-frontend/src/common/config/IOptionsConfig.ts import { IConfigCollection } from "common/config/ICommonConfig"; export type IOptionsConfig = IConfigCollection<IOptionConfig>; export interface IOptionConfig { name: string; expression: string; } <file_sep>/dhcp-ui-frontend/src/common/settings/IDHCPUISettings.ts export default interface IDHCPUISettings { serviceName: string; configDir: string; logFile: string; logInJournal: boolean; leaseFile: string; } <file_sep>/dhcp-ui-frontend/src/common/ITableRow.ts export default interface ITableRow<T> { key: string; values: T[]; } <file_sep>/dhcp-ui-frontend/src/common/Lease.ts import * as moment from "moment"; import IData from "./IData"; export interface ITransmittedLease { address: number; hardware: number; ends: string; hostname: string; } export default class Lease implements IData { public key: string; public address: string; public hardware: string; public ends: string; public hostname: string; constructor(source: ITransmittedLease) { this.address = this.toDotted(source.address); this.hardware = this.toMac(source.hardware.toString(16)); this.ends = moment(source.ends).format("DD/MM/YYYY HH:mm:ss"); this.hostname = source.hostname; this.key = this.address; } private toDotted(ipNum: number): string { return [...Array(4).keys()].map(i => (ipNum >> (i * 8)) & 255).reverse().join("."); } private toMac(hex: string): string { hex = this.pad(hex, 12); for (let i = 2; i <= 14; i += 3) { hex = hex.substr(0, i) + ":" + hex.substr(i); } return hex; } private pad(str: string, size: number): string { while (str.length < size) { str = "0" + str; } return str; } } <file_sep>/dhcp-ui-backend/requirements.txt flask flask-socketio flask-cors watchdog eventlet blinker<file_sep>/dhcp-ui-frontend/src/common/config/ICommonConfig.ts export interface IConfigCollection<T> { [id: number]: T; } export interface ICommonConfig<T> { common: T; } <file_sep>/dhcp-ui-frontend/src/common/config/IDHCPConfig.ts import { IDHCPSubnetsConfig } from "common/config/subnet/IDHCPSubnet"; import IDDNSConfig from "./ddns/IDDNSConfig"; import IGlobalConfig from "./IGlobalConfig"; export default interface IDHCPConfig { global: IGlobalConfig; ddns: IDDNSConfig; subnets: IDHCPSubnetsConfig; } <file_sep>/dhcp-ui-backend/src/lease_parser.py from ipaddress import IPv4Address from json import JSONEncoder from datetime import datetime from typing import Dict, Any, List, Callable, Optional, Tuple class Lease: def __init__(self, address: IPv4Address) -> None: self._values: Dict[str, Any] = { 'address': int(address) } def get_serializable(self) -> Dict[str, Any]: return self._values def set_value(self, statement: str, value: Any): self._values[statement] = value class Parser: def __init__(self, filename: str) -> None: self._filename = filename self._parsed_leases: List[Lease] = [] self._active_lease: Optional[Lease] = None self._actions = { 'lease': self._begin_lease, '}': self._end_lease, 'starts': _date_parser('starts', self._set_lease_value), 'ends': _date_parser('ends', self._set_lease_value), 'tstp': _date_parser('tstp', self._set_lease_value), 'tsfp': _date_parser('tsfp', self._set_lease_value), 'atsfp': _date_parser('atsfp', self._set_lease_value), 'cltt': _date_parser('cltt', self._set_lease_value), 'hardware': self._lease_hardware, 'uid': self._lease_uid, 'binding state': _binding_state_parser('binding state', self._set_lease_value), 'next binding state': _binding_state_parser('next binding state', self._set_lease_value), 'rewind binding state': _binding_state_parser('rewind binding state', self._set_lease_value), 'set': _set_parser(self._set_lease_value), 'option': _option_parser(self._set_lease_value), 'client-hostname': self._lease_client_hostname } def _set_lease_value(self, name: str, value: Any) -> None: assert self._active_lease is not None self._active_lease.set_value(name, value) def reset(self): self._parsed_leases = [] def get_leases(self) -> List[Lease]: self.reset() with open(self._filename) as f: linenum = 1 for line in [line.strip().strip(';') for line in f if not line.startswith('#')]: if not line: continue args = line.split() scanned = self._scan_statement(args) if not scanned: # print('unknown line #' + str(linenum), line) pass else: statement, call_args = scanned func = self._actions[statement] func(call_args) linenum += 1 assert self._active_lease is None return self._parsed_leases def _scan_statement(self, args: List[str]) -> Optional[Tuple[str, List[str]]]: for i in range(len(args)): statement = ' '.join(args[0:i + 1]) if statement in self._actions: return (statement, args[i + 1:]) return None def _begin_lease(self, args: List[str]) -> None: assert self._active_lease is None assert args[1] == '{' address = IPv4Address(args[0]) self._active_lease = Lease(address) def _end_lease(self, args: List[str]) -> None: assert self._active_lease is not None self._parsed_leases.append(self._active_lease) self._active_lease = None def _lease_hardware(self, args: List[str]) -> None: hardware = args[0] address = int(args[1].replace(':', ''), 16) self._set_lease_value('hardware', address) def _lease_uid(self, args: List[str]) -> None: uid = args[0].strip('"') self._set_lease_value('uid', uid) def _lease_client_hostname(self, args: List[str]) -> None: hostname = args[0].strip('"') self._set_lease_value('client-hostname', hostname) def _date_parser(name: str, set_lease_value: Callable[[str, Any], None]): def _parse(args: List[str]): full_datestr = args[1] + ' ' + args[2] date = datetime.strptime(full_datestr, '%Y/%m/%d %H:%M:%S') set_lease_value(name, date.isoformat()) return _parse def _binding_state_parser(name: str, set_lease_value: Callable[[str, Any], None]): def _parse(args: List[str]): state = args[0] set_lease_value(name, state) return _parse def _set_parser(set_lease_value: Callable[[str, Any], None]): def _parse(args: List[str]): variable_name = args[0] value = args[2].strip('"') set_lease_value('set ' + variable_name, value) return _parse def _option_parser(set_lease_value: Callable[[str, Any], None]): def _parse(args: List[str]): variable_name = args[0] value = args[1].strip('"') set_lease_value('option ' + variable_name, value) return _parse <file_sep>/dhcp-ui-frontend/src/common/config/ddns/IDDNSConfig.ts import { IDDNSZones } from "common/config/ddns/IDDNSZone"; import { IDNSSECKeys } from "common/config/ddns/IDNSSECKey"; import { ICommonConfig } from "common/config/ICommonConfig"; export enum DDNSUpdateStyle { AdHoc = "ad-hoc", Interim = "interim", None = "none" } export default interface IDDNSConfig extends ICommonConfig<ICommonDDNSConfig> { keys: IDNSSECKeys; zones: IDDNSZones; } export interface ICommonDDNSConfig { updates: boolean; updateStyle: DDNSUpdateStyle; domainName: string; reverseDomainName: string; ignoreClientUpdates: boolean; updateStaticLeases: boolean; useHostDeclNames: boolean; } <file_sep>/dhcp-ui-frontend/src/common/config/subnet/IDHCPSubnet.ts import { IConfigCollection } from "common/config/ICommonConfig"; import { IHostsConfig } from "common/config/IHostsConfig"; import { IOptionsConfig } from "common/config/IOptionsConfig"; export type IDHCPSubnetsConfig = IConfigCollection<IDHCPSubnet>; export default interface IDHCPSubnet { common: ICommonDHCPSubnetConfig; options: IOptionsConfig; hosts: IHostsConfig; } export interface ICommonDHCPSubnetConfig { subnet: string; range: string; } <file_sep>/dhcp-ui-backend/test.py class Test: def __init__(self): self._a_b: int = None <file_sep>/dhcp-ui-frontend/src/common/config/ddns/IDNSSECKey.ts import { IConfigCollection } from "common/config/ICommonConfig"; export enum DNSSECAlgorithm { HMAC_MD5 = "HMAC-MD5", HMAC_SHA1 = "HMAC-SHA1", HMAC_SHA224 = "HMAC-SHA224", HMAC_SHA256 = "HMAC-SHA256", HMAC_SHA384 = "HMAC-SHA384", HMAC_SHA512 = "HMAC-SHA512" } export type IDNSSECKeys = IConfigCollection<IDNSSECKey>; export interface IDNSSECKey { name: string; algorithm: DNSSECAlgorithm; key: string; } <file_sep>/dhcp-ui-frontend/src/common/config/IConfigProps.ts export type ValueOf<T> = T[keyof T]; export default interface IConfigProps<T> { config: T; onChange: (name: keyof T, value?: ValueOf<T>) => void; } export interface ICollectionConfigProps<T> extends IConfigProps<T> { onDelete: () => void; } export type ConfigKey = string | number; export function handleConfigChange<T>(config: keyof T, props: IConfigProps<T>) { return (name: ConfigKey, value: {} | null | undefined) => { const conf = props.config[config]; if (value == null) { delete conf[name]; } else { conf[name] = value; } props.onChange(config, conf); }; } <file_sep>/dhcp-ui-frontend/src/common/SortOrder.ts export enum SortOrder { Unsorted, Ascending, Descending } <file_sep>/dhcp-ui-backend/entrypoint.sh #!/bin/sh dhcpd python3 -m flask run --host 0.0.0.0<file_sep>/dhcp-ui-frontend/src/common/IData.ts export default interface IData { key: string; } <file_sep>/dhcp-ui-backend/src/watcher.py from os import path from watchdog.observers.polling import PollingObserver from watchdog.events import FileSystemEventHandler from blinker import NamedSignal class Watcher: def __init__(self, filename: str, signal: NamedSignal) -> None: self._filename = filename self._changed_signal: NamedSignal = signal handler = WatcherEventHandler(filename, self._changed) obs = PollingObserver() obs.schedule(handler, path.dirname(filename)) obs.start() self._observer = obs def stop(self) -> None: self._observer.stop() self._observer.join() def _changed(self) -> None: self._changed_signal.send(self) class WatcherEventHandler(FileSystemEventHandler): def __init__(self, filename: str, callback) -> None: self._filename = filename self._callback = callback def on_modified(self, event): if event.src_path == self._filename: self._callback() return super().on_modified(event) <file_sep>/dhcp-ui-backend/Dockerfile # This Dockerfile, and the accompanying docker-compose.yml, are meant for building a local development environment FROM alpine:latest RUN apk add \ python3 \ python3-dev \ bind \ dhcp \ build-base \ yaml-dev WORKDIR /dhcp-ui COPY requirements.txt ./ ENV PYTHONUNBUFFERED 1 RUN /usr/bin/python3 -m pip install -r requirements.txt COPY entrypoint.sh ./ COPY DHCPUI_SETTINGS.dockerdev.cfg ./ ENV FLASK_APP src/dhcp-ui.py ENV FLASK_ENV development ENV DHCPUI_SETTINGS ../DHCPUI_SETTINGS.dockerdev.cfg COPY sample/dhcpd.conf /etc/dhcpd.conf RUN touch /var/lib/dhcp/dhcpd.leases # COPY sample/dhcpd.leases /var/lib/dhcp/ # COPY src/ src/ EXPOSE 5000 ENTRYPOINT ["/dhcp-ui/entrypoint.sh"]<file_sep>/dhcp-ui-frontend/src/common/ITableColumn.ts export default interface ITableColumn { header: string; property: string; } <file_sep>/dhcp-ui-frontend/src/common/IModalState.ts export default interface IModalState { isModalOpen: boolean; } <file_sep>/dhcp-ui-frontend/src/common/ip/IP.ts export class IPAddress { public static parseString(addressString: string) { const octets = addressString.split(".").map(Number); if (octets.length !== 4 || octets.some(octet => octet < 0 || octet > 255)) { throw TypeError(addressString + " is not a valid IPv4 address"); } return new IPAddress(octets); } private readonly octet1: number; private readonly octet2: number; private readonly octet3: number; private readonly octet4: number; private constructor(octets: number[]) { this.octet1 = octets[0]; this.octet2 = octets[1]; this.octet3 = octets[2]; this.octet4 = octets[3]; } public toString(): string { return this.octet1 + "." + this.octet2 + "." + this.octet3 + "." + this.octet4; } } export class Subnet { public static parseCidr(subnetString: string): Subnet { const args = subnetString.split("/"); const identifier = IPAddress.parseString(args[0]); const cidr = Number(args[1]); return new Subnet(identifier, cidr); } public static fromIdentifierAndMask(identifier: IPAddress, mask: IPAddress) { return new Subnet(identifier, 32); } public static fromIdentifierAndCidr(identifier: IPAddress, cidr: number) { return new Subnet(identifier, cidr); } public identifier: IPAddress; public cidr: number; private constructor(identifier: IPAddress, cidr: number) { this.identifier = identifier; this.cidr = cidr; } public toString(): string { return this.identifier.toString() + "/" + this.cidr; } } export class AddressRange { public static fromAddressPair(from: IPAddress, to: IPAddress) { return new AddressRange(from, to); } public static fromAddressStringPair(from: string, to: string) { return new AddressRange(IPAddress.parseString(from), IPAddress.parseString(to)); } public static fromRangeString(rangeString: string) { const rangeArgs = rangeString.split("-"); return new AddressRange(IPAddress.parseString(rangeArgs[0]), IPAddress.parseString(rangeArgs[1])); } public from: IPAddress; public to: IPAddress; private constructor(from: IPAddress, to: IPAddress) { this.from = from; this.to = to; } public toString(): string { return this.from.toString() + "-" + this.to.toString(); } } <file_sep>/dhcp-ui-frontend/src/common/IInputProps.ts export default interface IInputProps<T> { label: string; name: string; value?: T; // tslint:disable-next-line:no-any onChange?: (event: any) => void; } <file_sep>/dhcp-ui-frontend/src/common/config/IGlobalConfig.ts import { ICommonConfig } from "common/config/ICommonConfig"; import { IOptionsConfig } from "./IOptionsConfig"; export default interface IGlobalConfig extends ICommonConfig<ICommonGlobalConfig> { options: IOptionsConfig; } export interface ICommonGlobalConfig { authoritative: boolean; defaultLeaseTime: number; maxLeaseTime: number; }
8b3f5396e6fdf63e4bfe5844967bd0ba320b18c8
[ "Python", "Text", "TypeScript", "Dockerfile", "Shell" ]
26
TypeScript
Spanfile/DHCP-UI
31baf31ff0f4a497ef6c427c3ef13fbdaff9a419
80c15ca466dc743191eb16cb85f4d2ea9143beef
refs/heads/master
<file_sep>import React, { Component } from 'react' import * as Mess from './../../constants/Message' export default class CartItem extends Component { ChangeNumber(id,number){ this.props.changeNumber(id,number); this.props.changeMessenger(Mess.MSG_UPDATE_CART_SUCCESS); } RemoveCartItem (id) { this.props.removeCartItem(id); this.props.changeMessenger(Mess.MSG_DELETE_PRODUCT_IN_CART_SUCCESS); } render() { var {cart,quantity} = this.props; return ( <tr> <td style={{textAlign:"center"}}> <div className="col-xs-8 col-sm-8 col-md-8 col-lg-8" style={{ height: 100, width: 100 }}> <div className="thumbnail" > <img src={cart.src} alt={cart.name} /> </div> </div> <span>{cart.name}</span> </td> <td style={{textAlign:"center"}}>{cart.price}$</td> <td style={{textAlign:"center"}}> <span> <button type="button" className="btn btn-warning" onClick = {()=>this.ChangeNumber(cart.id,-1)}>-</button> </span> <span style={{padding:20}}>{quantity}</span> <span> <button type="button" className="btn btn-warning" onClick = {()=>this.ChangeNumber(cart.id,1)}>+</button> </span> </td> <td style={{textAlign:"center"}}>{cart.price * quantity}$</td> <td style={{textAlign:"center"}}> <button type="button" className="btn btn-default" onClick = {()=>this.RemoveCartItem(cart.id)}>Xóa</button> </td> </tr> ) } }<file_sep>import React, { Component } from 'react' export default class PickerColor extends Component { constructor(props) { super(props); this.state = { colors : ['red','green','blue','#ccc'] } } showcolor(color){ return { backgroundColor: color }; } changecolor(color){ this.props.ChangeColor(color); } render() { var eleColor = this.state.colors.map((color,index)=>{ return ( <span key={index} style={this.showcolor(color)} className={color===this.props.color?"active":""} onClick={()=>this.changecolor(color)}></span> ); }); return ( <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6"> <div className="panel panel-primary"> <div className="panel-heading"> <h3 className="panel-title">Color picker</h3> </div> <div className="panel-body"> {eleColor} </div> </div> </div> ) } }<file_sep>import React, { Component } from 'react' import {connect} from 'react-redux' import Messenger from './../component/component_tutorial_redux/Messenger' class MessengerContainer extends Component { render() { return ( <Messenger menssenger = {this.props.messg}/> ) } } const mapStateToProps = state => { return ({ messg: state.messenger }); } export default connect(mapStateToProps, null)(MessengerContainer);<file_sep>import React, { Component } from 'react' import ProductsContainer from './../../containers/ProductsContainer' import MessengerContainer from './../../containers/MessengerContainer' import CartContainer from './../../containers/CartContainer' import appReducer from './../../reducers/index'; import { Provider } from 'react-redux' import { createStore } from 'redux' const store = createStore(appReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ); export default class ShopingCart extends Component { render() { return ( <Provider store={store}> <div> <div className="container"> <h1 style={{ textAlign: "center", marginBottom:50}}>Danh Sách Sản Phẩm</h1> <ProductsContainer /> <div className="row"> <div className="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <MessengerContainer /> <div style = {{paddingTop:50}}> <CartContainer /> </div> </div> </div> </div> </div> </Provider> ); } }<file_sep>import React, { Component } from 'react' import CartItem from './CartItem' import CartResult from './CartResult' import * as Message from './../../constants/Message' export default class Cart extends Component { render() { var {listCart,changeNumber,changeMess} = this.props; var eleCart = Message.MSG_CART_EMPTY; if (listCart.length > 0) { eleCart = listCart.map((item,index) => { return( <CartItem key = {index} cart = {item.product} quantity = {item.quantity} changeNumber = {changeNumber} changeMessenger={changeMess} removeCartItem = {this.props.removeCartItem}/> ); }); var total = 0; listCart.forEach((item, index) => { total += item.product.price * item.quantity; }); } return ( <table className="table table-hover"> <thead> <tr> <th style={{textAlign:"center"}}>Sản Phẩm</th> <th style={{textAlign:"center"}}>Giá</th> <th style={{textAlign:"center"}}>Số Lượng</th> <th style={{textAlign:"center"}}>Tổng Cộng</th> <th></th> </tr> </thead> <tbody> {eleCart} <CartResult total = {total}/> </tbody> </table> ) } } <file_sep>import * as Types from './../constants/ActionType' var data = JSON.parse(localStorage.getItem("CART")); var initialState = data ? data : []; const cart = (state = initialState,action) => { var products = [...state]; switch(action.type) { case Types.ADD_TO_CART: var findIndex = -1; findIndex = FindIndex(products,action.product.id); if (findIndex < 0) { products.push({product:action.product,quantity:action.quantity}); } else { products[findIndex].quantity += action.quantity; } localStorage.setItem("CART", JSON.stringify(products)); return products; case Types.CHANGE_NUMBER: let index = -1; index = FindIndex(products,action.id); if (index >= 0) { products[index].quantity += action.number; if (products[index].quantity <=0 ) { products.splice(index,1); } localStorage.setItem("CART", JSON.stringify(products)); } if (products.length <= 0) { localStorage.removeItem("CART"); } return products; case Types.REMOVE_CART_ITEM: var indexItem = -1; indexItem = FindIndex(products,action.id); products.splice(indexItem,1); localStorage.setItem("CART", JSON.stringify(products)); return products; default : return [...state]; } } var FindIndex = (products,id) => { var findIndex = -1; products.forEach((productCart,index)=>{ if(productCart.product.id === id){ findIndex = index; } }); return findIndex; } export default cart;<file_sep>import React from 'react'; import './App.css'; //import TutorialStateProps from './TutorialStateProps' //import Todolist from './Todolist' import ShopingCart from './component/component_tutorial_redux/ShopingCart' // function App() { // const [count,setcount] = useState(0); // const [number,setnumber] = useState(0); // useEffect(() => { // console.log(count); // // setcount(count + 1); // }); // return ( // <div className="App"> // <p>You clicked {count+' : '+number} times</p> // <button onClick={() => {setcount(count + 1);setnumber(number+1);}}> // Click me // </button> // </div> // ); // } // export default App; class App extends React.Component { // const [count,setcount] = useState(0); // const [number,setnumber] = useState(0); // constructor(props) { // super(props); // this.state = { // number: 0 // } // console.log("contructor"); // } // componentWillUnmount() { // console.log("wil UnMount"); // this.setState({ number: 55 }); // } // componentWillMount() { // console.log("wil Mount"); // } // componentDidMount() { // console.log(this.state.number); // console.log("did mount"); // this.setState({ number: 55 }); // } // componentDidUpdate() { // console.log("did Update"); // console.log(this.state.number); // } render() { // console.log("contructor - will Mount - render - did Mount - render - dipUpdate"); return ( //<TutorialStateProps /> //<Todolist /> <ShopingCart /> ); } } export default App;<file_sep>import { combineReducers } from 'redux' import product from './product' import cart from './cart' import messenger from './messenger' const appReducers = combineReducers ({ product, cart, messenger }); export default appReducers;<file_sep>import React, { Component } from 'react' import ProducItem from './ProductItem' export default class Product extends Component { render() { var elemProduct = this.props.products.map((product,index) => { return <ProducItem key={index} product={product} addProductCart = {this.props.addCart} changeMessenger = {this.props.changeMessg}/> }); return ( <div> {elemProduct} </div> ); } } <file_sep>import React, { Component } from 'react' export default class TaskItem extends Component { DeleteItem=(id)=>{ this.props.deleteItem(id); } ChangStatus=(id)=>{ this.props.changeStatus(id); } UpdateItem =(id)=>{ this.props.updateItem(id); } render() { var {id,name,status,} = this.props.item; var {index} = this.props; return ( <tr> <td>{index +1}</td> <td> {name} </td> <td style={{ textAlign: 'center' }}> <button type="button" className={status?"btn btn-danger":"btn btn-warning"} onClick={()=>this.ChangStatus(id)}>{status?"Kích Hoạt":"Ẩn"}</button> </td> <td style={{ textAlign: 'center' }}> <button type="button" className="btn btn-warning" onClick={()=>this.UpdateItem(id)}><i className="fas fa-pencil-alt" >&nbsp;</i>Sửa</button>&nbsp;&nbsp; <button type="button" className="btn btn-danger" onClick={()=>this.DeleteItem(id)}><i className="far fa-trash-alt">&nbsp;</i>Xóa</button> </td> </tr> ) } }<file_sep>import React, { Component } from 'react' import FormAddTodo from './component/component_todolist/FormAddTodo' import Control from './component/component_todolist/Control' import TaskTodo from './component/component_todolist/TaskTodo' export default class Todolist extends Component { constructor(props) { super(props); var task = [ {id:1,name:"React js",status:true,}, {id:2,name:"Node js",status:true,}, {id:3,name:"React Native",status:false,}, {id:4,name:"Angular",status:true,} ] this.state = { task:task, status: true, taskEditing:"", filter:{ text:"", status:0 } } } ToggelAdd=()=>{ this.setState({ status: false }); } TurnOff = ()=>{ this.setState({ status: true, taskEditing:"" }); } AddTodo = (item)=>{ var list = this.state.task; if (item.id) { var index = this.FindIndexItem(list,item.id);console.log(item); list[index] = item; this.setState({ task:list, status: true }); } else { item.id = list.length+1; list.push(item); this.setState({ task:list, status: true }); } } DeleteItem=(id)=>{ var list = this.state.task; var index = this.FindIndexItem(list,id); if(index>=0){ list.splice(index,1); } this.setState({ task:list }); } ChangeStatus=(id)=>{ var list = this.state.task; var index = this.FindIndexItem(list,id); list[index].status = !list[index].status; this.setState({ task:list }); } UpdateItem = (id) =>{ var list = this.state.task; var index = this.FindIndexItem(list,id); var dataEdit = ""; if(index >= 0){ dataEdit=list[index]; } this.setState({ taskEditing: dataEdit, status: false }); } OnSearch = (keyword) => { var list = this.state.task; var resultSearch = []; list.forEach((item) => { if(item.name.toLowerCase().indexOf(keyword.toLowerCase()) >=0) { resultSearch.push(item); } }); this.setState({ task:resultSearch }); } OnSort = (sortName, value) => { var list = this.state.task; if(sortName === "name") { list.sort((a,b) => { if (a.name > b.name) { return value; } else if (a.name < b.name) { return -value; } else return 0; }); this.setState({ task:list }); } else { list.sort((a,b) => { if (a.status > b.status) { return -value; } else if (a.status < b.status) { return value; } else return 0; }); this.setState({ task:list }); } } searchTable = (textSearch,statusSearch) => { this.setState({ filter:{ text:textSearch, status:Number(statusSearch) } }); } FindIndexItem(tasks,id){ var result = -1; tasks.forEach((task,index)=>{ if(task.id === id){ result = index; } }); return result } render() { var {task,filter} = this.state; if (filter) { if (filter.text) { task = task.filter((item) => { return item.name.toLowerCase().indexOf(filter.text.toLowerCase()) !== -1; }); } if (filter.status) { task = task.filter((item) => { if (filter.status === 1) { return item.status === true; } else { return item.status === false; } }); } } var eletoggel = !this.state.status ?<FormAddTodo status={this.TurnOff} addTodo = {this.AddTodo} task={this.state.taskEditing}/>:""; return ( <div className="container"> <div style={{ textAlign: "center" }}> <h1> Quản Lý Công Việc</h1> </div> <div className="row mt-50"> {eletoggel} <div className={this.state.status?"col-xs-12 col-sm-12 col-md-12 col-lg-12":"col-xs-8 col-sm-8 col-md-8 col-lg-8"}> <button type="button" className="btn btn-sm btn-primary" onClick={()=>this.ToggelAdd()}><i className="fas fa-plus">&nbsp;</i>Thêm Công Việc</button> <div className="row mt-15"> <Control onsearch={this.OnSearch} onsort={this.OnSort}/> <div className="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <div className="table-responsive mt-15"> <TaskTodo task={task} deleteitem={this.DeleteItem} changeStatus={this.ChangeStatus} updateItem={this.UpdateItem} onchange = {this.searchTable} /> </div> </div> </div> </div> </div> </div > ) } }<file_sep>import React, { Component } from 'react' export default class Sort extends Component { OnSort = (sortName, value) => { this.props.onSort(sortName,value); } render() { return ( <div className="dropdown"> <button className="btn btn-primary dropdown-toggle" type="button" id="dropdowrMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true" > Sắp xếp <i className="fas fa-caret-square-down"></i> </button> <ul className="dropdown-menu" aria-labelledby="dropdowrMenu1"> <li style={{ padding: 10, fontSize: 16, fontWeight: "bold", cursor: "pointer"}} onClick = {() => this.OnSort('name',1)}> <i className="fas fa-sort-alpha-down">&nbsp;</i>Tên A-Z </li> <li style={{ padding: 10, fontSize: 16, fontWeight: "bold", cursor: "pointer"}} onClick = {() =>this.OnSort('name',-1)}> <i className="fas fa-sort-alpha-up">&nbsp;</i>Tên Z-A </li> <li role="separator" className="divider"></li> <li style={{ padding: 10, fontSize: 16, fontWeight: "bold", cursor: "pointer"}} onClick = {() =>this.OnSort('status',1)}> Kích Hoạt </li> <li style={{ padding: 10, fontSize: 16, fontWeight: "bold", cursor: "pointer"}} onClick = {() =>this.OnSort('status',-1)}> Ẩn </li> </ul> </div> ) } }<file_sep>var initialState = [ { id:1, src:'https://cdn.tgdd.vn/Products/Images/42/179530/samsung-galaxy-s10-plus-black-400x460.png', name: 'Điện thoại Samsung Galaxy S10+', desc: 'Điện thoại do sam sung san xuất', price: 350, inventory:10 }, { id:2, src:'https://cdn.tgdd.vn/Products/Images/42/190322/iphone-xs-max-256gb-white-400x460.png', name: 'Điện thoại iphone XS MAX 256 GB', desc: 'Điện thoại do apple san xuất', price: 450, inventory:5 }, { id:3, src:'https://cdn.tgdd.vn/Products/Images/42/199801/oppo-f11-mtp-400x460.png', name: 'Điện thoại OPPO F11 PRO XANH 128 GB', desc: 'Điện thoại do OPPO san xuất', price: 150, inventory:0 } ] const productReducer = (state = initialState,action) => { switch(action.type) { default : return [...state] } } export default productReducer;<file_sep>import React, { Component, Fragment } from 'react' import Search from './Search' import Sort from './Sort' export default class Control extends Component { OnSearch = (keyword) => { this.props.onsearch(keyword); } OnSort = (sortName, value) =>{ this.props.onsort(sortName,value); } render() { return ( <Fragment> <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6"> <Search onSearch={this.OnSearch}/> </div> <div className = "col-xs-6 col-sm-6 col-md-6 col-lg-6"> <Sort onSort={this.OnSort}/> </div> </Fragment> ) } }<file_sep>import React, { Component } from 'react' import {connect} from 'react-redux' import Cart from './../component/component_tutorial_redux/Cart' import * as Message from './../constants/Message' import {actChangeNumber,actChangeMess,actDeleteCartItem} from './../actions/index' class CartContainer extends Component { render() { return ( this.ShowCart() ); } ShowCart = () => { if(this.props.cart.length > 0) { return (<Cart listCart = {this.props.cart} changeNumber = {this.props.changeNumber} changeMess = {this.props.changeMessenger} removeCartItem = {this.props.removeCartItem}/>); } return Message.MSG_CART_EMPTY; } } const MapStateToProps = state => { return ({ cart : state.cart }); } const MapDispatchToProps = dispatch => { return ({ changeNumber: (id,number) =>{ dispatch(actChangeNumber(id,number)); }, changeMessenger: (mes) => { dispatch(actChangeMess(mes)); }, removeCartItem: (id) => { dispatch(actDeleteCartItem(id)); } }); } export default connect(MapStateToProps, MapDispatchToProps)(CartContainer);<file_sep>export const ADD_TO_CART = "ADD_TO_CART"; export const CHANGE_MESSENGER = "CHANGE_MESSENGER"; export const CHANGE_NUMBER = "CHANGE_NUMBER"; export const REMOVE_CART_ITEM = "REMOVE_CART_ITEM";<file_sep>import React, { Component } from 'react' export default class CartResult extends Component { render() { return ( <tr> <td></td> <td></td> <td><h3>Tổng Cộng</h3></td> <td><h3>{this.props.total}$</h3></td> <td></td> </tr> ) } }<file_sep>import React, { Component } from 'react' export default class Search extends Component { constructor(props) { super(props); this.state = { keyword:"" } } Onchange = (event) =>{ var value = event.target.value; this.setState({ keyword:value }); } Onsearch = () =>{ this.props.onSearch(this.state.keyword); } render() { return ( <div className="input-group"> <input type="text" name="keyword" className="form-control" placeholder="Nhập từ khóa..." value={this.state.keyword} onChange={this.Onchange} /> <span className="input-group-btn" style={{ margin: 0, padding: 0 }}><button type="button" className="btn btn-primary" onClick={this.Onsearch}><i className="fas fa-search">&nbsp;</i>Tìm</button></span> </div> ) } }<file_sep>import * as Types from './../constants/ActionType' export const actAddToCart = (product, quantity) => { return { type : Types.ADD_TO_CART, product, quantity } } export const actChangeMess = (messenger) => { return { type: Types.CHANGE_MESSENGER, messenger } } export const actChangeNumber = (id,number) => { return { type: Types.CHANGE_NUMBER, number, id } } export const actDeleteCartItem = (id) => { return { type: Types.REMOVE_CART_ITEM, id } }<file_sep>import React, { Component } from 'react' import PickerColor from './component/component_src_color/PickerColor' import ChangeFontSize from './component/component_src_color/ChangeFontSize' import Reset from './component/component_src_color/Reset' import Result from './component/component_src_color/Result' import './Tutorial.css'; export default class TutorialStateProps extends Component { constructor(props) { super(props); this.state = { color:'red', fontsize:12, } this.changeFontSize = this.changeFontSize.bind(this); } ChangeColor=(color)=>{// es6 ko can bind this.setState({ color:color }); } changeFontSize(value){ let fontsize = this.state.fontsize +value; if(fontsize>=12 && fontsize<=30){ this.setState({ fontsize:fontsize }); }else{ alert("font chữ bạn khích thước phải lớn hơn 12 và nhỏ hơn 30"); } } reset=()=>{ this.setState({ color:'red', fontsize:12, }); } render() { return ( <div className="container mt-50"> <div className="row"> <PickerColor color = {this.state.color} ChangeColor = {this.ChangeColor}/> <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6"> <ChangeFontSize size = {this.state.fontsize} changeFontSize={this.changeFontSize}/> <Reset reset = {this.reset}/> </div> <Result color = {this.state.color} size = {this.state.fontsize}/> </div> </div> ) } }
53010b4c4b006a28056680f0ce67b5f9462ae01e
[ "JavaScript" ]
20
JavaScript
TuanDong/React-JS
7dd8b47696f674e80d10cf23567af30eb67687a0
cff50849eb3a34e6defcdaae9948905b8448c144
refs/heads/master
<file_sep>import LinearSearcher import unittest class TestLinearSearcher(unittest.TestCase): #Test 1 def test_list_element_is_available(self): '''find the element 5 in list''' list = [3, 1, 5, 2, 4] expected = True actual = LinearSearcher.isAvailable(list, 5) self.assertEqual(expected, actual) #Test 2 def test_list_element_is_not_available(self): '''find the element 5 in list''' list = [3, 1, 5, 2, 4] expected = False actual = LinearSearcher.isAvailable(list, 6) self.assertEqual(expected, actual) #Test 3 def test_list_list_is_mono_type_true(self): '''Expected list is mono type''' list = [3, 1, 5, 2, 4] expected = True actual = LinearSearcher.isMonoTypeList(list) self.assertEqual(expected, actual) #Test 4 def test_list_list_is_mono_type_false(self): '''Expected list is non mono type''' list = [3, 1, 5, 2, 4, "Six"] expected = False actual = LinearSearcher.isMonoTypeList(list) self.assertEqual(expected, actual) #Test 5 def test_list_list_is_empty(self): '''Expected list is Empty''' list = [] expected = True actual = LinearSearcher.isEmptyList(list) self.assertEqual(expected, actual) #Test 6 def test_list_list_is_non_empty(self): '''Expected list is Non_Empty''' list = [1] expected = False actual = LinearSearcher.isEmptyList(list) self.assertEqual(expected, actual) #Test 7 def test_list_find_size_of_list(self): '''Expected Size is 5''' list = [3, 1, 5, 2, 4] expected = 5 actual = LinearSearcher.sizeOfList(list) self.assertEqual(expected, actual) #Test 8 def test_list_for_single_element(self): '''Expected isSilgleElementList is True''' list = [3] expected = True actual = LinearSearcher.isSingleElementList(list) self.assertEqual(expected, actual) #Test 9 def test_list_search_for_element_in_empty_list(self): '''Searching for element 3 in empty list''' list = [] expected = "Empty List" actual = LinearSearcher.searcher(list,3) self.assertEqual(expected, actual) #Test 10 def test_list_finding_max_element_in_list(self): '''List has max element is 10''' list = [1, 2, 3, 10, 4, 7, 5, 9, 0] expected = 10 actual = LinearSearcher.findMaxElement(list) self.assertEqual(expected, actual) #Test 11 def test_list_finding_max_element_in_list_empty_list(self): '''Empty list but we trying to find element 10''' list = [] expected = "Invalid List" actual = LinearSearcher.findMaxElement(list) self.assertEqual(expected, actual) #Test 12 def test_list_finding_min_element_in_list(self): '''List has max element is 10''' list = [1, 2, 3, 10, 4, 7, 5, 9, 0] expected = 0 actual = LinearSearcher.findMinElement(list) self.assertEqual(expected, actual) #Test 13 def test_list_finding_min_element_in_list_empty_list(self): '''Empty list but we trying to find element 10''' list = [] expected = "Invalid List" actual = LinearSearcher.findMinElement(list) self.assertEqual(expected, actual) #Test 14 def test_list_finding_first_element_in_list(self): '''List has first element is 1''' list = [1, 2, 3, 10, 4, 7, 5, 9, 0] expected = 1 actual = LinearSearcher.findFirstElement(list) self.assertEqual(expected, actual) #Test 15 def test_list_finding_first_element_in_list_empty_list(self): '''Empty list but we trying to find first element''' list = [] expected = "Invalid List" actual = LinearSearcher.findFirstElement(list) self.assertEqual(expected, actual) #Test 16 def test_list_finding_last_element_in_list(self): '''List has last element is 1''' list = [1, 2, 3, 10, 4, 7, 5, 9, 20] expected = 20 actual = LinearSearcher.findLastElement(list) self.assertEqual(expected, actual) #Test 17 def test_list_finding_last_element_in_list_empty_list(self): '''Empty list but we trying to find last element''' list = [] expected = "Invalid List" actual = LinearSearcher.findLastElement(list) self.assertEqual(expected, actual) #Test 18 def test_list_finding_position_of_element_in_list(self): '''List has last element is 1''' list = [1, 2, 3, 10, 4, 7, 5, 9, 20] expected = 3 actual = LinearSearcher.findPositionOfElement(list,10) self.assertEqual(expected, actual) #Test 19 def test_list_finding_position_of_element_not_available_in_list(self): '''List has last element is 1''' list = [1, 2, 3, 10, 4, 7, 5, 9, 20] expected = "Can't Find an Element in List" actual = LinearSearcher.findPositionOfElement(list,50) self.assertEqual(expected, actual) #Test 20 def test_list_finding_the_list_is_sorted_in_assending_order(self): '''This is Sorted List''' list = [1, 2, 3, 4, 5, 6, 7, 8, 9] expected = True actual = LinearSearcher.isSortedList(list) self.assertEqual(expected, actual) #Test 21 def test_list_finding_the_list_is_sorted_in_desending_order(self): '''This is Sorted List''' list = [9, 8, 7, 6, 5, 4, 3, 2, 1] expected = True actual = LinearSearcher.isSortedList(list) self.assertEqual(expected, actual) #Test 22 def test_list_finding_the_list_is_not_sorted(self): '''This is Non Sorted List''' list = [1, 7, 3, 4, 9, 6, 2, 8, 5] expected = False actual = LinearSearcher.isSortedList(list) self.assertEqual(expected, actual) #Test 23 def test_list_finding_the_list_is_sorted_but_list_is_empty(self): '''This is Non Sorted List''' list = [] expected = "Invalid List" actual = LinearSearcher.isSortedList(list) self.assertEqual(expected, actual) #Test 24 def test_list_finding_the_element_in_position_of_list(self): '''List has Element 7 in 5th position''' list = [1, 10, 3, 4, 9, 7, 2, 8, 10] expected = 7 actual = LinearSearcher.findTheElementInPosition(list, 5) self.assertEqual(expected, actual) #Test 25 def test_list_finding_the_element_in_position_of_list_position_outbound(self): '''List has Element 7 in 5th position''' list = [1, 10, 3, 4, 9, 7, 2, 8, 10] expected = "Position is OutBound" actual = LinearSearcher.findTheElementInPosition(list, 20) self.assertEqual(expected, actual) #Test 26 def test_list_finding_the_element_in_position_of_list_but_list_is_empty(self): '''Empty List but tyring to find element in 5th position''' list = [] expected = "Invalid List" actual = LinearSearcher.findTheElementInPosition(list, 5) self.assertEqual(expected, actual) if __name__ == '__main__': unittest.main() <file_sep># pythonTrys ## Data Compressor https://goo.gl/Oo2rma ## Data Encryptor https://goo.gl/dSkMGz ## Visualization of sorting https://visualgo.net/en/sorting ## Linear Search CDJ http://10.100.8.8/kata/edit/86A713A750?avatar=moose <file_sep>def sizeOfList(list): return len(list) def isMonoTypeList(list): type_to_compare = type(list[0]) for thing in list: if type_to_compare != type(thing): return False return True def isEmptyList(list): if sizeOfList(list) == 0: return True else: return False def isSingleElementList(list): if sizeOfList(list) == 1: return True else: return False def searcher(list, element): if isEmptyList(list): return "Empty List" else: for thing in list: if thing == element: return True return False def isAvailable(list, element): return searcher(list, element) def findMaxElement(list): if not isEmptyList(list): if isSingleElementList(list): return list[0] else: max_element = list[0] for element in list: if(max_element <= element): max_element = element return max_element else: return "Invalid List" def findMinElement(list): if not isEmptyList(list): if isSingleElementList(list): return list[0] else: min_element = list[0] for element in list: if(min_element >= element): min_element = element return min_element else: return "Invalid List" def findFirstElement(list): if not isEmptyList(list): if isSingleElementList(list): return list[0] else: return list[0] else: return "Invalid List" def findLastElement(list): if not isEmptyList(list): if isSingleElementList(list): return list[0] else: return list[sizeOfList(list)-1] else: return "Invalid List" def findPositionOfElement(list, element_to_find_position): if not isEmptyList(list) and isAvailable(list, element_to_find_position): if isSingleElementList(list): return 0 else: position = 0 for element in list: if element == element_to_find_position: return position else: position += 1 else: return "Can't Find an Element in List" def isSortedList(list): if not isEmptyList(list) and isMonoTypeList(list): if isSingleElementList(list): return True else: first_element = findFirstElement(list) last_element = findLastElement(list) if first_element < last_element: for element in list: if element < first_element or element > last_element: return False return True else: if first_element > last_element: for element in list: if element > first_element or element < last_element: return False return True else: return "Invalid List" def findTheElementInPosition(list, position_of_element): if (not isEmptyList(list)): if ((sizeOfList(list)-1) >= position_of_element): return list[position_of_element] else: return "Position is OutBound" else: return "Invalid List"
26081eb1b0b7a20bc9bc84aaf24c97e20121133d
[ "Markdown", "Python" ]
3
Python
rajasekaran36/pythonTrys
8c8e4472774cef9dab3101e265ce191b451bead9
45fa977dca533434ecfaa4f17a1318437ef95cf6
refs/heads/main
<file_sep>const News = require('../models/News') module.exports = async (req, res) => { const news = await News.findById(req.params.id) res.render('news', { news }) }<file_sep>const News = require('../models/News') module.exports = async (req, res) => { const allNews = await News.find({}) const sport_News = await News.find({ category: 'Sports' }) const busi_News = await News.find({ category: 'Business' }) const tech_News = await News.find({ category: 'Technology' }) res.render('index', { allNews, sport_News, busi_News, tech_News }) }<file_sep>module.exports = (req, res) => { console.log('Register Errors: ' + req.flash('errors')) res.render('register', { errors: req.flash('errors') }) }<file_sep>const User = require('../models/User') const bcrypt = require('bcrypt') module.exports = (req, res) => { User.findOne({ email: req.body.email }, (err, user) => { if (!err) { bcrypt.compare(req.body.password, user.password, function(err, result) { if (err) { console.log('Password Incorrect: ' + err) res.redirect('/login') } console.log('Succesful: ' + result) req.session.username = user.username req.session.userId = user._id res.redirect('/') }); } console.log('No such user exists: ' + err) }) }<file_sep>// Requiring all packages const express = require('express') const ejs = require('ejs') const mongoose = require('mongoose') const session = require('express-session') const flash = require('connect-flash') const bodyParser = require('body-parser') const path = require('path') // Init Express const app = express() // Connecting to Database mongoose.connect('mongodb://127.0.0.1/news_database', { useNewUrlParser: true }); // Middlewares const loginStatus = require('./middleware/checkLogin') const auth = require('./middleware/authentication') const auth_login = require('./middleware/login') // Using Default Middlewares app.set('view engine', 'ejs') app.use(session({ name: "my_session", secret: 'keyboard cat', })) app.use(flash()) app.use(express.static('public')) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(express.urlencoded({ extended: true })) app.use(loginStatus) // Controllers const homeController = require('./controller/home') const postController = require('./controller/post') const contactController = require('./controller/contact') const loginController = require('./controller/login') const registerController = require('./controller/register') const storeUserController = require('./controller/storeUser') const loginUserController = require('./controller/loginUser') const storePostController = require('./controller/storePost') const newsPageController = require('./controller/news') const logoutController = require('./controller/logout') // Login Global global.loggedIn = null global.name = "" // Routing app.get('/', homeController) app.get('/post', auth, postController) app.get('/contact', contactController) app.get('/login', auth_login, loginController) app.get('/register', auth_login, registerController) app.get('/news/:id', newsPageController) app.get('/logout', logoutController) app.post('/store-user', storeUserController) app.post('/login-user', loginUserController) app.post('/store-post', storePostController) app.listen(5000, () => { console.log('Listening to 5000') })<file_sep>const mongoose = require('mongoose') const Schema = mongoose.Schema const NewsSchema = new Schema({ title: { type: String, required: [true, 'Please enter the title'] }, category: { type: String, required: [true, 'Please enter the category'] }, image: { type: String, required: [true, 'Please uplaod image'] }, post: { type: String, required: [true, 'Please enter the post'], minlength: [500, 'Post too short'] }, username: { type: String, required: [true, 'Please provide username'] }, created_at: { type: Date, default: Date.now() } }) const News = mongoose.model("News", NewsSchema) module.exports = News<file_sep>const News = require('../models/News') const path = require('path') const multer = require('multer'); // Set File Storage Engine const storage = multer.diskStorage({ destination: function(req,file,callback) { callback(null, 'public/uploads/'); }, filename: (req, file, cb) => { cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)) } }) // Init Upload const upload = multer({ storage: storage }).single('image'); module.exports = (req, res) => { upload(req, res, (err) => { if (err) { console.log('Image Uploadation Error: ' + err) return res.redirect('/post') } const filename = req.file.filename News.create({ ...req.body, image: filename, username: req.session.username }, (err, post) => { if (err) { console.log('Post not created: ' + err) return res.redirect('/post') } console.log('Post Succsecfully Created: ' + post) return res.redirect('/') }) }) }
0e76a269821aebf9a968e9afedb6225a5b999aa1
[ "JavaScript" ]
7
JavaScript
AsfandToor/News_Site
8f5f1fff8d50bd5507bb7fd5d60b47ed06f7bdc0
0f8592d3e2081d406a8a7a5d5864452cbd893dda
refs/heads/master
<file_sep>``` title: Dienstleistungen layout: page tags: ['intro','page'] pageOrder: 2 keywords: service, abgasuntersuchung, hauptuntersuchung, unfallinstantsetzung, reifen, klima description: Hier stellen wir Ihnen unsere Dienstleistungen vor. ``` <img src="/images/icons/fahrzeuge.png" alt="Fahrzeuge" class="pull-center" /> Fahrzeugvermittlung Neu-/Gebrauchtwagen<br /> <img src="/images/icons/inspektion.png" alt="Inspektion" class="pull-center" /> Kundendienst und Reparatur alle Fabrikate<br /> <img src="/images/icons/huau.png" alt="Abgasuntersuchung" class="pull-center" /> anerkannter AU-Betrieb für Benzin & Diesel<br /> <img src="/images/icons/huau.png" alt="Hauptuntersuchung" class="pull-center" /> Hauptuntersuchung in unserem Betrieb\*, jeden Mittwoch<br /> <img src="/images/icons/unfall.png"alt="Unfall" class="pull-center" /> Unfallinstandsetzung<br /> <img src="/images/icons/achsen.png" alt="Achsvermessung" class="pull-center" /> elektronische Fahrwerksvermessung<br /> <img src="/images/icons/reifenservice.png" alt="Reifenservice" class="pull-center" /> Reifenservice<br /> <img src="/images/icons/klimaservice.png" alt="Klimaservice" class="pull-center" /> Klimaservice<br /> <img src="/images/icons/ec.png" alt="ec-Karte" class="pull-center"/> Zahlung per ec-Karte<br /> <br /> <small>\* HU nach §29 StVZO wird von einer amtlich anerkannten Überwachungsorganisation durchgeführt.</small><file_sep>``` title: Kontakt layout: page tags: ['intro','page'] pageOrder: 4 keywords: kontakt, email description: Hier nehmen wir gerne Ihre Anfrage entgegen. ``` <h3>Anfrage</h3> <form class="form-horizontal" role="form" method="post" action="submit.php"> <div class="form-group"> <label for="inputName3" class="col-sm-2 control-label">Name</label> <div class="col-sm-10"> <input name="name" class="form-control" id="inputName3" placeholder="Name"> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Email</label> <div class="col-sm-10"> <input name="email" class="form-control" id="inputEmail3" placeholder="Email"> </div> </div> <div class="form-group"> <label for="inputMessage3" class="col-sm-2 control-label">Nachricht</label> <div class="col-sm-10"> <textarea name="message" class="form-control" id="inputMessage3"></textarea> </div> </div> <div class="antispam"> <label for="inputUrl3" class="col-sm-2 control-label">Dieses Feld nicht ausfüllen!</label> <div class="col-sm-10"> <input name="url" /> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Absenden</button> </div> </div> </form> <file_sep><?php // if the url field is empty if(isset($_POST['url']) && $_POST['url'] == ''){ // put your email address here $youremail = '<EMAIL>'; // prepare a "pretty" version of the message // Important: if you added any form fields to the HTML, you will need to add them here also $body = "Folgende Anfrage wurde über das Kontaktformular abgesendet: Name: $_POST[name] E-Mail: $_POST[email] Message: $_POST[message]"; // Use the submitters email if they supplied one // (and it isn't trying to hack your form). // Otherwise send from your email address. if( $_POST['email'] && !preg_match( "/[\r\n]/", $_POST['email']) ) { $headers = "From: $_POST[email]"; } else { $headers = "From: $youremail"; } // finally, send the message mail($youremail, 'Anfrage ueber Homepage', $body, $headers ); } // otherwise, let the spammer think that they got their message through ?> header('Location: http://www.auto-hartmann.de/danke.html'); exit('Weiterleitung zu http://www.auto-hartmann.de/danke.html');<file_sep>``` title: Standort layout: page tags: ['intro','page'] pageOrder: 5 keywords: standort, anfahrt description: Hier finden Sie unseren Standort und die Anfahrtsbeschreibung. ``` Unser Standort liegt direkt an der B26 zwischen Bamberg und Eltmann. Sie erreichen uns auch über die Autobahn A70 und der Ausfahrt Viereth-Trunstadt. <iframe width="100%" height="400" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://umap.openstreetmap.fr/de/map/auto-hartmann_13431" style="border: 1px solid black"></iframe> <file_sep>``` title: Impressum layout: page tags: ['intro','page'] pageOrder: 6 keywords: impressum, kontakt, anschrift description: Hier finden Sie unser Impressum. ``` <h3>Firmeninformation</h3> Anschrift: <br/> <address itemprop="address" itemscope itemtype="http://schema.org/AutoRepair"> <span class="contact-name" itemprop="name"><strong><NAME></strong><br/></span> Inh. <NAME><br /> <div itemprop="address" itemscope itemtype="http://schema.org/PostalAddress"> <span class="contact-street" itemprop="streetAddress">Trunstadter Hauptstr. 2b<br/></span> <span class="contact-postcode" itemprop="postalCode">96191</span> <span class="contact-suburb" itemprop="addressLocality">Viereth-Trunstadt<br/></span> <span class="contact-country" itemprop="addressCountry">Deutschland<br/></span> </div> <br/> Telefon: <span class="contact-telephone" itemprop="telephone">+49 (0) 9503 7667</span><br/> Telefax: <span class="contact-fax" itemprop="faxNumber">+49 (0) 9503 4677</span><br/> Email: <a href="/kontakt/">Kontakt</a><br /> Internet: <span class="contact-webpage"><a href="http://www.auto-hartmann.de" target="_blank" itemprop="url">http://www.auto-hartmann.de</a></span><br/> USt.IdNr.: <span class="contact-taxID" itemprop="taxID">DE132223407</span><br /> </address> <h3>Rechtliche Hinweise</h3> Inhaltlich Verantwortlicher gemäß §10 Absatz 3 MDStV:<br /> <NAME><br /> <br /> Technisch Verantwortlicher:<br /> <NAME><br /><file_sep>--- layout: 'default' title: 'Danke' --- Vielen Dank für Ihre Anfrage. Wir werden diese umgehend bearbeiten. <file_sep>``` title: Links layout: page tags: ['intro','page'] pageOrder: 3 keywords: links description: Auflistung von Links zu Partnern und örtlichen Gemeinschaften. ``` <div class="row" class="text-center"> <div class="col-lg-6"> <h3>Partner</h3> <ul> <li><a href="http://www.grasser-edv.de" target="_blank">Grasser-EDV</a> <i>unser Webhostingpartner</i><br /></li> <li><a href="http://www.it4workflow.de" target="_blank">it 4 workflow</a> <i>Betreuung der Seite</i><br /></li> <li><a href="http://www.haraldhartmann.de" target="_blank"><NAME></a> <i>Webmaster der Seite</i><br /></li> </ul> </div> <div class="col-lg-6"> <h3>Örtliche Gemeinschaften</h3> <ul> <li><a href="http://www.trunstadter-musikanten.de" target="_blank" >Trunstadter Musikanten</a></li> <li><a href="http://www.ritter-vom-hahn.de" target="_blank" >Ritter vom Hahn</a></li> <li><a href="http://www.singen-trunstadt.de" target="_blank" >Singgemeinschaft Trunstadt</a></li> <li><a href="http://www.viereth-trunstadt.de" target="_blank">Gemeinde Viereth-Trunstadt</a></li> </ul> </div> </div>
0db424be4cee81c28949526441077e9c9943928d
[ "Markdown", "HTML", "PHP" ]
7
Markdown
it4workflow/autohartmann
0f9ca56fb5b815abefd94733b65cc4e98e9594dc
0496c4281c06ce0771ed11c1f65f629677ba1fbc
refs/heads/master
<repo_name>MarsMuse/gateway<file_sep>/ServiceVendor/src/main/java/com/artisan/auth/EnvironmentController.java package com.artisan.auth; import com.artisan.transmit.slot.FlumeBootStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.net.InetAddress; import java.util.Enumeration; import java.util.Map; import java.util.Set; /** * * @author <NAME> * @date 2018/7/10 下午4:15 * 环境信息 * */ @Controller @RequestMapping(value = "envInfo") public class EnvironmentController { private Logger log = LoggerFactory.getLogger(EnvironmentController.class); @Resource private RestTemplate restTemplate; @Resource AuthSl authSl; @RequestMapping(value = "showHost",method = RequestMethod.GET) @ResponseBody public String showHost(HttpServletRequest request){ log.info("主机展示被调用"); String loginInfo = request.getHeader("loginName"); log.info("loginName传递:{}。", loginInfo); String hostAddress; try { InetAddress address = InetAddress.getLocalHost(); hostAddress = address.getHostAddress(); }catch (Exception e){ log.info("获取主机出现错误", e); hostAddress = "unKnown"; } FlumeBootStream.addParameter("artist-MARS","222222222"); FlumeBootStream.addParameter("artist-MARS1","wwwwwww"); FlumeBootStream.addParameter("artist-MARS2","eeeeeeee"); FlumeBootStream.addParameter("artist-MARS4","rrrrrfrr"); FlumeBootStream.addParameter("artist-MARS5","ttttttfft"); FlumeBootStream.addParameter("CTTc-MARS6","dfffffff"); FlumeBootStream.addParameter("CTTc-MARS7","fffffffff"); return authSl.show(); } @RequestMapping(value = "source",method = RequestMethod.GET) public String reDirect(HttpServletResponse response,RedirectAttributes attr) { log.info("重定向入口"); attr.addAttribute("test","test"); return "redirect:/envInfo/target"; } @RequestMapping(value = "target",method = RequestMethod.GET) @ResponseBody public String targetDirect(HttpServletRequest request){ Map<String,String> ti = FlumeBootStream.getParameterKeyLowerCase(); Set<String> keySet = ti.keySet(); if(ti.isEmpty()){ return "error"; } for(String key:keySet){ log.info("获取到键:{},值:{}。",key,ti.get(key)); } return "success"; } } <file_sep>/ServiceVendor/src/main/resources/application.properties server.port=8088 spring.application.name=AUTH-VENDOR spring.profiles.active=first spring.jersey.application-path=rest eureka.client.serviceUrl.defaultZone=http://admin:123@eureka.yds.lan/eureka/ logging.level.com.artisan.auth.AuthSl=DEBUG AUTH-SL.ribbon.ReadTimeout=2500<file_sep>/AuthenticationService/src/main/java/com/cttc/auth/constant/SignInConstants.java package com.cttc.auth.constant; /** * * @author xz man * @date 2018/7/23 下午3:42 * @since v1.0 * 登录常量 * */ public enum SignInConstants { WEB_LOGIN_NAME("loginName","Web端登录名"), WEB_PASSWORD("<PASSWORD>","<PASSWORD>"), WEB_SOURCE_USER("1","web端用户"), APP_LOGIN_NAME("loginName","APP端登录名"), APP_PASSWORD("<PASSWORD>","<PASSWORD>"), APP_SOURCE_USER("2","APP端用户"); /** * 表单名称 */ private String formName; /** * 描述 */ private String describe; private SignInConstants(String formName, String describe) { this.formName = formName; this.describe = describe; } public String getFormName() { return formName; } } <file_sep>/README.md # gateway SpringCloudGateway <file_sep>/GateWayApp/src/main/java/com/cttc/gateway/service/TestServive.java package com.cttc.gateway.service; import com.cttc.gateway.entity.UserInfo; public class TestServive { public static void main(String[] args) { UserInfo info = new UserInfo("a",1); System.out.println(info.hashCode()); info.setAge(10); System.out.println(info); } } <file_sep>/AuthenticationService/src/main/java/com/cttc/auth/entity/UserInfo.java package com.cttc.auth.entity; import lombok.Data; /** * * @author xz man * @date 2018/7/23 上午11:51 * 用户信息--存储前端需要的基本信息 * */ @Data public class UserInfo { /** * 主键 */ private String id; /** * 登录名 */ private String loginName; /** * 用户来源(1:web端 ,2: 移动端) */ private String userSource; } <file_sep>/ServiceConsumer/src/main/resources/application.properties server.port=8099 spring.application.name=AUTH-CON eureka.client.serviceUrl.defaultZone=http://eureka.didispace.com/eureka/ AUTH-SERVICE.ribbon.ReadTimeout=2500 logging.level.com.cttc.consumer.client.AuthServiceClient = DEBUG test.array=aaa,bbb <file_sep>/AuthenticationService/src/main/java/com/cttc/auth/service/UserLoginService.java package com.cttc.auth.service; import com.cttc.auth.entity.UserInfo; /** * * @author xz man * @date 2018/7/23 下午4:21 * @since v1.0 * 用户登录服务 * */ public interface UserLoginService { /** * * @author xz man * @date 2018/7/23 下午4:20 * @since v1.0 * 方法描述: web端用户登录 * */ UserInfo webUserLogin(String loginName, String password) throws Exception; /** * * @author xz man * @date 2018/7/23 下午4:20 * @since v1.0 * 方法描述: app 端用户登录 * */ UserInfo appUserLogin(String loginName, String password) throws Exception; }
0399da361ed17c76f8c9c1468b1c929b5abfdebd
[ "Markdown", "Java", "INI" ]
8
Java
MarsMuse/gateway
ea7cc8eaa54cff23fc7250b641ac7ae8a173a72a
f4155a914bd5cf0937479b6fd1d6e289f58f24e8
refs/heads/master
<file_sep>export class OrigDestPairs { DestinationPairs: string; Counts: number; }<file_sep>import { Component, OnInit, SystemJsNgModuleLoader } from '@angular/core'; import { Data } from '../models/data'; import { DataService } from '../service/data.service'; @Component({ selector: 'app-data-list', templateUrl: './data-list.component.html', styleUrls: ['./data-list.component.css'] }) export class DataListComponent implements OnInit { startDate = "2000-01-01"; endDate = "2050-01-01"; headers = ["origin","destination","search_for_arrival","date_travel","time_travel"]; public data: Data[]; constructor(private ds: DataService) {} ngOnInit(): void { this.getAllData(); } getAllData(){ this.ds.getAllData().subscribe(data => { this.data = data; console.log(data)}, error => { console.error(error); }); } } <file_sep>import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Data } from '../models/data'; import { DestCount} from '../models/destCount'; import { OrigCount} from '../models/origCount'; import { OrigDestPairs } from '../models/origDestPairs'; import { SearchByTime } from '../models/srchByTime'; import { SearchByHour } from '../models/srchByHour'; import { Count } from '../models/count'; @Injectable() export class DataService { public dataServiceURI: string = 'https://api.destination-insights.osoc.be/api/data'; //public dataServiceURI: string = 'http://localhost:3000/api/data'; private contentHeaders: HttpHeaders; constructor(private http: HttpClient) { this.contentHeaders = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded'); } // Get all the data getAllData(): Observable<Data[]> { let url = `${this.dataServiceURI}`; return this.http.get<Data[]>(url); } getDestCountData(): Observable<DestCount[]>{ let url = `${this.dataServiceURI}/cntDest`; return this.http.get<DestCount[]>(url); } getOrigCountData(): Observable<OrigCount[]>{ let url = `${this.dataServiceURI}/cntOrig`; return this.http.get<OrigCount[]>(url); } getOrigDestPairsData(): Observable<OrigDestPairs[]> { let url = `${this.dataServiceURI}/origDestPairs`; return this.http.get<OrigDestPairs[]>(url); } getSearchesByTime(): Observable<SearchByTime[]> { let url = `${this.dataServiceURI}/searchesByTime`; return this.http.get<SearchByTime[]>(url); } getSearchesByHour(): Observable<SearchByHour> { let url = `${this.dataServiceURI}/searchesByHour`; return this.http.get<SearchByHour>(url); } } <file_sep>export class Request { start_date: string; end_date: string; date_type: string; rows: number; }<file_sep>export class SearchByTime { Date: string; Counts: number; }<file_sep>import { Component, OnInit } from '@angular/core'; import { DataService } from '../service/data.service'; import { FileUploader } from 'ng2-file-upload'; const URL = 'https://api.destination-insights.osoc.be/api/data/'; @Component({ selector: 'app-upload', templateUrl: './upload.component.html', styleUrls: ['./upload.component.css'] }) export class UploadComponent implements OnInit { uploader: FileUploader; hasBaseDropZoneOver:boolean; response: string; ngOnInit() { this.uploader = new FileUploader({ url: 'https://api.destination-insights.osoc.be/api/data/', }); this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; }; this.hasBaseDropZoneOver = false; this.response = ''; this.uploader.response.subscribe(res => this.response = res); } public fileOverBase(e:any):void{ this.hasBaseDropZoneOver = e; } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { DataListComponent } from './data-list/data-list.component'; import { UploadComponent } from './upload/upload.component'; import { DataService } from './service/data.service'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { FileUploadModule } from 'ng2-file-upload'; import { FormsModule } from '@angular/forms'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { DashboardComponent } from './dashboard/dashboard.component'; import { GraphOrigDestComponent} from './graph-orig-dest/graph-orig-dest.component'; import { TablePairsComponent } from './table-pairs/table-pairs.component'; import { AmountOfSearchesComponent } from './amount-of-searches/amount-of-searches.component'; import { SearchesByHourComponent } from './searches-by-hour/searches-by-hour.component'; import { AuthGuard } from './service/auth.guard'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { LoaderComponent } from './shared/loader/loader.component'; import { LoaderService } from './service/loader.service'; import { LoaderInterceptor } from './service/loader.interceptor' // define the routes const appRoutes: Routes = [ { path: 'graph', component: GraphOrigDestComponent, canActivate: [AuthGuard]}, { path: 'list', component: DataListComponent, canActivate: [AuthGuard] }, { path: 'upload', component: UploadComponent, canActivate: [AuthGuard] }, { path: 'table-pairs', component: TablePairsComponent, canActivate: [AuthGuard] }, { path: 'number-searches', component: AmountOfSearchesComponent, canActivate: [AuthGuard] }, { path: 'srchHours', component: SearchesByHourComponent, canActivate: [AuthGuard] }, { path: '', component: DashboardComponent}, ]; @NgModule({ imports: [RouterModule.forRoot(appRoutes), BrowserModule, HttpClientModule, ReactiveFormsModule, FormsModule, NgbModule, BrowserAnimationsModule, FileUploadModule, MatProgressSpinnerModule ], declarations: [AppComponent, DataListComponent, UploadComponent, DashboardComponent, TablePairsComponent, AmountOfSearchesComponent, SearchesByHourComponent, LoaderComponent], providers: [DataService, LoaderService, { provide: HTTP_INTERCEPTORS, useClass: LoaderInterceptor, multi: true }], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>export class OrigCount { Origin: string; Counts: number; }<file_sep>import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common' import * as Chart from 'chart.js'; import { DataService } from '../service/data.service'; import { DestCount } from '../models/destCount'; import { OrigCount } from '../models/origCount'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-graph-orig-dest', templateUrl: './graph-orig-dest.component.html', styleUrls: ['./graph-orig-dest.component.css'] }) export class GraphOrigDestComponent implements OnInit { startDate = "2000-01-01"; endDate = "2050-01-01"; public loadingDestinations = false; public loadingOrigins = false; canvasOrig: any; ctxOrig: any; canvasDest: any; ctxDest: any; public dataDest: DestCount[]; public dataOrig: OrigCount[]; public labelsDest: string[] = []; public datasetDest: number[] = []; public labelsOrig: string[] = []; public datasetOrig: number[] = []; constructor(private ds: DataService) { } ngOnInit(): void { //gets the data for the destination count this.getDestCountData(); //gets the data for the origin count this.getOrigCountData(); } //gets the data for the destination count getDestCountData() { this.loadingDestinations = true; //receive data let body = { startDate: this.startDate, endDate: this.endDate } this.ds.getDestCountData().subscribe(data => { this.dataDest = data; console.log(data) this.dataDest.forEach(data => this.labelsDest.push(data.Destination)); this.dataDest.forEach(data => this.datasetDest.push(data.Counts)); this.generateDestChart(); this.loadingDestinations = false; }, error => { console.error(error); }); } //gets the data for the origin count getOrigCountData() { this.loadingOrigins = true; let body = { startDate: this.startDate, endDate: this.endDate } this.ds.getOrigCountData().subscribe(data => { this.dataOrig = data; console.log(this.dataOrig); this.dataOrig.forEach(item => { this.labelsOrig.push(item.Origin); }); this.dataOrig.forEach(data => this.datasetOrig.push(data.Counts)); this.generateOrigChart(); this.loadingDestinations = false; }, error => { console.error(error); }); } //generates the destination chart generateDestChart() { this.canvasDest = document.getElementById('destChart'); this.ctxDest = this.canvasDest.getContext('2d'); let myChart = new Chart(this.ctxDest, { type: 'bar', data: { labels: this.labelsDest, datasets: [{ label: 'Most searched for destination', data: this.datasetDest, backgroundColor: ["#006ab3", , , , , , , , "#444"], borderWidth: 1 }] }, options: {} }) } //generates the origin chart generateOrigChart() { this.canvasOrig = document.getElementById('origChart'); this.ctxOrig = this.canvasOrig.getContext('2d'); let myChart = new Chart(this.ctxOrig, { type: 'bar', data: { labels: this.labelsOrig, datasets: [{ label: 'Most searched for origin', data: this.datasetOrig, backgroundColor: ["#006ab3", , , , , , , , "#444"], borderWidth: 1 }] }, options: {} }) } } <file_sep>export class DestCount { Destination: string; Counts: number; }<file_sep>import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common' import * as Chart from 'chart.js'; import { DataService } from '../service/data.service'; import { SearchByTime } from '../models/srchByTime'; import { SearchByHour } from '../models/srchByHour'; import { Count } from '../models/count'; import { FormControl } from '@angular/forms'; import { toInteger } from '@ng-bootstrap/ng-bootstrap/util/util'; @Component({ selector: 'app-searches-by-hour', templateUrl: './searches-by-hour.component.html', styleUrls: ['./searches-by-hour.component.css'] }) export class SearchesByHourComponent implements OnInit { startDate = "2000-01-01"; endDate = "2050-01-01"; public loadingSearchesByHour = false; canvasByHour: any; ctxByHour: any; public dataByHour: Array<Array<Count>>; public labelsHours: string[] = []; public datasetCounts = []; constructor(private ds: DataService) { } ngOnInit(): void { this.getByTimeData(); } getByTimeData() { this.loadingSearchesByHour = true; //receive data this.ds.getSearchesByHour().subscribe(data => { console.log(data); for (const [key, value] of Object.entries(data)) { console.log(key); var temp: number[] = []; value.map((item) => { if(key === "day_0") this.labelsHours.push(item.Hour); temp.push(parseInt(item.Counts)) }) this.datasetCounts.push(temp); } this.generateByTimeChart(); this.loadingSearchesByHour = false; }, error => { console.error(error); }); } generateByTimeChart() { var dataSets = []; var color = ["rgba(241,28,39,0.1)", //red "rgba(28,145,241,0.1)",//blue "rgba(231,221,28,0.1)", //yellow "rgba(38,231,28,0.1)", //green "rgba(28,231,221,0.1)", //cyan "rgba(231,228,211,1)", //pink "rgba(239,107,51,0.1)", //orange ]; var colorBorder = ["rgba(241,28,39,1)", //red "rgba(28,145,241,1)",//blue "rgba(231,221,28,1)", //yellow "rgba(38,231,28,1)", //green "rgba(28,231,221,1)", //cyan "rgba(231,228,211,1)", //pink "rgba(239,107,51,1)", //orange ]; this.datasetCounts.map((dataCount, index) => { dataSets.push({ label: `Day ${index+1}`, data: dataCount, borderColor: colorBorder[index], backgroundColor: color[index], borderWidth: 1 }) }) this.canvasByHour = document.getElementById('ByTimeChart'); this.ctxByHour = this.canvasByHour.getContext('2d'); let myChart = new Chart(this.ctxByHour, { type: 'radar', data: { labels: this.labelsHours, datasets: dataSets, }, options: {} }) } }<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AmountOfSearchesComponent } from './amount-of-searches.component'; describe('AmountOfSearchesComponent', () => { let component: AmountOfSearchesComponent; let fixture: ComponentFixture<AmountOfSearchesComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AmountOfSearchesComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AmountOfSearchesComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>export class Count { Hour: string Counts: number; }<file_sep>import { Count } from '../models/count'; export class SearchByHour { Day: string Counts: Count }<file_sep>import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common' import * as Chart from 'chart.js'; import { DataService } from '../service/data.service'; import { SearchByTime } from '../models/srchByTime'; import { SearchByHour } from '../models/srchByHour'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-amount-of-searches', templateUrl: './amount-of-searches.component.html', styleUrls: ['./amount-of-searches.component.css'] }) export class AmountOfSearchesComponent implements OnInit { public loadingSearchesByTime = false; canvasByTime: any; ctxByTime: any; public dataByTime: SearchByTime[]; public labelsByTime: string[] = []; public datasetByTime: number[] = []; constructor(private ds: DataService) { } ngOnInit(): void { this.getByTimeData(); } getByTimeData() { this.loadingSearchesByTime = true; //receive data this.ds.getSearchesByTime().subscribe(data => { this.dataByTime = data; console.log(data) this.dataByTime.forEach(data => this.labelsByTime.push(data.Date)); this.dataByTime.forEach(data => this.datasetByTime.push(data.Counts)); this.generateByTimeChart(); this.loadingSearchesByTime = false; }, error => { console.error(error); }); } generateByTimeChart() { this.canvasByTime = document.getElementById('ByTimeChart'); this.ctxByTime = this.canvasByTime.getContext('2d'); let myChart = new Chart(this.ctxByTime, { type: 'line', data: { labels: this.labelsByTime, datasets: [{ label: 'Number of searches per day', data: this.datasetByTime, borderColor: ["#006ab3"], backgroundColor: ["#dadbd9"], borderWidth: 1 }] }, options: {} }) } } <file_sep> export class Data { origin: string; destination: string; search_for_arrival: number; date_travel: string; time_travel: string; date_request: string time_request: string; }
dfe38b4664d673854a34a40a1f61941b768a36cf
[ "TypeScript" ]
16
TypeScript
oSoc20/destination-insight-fe
09772c4e8bb5c09f7c9a5f9cc3efa5afb0bd6992
09ed62a80c50bc7b41c711898b65d79a37419db1
refs/heads/master
<repo_name>dseskey/noggleboggle-aws<file_sep>/rest/src/handlers/registration.js const Bluebird = require("bluebird"); const mongoose = require('mongoose'); const validator = require('validator'); const UserModel = require('../model/User.js'); mongoose.Promise = Bluebird; const createErrorResponse = (statusCode, message) => ({ statusCode: statusCode || 501, headers: { 'Content-Type': 'text/plain' }, body: message || 'Incorrect id', }); const createSuccessResponse = (statusCode, message) => ({ statusCode: statusCode || 204, headers: { 'Content-Type': 'text/plain' }, body: message || 'No Content', }); const mongoString = process.env.MONGO_URL; const dbExecute = (db, fn) => db.then(fn).finally(() => db.close()); function dbConnectAndExecute(dbUrl, fn) { return dbExecute(mongoose.connect(dbUrl), fn); } module.exports.setupUser = (event, context, callback) => { const data = JSON.parse(event.body); let token = event.headers.Authorization; if (!token) { callback(null, createErrorResponse(401, 'Unauthorized')); } else { const keys_url = process.env.COGNITO_KEYS_URL; const axios = require('axios').default; axios.get(keys_url) .then(function (response) { let keyResponse = response.data.keys; var jwt = require('jsonwebtoken'); var jwkToPem = require('jwk-to-pem'); var pem = jwkToPem(keyResponse[0]); let decryptedToken = jwt.verify(token, pem, { algorithms: ['RS256'] }, function (err, decodedToken) { if (err) { callback(null, createErrorResponse(401, 'Unauthorized')); } return decodedToken; }); if (decryptedToken == undefined) { console.log("Token Not Present"); callback(null, createErrorResponse(401, 'Unauthorized')); } let cognitoUser = decryptedToken['cognito:username']; const user = new UserModel({ firstName: data.firstName, lastName: data.lastName, email: data.email, displayName: data.displayName, nickname: data.nickname, userId: cognitoUser }); if (user.validateSync()) { callback(null, createErrorResponse(400, 'The correct fields to create a user were not provided.')); return; } dbConnectAndExecute(mongoString, () => ( user .save() .then(() => { callback(null, { statusCode: 201, body: 'The user was successfully created.', } ) }).catch(err => { callback(null, createErrorResponse(err.statusCode, err.message)) }) )); }) .catch(function (error) { // handle error callback(null, createErrorResponse(500, "There was an error creating the user. Please contact your trivia admin.")) }) }; }<file_sep>/websocket/src/handlers/auth.js const jose = require("node-jose"); const fetch = require("node-fetch"); require('dotenv').config() const KEYS_URL = 'https://cognito-idp.'+process.env.AWS_REGION+'.amazonaws.com/'+process.env.USER_POOL_ID+'/.well-known/jwks.json'; const clientIds = process.env.CLIENT_IDS; const {informational, error, warning} = require('../logging/log'); const {Unauthorized, BadRequest, InternalServerError} = require('../httpResponseSturctures'); module.exports.authorization = async (event, context, callback) => { if(!event.queryStringParameters){ let badRequestResponse = BadRequest; badRequestResponse.message = "Missing token"; callback(null,badRequestResponse); } const { queryStringParameters: { NBU }, methodArn, } = event; let policy; try { policy = await authCognitoToken(NBU, methodArn, callback); informational("Authorization","Success","try_1","Successful authorization of " + policy.context.email); callback(null, policy); } catch (error) { callback(error); } }; const authCognitoToken = async (token, methodArn,callback) => { if (!token){ let badRequestResponse = badRequest; badRequestResponse.message = "Missing token"; throw new Error(badRequest); } const app_client_id = process.env.APP_CLIENT_ID; const sections = token.split("."); let authHeader = jose.util.base64url.decode(sections[0]); authHeader = JSON.parse(authHeader); const kid = authHeader.kid; const rawRes = await fetch(KEYS_URL); const response = await rawRes.json(); if (rawRes.ok) { const keys = response["keys"]; let key_index = -1; keys.some((key, index) => { if (kid == key.kid) { key_index = index; } }); const foundKey = keys.find((key) => { return kid === key.kid; }); if (!foundKey) { let internalServerErrorRequest = InternalServerError; internalServerErrorRequest.message = "Failed to process token with key."; error("auth","authCognitoToken","key_retrieval"," Public key not found in jwks.json for Cognito User Pool."); throw new Error(internalServerErrorRequest); } const jwkRes = await jose.JWK.asKey(foundKey); const verifyRes = await jose.JWS.createVerify(jwkRes).verify(token); const claims = JSON.parse(verifyRes.payload); const current_ts = Math.floor(new Date() / 1000); if (current_ts > claims.exp) { let unauthorizedResponse = Unauthorized; unauthorizedResponse.message = "Token has expired."; error("auth","authCognitoToken","token_active_check","The token has expired for token " + token); return ({success: false, response: unauthorizedResponse}); } //USE ENV PARAMETER if (!clientIds.includes(claims.aud)) { let incorrectClientResponse = Unauthorized; incorrectClientResponse.message = "Token was not issued for this application."; error("auth","authCognitoToken","token-correct-audience","The token " + token + " was not issued by a valid client ID. It was ussed by: " + claims.aud); throw new Error(incorrectClientResponse); } else { var policy = generatePolicy("me", "Allow", methodArn); policy.context = claims; return policy; } } let invaliidKeyURLError = InternalServerError; invaliidKeyURLError.message = "Failed to process token, could not validate with the identity store." throw new Error((invaliidKeyURLError)); }; const generatePolicy = function (principalId, effect, resource) { var authResponse = {}; authResponse.principalId = principalId; if (effect && resource) { var policyDocument = {}; policyDocument.Version = "2012-10-17"; policyDocument.Statement = []; var statementOne = {}; statementOne.Action = "execute-api:Invoke"; statementOne.Effect = effect; statementOne.Resource = resource; policyDocument.Statement[0] = statementOne; authResponse.policyDocument = policyDocument; } return authResponse; }; const generateAllow = function (principalId, resource) { return generatePolicy(principalId, "Allow", resource); }; const generateDeny = function (principalId, resource) { return generatePolicy(principalId, "Deny", resource); };<file_sep>/websocket/src/db.js const AWS = require('aws-sdk'); const ddb = new AWS.DynamoDB.DocumentClient(); const db = { Table: process.env.APPLICATION_TABLE, Primary: { Key: 'pk', Range: 'sk', User: 'gameId' }, Connection: { Primary: { Key: 'pk', Range: 'sk', User: 'gameId' }, Channels: { Index: 'reverse', Key: 'sk', Range: 'pk', User: 'gameId' }, Prefix: 'CONNECTION|', Entity: 'CONNECTION' }, Channel: { Primary: { Key: 'pk', Range: 'sk', User: 'gameId' }, Connections: { Key: 'pk', Range: 'sk', User: 'gameId' }, Messages: { Key: 'pk', Range: 'sk', User: 'gameId' }, Prefix: 'CHANNEL|', Entity: 'CHANNEL' }, User: { Primary: { Key: 'pk', Range: 'sk', User: 'gameId' }, Prefix: 'USER|', Entity: 'USER' }, Message: { Primary: { Key: 'pk', Range: 'sk' }, Prefix: 'MESSAGE|', Entity: 'MESSAGE' } } const channelRegex = new RegExp(`^${db.Channel.Entity}\|`); const messageRegex = new RegExp(`^${db.Message.Entity}\|`); const connectionRegex = new RegExp(`^${db.Connection.Entity}\|`); const userRegex = new RegExp(`^${db.User.Entity}\|`); function parseEntityId(target) { console.log('ENTITY ID A ', target) if (typeof target === 'object') { // use from raw event, only needed for connectionId at the moment target = target.requestContext.connectionId; } else { // strip prefix if set so we always get raw id target = target.replace(connectionRegex, '').replace(userRegex, '') .replace(channelRegex, '') .replace(messageRegex, ''); } return target.replace('|', ''); // why?! } async function fetchConnectionSubscriptions(connection) { const connectionId = parseEntityId(connection) console.log('items'); const results = await ddb.query({ TableName: db.Table, KeyConditionExpression: `${db.Connection.Primary.Key } = :connectionId`, ExpressionAttributeValues: { ":connectionId": `${db.Connection.Prefix}${connectionId}` } }).promise(); console.log(results.Items); return results.Items; } async function fetchChannelSubscriptions(channel) { const channelId = parseEntityId(channel); const results = await ddb.scan({ TableName: db.Table, FilterExpression: 'gameId = :gameId', ExpressionAttributeValues: { ':gameId': `${db.Channel.Prefix}${channelId}` }, }).promise(); return results.Items; } async function updateChannelId(event, gameId) { const body = JSON.parse(event.body); let x = await ddb.update({ TableName: db.Table, Key: { "pk": `${db.Connection.Prefix}${parseEntityId(event)}`, "sk": `${db.User.Prefix}${event.requestContext.authorizer['cognito:username']}` }, UpdateExpression: "set gameId = :gameId", ExpressionAttributeValues: { ":gameId": `${db.Channel.Prefix}${gameId}` } }).promise(); console.log(x); return x; } // [db.Channel.Connections.Key]: `${db.Connection.Prefix}${db.parseEntityId(event) // }`, // [db.Channel.Connections.Range]: `${db.User.Prefix}${userId}`, async function getChannelIdFromConnection(event) { const body = JSON.parse(event.body); const results = await ddb.get({ TableName: db.Table, Key: { "pk": `${db.Connection.Prefix}${parseEntityId(event)}`, "sk": `${db.User.Prefix}${event.requestContext.authorizer['cognito:username']}` }, }).promise(); return results.Item.gameId; } const client = { ...db, parseEntityId, fetchConnectionSubscriptions, fetchChannelSubscriptions, updateChannelId, getChannelIdFromConnection, Client: ddb } module.exports = client<file_sep>/websocket/src/handlers/gamePlay/joinGame.js "use strict"; const db = require("../../db"); const ws = require("../../websocket-client"); const sanitize = require("sanitize-html"); const mongoConnection = require('../../mongo/mongoConnection').connectToDatabase; const { queryDatabaseForGameCode } = require('../../mongo/mongoActions'); const { processGameState } = require('../../utilities'); const { addUserToGame } = require('../../mongo/mongoActions'); const { Success, BadRequest, Unauthorized, InternalServerError } = require('../../httpResponseSturctures'); const {error} = require('../../logging/log'); const wsClient = new ws.Client(); const success = { statusCode: 200 }; const fail500 = { statusCode: 500 }; async function join(event, context, callback) { const body = JSON.parse(event.body); const gameId = body.payload.gameId; const userId = event.requestContext.authorizer['cognito:username']; try { var mongoDb; try { mongoDb = await mongoConnection(); } catch (error) { error("joinGame", "join", "database_connection", JSON.stringify(error)); let dbConnectionError = InternalServerError; dbConnectionError.message = "Error contacting the game database"; let isMessageSent = wsClient.send(event, { event: "game-status-error", channelId: body.channelId, payload: dbConnectionError }); if (isMessageSent) { return success; } else { return fail500; } } const gameDetails = await queryDatabaseForGameCode(mongoDb, gameId); if (gameDetails.statusCode) { if (gameDetails.statusCode == 400) { error("joinGame", "join", "queryForGame", "Could not find a game with the provided game code" + gameId); let gameNotFoundError = BadRequest; gameNotFoundError.message = "Could not find a game with the provided game code."; let isMessageSent = await wsClient.send(event, { event: "game-status-error", channelId: body.channelId, payload: gameNotFoundError }); if (isMessageSent) { return success; } else { return fail500; } } else { error("joinGame", "join", "queryGameProcessError", JSON.stringify(error)); let dbProcessError = InternalServerError; dbProcessError.message = "There was an error trying to load the game. Please try again later."; let isMessageSent = await wsClient.send(event, { event: "game-status-error", channelId: body.channelId, payload: dbProcessError }); if (isMessageSent) { return success; } else { return fail500; } } } else { if (!(userId == gameDetails.owner)) { var gameStatusForUser; gameStatusForUser = await getGameStatusForJoining(mongoDb, gameDetails, userId); if (gameStatusForUser.status =='error') { let isMessageSent = await wsClient.send(event, { event: "game-status-error", channelId: gameId, data: gameStatusForUser.payload }); if(isMessageSent){ return success; }else{ return fail500; } } else { await db.updateChannelId(event,gameId); let playerResponseObject = Success; playerResponseObject.payload = gameStatusForUser; let isMessageSent = await wsClient.send(event, { event: "join-game-success", channelId: gameId, data: playerResponseObject }, userId); if(isMessageSent){ return success; }else{ return fail500; } } } else { /*--Game Master Joining--*/ await db.updateChannelId(event,gameId); let gameMasterResponseObject = Success; gameMasterResponseObject.payload = { message: "Game master has successfully joined the game.", currentQuestion: gameDetails.questionDetail.currentQuestion, isOpen: gameDetails.isOpen, isComplete: gameDetails.isComplete, isStarted: gameDetails.isStarted }; let isMessageSent = await wsClient.send(event, { event: "join-game-success", channelId: gameId, data: gameMasterResponseObject }, userId); if (isMessageSent) { return success; } else { return fail500; } } } } catch (err) { console.error(err); } } async function getGameStatusForJoining(mongoDb, gameDetails, userId) { /*--We process game state first so we don't add a user to a completed game and waste a DB I/O cycle--**/ let processedGameState = processGameState(gameDetails); /*--Check if the user is already part of the game, the message shown to the end user will be different depending on status--*/ let foundUser = gameDetails.players.filter(player => player.playerId == userId); if (foundUser < 1) { if (processedGameState.gameStatus.toLowerCase() == 'complete') { /*--The user was not found as a player in the game AND the game is complete, so do not add them to the game--*/ let willNotAddUserToGamePayload = BadRequest; willNotAddUserToGamePayload.message = "The user cannot be added to the game as the game has completed." return { "status": "error", "payload": willNotAddUserToGamePayload }; } else { /*--If the user was not found as a player in the game AND the game is either not started or in progress, add them to the game-- */ try { await addUserToGame(mongoDb, gameDetails, userId); return processedGameState; } catch (error) { error("joinGame", "getGameStatusForJoining", "adding user to game", JSON.stringify(error)); let addingUserToGameInternalServerError = InternalServerError; addingUserToGameInternalServerError.message = "Ther was an error adding the user to the game ." return { "status": "error", "payload": addingUserToGameInternalServerError }; } } } else { processedGameState = processGameState(gameDetails); return processedGameState; } } module.exports = { join }; <file_sep>/websocket/src/mongo/mongoActions.js const { informational, error, warning } = require('../logging/log'); var ObjectId = require('mongodb').ObjectId; convertToObjectId = (idString) => { try { return (new ObjectId(idString)); } catch (error) { console.log(error); } } function queryDatabaseForGameCode(mongoDb, gameId) { return mongoDb.collection('games').findOne({ _id: convertToObjectId(gameId) }) .then((gameDetail) => { if (gameDetail == null) { return { statusCode: 400, message: "Game not found." }; } return gameDetail; }) .catch(error => { console.log('=> an error occurred: ', err); return { statusCode: 500, message: "There was an error accessing the games collection for pulling game details." }; }); } function addUserToGame(mongoDb, gameDetails, userId) { gameDetails.players.push({ playerId: userId, totalPoints: 0, answers: [] }); return new Promise((resolve, reject) => { let gamesCollection = mongoDb.collection('games'); try { gamesCollection.updateOne({ _id: gameDetails._id }, { $set: { players: gameDetails.players } }); resolve({ status: "success", message: "The user was added to the game successfully." }); } catch (error) { error('mongoActions','addUserToGame',"updateOneError", JSON.stringify(error)); reject({ status: "error", message: 'There was an error accessing the games collection for updating game details.', error: error }); } }) }; function submitAnswerToDataBase(mongoDb, gameId, playerDetail) { return new Promise((resolve, reject) => { let gamesCollection = mongoDb.collection('games'); try { gamesCollection.updateOne({ _id: convertToObjectId(gameId), "players.playerId": playerDetail.playerId }, { $set: { "players.$": playerDetail } }); resolve({ status: "success", message: "Answer Submitted. Please Wait" }); } catch (error) { reject({ status: "error", message: 'There was an error updating the player\'s answers.', error: error }); } }) }; function incrementQuestion(mongoDb, gameId, userId) { return new Promise((resolve, reject) => { let gamesCollection = mongoDb.collection('games'); gamesCollection.findOneAndUpdate({ _id: convertToObjectId(gameId), owner: userId }, { $inc: { "questionDetail.currentQuestion": 1 } }).then((gameResult) => { if (gameResult.value.questionDetail.currentQuestion + 1 < gameResult.value.questionDetail.questions.length) { let nextQuestion = gameResult.value.questionDetail.questions[gameResult.value.questionDetail.currentQuestion + 1]; delete nextQuestion.answerId; resolve({ status: "CONTINUE", question: nextQuestion }); } else { resolve({ status: "END", message: "End of Game" }) } resolve({ status: "success", message: "Question Succesfully incremented. " }) }).catch(error => { reject({ status: "error", message: 'There was an error incrementing the question.', error: error }); }); }); } function getDetailsForScoreboard(mongoDb, gameId, userId) { console.log("=> In Details"); console.log(gameId); console.log(userId); return new Promise((resolve, reject) => { let gamesCollection = mongoDb.collection('games'); let usersCollection = mongoDb.collection('users'); gamesCollection.findOne({ _id: convertToObjectId(gameId) , owner: userId}).then((game) => { console.log("=>game"); console.log(game); let usersInGameWithScore = game.players.map((player) => { return { playerId: player.playerId, totalPoints: player.totalPoints } }) console.log(usersInGameWithScore); usersCollection.find({ userId: { $in: game.players.map(player => player.playerId) } }).project({ userId: 1, displayName: 1 }).toArray((err, users) => { if (err) { reject({ message: 'There was an error getting the users for scoreboard.', error: error }); } resolve({ usersFromDb: users, playersAndScores: usersInGameWithScore }) }); }).catch(error => { console.log('THIS ERROR'); console.log(error); reject({ status: "error", message: 'Could not get the game to generate the scoreboard.', error: error }); }); }) }; function openGame(mongoDb, gameId, userId) { return new Promise((resolve, reject) => { let gamesCollection = mongoDb.collection('games'); /*--Get collection and grab question list and current question, see if we have more questions--*/ try { gamesCollection.findOneAndUpdate({ _id: convertToObjectId(gameId), owner: userId }, { $set: { isOpen: true, isStarted: true } }).then((gameResult) => { let question = gameResult.value.questionDetail.questions[gameResult.value.questionDetail.currentQuestion]; delete question.answerId; resolve({ status: "CONTINUE", question: question }); }).catch((error) => { reject({ message: 'There was an error accessing the games collection for starting the game.', error: error }); }); } catch (error) { reject({ message: 'There was an error accessing the games collection for starting the game with the given ID', error: error }); } }); } module.exports = { queryDatabaseForGameCode, submitAnswerToDataBase, addUserToGame, incrementQuestion, getDetailsForScoreboard, openGame }<file_sep>/websocket/src/handlers/gamePlay/submitAnswer.js "use strict"; const db = require("../../db"); const ws = require("../../websocket-client"); const sanitize = require("sanitize-html"); const mongoConnection = require('../../mongo/mongoConnection').connectToDatabase; const getGameDetails = require('../../mongo/mongoActions').queryDatabaseForGameCode; const submitAnswerToDataBase = require('../../mongo/mongoActions').submitAnswerToDataBase; const getUserAndGameIdFromConnection = require('../../utilities').getUserAndGameIdFromConnection; const {informational, error, warning} = require('../../logging/log'); const getGameIdFromConnection = require('../../utilities').getGameIdFromConnection; const wsClient = new ws.Client(); const success = { statusCode: 200 }; const fail500 = { statusCode: 500 }; async function submit(event, context, callback) { const body = JSON.parse(event.body); const questionSubmission = body.payload; const userId = event.requestContext.authorizer['cognito:username']; // {"questionId":0, "answer":1, "type": "multipleChoice"} try { let gameAndUserIdStatus = await getUserAndGameIdFromConnection(event); console.log(gameAndUserIdStatus); if (!gameAndUserIdStatus.status == 'success') { let message = gameAndUserIdStatus.message; console.log('==> Error getting user ID and game ID ' + JSON.stringify(error)); return wsClient.send(event, { event: "game-status-error", channelId: body.channelId, message }); } else { let { userId, gameId } = gameAndUserIdStatus; const mongoDb = await mongoConnection(); const gameDetails = await getGameDetails(mongoDb, gameId); if (doesUserExistInGame(gameDetails, userId)) { //If the user doesn't exist in the game yet, reject //Build response and fail // reject({ message: 'User is not part of game, please join the game' }); } else { if (gameDetails.questionDetail.currentQuestion != questionSubmission.questionId) { //Build response and fail let message = "The question submitted is not the current active question. Please wait for the next question." return wsClient.send(event, { event: "game-status-error", channelId: body.channelId, message }); // reject('This is not the current question for this game.'); } else if (questionPreviouslyAnsweredByUser(gameDetails, userId, questionSubmission.questionId)) { //Build response and fail let message = "You have previously answered the question. Please wait for the next question." return wsClient.send(event, { event: "game-status-error", channelId: body.channelId, message }); // reject('This question has been previously answered by the user.'); } else { let playerUpdateObject = buildGameDetailForUserAnswerUpdate(gameDetails, userId, questionSubmission); let storageResult = await submitAnswerToDataBase(mongoDb, gameId, playerUpdateObject); let message = storageResult.message; return wsClient.send(event, { event: "game-status-success", channelId: body.channelId, message }); } } } } catch (err) { console.error(err); let message = "There was an error submitting your answer, please try again. If this issue continues, please contact your game master." return wsClient.send(event, { event: "game-status-error", channelId: body.channelId, message }); } } function doesUserExistInGame(gameDetails, userId) { let foundUser = gameDetails.players.filter(player => player.playerId == userId); return foundUser > 1; } function questionPreviouslyAnsweredByUser(gameDetails, userId, submittedId) { let playerDetails = gameDetails.players.filter((playerDetail) => playerDetail.playerId == userId)[0]; if (playerDetails.answers.filter((answer) => answer.questionId == submittedId).length > 0) { return true; } else { return false; } } function buildGameDetailForUserAnswerUpdate(gameDetails, userId, submittedAnswer) { //Check if answer is right and build accordingly. let gameDetailQuestion = gameDetails.questionDetail.questions.find((question) => question.questionId == submittedAnswer.questionId); let playerDetails = gameDetails.players.find((player) => player.playerId === userId); let userAnswer = {}; userAnswer.questionId = submittedAnswer.questionId; userAnswer.answer = submittedAnswer.answer; if (gameDetailQuestion.type === 'multipleChoice') { if (gameDetailQuestion.answerId == submittedAnswer.answer) { userAnswer.pointsAwarded = gameDetailQuestion.pointsAvailable; playerDetails.answers.push(userAnswer); playerDetails.totalPoints = playerDetails.totalPoints + gameDetailQuestion.pointsAvailable; } else { userAnswer.pointsAwarded = 0; playerDetails.answers.push(userAnswer); playerDetails.totalPoints = playerDetails.totalPoints + 0; } }else if (gameDetailQuestion.type === 'openEnded') { let correctAnswer = gameDetailQuestion.answerOptions.filter((option) => { return option.toLowerCase() == submittedAnswer.answer.toLowerCase(); }) console.log(correctAnswer) if (correctAnswer.length > 0) { userAnswer.pointsAwarded = gameDetailQuestion.pointsAvailable; playerDetails.answers.push(userAnswer); playerDetails.totalPoints = playerDetails.totalPoints + gameDetailQuestion.pointsAvailable; } else { userAnswer.pointsAwarded = 0; playerDetails.answers.push(userAnswer); playerDetails.totalPoints = playerDetails.totalPoints + 0; } } else { } return playerDetails; } module.exports = { submit }; <file_sep>/websocket/src/handlers/showScoreboard.js const db = require("../db"); const ws = require("../websocket-client"); const sanitize = require("sanitize-html"); "use strict"; const mongoConnection = require('../mongo/mongoConnection').connectToDatabase; const getDetailsForScoreboard = require('../mongo/mongoActions').getDetailsForScoreboard; const getUserAndGameIdFromConnection = require('../utilities').getUserAndGameIdFromConnection; let cachedDb = null; const wsClient = new ws.Client(); const success = { statusCode: 200 }; const fail500 = { statusCode: 500 }; async function show(event, context, callback) { const body = JSON.parse(event.body); try { let gameAndUserIdStatus = await getUserAndGameIdFromConnection(event); if (!gameAndUserIdStatus.status == 'success') { let message = gameAndUserIdStatus.message; console.log('==> Error getting user ID and game ID ' + JSON.stringify(error)); return wsClient.send(event, { event: "game-status-error", channelId: body.channelId, message }); } else { let { userId, gameId } = gameAndUserIdStatus; const mongoDb = await mongoConnection(); const usersAndPlayersScores = await getDetailsForScoreboard(mongoDb, gameId, userId); let usersFromDb = usersAndPlayersScores.usersFromDb; let playersAndScores = usersAndPlayersScores.playersAndScores.sort((a, b) => (a.totalPoints > b.totalPoints) ? -1 : ((b.totalPoints > a.totalPoints) ? 1 : 0)); let scoreboard = playersAndScores.map((player) => { let user = usersFromDb.find((user) => user.userId == player.playerId); return ({ playerId: player.playerId, totalScore: player.totalPoints, displayName: user.displayName }) }); let payload = scoreboard; // sendMessage(event, "game-status-success", gameId, payload); const subscribers = await db.fetchChannelSubscriptions(gameId); const results = subscribers.map(async subscriber => { const subscriberId = db.parseEntityId( subscriber[db.Channel.Connections.Range] ); return wsClient.send(subscriberId, { event: "game-status-success", channelId: gameId, payload }); }); } } catch (err) { console.error(err); let message = "There was an error generating the scoreboard." return wsClient.send(event, { event: "game-status-error", channelId: body.channelId, message }); } } module.exports = { show }; <file_sep>/websocket/src/handlers/gameManagement/nextQuestion.js "use strict"; const db = require("../../db"); const ws = require("../../websocket-client"); const sanitize = require("sanitize-html"); const mongoConnection = require('../../mongo/mongoConnection').connectToDatabase; const incrementQuestion = require('../../mongo/mongoActions').incrementQuestion; const { getGameIdFromConnection } = require("../../utilities"); let cachedDb = null; const wsClient = new ws.Client(); const success = { statusCode: 200 }; const fail500 = { statusCode: 500 }; async function next(event, context, callback) { /*-- -Get connection from event.body. -Use connection ID or username to get channel (use connection ID if a user can only play one game at a time) -Use channel ID (which is game ID to get game status and increment question) - --*/ const body = JSON.parse(event.body); let gameId = await getGameIdFromConnection(event); let userId = event.requestContext.authorizer['cognito:username']; console.log("GAME ID:") console.log(gameId); if (!gameId || gameId === '\'\'') { let message = "You have not joined a game, please join a game and try again!." return wsClient.send(event, { event: "game-status-error", channelId: gameId, message }); } else { try { const mongoDb = await mongoConnection(); const incrementStatus = await incrementQuestion(mongoDb, gameId, userId); let payload; if (incrementStatus.status == "CONTINUE") { payload = { "status": incrementStatus.status, "question": incrementStatus.question } } else { payload = { "status": incrementStatus.status, "message": incrementStatus.message } } // sendMessage(event, "game-status-success", gameId, payload); const subscribers = await db.fetchChannelSubscriptions(gameId); const results = subscribers.map(async subscriber => { const subscriberId = subscriber.pk.replace(db.Connection.Prefix, ''); // const subscriberId = db.parseEntityId( // subscriber[db.Channel.Connections.Range] // ); return wsClient.send(subscriberId, { event: "game-status-success", channelId: gameId, payload }); }); } catch (err) { console.error(err); let message = "There was an error incrementing the question, please try again." return wsClient.send(event, { event: "game-status-error", channelId: gameId, message }); } } // if (!gameAndUserIdStatus.status == 'success') { // let message = gameAndUserIdStatus.message; // console.log('==> Error getting user ID and game ID ' + JSON.stringify(error)); // return wsClient.send(event, { // event: "game-status-error", // channelId: body.channelId, // message // }); // } else { // let { userId, gameId } = gameAndUserIdStatus; // try { // const mongoDb = await mongoConnection(); // const incrementStatus = await incrementQuestion(mongoDb, gameId, userId); // let payload; // if (incrementStatus.status == "CONTINUE") { // payload = { "status": incrementStatus.status, "question": incrementStatus.question } // } else { // payload = { "status": incrementStatus.status, "message": incrementStatus.message } // } // // sendMessage(event, "game-status-success", gameId, payload); // const subscribers = await db.fetchChannelSubscriptions(gameId); // console.log("=> SUBSCRIBERS"); // console.log(subscribers); // const results = subscribers.map(async subscriber => { // const subscriberId = db.parseEntityId( // subscriber[db.Channel.Connections.Range] // ); // return wsClient.send(subscriberId, { // event: "game-status-success", // channelId: gameId, // payload // }); // }); // } catch (err) { // console.error(err); // let message = "There was an error incrementing the question, please try again." // return wsClient.send(event, { // event: "game-status-error", // channelId: gameId, // message // }); // } // } } async function sendMessage(event, eventResponseType, gameId, payload) { // save message for future history // saving with timestamp allows sorting // maybe do ttl? await Promise.all(results); return success; } module.exports = { next }; <file_sep>/websocket/src/mongo/mongoConnection.js const MongoClient = require('mongodb').MongoClient; require('dotenv').config() const {informational, error, warning} = require('../logging/log'); let cachedDb = null; function connectToDatabase() { return new Promise((resolve, reject) => { if (cachedDb) { informational('mongo/mongoConnection','connectToDatabase','promise','Using Cached MongoDB Connection.') resolve(cachedDb); } MongoClient.connect(process.env.MONGODB_URI, function (err, mongoDb) { if (err) { error('mongo/mongoConnection','connectToDatabase', 'MongoClient.Connect', err); reject(err); } else { // let connection = mongoDb.db('noggle-boggle-trivia-dev'); informational('mongo/mongoConnection','connectToDatabase','promise','Using NON-Cached MongoDB Connection.') cachedDb = mongoDb.db(process.env.MONGODB_TABLE_NAME);; resolve(cachedDb); } }); }); // return MongoClient.connect(uri) // .then(db => { // console.log('=> connectingNonCached to database'); // cachedDb = db; // return cachedDb; // }); } module.exports = { connectToDatabase }; <file_sep>/websocket/src/handlers/broadcast.js const db = require("../db"); const ws = require("../websocket-client"); const {BadRequest, Unauthorized, InternalServerError} = require('../httpResponseSturctures'); const wsClient = new ws.Client(); const success = { statusCode: 200 }; const invalidTokenResponse = { statusCode: 401 }; const internalServerError = { statusCode: 500 }; const badRequest = { statusCode: 400 }; // oh my... this got out of hand refactor for sanity async function broadcaster(event, context) { // info from table stream, we'll learn about connections // disconnections, messages, etc // get all connections for channel of interest // broadcast the news const results = event.Records.map(async record => { let connectionId = null; //Used if and only if this is a first connection attempt. switch (record.dynamodb.Keys[db.Primary.Key].S.split("|")[0]) { // Connection entities case db.Channel.Entity: break; // Channel entities (most stuff) case db.Connection.Entity: // figure out what to do based on full entity model console.log('hello1') // get secondary ENTITY| type by splitting on | and looking at first part switch (record.dynamodb.Keys[db.Primary.Key].S.split("|")[0]) { // if we are a CONNECTION case db.Connection.Entity: { let eventType = "sub"; connectionId = event.Records[0].dynamodb.Keys.pk.S.split("|")[1]; if (record.eventName === "REMOVE") { eventType = "unsub"; } else if (record.eventName === "UPDATE") { // currently not possible, and not handled break; } // A connection event on the channel // let all users know a connection was created or dropped const channelId = db.parseEntityId( record.dynamodb.Keys[db.Primary.Key].S ); const subscribers = await db.fetchChannelSubscriptions(channelId); console.log("SUBSCRIBERS"); console.log(subscribers); // const results = subscribers.map(async subscriber => { // const subscriberId = db.parseEntityId( // subscriber[db.Channel.Connections.Range] // ); // console.log("CONN ID"); // console.log(connectionId); // return wsClient.send( // (connectionId != null ? connectionId : subscriberId), // really backwards way of getting connection id // { // event: `subscriber_${eventType}`, // channelId, // // sender of message "from id" // subscriberId: db.parseEntityId( // record.dynamodb.Keys[db.Primary.Key].S // ) // } // ); // }); console.log("CONN ID"); console.log(connectionId); return wsClient.send( connectionId, { event: `subscriber_${eventType}`, channelId, // sender of message "from id" subscriberId: db.parseEntityId( record.dynamodb.Keys[db.Primary.Key].S ) } ); // await Promise.all(results); console.log('YAYA') break; } // If we are a MESSAGE case db.Message.Entity: { if (record.eventName !== "INSERT") { return success; } // We could do interesting things like see if this was a bot // or other system directly adding messages to the dynamodb table // then send them out, otherwise assume it was already blasted out on the sockets // and no need to send it again! break; } default: console.log('hello2') break; } break; default: console.log('hello3') break; } }); await Promise.all(results); return success; } // module.exports.loadHistory = async (event, context) => { // // only allow firs module.exports = { broadcaster }; <file_sep>/websocket/src/handler.js const db = require("./db"); const ws = require("./websocket-client"); const sanitize = require("sanitize-html"); require('dotenv').config(); const { BadRequest, Unauthorized, InternalServerError } = require('./httpResponseSturctures'); var randomstring = require("randomstring"); const wsClient = new ws.Client(); const success = { statusCode: 200 }; const invalidTokenResponse = { statusCode: 401 }; const internalServerError = { statusCode: 500 }; const badRequest = { statusCode: 400 }; async function createConnection(event, context) { /*--The authorizer has already obtained the Cognito info, use it to create a connection WITHOUT a channel (a channel is a game which we do not take at connect)--*/ let userId = event.requestContext.authorizer['cognito:username']; // const channelId = JSON.parse(event.body).channelId; await db.Client.put({ TableName: db.Table, Item: { [db.Channel.Connections.Key]: `${db.Connection.Prefix}${db.parseEntityId(event) }`, [db.Channel.Connections.Range]: `${db.User.Prefix}${userId}`, [db.Channel.Connections.User]: `${db.Channel.Prefix}''` } }).promise(); // Instead of broadcasting here we listen to the dynamodb stream // just a fun example of flexible usage // you could imagine bots or other sub systems broadcasting via a write the db // and then streams does the rest return success; // let gameCode = queryStringParameters.GAME; // if (gameCode) { // // let gameCode = event.headers['X-GID']; // try { // var mongoDb; // try { // mongoDb = await mongoConnection(); // } catch (error) { // let message = "Error connecting to the game database." // console.log('==> Error connecting to MongoDb: ' + JSON.stringify(error)); // return internalServerError; // } // const gameDetails = await queryDatabaseForGameCode(mongoDb, gameCode); // if (gameDetails.statusCode) { // if (gameDetails.statusCode == 400) { // let message = "Could not find a game with the provided game code."; // return invalidTokenResponse; // } else { // let message = "There was an error trying to load the game. Please try again later."; // return internalServerError; // } // } // else { // //Add user to game, then subscribe the user to the channel // let userId = event.requestContext.authorizer['cognito:username']; // let addedUserToGame = await addUserToGame(mongoDb, gameDetails, userId); // //Subscribe to the channel // if (addedUserToGame) { // await subscribeToGameChannel( // { // ...event, // body: JSON.stringify({ // action: "subscribe", // channelId: randomstring.generate(24) // }) // }, // context, // userId // ); // } else { // return internalServerError; // } // } // } catch (err) { // console.error(err); // } // } else { // return badRequest; // } // return success; } async function destroyConnection(event, context) { const item = await db.Client.delete({ TableName: db.Table, Key: { [db.Channel.Connections.Key]: `${db.Connection.Prefix}${db.parseEntityId(event) }`, [db.Channel.Connections.Range]: `${db.User.Prefix}${event.requestContext.authorizer['cognito:username']}` } }).promise(); return success; } async function connectionManager(event, context) { // we do this so first connect EVER sets up some needed config state in db // this goes away after CloudFormation support is added for web sockets await wsClient._setupClient(event); /*--End Verify Cognito Token--*/ if (event.requestContext.eventType === "CONNECT") { await createConnection(event, context); return success; } else if (event.requestContext.eventType === "DISCONNECT") { // unsub all channels connection was in await destroyConnection(event, context); return success; } } async function defaultMessage(event, context) { let invalidActionTypeReponse = BadRequest; invalidActionTypeReponse.message = "This action is not supported." await wsClient.send(event, { event: "error", data: invalidActionTypeReponse }); return success; } async function sendMessage(event, context) { // save message for future history // saving with timestamp allows sorting // maybe do ttl? const body = JSON.parse(event.body); const messageId = `${db.Message.Prefix}${Date.now()}`; const name = body.name .replace(/[^a-z0-9\s-]/gi, "") .trim() .replace(/\+s/g, "-"); const content = sanitize(body.content, { allowedTags: ["ul", "ol", "b", "i", "em", "strike", "pre", "strong", "li"], allowedAttributes: {} }); // save message in database for later const item = await db.Client.put({ TableName: db.Table, Item: { [db.Message.Primary.Key]: `${db.Channel.Prefix}${body.channelId}`, [db.Message.Primary.Range]: messageId, ConnectionId: `${event.requestContext.connectionId}`, Name: name, Content: content, mongo: mongoCollection } }).promise(); const subscribers = await db.fetchChannelSubscriptions(body.channelId); const results = subscribers.map(async subscriber => { const subscriberId = db.parseEntityId( subscriber[db.Channel.Connections.Range] ); return wsClient.send(subscriberId, { event: "channel_message", channelId: body.channelId, name, content }); }); await Promise.all(results); t } async function channelManager(event, context) { const action = JSON.parse(event.body).action; switch (action) { case "subscribeChannel": await subscribeChannel(event, context); break; case "unsubscribeChannel": await unsubscribeChannel(event, context); break; default: break; } return success; } async function subscribeToGameChannel(event, context, userId) { const channelId = JSON.parse(event.body).channelId; await db.Client.put({ TableName: db.Table, Item: { [db.Channel.Connections.Key]: `${db.Connection.Prefix}${db.parseEntityId(event) }`, [db.Channel.Connections.Range]: `${db.User.Prefix}${userId}`, [db.Channel.Connections.User]: `${db.Channel.Prefix}${channelId}` } }).promise(); // Instead of broadcasting here we listen to the dynamodb stream // just a fun example of flexible usage // you could imagine bots or other sub systems broadcasting via a write the db // and then streams does the rest return success; } async function subscribeChannel(event, context) { const channelId = JSON.parse(event.body).channelId; await db.Client.put({ TableName: db.Table, Item: { [db.Channel.Connections.Key]: `${db.Channel.Prefix}${channelId}`, [db.Channel.Connections.Range]: `${db.Connection.Prefix}${db.parseEntityId(event) }` } }).promise(); // Instead of broadcasting here we listen to the dynamodb stream // just a fun example of flexible usage // you could imagine bots or other sub systems broadcasting via a write the db // and then streams does the rest return success; } async function unsubscribeChannel(event, context) { const channelId = JSON.parse(event.body).channelId; const item = await db.Client.delete({ TableName: db.Table, Key: { [db.Channel.Connections.Key]: `${db.Channel.Prefix}${channelId}`, [db.Channel.Connections.Range]: `${db.Connection.Prefix}${db.parseEntityId(event) }` } }).promise(); return success; } var ObjectId = require('mongodb').ObjectId; convertToObjectId = (idString) => { try { return (new ObjectId(idString)); } catch (error) { console.log(error); } } function queryDatabaseForGameCode(mongoDb, gameId) { return mongoDb.collection('games').findOne({ _id: convertToObjectId(gameId) }) .then((gameDetail) => { if (gameDetail == null) { return { statusCode: 400, message: "Game not found." }; } return gameDetail; }) .catch(error => { console.log('=> an error occurred: ', err); return { statusCode: 500, message: "There was an error accessing the games collection for pulling game details." }; }); } module.exports = { connectionManager, defaultMessage, sendMessage, // broadcast, subscribeChannel, unsubscribeChannel, channelManager, };
03f17093258c2b7c7cfb2572878b88b5d51735d0
[ "JavaScript" ]
11
JavaScript
dseskey/noggleboggle-aws
d1885b2e74915c112616c81ceb991b399cf1f18a
200461844188b194ea0687b3d8b1ff31030efb70
refs/heads/master
<file_sep>import numpy as np import kmeans import common import naive_em import em X = np.loadtxt("toy_data.txt") # TODO: Your code here for K in [1,2,3,4]: costs = [] for seed in range(10000): mixture, post = common.init(X, K, seed= seed) mixture, post, cost = kmeans.run(X, mixture, post) costs.append(cost) print(np.min(costs))<file_sep>import numpy as np import em import common import naive_em import pandas as pd #X = np.loadtxt("test_incomplete.txt") #X_gold = np.loadtxt("test_complete.txt") #K = 4 #n, d = X.shape #seed = 0 # Question 4 # X = np.loadtxt('toy_data.txt') # for K in range(1,5): # logs = [] # for seed in range(5): # mixture, post = common.init(X,K, seed) # mu_s, var_s, p_s = mixture.mu, mixture.var, mixture.p # mixture, post, LL = naive_em.run(X , mixture, post) # common.plot(X, mixture, post, f"k:{K}, seed: {seed}") # logs.append(LL) # print('############## K = ',K) # print('Log likelihood: ', np.max(logs)) # Question 5 X = np.loadtxt('toy_data.txt') results = [] for K in range(1,5): for seed in range(5): mixture, post = common.init(X,K, seed) mu_s, var_s, p_s = mixture.mu, mixture.var, mixture.p mixture, post, LL = naive_em.run(X , mixture, post) BIC = common.bic(X, mixture, LL) results.append([K ,seed, BIC]) output = pd.DataFrame(results, columns=['K', 'seed', 'BIC']) print(output) max_bic_row = output['BIC'].idxmax() print('Answer') print(output.iloc[[max_bic_row]]) <file_sep># <a href="https://www.edx.org/course/machine-learning-with-python-from-linear-models-to-deep-learning">MITx Machine Learning </a> An in-depth exploration to the field of machine learning, from linear models to deep learning and reinforcement learning, through hands-on Python projects. ## Projects: * Automatic Review Analyzer * Digit Recognition with Neural Networks * The Netflix Problem * Text Based Game ## Lectures: * Introduction * Linear classifiers, separability, perceptron algorithm * Maximum margin hyperplane, loss, regularization * Stochastic gradient descent, over-fitting, generalization * Linear regression * Recommender problems, collaborative filtering * Non-linear classification, kernels * Learning features, Neural networks * Deep learning, back propagation * Recurrent neural networks * Recurrent neural networks * Generalization, complexity, VC-dimension * Unsupervised learning: clustering * Generative models, mixtures * Mixtures and the EM algorithm * Learning to control: Reinforcement learning * Reinforcement learning continued * Applications: Natural Language Processing <file_sep>"""Mixture model using EM""" from typing import Tuple import numpy as np from common import GaussianMixture def estep(X: np.ndarray, mixture: GaussianMixture) -> Tuple[np.ndarray, float]: """E-step: Softly assigns each datapoint to a gaussian component Args: X: (n, d) array holding the data mixture: the current gaussian mixture Returns: np.ndarray: (n, K) array holding the soft counts for all components for all examples float: log-likelihood of the assignment """ from scipy.stats import multivariate_normal mu_s, var_s, p_s = mixture.mu, mixture.var, mixture.p K,d = mu_s.shape n = X.shape[0] E = np.zeros((n,K)) for i in range(n): x = X[i] for j,mu in enumerate(mu_s): var, p = var_s[j], p_s[j] norm = multivariate_normal.pdf(x, mean=mu, cov=var) E[i,j] = p*norm LL = np.log(E.sum(axis=1)).sum() E = E/np.sum(E, axis=1).reshape((-1,1)) return E, LL def mstep(X: np.ndarray, post: np.ndarray) -> GaussianMixture: """M-step: Updates the gaussian mixture by maximizing the log-likelihood of the weighted dataset Args: X: (n, d) array holding the data post: (n, K) array holding the soft counts for all components for all examples Returns: GaussianMixture: the new gaussian mixture """ d = X.shape[1] n,K = post.shape mu = np.zeros((K,d)) var = np.zeros(K,) p = post.sum(axis=0)/n for j in range(K): for i in range(n): x = X[i] mu[j,:] += x*post[i,j] mu[j,:] /= (n*p[j]) for j in range(K): sigma = np.zeros((d,d)) for i in range(n): x = X[i] sigma += post[i,j]*np.dot(x-mu[j,:], x-mu[j,:]) var[j] = sigma[0][0]/d var[j] /= (n*p[j]) return GaussianMixture(mu, var, p) def run(X: np.ndarray, mixture: GaussianMixture, post: np.ndarray) -> Tuple[GaussianMixture, np.ndarray, float]: """Runs the mixture model Args: X: (n, d) array holding the data post: (n, K) array holding the soft counts for all components for all examples Returns: GaussianMixture: the new gaussian mixture np.ndarray: (n, K) array holding the soft counts for all components for all examples float: log-likelihood of the current assignment """ LL_old = None while True: post, LL = estep(X, mixture) mixture = mstep(X, post) if LL_old is None: LL_old = LL continue if (LL - LL_old) <= (10**-6)* np.abs(LL): break else: LL_old = LL return mixture, post, LL
4fb8ab69e173c109889bd67b12c58caa836d3f59
[ "Markdown", "Python" ]
4
Python
mohsinali5152/MITx_machine_learning
d83e8583c91bcef1edc8222caedb63d62d4da36d
4254a522a3021cde6020f98abcc4dadbc7f689be
refs/heads/master
<repo_name>elitenomad/mobilApp<file_sep>/platforms/ios/www/js/chats/index.js /** * Created by pranavaswaroop on 28/07/2014. */ angular.module('chatApp.tabs.chats',[]);
bfd05d6de318db9e20929a313a9af029ad0f7d15
[ "JavaScript" ]
1
JavaScript
elitenomad/mobilApp
8946fd92bcd181ec1a70910b91c67f53491eb218
ae62cbca34da85e6c6e20d6a987aae101ca6d3a7
refs/heads/master
<repo_name>lovePelmeshki/URIS_KP<file_sep>/Model/Place.cs using System.Collections.Generic; namespace URIS_KP { /// <summary> /// Место (точка), где установлен датчик на локации /// </summary> public class Place { public int Id { get; set; } public string Name { get; set; } /// <summary> /// На какой локации /// </summary> public int LocationId { get; set; } public virtual Location Location { get; set; } /// <summary> /// Список датчиков на точке /// </summary> public ICollection<Detector> Detectors { get; set; } } } <file_sep>/Model/Employee.cs using System.Collections.Generic; namespace URIS_KP { public class Employee { public int Id{ get; set; } public string SecondName{ get; set; } public string Name{ get; set; } /// <summary> /// Должность сотрудника /// </summary> public virtual int PositionId { get; set; } public virtual Position Position { get; set; } /// <summary> /// Список заявок сотрудника /// </summary> public virtual ICollection<Request> Requests { get; set; } /// <summary> /// Список обслуживаний /// </summary> public virtual ICollection<Service> Services { get; set; } } } <file_sep>/Model/Request.cs using System; namespace URIS_KP { /// <summary> /// Заявка /// </summary> public class Request { public int Id { get; set; } /// <summary> /// Кто открыл заявку /// </summary> public int EmployeeIdWhosOpen { get; set; } public virtual Employee EmployeeWhosOpen { get; set; } // навигационное свойсвтво? https://metanit.com/sharp/helpdeskmvc/2.1.php /// <summary> /// Кто закрыл заявку /// </summary> public int? EmployeeIdWhosClosed { get; set; } public virtual Employee EmployeeWhosClosed { get; set; } /// <summary> /// Дата открытия заявки /// </summary> public DateTime CreatedDate { get; set; } /// <summary> /// Дата закрытия заявкт /// </summary> public DateTime? CloseDate { get; set; } public string Status { get; set; } public string Discription { get; set; } /// <summary> /// Неисправный датчик /// </summary> public int? DetectorId { get; set; } public virtual Detector Detector { get; set; } // навигационное свойство? } } <file_sep>/Model/District.cs  using System.Collections.Generic; namespace URIS_KP { public class District { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<Location> Locations { get; set; } } } <file_sep>/Model/Service.cs using System; namespace URIS_KP { /// <summary> /// Плановое обслуживание датчиков /// </summary> public class Service { public int Id { get; set; } /// <summary> /// Тип обслуживания (Тех.процесс, Замена) /// </summary> public string Type { get; set; } // устанавливается только через ComboBox /// <summary> /// Дата и время обслуживания /// </summary> public DateTime ServiceDate { get; set; } public DateTime NextServiceDate { get; set; } /// <summary> /// Датчик, который обслуживался /// </summary> public int DetectorId { get; set; } public virtual Detector Detector { get; set; } /// <summary> /// Сотрудник, производивший обслуживание /// </summary> public int EmployeeId { get; set; } public virtual Employee Employee { get; set; } public string GetServiceDate() { return ServiceDate.ToString(); } public string GetNextServiceDate() { return NextServiceDate.ToShortDateString(); } public void ChangeDetectors(Detector oldDetector, Detector newDetector) { int place = oldDetector.PlaceId; oldDetector.PlaceId = 9999; // go to Sklad oldDetector.Status = "Ожидает отправки в ремонт"; newDetector.PlaceId = place; // go to place newDetector.Status = "В работе"; } } } <file_sep>/Model/Position.cs using System.Collections.Generic; namespace URIS_KP { /// <summary> /// Должность /// </summary> public class Position { public int Id { get; set; } public string Name{ get; set; } /// <summary> /// Список сотрудников на определенной должности /// </summary> public virtual ICollection<Employee> Employees { get; set; } public override string ToString() { return Name; } } } <file_sep>/Model/Location.cs  using System.Collections.Generic; namespace URIS_KP { /// <summary> /// Локация охраняемого объекта (так сказать адрес объекта, но не адрес) /// </summary> public class Location { public int Id{ get; set; } public string Name { get; set; } /// <summary> /// Район, в котором находится объект /// </summary> public int DistrictId { get; set; } public virtual District District { get; set; } /// <summary> /// Список датчиков, установленных на текущей локации /// </summary> public virtual ICollection<Place> Places { get; set; } } } <file_sep>/Model/Detector.cs using System; using System.Collections.Generic; namespace URIS_KP { public class Detector { public int Id { get; set; } /// <summary> /// Дата проверки датчика в ремонтных мастерских /// </summary> public DateTime CheckDate { get; set; } public DateTime NextCheckDate { get => CheckDate.AddMonths(6); } /// <summary> /// Дата установки датчика /// </summary> public DateTime InstallationDate { get; set; } /// <summary> /// Дата демонтажа датчика /// </summary> public DateTime? DismantlingDate { get => InstallationDate.AddYears(5); } /// <summary> /// Статус датчика /// </summary> public string Status { get; set; } // устанавливается только через ComboBox (В работе, в ремонте, на складе, ожидает отправки в ремонт) /// <summary> /// Где установлен датчик /// </summary> public int PlaceId { get; set; } public Place Place { get; set; } /// <summary> /// когда обслуживался датчик /// </summary> public virtual ICollection<Service> Services { get; set; } /// <summary> /// Заявки по датчику /// </summary> public virtual ICollection<Request> Requests { set; get; } public string GetCheckDate() { return CheckDate.ToShortDateString(); } public string GetNextCheckDate() { return NextCheckDate.ToShortDateString(); } /// <summary> /// Отправить в мастерские /// </summary> /// <param name="detector"></param> public void SendToRepair() { PlaceId = 9998; // go to masterskie Status = "В мастерских"; } } } <file_sep>/DataBaseContext.cs using System.Data.Entity; namespace URIS_KP { /// <summary> /// Контекст базы данных /// </summary> class DataBaseContext : DbContext { public DataBaseContext() : base("DBConnection") { } public DbSet<Detector> Detectors { get; set; } public DbSet<District> Districts { get; set; } public DbSet<Employee> Employees { get; set; } public DbSet<Location> Locations { get; set; } public DbSet<Place> Places { get; set; } public DbSet<Position> Positions { get; set; } public DbSet<Request> Requests { get; set; } public DbSet<Service> Services { get; set; } } }
862c8c2a6529b1efdc08fd10ddff089d36a7c7e4
[ "C#" ]
9
C#
lovePelmeshki/URIS_KP
1ca5018b2e55eb64ac093a8f905adaa11516c5ff
886d34efc44bb8642ec0e0852bb41a1776bbed25
refs/heads/master
<file_sep># Walking the BSR Parser Forest The parser builds a BSR set in the package `<module>/goutil/bsr` generated by gogll. Package `bsr` exports two functions to walk the parse forest: 1. `func GetRoot() (roots []Slot)` returns the roots of all complete parse trees recognised by the parser. If the grammar is unambiguous there will be only one root. 1. `func (s Slot) GetNTChild(nt string) Slot` returns the BSR `Slot` with matching nonterminal `nt`, left- and right extent. A parse tree can be walked as follows: 1. Use `GetRoot()` to get the root of the parse tree. 1. Call `GetNTChild(nt)` to get get the BSR of symbol `nt`.<file_sep>// Copyright 2019 <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. /* Package da disambiguates the BSR set. */ package da import ( "github.com/goccmack/gogll/goutil/bsr" "github.com/goccmack/gogll/parser/symbols" "strings" ) func Go() { // fmt.Println("da.Go") daReservedWords() removeNTsWithoutChildren() } func daReservedWords() { for _, b := range bsr.GetAll() { if reservedWord(b.GetString()) && b.Label.Head() == "NonTerminal" { // fmt.Println("daReservedWords", b, b.GetString()) b.Ignore() } } } // func removeNTsWithoutChildren() { // reps := 0 // for again := true; again; { // again = false // for _, b := range bsr.GetAll() { // for i, s := range b.Label.Symbols() { // reps++ // if symbols.IsNonTerminal(s) && len(b.GetNTChildrenI(i)) == 0 { // // fmt.Printf("remove %s\n", b) // b.Ignore() // again = true // } // } // } // } // fmt.Printf("da.removeNTsWithoutChildren: %d reps\n", reps) // } func removeNTsWithoutChildren() { // fmt.Println("da.removeNTsWithoutChildren") for _, rt := range bsr.GetRoots() { removeZombieChildren(rt) } } func removeZombieChildren(nt bsr.BSR) { // fmt.Println("da.removeZombieChildren", nt) if nt.Label.Head() == "Sep" || nt.Label.Head() == "SepE" { return } for i, s := range nt.Label.Symbols() { if symbols.IsNonTerminal(s) { for _, c := range nt.GetNTChildrenI(i) { removeZombieChildren(c) } if len(nt.GetNTChildrenI(i)) == 0 { nt.Ignore() } } } } func reservedWord(s string) bool { switch s { case "empty": return true case "any": return true // case "anyof": // return true case "letter": return true case "number": return true case "space": return true case "upcase": return true case "lowcase": return true // case "not": // return true } if strings.HasPrefix(s, "anyof") || strings.HasPrefix(s, "not") { return true } return false } <file_sep>/* Copyright 2019 <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. */ package main import ( "fmt" "github.com/goccmack/gogll/cfg" "github.com/goccmack/gogll/da" "github.com/goccmack/gogll/frstflw" genff "github.com/goccmack/gogll/gen/firstfollow" "github.com/goccmack/gogll/gen/golang" "github.com/goccmack/gogll/gen/slots" "github.com/goccmack/gogll/gen/symbols" "github.com/goccmack/gogll/goutil/bsr" "github.com/goccmack/gogll/gslot" "github.com/goccmack/gogll/parser" "github.com/goccmack/gogll/sa" "io/ioutil" "os" "runtime/pprof" ) func main() { cfg.GetParams() if *cfg.CPUProfile { f, err := os.Create("cpu.prof") if err != nil { fmt.Println("could not create CPU profile: ", err) os.Exit(1) } defer f.Close() if err := pprof.StartCPUProfile(f); err != nil { fmt.Println("could not start CPU profile: ", err) os.Exit(1) } defer pprof.StopCPUProfile() } if err, errs := parser.ParseFile(cfg.SrcFile); err != nil { fail(err, errs) } da.Go() g, errs := sa.Go() if errs != nil { for _, err := range errs { fmt.Println(err) } os.Exit(1) } symbols.Gen(g) ff := frstflw.New(g) genff.Gen(g, ff) gs := gslot.New(g, ff) slots.Gen(gs) golang.Gen(g, gs, ff) } func fail(err error, errs []*parser.ParseError) { fmt.Printf("ParseError: %s\n", err) // parser.DumpCRF(errs[0].InputPos) bsr.Dump() for _, e := range errs { fmt.Println("", e) } } func getInput() string { buf, err := ioutil.ReadFile(cfg.SrcFile) if err != nil { panic(err) } return string(buf) } <file_sep># Notes on development of gogll v1 # git This separate git worktree was created inside the gogll git repo by: ``` git branch gogll1 git worktree add ../gogll1 gogll1 ``` Merge back: ``` cd ../gogll git merge gogll1 rm -rf ../gogll1 git worktree prune ```<file_sep>// Copyright 2019 <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. package bsr import ( "bytes" "github.com/goccmack/gogll/goutil/ioutil" "text/template" ) func Gen(bsrFile string, pkg string) { tmpl, err := template.New("bsr").Parse(bsrTmpl) if err != nil { panic(err) } buf := new(bytes.Buffer) if err = tmpl.Execute(buf, pkg); err != nil { panic(err) } if err = ioutil.WriteFile(bsrFile, buf.Bytes()); err != nil { panic(err) } } const bsrTmpl = ` // Package bsr is generated by gogll. Do not edit. // Copyright 2019 <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. /* Package bsr implements a Binary Subtree Representation set as defined in Scott et al Derivation representation using binary subtree sets, Science of Computer Programming 175 (2019) */ package bsr import ( "fmt" "os" "sort" "strings" "unicode/utf8" "{{.}}/parser/slot" ) type bsr interface { LeftExtent() int RightExtent() int Pivot() int } var ( set *bsrSet startSym string ) type bsrSet struct { slotEntries map[BSR]bool ignoredSlots map[BSR]bool stringEntries map[stringBSR]bool rightExtent int I []byte } // BSR is the binary subtree representation of a parsed nonterminal type BSR struct { Label slot.Label leftExtent int pivot int rightExtent int } type stringBSR struct { Label slot.Label leftExtent int pivot int rightExtent int } func newSet(I []byte) *bsrSet { return &bsrSet{ slotEntries: make(map[BSR]bool), ignoredSlots: make(map[BSR]bool), stringEntries: make(map[stringBSR]bool), rightExtent: 0, I: I, } } /* Add a bsr to the set. (i,j) is the extent. k is the pivot. */ func Add(l slot.Label, i, k, j int) { // fmt.Printf("bsr.Add(%s,%d,%d,%d)\n", l,i,k,j) if l.EoR() { insert(BSR{l, i, k, j}) } else { if l.Pos() > 1 { insert(stringBSR{l, i, k, j}) } } } func AddEmpty(l slot.Label, i int) { insert(stringBSR{l, i, i, i}) } func Contain(nt string, left, right int) bool { // fmt.Printf("bsr.Contain(%s,%d,%d)\n",nt,left,right) for e, _ := range set.slotEntries { // fmt.Printf(" (%s,%d,%d)\n",e.Label.Head(),e.leftExtent,e.rightExtent) if e.Label.Head() == nt && e.leftExtent == left && e.rightExtent == right { // fmt.Println(" true") return true } } // fmt.Println(" false") return false } // GetAll returns all BSR grammar slot entries func GetAll() (bsrs []BSR) { for b := range set.slotEntries { bsrs = append(bsrs, b) } return } // GetRightExtent returns the right extent of the BSR set func GetRightExtent() int { return set.rightExtent } // GetRoot returns the root of the parse tree of an unambiguous parse. // GetRoot fails if the parse was ambiguous. Use GetRoots() for ambiguous parses. func GetRoot() BSR { rts := GetRoots() if len(rts) != 1 { failf("%d parse trees exist for start symbol %s", len(rts), startSym) } return rts[0] } // GetRoots returns all the roots of parse trees of the start symbol of the grammar. func GetRoots() (roots []BSR) { for s, _ := range set.slotEntries { if s.Label.Head() == startSym && s.leftExtent == 0 && s.rightExtent == set.rightExtent { roots = append(roots, s) } } return } // GetNTSlot returns all slot entries of the NT, 'nt' func GetNTSlot(nt string) (slots []BSR) { for bsr := range set.slotEntries { if bsr.Label.Head() == nt { slots = append(slots, bsr) } } return } func getString(l slot.Label, leftExtent, rightExtent int) stringBSR { for str, _ := range set.stringEntries { if str.Label == l && str.leftExtent == leftExtent && str.rightExtent == rightExtent { return str } } fmt.Printf("Error: no string %s left extent=%d right extent=%d pos=%d\n", strings.Join(l.Symbols()[:l.Pos()], " "), leftExtent, rightExtent, l.Pos()) panic("must not happen") } func Init(startSymbol string, I []byte) { set = newSet(I) startSym = startSymbol } func insert(bsr bsr) { if bsr.RightExtent() > set.rightExtent { set.rightExtent = bsr.RightExtent() } switch s := bsr.(type) { case BSR: set.slotEntries[s] = true case stringBSR: set.stringEntries[s] = true default: panic(fmt.Sprintf("Invalid type %T", bsr)) } } // Alternate returns the index of the grammar rule alternate. func (b BSR) Alternate() int { return b.Label.Alternate() } // GetNTChild returns the BSR of occurrence i of nt in s. // GetNTChild fails if s has ambiguous subtrees of occurrence i of nt. func (b BSR) GetNTChild(nt string, i int) BSR { bsrs := b.GetNTChildren(nt, i) if len(bsrs) != 1 { ambiguousSlots := []string{} for _, c := range bsrs { ambiguousSlots = append(ambiguousSlots, c.String()) } fail(b, "%s is ambiguous in %s\n %s", nt, b, strings.Join(ambiguousSlots, "\n ")) } return bsrs[0] } // GetNTChildI returns the BSR of NT symbol[i] in s. // GetNTChildI fails if s has ambiguous subtrees of NT i. func (b BSR) GetNTChildI(i int) BSR { bsrs := b.GetNTChildrenI(i) if len(bsrs) != 1 { fail(b, "NT %d is ambiguous in %s", i, b) } return bsrs[0] } // GetNTChild returns all the BSRs of occurrence i of nt in s func (b BSR) GetNTChildren(nt string, i int) []BSR { // fmt.Printf("GetNTChild(%s,%d) %s\n", nt, i, b) positions := []int{} for j, s := range b.Label.Symbols() { if s == nt { positions = append(positions, j) } } if len(positions) == 0 { fail(b, "Error: %s has no NT %s", b, nt) } return b.GetNTChildrenI(positions[i]) } // GetNTChildI returns all the BSRs of NT symbol[i] in s func (b BSR) GetNTChildrenI(i int) []BSR { // fmt.Printf("bsr.GetNTChildI(%d) %s\n", i, b) if i >= len(b.Label.Symbols()) { fail(b, "Error: cannot get NT child %d of %s", i, b) } if len(b.Label.Symbols()) == 1 { return getNTSlot(b.Label.Symbols()[i], b.pivot, b.rightExtent) } if len(b.Label.Symbols()) == 2 { if i == 0 { return getNTSlot(b.Label.Symbols()[i], b.leftExtent, b.pivot) } return getNTSlot(b.Label.Symbols()[i], b.pivot, b.rightExtent) } idx := b.Label.Index() str := stringBSR{b.Label, b.leftExtent, b.pivot, b.rightExtent} for idx.Pos > i+1 && idx.Pos > 2 { idx.Pos-- str = getString(slot.GetLabel(idx.NT, idx.Alt, idx.Pos), str.leftExtent, str.pivot) // fmt.Printf(" %s\n", str) } if i == 0 { return getNTSlot(b.Label.Symbols()[i], str.leftExtent, str.pivot) } return getNTSlot(b.Label.Symbols()[i], str.pivot, str.rightExtent) } func (b BSR) GetString() string { return string(set.I[b.LeftExtent():b.RightExtent()]) } func (b BSR) Ignore() { // fmt.Printf("bsr.Ignore %s\n", b) delete(set.slotEntries, b) set.ignoredSlots[b] = true } func (s BSR) LeftExtent() int { return s.leftExtent } func (s BSR) RightExtent() int { return s.rightExtent } func (s BSR) Pivot() int { return s.pivot } func (s BSR) String() string { return fmt.Sprintf("%s,%d,%d,%d - %s", s.Label, s.leftExtent, s.pivot, s.rightExtent, set.I[s.LeftExtent():s.RightExtent()]) } func (s stringBSR) LeftExtent() int { return s.leftExtent } func (s stringBSR) RightExtent() int { return s.rightExtent } func (s stringBSR) Pivot() int { return s.pivot } func (s stringBSR) Empty() bool { return s.leftExtent == s.pivot && s.pivot == s.rightExtent } func (s stringBSR) String() string { // fmt.Printf("bsr.stringBSR.stringBSR(): %s, %d, %d, %d\n", // s.Label.Symbols(), s.leftExtent, s.pivot, s.rightExtent) ss := s.Label.Symbols()[:s.Label.Pos()] str := strings.Join(ss, " ") return fmt.Sprintf("%s,%d,%d,%d - %s", str, s.leftExtent, s.pivot, s.rightExtent, set.I[s.LeftExtent():s.RightExtent()]) } func Dump() { DumpSlots() DumpStrings() } func DumpSlots() { fmt.Printf("Slots (%d)\n", len(getSlots())) for _, s := range getSlots() { DumpSlot(s) } } func DumpSlot(s BSR) { fmt.Println(s) } func DumpStrings() { fmt.Printf("Strings(%d)\n", len(getStrings())) for _, s := range getStrings() { dumpString(s) } } func dumpString(s stringBSR) { fmt.Println(s) } func getSlots() (slots []BSR) { for s := range set.slotEntries { slots = append(slots, s) } sort.Slice(slots, func(i, j int) bool { return slots[i].Label < slots[j].Label }) return } func getStrings() (strings []stringBSR) { for s := range set.stringEntries { strings = append(strings, s) } sort.Slice(strings, func(i, j int) bool { return strings[i].Label < strings[j].Label }) return } func getNTSlot(nt string, leftExtent, rightExtent int) (bsrs []BSR) { for sl, _ := range set.slotEntries { if sl.Label.Head() == nt && sl.leftExtent == leftExtent && sl.rightExtent == rightExtent { bsrs = append(bsrs, sl) } } return } func fail(b BSR, format string, a ...interface{}) { msg := fmt.Sprintf(format, a...) line, col := getLineColumn(b.LeftExtent(), set.I) fmt.Printf("Error in BSR: %s at line %d col %d\n", msg, line, col) os.Exit(1) } func failf(format string, args ...interface{}) { fmt.Printf("Error in BSR: %s\n", fmt.Sprintf(format, args...)) os.Exit(1) } func decodeRune(str []byte) (string, rune, int) { if len(str) == 0 { return "$", '$', 0 } r, sz := utf8.DecodeRune(str) if r == utf8.RuneError { panic(fmt.Sprintf("Rune error: %s", str)) } switch r { case '\t', ' ': return "space", r, sz case '\n': return "\\n", r, sz } return string(str[:sz]), r, sz } func getLineColumn(cI int, I []byte) (line, col int) { line, col = 1, 1 for j := 0; j < cI; { _, r, sz := decodeRune(I[j:]) switch r { case '\n': line++ col = 1 case '\t': col += 4 default: col++ } j += sz } return } ` <file_sep>.PHONY: all all: gogll gogll2.bnf clean: rm -rf parser; \ rm *.txt<file_sep>.PHONY: all clean all: gogll g.md go test -v clean: rm *.txt; \ rm -rf parser; \ rm -rf goutil
341af431097af4fcbf53a913d6e7474db6bb5839
[ "Markdown", "Go", "Makefile" ]
7
Markdown
isgasho/gogll
ca68cd7264a5b106ef0b61d846622c31b5693047
afe6722476f392dd4e361ccf546aca31dedca4df
refs/heads/master
<repo_name>MaherAliwe/Financial-Front<file_sep>/src/pages/CategoryExpense.js import React from 'react' export default function CategoryExpense() { return ( <div> <h1>Category expense page </h1> </div> ) } <file_sep>/src/pages/MonthlyReports.js import React from 'react' export default function MonthlyReports() { return ( <div> <h1>monthly reports here</h1> </div> ) } <file_sep>/src/pages/WeeklyReports.js import React from 'react' export default function WeeklyReports() { return ( <div> <h1>weekly reports here</h1> </div> ) } <file_sep>/src/pages/Income.js import React from 'react' export default function Income() { return ( <div> <h1>income page</h1> </div> ) }
d1f9f55654ab3bf7430b22f1bcda4fbae43e2e7b
[ "JavaScript" ]
4
JavaScript
MaherAliwe/Financial-Front
d8d92c785c162b0497fc40ab6d8a546de4ac0a98
674e3ca2b71ec646b0f69c7beb13f12b38d45e9d
refs/heads/main
<repo_name>dianabivol/tekwill-homework<file_sep>/src/com/tekwill/learning/basics/acessmodifiers/testing/Doc.java package com.tekwill.learning.basics.acessmodifiers.testing; import com.tekwill.learning.basics.accessmodifiers.software.Employee; public class Doc { Employee employee; public void checkPublic() { employee.publicfirstName = "A"; employee.publicdoWork(); // without reference doesn't work //publicfirstName = "A"; //publicdoWork() } public void checkProtected() { // employee.protectedfirsName = "A"; // employee.protecteddoWork(); } public void checkDefault() { // employee.defaultfirstName = "A"; // employee.defaultdoWork(); } public void checkPrivate() { // employee.privatefirstName = "A"; // employee.privatedoWork(); } }<file_sep>/README.md # tekwill-homework homework <file_sep>/src/com/tekwill/learning/basics/FightSong.java package com.tekwill.learning.basics; public class FightSong { public static void main(String[] args) { System.out.println("Go, team, go!\n" + "You can do it.\n" + "\t\t\t\t\t\t\t\n" + "Go, team, go!\n" + "You can do it.\n" + "you're the best,\n" + "In the West.\n" + "Go, team, go!\n" + "you can do it\n" + "\t\t\t\t\t\t\t\n" + "Go, team, go!\n" + "You can do it.\n" + "you're the best,\n" + "In the West.\n" + "Go, team, go!\n" + "you can do it\n" + "\t\t\t\t\t\t\t\n" + "Go, team, go!\n" + "You can do it.\n"); } } <file_sep>/src/com/tekwill/learning/basics/ChairTableDemo.java package com.tekwill.learning.basics; public class ChairTableDemo { public static void main(String[] args) { System.out.println("x X\n" + "x X\n" + "x XXXXXXXXXX X\n" + "xxxxx X X xxxxx\n" + "x x X X X x\n" + "x x x x x x\n"); } }
23fa73007b8ee976b3017fc44df97cc8f3727eeb
[ "Markdown", "Java" ]
4
Java
dianabivol/tekwill-homework
bbdd019dde1fc510556b0c323f6e54621d1edee3
170223e7acc89fb02fedb232e8824ea3807e80cd
refs/heads/master
<repo_name>jod35/ruby-adventuring<file_sep>/case expressions.rb def get_DayName(abr) day_name="" case abr when "mon" day_name ="Monday" when "tue" day_name ="Tuesday" when "wed" day_name ="Wednesday" when "thur" day_name ="Thursday" when "fri" day_name ="Friday" when "sat" day_name="Saturday" when "sun" day_name ="Sunday" else day_name="Invalid Abbreviation" end return day_name end puts get_DayName("mon")<file_sep>/return statements.rb def cube(num) return num*num*num end puts cube(2) #8 def square(num) return num*num end puts square(1000) #1000000<file_sep>/reading from files/read.rb File.open("employees.txt","r") do |file| # puts file ##<File:0x000055a9569a55d8> # puts file.read() =begin Jona ,Sales Jin,Engineer Job,Electrician Jopen,hello =end # puts file.readlines() =begin Jona ,Sales Jin,Engineer Job,Electrician Jopen,hello =end puts file.readchar() for line in file.readlines() puts line end =begin ona ,Sales Jin,Engineer Job,Electrician Jopen,hello =end end<file_sep>/while.rb index = 2 while index <= 5 puts index index +=1 end<file_sep>/arrays.rb #an array is a store that can hold multiple values friends = Array["Jonathan","Jordan","Jeremiah"] =begin Jonathan Jordan Jeremiah =end # puts friends # accessing items in arrays # puts friends[0] #Jonathan # puts friends[2] #Jeremiah # accessing the last # puts friends[-1] #-1 points to the last #Jeremiah # puts friends[0,2] =begin Jonathan Jordan =end #it leaves out the item at index 2 #Modifying items in the array puts friends[0]="Jacob" puts friends =begin Jacob Jordan Jeremiah =end #Creating an array enemies= Array.new enemies[0]="Beer" enemies[1]="Ciggerettes" enemies[2]="Girls" puts enemies.length() #returns the number of items in the array. puts enemies.include? "Ciggerettes" #returns true puts enemies.reverse() =begin Girls Ciggerettes Beer =end #sorting the items puts enemies.sort() =begin Beer Ciggerettes Girls =end #this is only applies to an array of a single datatype<file_sep>/data_types.rb #the different data types in ruby # 1. string name = "JOnathan" #this is a string occupation="programmer" #2. numbers age=21 #this is a number (integer) weight=21.45 #this is floating point number #3.boolean married=true single=false # these are booleans # 4.null flaws=nil # this is a null value<file_sep>/getting user input.rb puts "Enter your name" name = gets.chomp() puts "Enter your age" age=gets.chomp() # gets.chomp() gets rid of the unnecessary new lines puts makes puts "Hello "+ name + ", You are cool." # Hello jona ,You are cool. puts "Hello " +name + ", You are " +age # Hello jona, You are cool. # Hello jona, You are 12 <file_sep>/for loop.rb friends=["JOna","Jerusha","Jordan","Jeremiah"] =begin for friend in friends puts friends end =end friends.each do |friend| puts friend end #looping through a range of numbers for i in 0..5 puts i end =begin 0 1 2 3 4 5 =end #same way 10.times do |i| puts i end =begin 0 1 2 3 4 5 6 7 8 9 =begin <file_sep>/hello.rb print "Hello World" #prints hello world <file_sep>/madlibs.rb puts "Enter a color: " color=gets.chomp() puts "Enter a plural noun: " plural_noun= gets.chomp() puts "Enter a celebrity name: " celebrity=gets.chomp() puts("Roses are #{color}") puts("#{plural_noun} are blue") puts("I love #{celebrity}")<file_sep>/OOP/inheritance.rb class Student def attend_lectures puts "I attend lectures" end def do_coursework puts "I do course work" end end class UnderGradStudent < Student def doOrientation puts "I do orientation" end def doTests puts "I do the most tests" end end jona =UnderGradStudent.new() puts jona.do_coursework #I do coursework (it inherits this method from Student class) puts jona.doOrientation #I do orientation (its own method)<file_sep>/strings.rb #strings are text puts "This is my string" # This is my string puts "Jeremiah lost Jerusha\'s book and Jonah\'s too" # Jeremiah lost Jerusha's book and Jonah's too puts "Hey \n There" # Hey # There #STRING METHODS #we can store a string in a variable my_phrase="Jona is cool" puts my_phrase #to lowercase letters puts my_phrase.downcase # jona is cool puts my_phrase.upcase # JONA IS COOL puts my_phrase.length() #12 (length of the string) phrase=" jona is cool " puts phrase.strip() #removing trailing and leading white spaces puts phrase.include? "cool" # true for this case #checking whether a string contains a certain string puts my_phrase[0] #J puts my_phrase[0,3] #Jon puts my_phrase.index("J") #ouputs the index at which J is which is 0.<file_sep>/variables.rb character_name="Jerusha" character_age="35" puts "There was a man named " +character_name puts "He was "+ character_age +" years old" character_name="Johnny" character_age="100" puts "He really liked the name " +character_name puts "But he didnt like being " +character_age<file_sep>/README.md # ruby-adventuring Just adventuring. Nothing serious ## About this repo This repository contains all code for my journey while learning the Ruby Programming Language. <file_sep>/OOP/the initialize method.rb class Book attr_accessor :name,:pages,:author def initialize(name,pages,author) @name=name @pages=pages @author=author end end book1=Book.new("Halrol",234,"<NAME>") puts book1.name #Halrol<file_sep>/math and numbers.rb puts -5.89 +100 #94.11 puts 2*10 #20 puts 2**3 #8 puts 10%3 #1 # we can store numbers in variables num=12 puts ("my number is " + num.to_s) #we have to convert it to string #my number is 12 num=-20 puts num.abs() #20 which is the absolute value num =23.45 puts num.round() # rounds it off to 23 puts num.ceil() #returns the higher number next to 23.45 (24) puts num.floor() #returns the lower number to 23.45 (23) #Using the methods in the Math class #squareroot puts Math.sqrt(100) #square root of 100 (10) #logarithm puts Math.log(1) #0 # Integers and floats puts 1+6 #7 puts 10.3 +1 #11.3 puts 10.0/2 #5.0 <file_sep>/reading from files/write.rb File.open("index.html","r+") do |file| puts file.read file.write( "<html> <h1>Hello World</h1> <p>this is awesome.</p> </html>" ) end <file_sep>/comparisons.rb def max(num1,num2,num3) if num1 >= num2 and num1 >= 3 return "#{num1} is the maximum" elsif num2 >= num1 and num2 >=num3 return "#{num2} is the maximum" else return "#{num3} is the maximum" end end puts max(1,2,3) def isDivisibleby3(num1,num2,num3) if num1 %3 ==0 return "#{num1} is divisible by 3" elsif num2 % 3 ==0 return "#{num2} is divisible by 3" elsif num3 % 3 ==0 return "#{num3} is divisible by 3" elsif num2%3==0 and num3 %3==0 return "#{num2} and #{num3} are divisible by 3." elsif num1%3==0 and num2 %3==0 return "#{num1} and #{num2} are divisible by 3." elsif num1%3 ==0 and num2 %3==0 and num3 %3==0 return "#{num1}, #{num2} and #{num3} are all divisible by 3." else return "none of the given numbers is divisible by 3" end end puts isDivisibleby3(1,2,3) #3 is divisible by 3 puts isDivisibleby3(1,33,2) #33 is divisible by 3 puts isDivisibleby3(1,22,45) #45 is divisible by 3 puts isDivisibleby3(33,3,21) # 33 is divisible by 3 <file_sep>/guessing game.rb secret_word ="Jonathan" count=0 guess="" guess_limit=3 out_of_guesses=false while guess !=secret_word and !out_of_guesses if count <guess_limit puts "enter your guess: " guess=gets.chomp() count +=1 else out_of_guesses=true end end if out_of_guesses puts "You lose" else puts "You lose" end <file_sep>/if statements.rb isMale=false isTall=true if isMale or isTall puts "Jona is Male or Tall" elsif isMale and !isTall puts "Jona is male but not tall" elsif !isMale and isTall puts"Jona is a short female tall person" else puts "Jona is neither female nor Short" end<file_sep>/drawing_shapes.rb puts " /|" puts " / |" puts " / |" puts " / |" puts " /____|" #this draws a triangle<file_sep>/exception handling/handle.rb # num=10/0 luckynums=[1,2,3,4,5,6,7] begin luckynums["dogs"] num=10/0 rescue ZeroDivisionError puts "DivisionByZeroError" rescue TypeError =>e puts e end<file_sep>/methods.rb def hi puts "Hello" #method declaration end hi #method invocation def sayhi(name,age) puts "Hello #{name}, you are #{age}" end sayhi("Jonathan",12) #Hello Jonathan #we can also give default params def Yo(name="<NAME>",age=-1) puts "Yo #{name}! You are #{age}" end Yo("Jonathan") #Yo Jonathan! You are -1<file_sep>/OOP/instance methods.rb class Book attr_accessor :name,:pages,:author def initialize(name,pages,author) @name=name @pages=pages @author=author end def has_many_pages if @pages >=500 return true else return false end end end book1=Book.new("Understanding",123,"Jona") book2=Book.new("Python",500,"Than") puts book1.has_many_pages #false puts book2.has_many_pages #true<file_sep>/OOP/classes and objects.rb # a class is a custom datatype that helps us to create real life objects # it is a template for creating objects class Book attr_accessor :name,:author,:pages end book1=Book.new() book1.name="Hello World" book1.author="<NAME>" book1.pages=234 puts book1.name #Hello World puts book1.pages #234 book2=Book.new() book2.name="Python" book2.pages=1000 book2.author="<NAME>" puts book2.author <file_sep>/basic calculator.rb =begin puts "Enter a number" num1 =gets.chomp() num2=gets.chomp() puts num1 +num2 =end # above code concatenates the numbers =begin puts "Enter the first number: " num1=gets.chomp() puts "Enter the second number: " num2=gets.chomp() puts (num1.to_i + num2.to_i) =end #this converts the string inputs to integers and then gives the output puts "Enter the first number: " num1=gets.chomp() puts "Enter the second number: " num2=gets.chomp() puts (num1.to_f + num2.to_f) #this gives good results even when integers are added to floats <file_sep>/exponent method.rb def power(base_num,power_num) result =1 power_num.times do |i| result=result* base_num end return result end puts power(2,3) #8 puts power(10,10)#10000000000<file_sep>/better calculator.rb def calculate(num1, num2,operator) if operator == "+" return num1 +num2 elsif operator == "-" return num1 -num2 elsif operator == "*" return num1 * num2 elsif operator =="/" return num1 / num2 else return "Invalid operation" end end puts "Enter first number" x= gets.chomp().to_f puts "Enter second number" y= gets.chomp().to_f puts "Enter operator" op=gets.chomp() puts calculate(x,y,op) <file_sep>/hashes.rb #hashes store data in key-value pairs like dictionaries in Python boys={ "1"=>"Jonathan", "2"=>"Jeremiah", "3"=>"Jordan" } puts boys #{"1"=>"Jonathan", "2"=>"Jeremiah", "3"=>"Jordan"} #to access one puts boys["1"] #Jonathan #to access two puts boys["2"] #Jeremiah #another way is countries={ :Uganda=>"Africa", :Brasil=>"South Africa", :China=>"Asia" } puts countries[:China] #Asia
4282f7ddcec1c6c83cbb2a812c5a8c5ceb0cecea
[ "Markdown", "Ruby" ]
29
Ruby
jod35/ruby-adventuring
6b84ae3fefd466df6af0f992c3025ecad88a5302
16b0717de9fb313f2902835a4ca64198dc6cdeff
refs/heads/master
<repo_name>acoelho/ExData_Plotting1<file_sep>/plot1.R #download data if needed if (!file.exists("./household_power_consumption.txt")) { if (!file.exists("./exdata%2Fdata%2Fhousehold_power_consumption.zip")) { fURL <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" download.file(fURL,destfile="exdata%2Fdata%2Fhousehold_power_consumption.zip") } unzip("./exdata%2Fdata%2Fhousehold_power_consumption.zip") } #read the data data <- read.table("household_power_consumption.txt", sep = ";", header=T, na.strings="?") #subset the data for the deisred dates subdata <- data[data$Date == "1/2/2007" | data$Date == "2/2/2007",] png(file="plot1.png") hist(subdata$Global_active_power, main = "Global Active Power", xlab = "Global Active Power (kilowatts)", col = "RED") #turn off device dev.off()<file_sep>/plot2.R #download data if needed if (!file.exists("./household_power_consumption.txt")) { if (!file.exists("./exdata%2Fdata%2Fhousehold_power_consumption.zip")) { fURL <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" download.file(fURL,destfile="exdata%2Fdata%2Fhousehold_power_consumption.zip") } unzip("./exdata%2Fdata%2Fhousehold_power_consumption.zip") } #read the data data <- read.table("household_power_consumption.txt", sep = ";", header=T, na.strings="?") #subset the data for the deisred dates subdata <- data[data$Date == "1/2/2007" | data$Date == "2/2/2007",] png(file="plot2.png") #plot Global Active power over time plot(strptime(paste(subdata$Date,subdata$Time), format = "%d/%m/%Y %H:%M:%S"), subdata$Global_active_power, ylab = "Global Active Power (kilowatts)", xlab = "", type = "l") #turn off device dev.off()<file_sep>/plot4.R #download data if needed if (!file.exists("./household_power_consumption.txt")) { if (!file.exists("./exdata%2Fdata%2Fhousehold_power_consumption.zip")) { fURL <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" download.file(fURL,destfile="exdata%2Fdata%2Fhousehold_power_consumption.zip") } unzip("./exdata%2Fdata%2Fhousehold_power_consumption.zip") } #read the data data <- read.table("household_power_consumption.txt", sep = ";", header=T, na.strings="?") #subset the data for the deisred dates subdata <- data[data$Date == "1/2/2007" | data$Date == "2/2/2007",] png(file="plot4.png") par("mfrow" = c(2,2)) plot(strptime(paste(subdata$Date,subdata$Time), format = "%d/%m/%Y %H:%M:%S"), subdata$Global_active_power, ylab = "Global Active Power", xlab = "", type = "l") plot(strptime(paste(subdata$Date,subdata$Time), format = "%d/%m/%Y %H:%M:%S"), subdata$Voltage, ylab = "Voltage", xlab = "datetime", type = "l") #plot Global Active power over time plot(strptime(paste(subdata$Date,subdata$Time), format = "%d/%m/%Y %H:%M:%S"), subdata$Sub_metering_1, ylab = "Energy sub metering", xlab = "", type = "s") points(strptime(paste(subdata$Date,subdata$Time), format = "%d/%m/%Y %H:%M:%S"), subdata$Sub_metering_2, type = "s", col = "red") points(strptime(paste(subdata$Date,subdata$Time), format = "%d/%m/%Y %H:%M:%S"), subdata$Sub_metering_3, type = "s", col = "blue") legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), bty = "n", lty = c(1,1), col=c("black", "red", "blue")) plot(strptime(paste(subdata$Date,subdata$Time), format = "%d/%m/%Y %H:%M:%S"), subdata$Global_reactive_power, ylab = "Global_reactive_power", xlab = "datetime", type = "l") dev.off()<file_sep>/plot3.R #download data if needed if (!file.exists("./household_power_consumption.txt")) { if (!file.exists("./exdata%2Fdata%2Fhousehold_power_consumption.zip")) { fURL <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" download.file(fURL,destfile="exdata%2Fdata%2Fhousehold_power_consumption.zip") } unzip("./exdata%2Fdata%2Fhousehold_power_consumption.zip") } #read the data data <- read.table("household_power_consumption.txt", sep = ";", header=T, na.strings="?") #subset the data for the deisred dates subdata <- data[data$Date == "1/2/2007" | data$Date == "2/2/2007",] png(file="plot3.png") #plot Global Active power over time plot(strptime(paste(subdata$Date,subdata$Time), format = "%d/%m/%Y %H:%M:%S"), subdata$Sub_metering_1, ylab = "Energy sub metering", xlab = "", type = "s") points(strptime(paste(subdata$Date,subdata$Time), format = "%d/%m/%Y %H:%M:%S"), subdata$Sub_metering_2, type = "s", col = "red") points(strptime(paste(subdata$Date,subdata$Time), format = "%d/%m/%Y %H:%M:%S"), subdata$Sub_metering_3, type = "s", col = "blue") legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty = c(1,1), col=c("black", "red", "blue")) dev.off()
e32a467c145cab72e2a346a8f28e66de9cdff274
[ "R" ]
4
R
acoelho/ExData_Plotting1
5e264f9a09d52807caba568fb5931b837591d475
80d330f77e3b4d29be634aaeb19494cd5d034821
refs/heads/master
<file_sep># config valid for current version and patch releases of Capistrano lock "~> 3.12.1" set :rbenv_type, :user set :rbenv_ruby, '2.6.3' set :application, "animatedgif" set :repo_url, "<EMAIL>:maful/animatedgif-me.git" set :user, "#{ENV['SERVER_USER']}" set :puma_threads, [4, 16] set :puma_workers, 0 set :pty, true set :use_sudo, false set :deploy_to, "/home/#{fetch(:user)}/apps/#{fetch(:application)}" set :deploy_via, :remote_cache set :puma_preload_app, true set :puma_init_active_record, true append :linked_dirs, 'log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'public/packs', '.bundle', 'node_modules' append :linked_files, %w{.rbenv-vars} set :keep_releases, 5 before "deploy:assets:precompile", "deploy:yarn_install" namespace :deploy do desc "Run rake yarn install" task :yarn_install do on roles(:web) do within release_path do execute("cd #{release_path} && yarn install --silent --no-progress --no-audit --no-optional") end end end end
992a1e55af4f6e9475f59fdc09db4a4473263008
[ "Ruby" ]
1
Ruby
maful/animatedgif-me
0875bad093a6c31201a1968464da86d36a22fe05
376627701a3fe5a59e6816fab2461e7ffb0af531
refs/heads/main
<file_sep>#!/bin/sh rm -r data_set rm -r running_time mkdir data_set mkdir running_time echo "Generating Data Set.." python runscript.py 1000 data_set/0_data_1000.txt python runscript.py 5000 data_set/1_data_5000.txt python runscript.py 10000 data_set/2_data_10000.txt python runscript.py 50000 data_set/3_data_50000.txt python runscript.py 75000 data_set/4_data_75000.txt python runscript.py 100000 data_set/5_data_100000.txt python runscript.py 500000 data_set/6_data_500000.txt echo "Generated Data Set Successfully." algorithm="" for i in $(seq 0 3); do if [ "$i" = "0" ]; then algorithm="selection_sort" elif [ "$i" = "1" ]; then algorithm="insertion_sort" elif [ "$i" = "2" ]; then algorithm="merge_sort" elif [ "$i" = "3" ]; then algorithm="quick_sort" else echo "out of range" fi for filename in data_set/*.txt; do echo "Running $algorithm algorithm for $filename" /Users/michael/Dev/algorithms/cmake-build-debug/2_sorting "$i" "$filename" "sorted_data.txt" "running_time/$algorithm.txt" /Users/michael/Dev/algorithms/cmake-build-debug/2_sorting "$i" "sorted_data.txt" "sorted_data.txt" "running_time/$algorithm.txt" done done <file_sep>// // Created by <NAME> on 07/05/2021. // #include <iostream> #include <unordered_map> #include "vector" int canMeasureTrees(std::vector<int> tapeValues, int noOfValues,int tapeLength, int x, int y) { /// check if tape values can measure x and y bool canMeasureX = false; bool canMeasureY = false; /// possible values to add to the tape to get x std::vector<int> xPossibleValues; xPossibleValues.push_back(x); for (int i = 0; i < noOfValues -1; i++) { for (int j = i + 1; j < noOfValues ; j++) { if (tapeValues[j] - tapeValues[i] == x && !canMeasureX) { canMeasureX = true; } if (tapeValues[j] - tapeValues[i] == y && !canMeasureY) { canMeasureY = true; } /// save the difference between the current value and x if(tapeValues[j] - x >= 0 ) xPossibleValues.push_back(tapeValues[j] - x); if (tapeValues[j] + x < tapeLength) xPossibleValues.push_back(tapeValues[j] + x); } } /// if yes => return 0; if (canMeasureX && canMeasureY) return 0; /// if one of them is false, then we only need one value to add. if (canMeasureX && !canMeasureY) return 1; if (!canMeasureX && canMeasureY) return 1; /// if both false, get the min number of needed values and return it; /// we cannot return 2 because one value can be added to make them both true. for (int xPossibleValue : xPossibleValues) { for (int j = 0; j < noOfValues; j++) { /// meaning that one of the added values for x can be used for y if (tapeValues[j] - xPossibleValue == y) return 1; } } return 2; } int main() { /// the number of distances on the measuring tape N, /// the length of the measuring tape L and the two allowed lengths of the trees X,Y int N, L, X, Y; std::cin>>N>>L>>X>>Y; std::vector<int> tapeValues(N); for (int i = 0; i < N; i++) { std::cin>>tapeValues[i]; } int minNoOfDistancesNeeded = canMeasureTrees(tapeValues, N,L, X,Y); std::cout<<minNoOfDistancesNeeded; return 0; } <file_sep>// // Created by <NAME> on 11/06/2021. // #include "iostream" #include "vector" #include "unordered_map" /// half of test cases fail int main() { int arraySize, partitionSize, partitionsNumber; std::cin>>arraySize>>partitionSize>>partitionsNumber; std::vector<int> array(arraySize); for (int i = 0; i < arraySize; i++) { std::cin>>array[i]; } std::vector<int*> used(arraySize); int maxSum = 0; for (int i = 0; i < partitionsNumber; i++) { int currentPartitionValue = 0; int maxPartitionValue = 0; int maxPartitionIndex; for (int j = 0; j <= arraySize - partitionSize; j++) { if(used[j] != nullptr) break; currentPartitionValue += array[j]; for (int k = 1; k < partitionSize; k++) { if (used[j + k] != nullptr) break; currentPartitionValue += array[j + k]; } if (maxPartitionValue < currentPartitionValue){ maxPartitionValue = currentPartitionValue; maxPartitionIndex = j; } currentPartitionValue = 0; } maxSum += maxPartitionValue; used[maxPartitionIndex] = &maxPartitionValue; } std::cout<<maxSum; return 0; } <file_sep># [The Penguin and perfect trees](https://www.hackerrank.com/contests/cmpn302-fall2021-hw3/challenges/the-penguin-and-perfect-trees) Bob the penguin has been recently interested in trees, but he has just found out about the perfect binary tree* and he became obsessed with it. Every day he draw a perfect binary tree and write down its inorder traversal in a seperate paper, but unfortunately he lost all his tree drawings and all he has now is the inorder traversal of this trees. Can you help him reconstruct this trees? *A perfect binary tree is a binary tree in which all interior nodes have two children and all leaves have the same depth or same level ![img.png](img.png) **Input Format** The first line contains N the number of nodes and the next line contains N space separated numbers represent the inorder traversal of the tree **Constraints** 1 <= N < 2^17 **Output Format** print the tree level by level and print each level from left to right for example the above tree should be printted 8 4 12 2 6 10 14 1 3 5 7 9 11 13 15 **Sample Input 0** ``` 15 9 8 5 2 1 4 7 6 3 10 13 12 15 11 14 ``` **Sample Output 0** ``` 6 2 12 8 4 10 11 9 5 1 7 3 13 15 14 ``` <file_sep># [Serve the burger](https://www.hackerrank.com/contests/cmpn302-fall2021-hw4/challenges/serve-the-burger) You have a restaurant that serves two sizes of burger either small or large, the small burger takes a grams of meat and the large takes b grams. You have the orders of n customers, every order needs x small burgers and y large burgers, and you are required to serve the maximum number possible of orders given that you have only d grams of meat available **Input Format** - The first line contains two integers n and d — the number of orders and the grams of meat you have, correspondingly. The second line contains two integers a and b — the weight of the small and large burgers, correspondingly. - Next n lines describe the orders. The i-th line contains two integers xi and yi — the number of small burgers and large burgers the i-th order lists, correspondingly. - All numbers on all lines are separated by single spaces. **Constraints** - (1 ≤ n ≤ 10^5, 1 ≤ d ≤ 10^9) (1 ≤ a ≤ b ≤ 10^4) (0 ≤ xi, yi ≤ 10^5) **Output Format** print the maximum number of orders that you can serve **Sample Input 0** ``` 3 10 2 3 1 4 2 1 1 0 ``` **Sample Output 0** ``` 2 ``` **Sample Input 1** ``` 3 6 6 6 1 1 1 0 1 0 ``` **Sample Output 1** ``` 1 ``` <file_sep>#include <iostream> #include <unordered_map> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; using std::unordered_map; typedef unordered_map<int, unordered_map<int, int>> _floor; typedef unordered_map<int,_floor> lair; void generateRoutes1(int n,int floorNo, int roomX,int roomY, lair _lair,int amount, int &minAmount) { amount+= _lair[floorNo][roomX][roomY]; if(floorNo == n-1 && roomX == n-1 && roomY == n-1){ if(amount < minAmount){ minAmount = amount; } return; } if(roomX < n-1) generateRoutes1(n, floorNo, roomX+1, roomY,_lair, amount, minAmount); if(roomY < n-1) generateRoutes1(n, floorNo, roomX, roomY+1,_lair, amount, minAmount); if(floorNo < n-1) generateRoutes1(n, floorNo+1, roomX, roomY,_lair, amount, minAmount); } void generateRoutes(int n,int floorNo, int roomX,int roomY, int* list,int amount, int &minAmount){ amount+= list[roomX + (roomY*n) +(n*n*floorNo)]; if(floorNo == n-1 && roomX == n-1 && roomY == n-1){ if(amount < minAmount){ minAmount = amount; } return; } if(roomX < n-1) generateRoutes(n, floorNo, roomX+1, roomY,list, amount, minAmount); if(roomY < n-1) generateRoutes(n, floorNo, roomX, roomY+1,list, amount, minAmount); if(floorNo < n-1) generateRoutes(n, floorNo+1, roomX, roomY,list, amount, minAmount); } int main() { int n; cin>>n; int n3 = n*n*n; int* list = new int[n3]; for(int i = 0 ; i< n3 ; i++){ cin>> list[i]; } int minAmount = std::numeric_limits<int>::max(); generateRoutes(n,0,0,0,list,0,minAmount); cout<<minAmount; return 0; } <file_sep> #include <iostream> #include "vector" #include "string" using std::cin; using std::cout; using std::endl; using std::vector; using std::string; void generateStrings(const string& generatedString,vector<int> counts, int stringLength, int k){ /// exit condition if(generatedString.size() == stringLength){ cout<<generatedString<<endl; return; } /// loop over all the numbers from 0 to k-1 for (int i = 0; i < k; ++i) { /// if we still need to add the number, generate a string with this number /// and decrement its occurrences if(counts[i] != 0){ counts[i]--; generateStrings(generatedString+std::to_string(i), counts, stringLength, k); /// increment the number again to be used in next callbacks counts[i]++; } } } /// \IMPLEMENTATION DONE /// \TESTCASES PASSED int main(){ /// k is the radix count int k, stringLength; cin>>k>>stringLength; /// create an array to hold how many occurrence should a number have vector<int> counts(k); for (int i = 0; i < k; ++i) { cin>>counts[i]; } /// recursive call generateStrings("", counts, stringLength, k); } <file_sep>// // Created by <NAME> on 06/03/2022. // #include <iostream> #include <vector> #include "algorithm" using std::cin; using std::cout; using std::endl; using std::vector; void generateTeam(const vector<char>& characters, vector<char> team,int teamSize, int N, int level){ if(team.size() == teamSize){ for (char name : team) { cout<<name; } cout<<endl; return; } if (N == level) return; team.push_back(characters[level]); generateTeam(characters, team, teamSize, N, level + 1); team.pop_back(); generateTeam(characters, team, teamSize, N, level + 1); } /// \IMPLEMENTATION DONE /// \TESTCASES PASSED int main() { int N, M; cin>>N>>M; vector<char> characters(N); vector<char> team; for(int i = 0; i<N;i++){ cin>>characters[i]; } std::sort(characters.begin(), characters.end()); generateTeam(characters,team, M,N,0); } <file_sep># [Paint the blocks](https://www.hackerrank.com/contests/cmpn302-fall2021-hw4/challenges/paint-the-blocks-1) You have a number of consequent blocks adjacent to each other and every block of width 1 m and height h[i] meter, you need to re-paint these blocks with the minimum number of steps given that you have two options, either you paint the blocks vertically, so you will paint only one block in one step, or you paint 1 m of all blocks with no gaps horizontally, for example if you have 4 blocks of sizes 2 3 2 3 you can paint the first 2 m meter horizontally of the 4 blocks in 2 steps but for the last meter of the second and fourth block you will not be able to do it in one step as there is a gap in the middle so each one will be done independently. Note: you can re-paint the blocks more than once **Input Format** - The first line contains integer n (1 ≤ n ≤ 5000) — the number of blocks. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 10^9). **Constraints** - (1 ≤ n ≤ 5000) (1 ≤ ai ≤ 10^9) **Output Format** - print in a single line the minimum number of steps needed to paint all the blocks **Sample Input 0** ``` 5 2 2 1 2 1 ``` **Sample Output 0** ``` 3 ``` **Explanation 0** you need to paint the blocks like that: the first step goes on height 1 horizontally along all the blocks. The second step goes on height 2 horizontally and paints the first and second blocks, and the third step (it can be horizontal and vertical) finishes painting the fourth block. **Sample Input 1** ``` 2 2 2 ``` **Sample Output 1** ``` 2 ``` **Explanation 1** paint the blocks with two steps, either two horizontal or two vertical strokes. <file_sep>// // Created by <NAME> on 09/05/2021. // #include "iostream" #include "vector" struct Node { int color; bool isParent; std::vector<Node*> children; }; /// a helper function to allocate a new node Node* createNode(int color) { Node* node = (Node*)malloc(sizeof(Node)); node->color = color; return node; } void getPossibleFriends(Node* root, int &currentFriends, int count, int maxNoOfDarkStreets) { if (root == nullptr) return; /// if the current street(node) is dark, increment count of dark streets if (root->color == 1) count++; /// if current node does not have any children , means it's a leaf /// then check for friend (node) validity (if it passed the maxDarkStreets(nodes)) if (root->children.empty()) { if (count <= maxNoOfDarkStreets) currentFriends++; return; } if(root->color == 0) count = 0; for (auto & child : root->children) { getPossibleFriends(child, currentFriends, count, maxNoOfDarkStreets); } } /// implementation not complete /// TODO -- complete int main() { /// N and M the number of nodes of the tree and the maximum number of consecutive dark nodes int N, M; std::cin >> N >> M; std::vector<Node *> nodes(N); /// initialize array of nodes int color; for (int i = 0; i < N; i++) { std::cin >> color; nodes[i] = createNode(color); } nodes[0]->isParent = true; std::vector<std::pair<int, int>> edges(N - 1); std::pair<int, int> tempEdge; for (int i = 0; i < N - 1; i++) { std::cin >> tempEdge.first >> tempEdge.second; edges[i] = tempEdge; } for (int i = 1; i < N - 1; i++) { /// check if any node index is redundant, if yes, then it's definitely a parent std::pair<int, int> firstEdge; std::pair<int, int> secondEdge; for (int j = 1; j < N -1; j++) { if (i != j) { if (edges[i].first == edges[j].first || edges[i].first == edges[j].second) { /// it's parent nodes[edges[i].first - 1]->isParent = true; // firstEdge = edges[i]; // secondEdge = edges[j]; } if (edges[i].second == edges[j].first || edges[i].second == edges[j].second) { nodes[edges[i].second - 1]->isParent = true; } } } } for (int i = 0; i < N-1; i++) { int firstIndex = edges[i].first; int secondIndex = edges[i].second; Node* firstNode = nodes[firstIndex]; Node* secondNode = nodes[secondIndex]; if (firstIndex == 1) { firstNode->children.push_back(nodes[secondIndex]); break; } if (secondIndex == 1) { secondNode->children.push_back(nodes[firstIndex]); break; } if (firstNode->isParent) { firstNode->children.push_back(nodes[secondIndex]); } else { secondNode->children.push_back(nodes[firstIndex]); } } int possibleFriends = 0; getPossibleFriends(nodes[0], possibleFriends, 0, M); std::cout<<possibleFriends; return 0; } <file_sep>#include <iostream> #include <unordered_map> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; using std::unordered_map; void generateTreasure(vector<vector<int>> generatedItems,vector<vector<int>> items, int noOfItems, int index, int &maxValue,int maxWeight){ if(index == noOfItems){ int maxV = 0; int weight = 0; if(!generatedItems[0].empty()){ for(int i = 0;i < generatedItems[0].size(); i++){ maxV += generatedItems[0][i]; weight += generatedItems[1][i]; } if(weight <= maxWeight){ if(maxV > maxValue) maxValue = maxV; } } return; } generateTreasure(generatedItems,items, noOfItems, index +1, maxValue, maxWeight); generatedItems[0].push_back(items[0][index]); generatedItems[1].push_back(items[1][index]); generateTreasure(generatedItems,items, noOfItems, index +1, maxValue, maxWeight); } int main() { int weight; cin>>weight; int n; cin>>n; vector<vector<int>> items (2, vector<int> (n)); int w, v; for(int i = 0; i<n;i++){ cin>>w>>v; items[0][i] = v; items[1][i] = w; } vector<vector<int>> generatedItems (2, vector<int> ()); int maxValue =0; generateTreasure(generatedItems, items, n, 0, maxValue, weight); cout<<maxValue<<endl; return 0; } <file_sep> # [Radix Count](https://www.hackerrank.com/contests/cmpn302-s2022-hw1/challenges/radix-count) Given a specific radix K and a length N, it is required to generate each string of length N in which the value of each digit could be from 0 to K-1, such that the generated string matches the given counts of each K value. For example, if K is 3, then 3 counts will be given, indicating the desired count of value 0, value 1, and value 2 respectively in the generated strings. Print the matching strings in lexicographical order. **Input Format** - one line containing K and N separated by a space - one line containing K numbers separated by a space, where each number represents the desired count of each value. Note: the sum of those numbers equals N (the number of digits). **Constraints** - K is from 2 to 5 - N is from 1 to 10 - the sum of all the counts will be N (the number of digits) **Output Format** - each matching string in a separate line in lexicographical order **Sample Input 0** ``` 3 4 2 0 2 ``` **Sample Output 0** ``` 0022 0202 0220 2002 2020 2200 ``` **Explanation 0** Note that: the count of digit value 0, 1, and 2 in each string is 2, 0, and 2 respectively. <file_sep># [Maximum sum](https://www.hackerrank.com/contests/cmpn302-fall2021-hw4/challenges/maximum-sum-13) Given an array of n integers you are required to partition this array to k partitions every partition has m consequent numbers such that the summation of these m*k numbers is maximum possible, note that the partitions should not overlap **Input Format** - The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ p[i] ≤ 10^9). **Output Format** - a single line — the maximum possible value of sum. **Sample Input 0** ``` 5 2 1 1 2 3 4 5 ``` **Sample Output 0** ``` 9 ``` **Explanation 0** here we need to partition the array into k = 1 partition, and the partition has to have 2 numbers, so the partitions we have here is from index 1 to 2 -> sum = 3 from index 2 to 3 -> sum = 5 from index 3 to 4 -> sum = 7 from index 4 to 5 -> sum = 9 so the maximum sum is 9 for the last partition **Sample Input 1** ``` 7 1 3 2 10 7 18 5 33 0 ``` **Sample Output 1** ``` 61 ``` **Explanation 1** here we need to select 3 partitions with 1 number, so we can select the three maximum numbers of the array 33 + 18 + 10 = 61 <file_sep>// // Created by <NAME> on 09/05/2021. // #include "iostream" #include "vector" #include "unordered_map" enum QueryType { SUB_TREE_SIZE = 1, SUB_TREES_COUNT = 2, }; struct Node { [[maybe_unused]] int index; Node *left, *right; }; /// a helper function to allocate a new node Node* createNode(int index) { Node* node = (Node*)malloc(sizeof(Node)); node->index = index; return node; } /// get the tree size from the current node /// tree sizes are cached results from previous recursions /// to speed up calculating tree size int getTreeSize(Node *root, std::unordered_map<int, int> &treeSizes){ if(root == nullptr){ return 0; } /// if key is found /// return the stored size if(treeSizes.find(root->index) != treeSizes.end()){ return treeSizes[root->index]; } /// else key is not found /// store the value int size = 1 + getTreeSize(root->left, treeSizes) + getTreeSize(root->right, treeSizes); treeSizes[root->index] = size; return size; } /// get subtrees count based on the given size void getSubTreesCount(Node* root,int size , int &count, std::unordered_map<int, int>& treeSizes) { if (root == nullptr) return; int leftSize = getTreeSize(root->left, treeSizes); int rightSize = getTreeSize(root->right, treeSizes); if (leftSize == size) { count++; } /// only go to the next left node when the size of its subtree is greater than the given size if (leftSize > size){ getSubTreesCount(root->left, size, count, treeSizes); } if (rightSize == size) { count++; } /// only go to the next right node when the size of its subtree is greater than the given size if (rightSize > size){ getSubTreesCount(root->right, size, count, treeSizes); } } /// \IMPLEMENTATION DONE /// \TESTCASES PASSED 10 out of 11 int main() { /// the number of nodes in the tree N. /// and number of queries Q int N, Q; std::cin>>N; std::vector<Node*> nodes(N); /// initialize array of nodes for (int i = 0; i < N; i++) { nodes[i] = createNode(i+1); } for (int i = 0; i < N; i++) { int leftIndex, rightIndex; std::cin >> leftIndex >> rightIndex; if (leftIndex == -1) { nodes[i]->left = nullptr; } else { nodes[i]->left = nodes[leftIndex-1]; } if (rightIndex == -1) { nodes[i]->right = nullptr; } else { nodes[i]->right = nodes[rightIndex-1]; } } std::cin>>Q; /// a vector to hold query data std::vector<std::pair<int, int>> queries(Q); /// temp pair to store user data std::pair<int, int> queryData; for (int i = 0; i < Q; i++) { std::cin >> queryData.first; std::cin >> queryData.second; queries[i] = queryData; } /// a map that holds tree size for each node /// key corresponds to the node index, value is the tree size for that node std::unordered_map<int, int> treeSizes; for (int i = 0; i < Q; i++) { /// loop over all the queries and execute them switch (queries[i].first) { /// if type one, print the tree size case QueryType::SUB_TREE_SIZE : { /// [queries[i].second] is the node number Node* requestedNode = nodes[queries[i].second - 1]; std::cout<<getTreeSize(requestedNode, treeSizes)<<std::endl; break; } /// if type two, print the count of subtrees that has the same given size case QueryType::SUB_TREES_COUNT : { /// [queries[i].second] is the requested size int requestedSize = queries[i].second; int count = 0; if (getTreeSize(nodes[0], treeSizes) == requestedSize) count++; getSubTreesCount(nodes[0], requestedSize, count, treeSizes); std::cout<<count<<std::endl; break; } } } return 0; } <file_sep>#include <iostream> #include <typeinfo> #include <typeindex> #include <unordered_map> #include <string> #include <memory> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; void checkMission(int sum, vector<int> coins, int total,int& result, int n,int index){ if(sum == total) result = 1; if(n==index) return; checkMission(sum + coins[index], coins, total, result, n, index+1); checkMission(sum, coins, total,result, n, index+1); } int main(){ int total; cin>>total; int size; cin>>size; vector<int> coins(size); for(int i =0;i<size;i++){ cin>>coins[i]; } int result = 0; checkMission(0, coins, total,result, size, 0); cout<<result<<endl; return 0; } <file_sep>#include <iostream> #include <typeindex> #include <unordered_map> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; void generateRoutes(vector<int> generatedRoutes, vector<int> routes, vector<bool> isUsed, int n,int index, vector<vector<int>> matrix, int& isTripPossible){ if(isTripPossible == 1) return; if(index == n){ if(matrix[generatedRoutes[0]][0] ==0){ return; } for(int i =0;i<generatedRoutes.size() - 1; i++){ if(matrix[generatedRoutes[i]][generatedRoutes[i+1]] ==0){ return; } } if(matrix[generatedRoutes[generatedRoutes.size()-1]][0] ==0){ return; } isTripPossible = 1; return; } for(int i =0; i < n ; ++i) { if(!isUsed[i]){ isUsed[i] = true; generatedRoutes.push_back(routes[i]); generateRoutes(generatedRoutes, routes,isUsed, n, index +1, matrix, isTripPossible); generatedRoutes.pop_back(); isUsed[i] = false; } } } int main() { int galxNo; cin>>galxNo; int edgesNo; cin>>edgesNo; vector<vector<int>> matrix(galxNo, vector<int>(galxNo)); int val1, val2; for(int i = 0; i<edgesNo;i++){ cin>>val1>>val2; matrix[val1][val2] = 1; matrix[val2][val1] = 1; for(int j = 0;j<galxNo;j++){ if(i==j){ matrix[i][j] = 0; } } } vector<int> routes (galxNo -1); for(int i = 0; i<galxNo -1;i++){ routes[i] = i + 1; } vector<int> generatedRoutes; vector<bool> isUsed(galxNo -1, false); int isTripPossible = 0; generateRoutes(generatedRoutes,routes,isUsed,galxNo - 1,0, matrix,isTripPossible); cout<<isTripPossible; return 0; } <file_sep># [Boss Lair](https://www.hackerrank.com/contests/cmpn302-fall2021-hw1/challenges/boss-lair) You are a hero entering a boss’s lair. The consists of N floors. Each _floor is square shaped and consists of multiple square-shaped rooms of similar size. Each _floor has N rows by N columns of rooms. From each room, you can access the same room in the _floor above, and the rooms to your right, and bottom directions. Upon entering each room, you pay a certain amount of gold. You enter from the lowest _floor from the room to the top left. The boss is at the highest _floor in the room to the bottom right. Given the amount paid for each room, find the minimum amount of gold needed to reach the boss’s room. You are required to answer the question above using brute force implemented using recursion. **Input Format** - The first line will contain N. - The next N lines will contain N numbers each denoting the gold required for each room in _floor 0 (lowest _floor). (Hint: you can input these numbers using cin normally. “cin >> var1 >> var2) - For each remaining _floor the same format is repeated. **Constraints** - 1 <= N <= 7. - Coins for each room is between 0 and 10000. - You cannot visit a room twice **Output Format** - The minimum amount of gold required to reach the boss’s room. **Sample Input 0** ``` 2 10 15 12 13 25 8 2 3 ``` **Sample Output 0** ``` 27 ``` **Explanation 0** The path taken is (10, 12, 2, 3)<file_sep># [Subtree Size](https://www.hackerrank.com/contests/cmpn302-fall2021-lab4/challenges/subtree-size) Mike and Tanya are bored, so they decided to play a game, Mike will create a tree rooted at node 1 and give it to Tanya, and she has to answer two types of queries type1- given a node on the tree she has to figure out the size of the node's subtree type2- given a size x she has to count the number of subtrees that have size x She will have to answer Q queries correctly to win, otherwise she will lose the game. You are allowed to use unordered_map and unordered_set if needed **Input Format** - The first line contains n, number of nodes in the tree. - Each of the next n lines contains two integers, a b, where a is the index of left child, and b is the index of right child of ith node. - Note: -1 is used to represent a null node. - The next line contains an integer q, the number of quires - Each of the next q lines contains two integers, x,y where x is the query type and y is the node number or a size value **Constraints** - 1 <= n <= 10000 - a = -1 or 2 <= a <= n - b = -1 or 2 <= b <= n - 1 <= q <= 100000 - x= {1,2} - 1 <= y <= 100000 **Output Format** for each query output the result on a single line **Sample Input 0** ``` 3 2 3 -1 -1 -1 -1 2 1 1 2 1 ``` **Sample Output 0** ``` 3 2 ``` **Sample Input 1** ``` 5 2 3 -1 4 -1 5 -1 -1 -1 -1 4 1 1 1 5 1 2 2 5 ``` **Sample Output 1** ``` 5 1 2 1 ``` <file_sep># [Treasure Cave 1](https://www.hackerrank.com/contests/cmpn302-fall2021-hw1/challenges/treasure-cave-1) Your team have stumbled upon a cave full of treasures, you have equipment that can hold up to a maximum weight W. The cave has a set of items each with a weight and a value. You can choose to take whichever items under the condition that the sum of weights of the chosen items is less than the maximum weight W. You are required to find the maximum total value with weight less than or equal to the given limit W. You are required to answer the question above using brute force implemented using recursion. **Input Format** - The first line will contain the limit W. - The second line will contain the number of items N. - The next N lines will contain an item each. Each line will contain two space-separated numbers representing the weight and the value of the item respectively. **Constraints** - Each item can be chosen once. - Number of items can be from 0 to 25. - W is between 1 and 10000 - Each item weight and value is between 1 and 10000 **Output Format** - One number indicating the maximum value. **Sample Input 0** ``` 14 5 2 2 12 4 1 1 1 2 4 10 ``` **Sample Output 0** ``` 15 ``` **Explanation 0** Items taken are items (0, 2, 3, 4) with value 15 and weight of 6. **Sample Input 1** ``` 10 4 7 3 1 2 4 2 6 6 ``` **Sample Output 1** ``` 8 ``` **Explanation 1** Items taken are items (1, 3) with value 8 and weight of 7.<file_sep>#!/bin/sh DIR="" CHALLENGE_NUM=0 if [ $# -eq 0 ] then echo "Missing options!" echo "(run $0 -h for help)" echo "" exit 1 fi while getopts "h" OPTION; do case $OPTION in h) echo "Usage:" echo "$0 <algorithm> <challenge number>" echo "" echo "available options: " echo "1) brute_force 2) sorting 3) trees 4) db" echo "" exit 0 ;; *) esac done if [ "$1" = "brute_force" ]; then DIR="1_brute_force" elif [ "$1" = "sorting" ]; then DIR="2_sorting" elif [ "$1" = "trees" ]; then DIR="3_trees" elif [ "$1" = "db" ]; then DIR="4_dynamic_programming" else echo "not supported" fi CHALLENGE_NUM=$2 while [ ${#CHALLENGE_NUM} -lt 2 ] ; do CHALLENGE_NUM="0${CHALLENGE_NUM}" done echo " add_executable("$DIR"_ch$CHALLENGE_NUM $DIR/challenge_$CHALLENGE_NUM/main.cpp) " >> CMakeLists.txt mkdir "$DIR/challenge_$CHALLENGE_NUM" cd "$DIR/challenge_$CHALLENGE_NUM" || exit echo " #include <iostream> using std::cin; using std::cout; using std::endl; /// \IMPLEMENTATION - /// \TESTCASES - int main(){ } " > main.cpp echo " # [<challenge_name>](<challenge_rrl>) <description> **Input Format** - **Constraints** - **Output Format** - **Sample Input 0** ``` ``` **Sample Output 0** ``` ``` **Explanation 0** " > readme.md <file_sep>// // Created by <NAME> on 05/05/2021. // #include <cmath> #include "iostream" #include "vector" void buildBinaryTree(std::vector<int> &binaryTree, std::vector<int> inOrder,int length , int index,int level, int i) { /// if tree contains only one element, exit the function if(length == 1) return; /// loop over all the nodes in the current level, /// No of nodes is 2^currentLevel for (int j = 0; j < static_cast<int>(pow(2, level)); ++j) { /// the current index is half the tree at that level, /// at level 1 => index = 7 => current index = 3, which is the index of the first node in that level int currentIndex = (index / 2) + (index + 1) * j; binaryTree[i] = inOrder[currentIndex]; i++; /// if binary tree size equals to the inOrder size, exit the function if (i == length) return; } /// call recursively with half the index, and with the next level of the tree buildBinaryTree(binaryTree, inOrder, length, index / 2, level + 1, i); } int main() { /// number of nodes int N; std::cin>> N; /// the inorder traversal of the tree std::vector<int> inOrder (N); for (int i = 0; i < N; i++) { std::cin>>inOrder[i]; } /// the perfect binary tree std::vector<int> binaryTree (N); /// initialize the binary tree with root (the root is the middle node in the inorder trv tree binaryTree[0] = inOrder[N/2]; /// first 3 args are the trees and its length, /// the index is half of the tree, level is the current level of the tree, /// and i the current index to add element at in binaryTree buildBinaryTree(binaryTree, inOrder, N, N/2, 1, 1); for (int i = 0; i < N; i++) { std::cout<<binaryTree[i]<< " "; } return 0; } <file_sep>// // Created by <NAME> on 11/03/2022. // #include <iostream> #include <climits> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; #define ROW_SIZE 3 #define TOP_LEFT_INDEX 0 #define BOTTOM_LEFT_INDEX 6 bool inGrid(int cellIndex, int gridSize){ return cellIndex >= 0 && cellIndex < gridSize; } void maxCarrots(int& currentCarrotsMax,int carrotsCount, const vector<int>& carrotsCountGrid, int cellIndex, vector<bool> visited, int currentJumps, int minJumps){ /// indicates what visited cells till now visited[cellIndex] = true; currentJumps += 1; /// add cell count to current carrots counts carrotsCount += carrotsCountGrid[cellIndex]; /// check if current carrots count is greater than the max if(carrotsCount > currentCarrotsMax){ /// update max carrots currentCarrotsMax = carrotsCount; } /// if both are negative, if(carrotsCount < 0 && currentCarrotsMax < 0){ if(carrotsCount < currentCarrotsMax && currentJumps <= minJumps){ currentCarrotsMax = carrotsCount; } } /// exit condition /// we reached the last cell if(cellIndex == BOTTOM_LEFT_INDEX){ return; } int gridSize = carrotsCountGrid.size(); int topCellIndex = cellIndex - ROW_SIZE; int downCellIndex = cellIndex + ROW_SIZE; int topRightCellIndex; int topLeftCellIndex; int downRightCellIndex ; int downLeftCellIndex ; /// means we are at the right edge of grid if((topCellIndex+1) % ROW_SIZE == 0){ /// set right cells as out of grid topRightCellIndex = -1; downRightCellIndex = -1; } else { topRightCellIndex = topCellIndex + 1; downRightCellIndex = downCellIndex + 1; } /// means we are at the left edge of grid if(topCellIndex % ROW_SIZE == 0){ /// set left cells as out of grid topLeftCellIndex = -1; downLeftCellIndex = -1; } else { topLeftCellIndex = topCellIndex - 1; downLeftCellIndex = downCellIndex - 1; } if(inGrid(topCellIndex, gridSize) && !visited[topCellIndex]){ maxCarrots(currentCarrotsMax, carrotsCount, carrotsCountGrid, topCellIndex, visited, currentJumps,minJumps); } if(inGrid(downCellIndex, gridSize) && !visited[downCellIndex]){ maxCarrots(currentCarrotsMax, carrotsCount, carrotsCountGrid, downCellIndex, visited, currentJumps,minJumps); } if(inGrid(topRightCellIndex, gridSize) && !visited[topRightCellIndex]){ maxCarrots(currentCarrotsMax, carrotsCount , carrotsCountGrid, topRightCellIndex, visited, currentJumps,minJumps); } if(inGrid(topLeftCellIndex, gridSize) && !visited[topLeftCellIndex]){ maxCarrots(currentCarrotsMax, carrotsCount , carrotsCountGrid, topLeftCellIndex, visited, currentJumps,minJumps); } if(inGrid(downRightCellIndex, gridSize) && !visited[downRightCellIndex]){ maxCarrots(currentCarrotsMax, carrotsCount , carrotsCountGrid, downRightCellIndex, visited, currentJumps,minJumps); } if(inGrid(downLeftCellIndex, gridSize) && !visited[downLeftCellIndex]){ maxCarrots(currentCarrotsMax, carrotsCount , carrotsCountGrid, downLeftCellIndex, visited, currentJumps,minJumps); } currentJumps -= 1; visited[cellIndex] = false; } /// \IMPLEMENTATION STOPPED /// \TESTCASES 6 / 15 int main(){ /// holds each cell carrots counts vector<int> grid(9); /// holds a boolean for each cell if it's previously visited or not vector<bool> visited(9, false); for (int & i : grid) { cin>>i; } int max = INT_MIN; maxCarrots(max, 0, grid, TOP_LEFT_INDEX, visited, 0, 3); cout<<max; } <file_sep># [Subtrees With Similar Size and Sum](https://www.hackerrank.com/contests/cmpn302-fall2021-hw3/challenges/subtrees-with-similar-size-and-sum) Given a binary tree determine if there exist two or more subtrees of size bigger than M that have the exact summation and exact size. You are allowed to use unordered_map and unordered_set if needed **Input Format** - The first line will contain the number of nodes in the tree N and the size M. - The following N numbers will contain the data in each node. - The next line will contain the number of edges in the tree E. - The following E lines will contain 3 values: - L or R to represent of this is a left or right child - Index of the parent. - Index of the child. **Constraints** - N is between 1 and 10^6 - Node 0 is always the root - Node values are between 1 and 10^4 **Output Format** One line containing 0 if no such subtrees exist and 1 otherwise. **Sample Input 0** ``` 7 1 4 2 6 4 15 5 10 6 L 0 1 R 0 2 L 1 3 R 1 4 L 2 5 R 2 6 ``` **Sample Output 0** ``` 1 ``` **Explanation 0** There exist two subtrees of size 3 with sum of 21. (2,4,15) and (6,5,10) ![img.png](img.png) <file_sep># [Galaxy Visiting](https://www.hackerrank.com/contests/cmpn302-fall2021-hw1/challenges/galaxy-visiting) Your team was able to find a group of wormholes connecting galaxies with each other. Starting from our galaxy you wish to visit each galaxy exactly once and then return to our galaxy. Some galaxies pairs are connected via a wormhole directly, and some are not. Your goal is to start at our galaxy, pass each galaxy exactly once and finish at our galaxy. The galaxies are represented as vertices in a graph and wormholes are represented as edges in an undirected graph. Given the graph, output 1 if such cycle exists and 0 otherwise. You are required to answer the question above using brute force implemented using recursion. **Input Format** - The first line will contain N, the number of galaxies (vertices). - The second line will contain E, the number of wormholes (edges). - The next E lines will contain an edge each. Each line will contain two space-separated numbers representing the vertices connected with the edge **Constraints** - Number of galaxies - including ours - varies between 1 and 10. - Our galaxy is always vertex 0 - Edges varies between 0 and (N*(N-1))/2 **Output Format** - 1 if the trip is possible 0 otherwise. **Sample Input 0** ``` 4 5 0 1 0 2 1 2 1 3 2 3 ``` **Sample Output 0** ``` 1 ``` **Explanation 0** This input corresponds to the following ![img.png](img.png) The trip taken is 0 -> 1 -> 3 -> 2 -> 0. Other cycles exist.<file_sep>## Implementations of some algorithms using c++ ### Topics - #### Brute Force - [Challenge 01](1_brute_force/challenge_01) - [Challenge 02](1_brute_force/challenge_02) - [Challenge 03](1_brute_force/challenge_03) - [Challenge 04](1_brute_force/challenge_04) - [Challenge 05](1_brute_force/challenge_05) - [Challenge 06](1_brute_force/challenge_06) - [Challenge 07](1_brute_force/challenge_07) - [Challenge 08](1_brute_force/challenge_08) - [Challenge 09](1_brute_force/challenge_09) - #### Sorting - [Insertion Sort](2_sorting/algorithms/insertion_sort.h) - [Selection Sort](2_sorting/algorithms/selection_sort.h) - [Quick Sort](2_sorting/algorithms/quick_sort.h) - #### Trees - [Challenge 01](3_trees/challenge_01) - [Challenge 02](3_trees/challenge_02) - [Challenge 03](3_trees/challenge_03) - [Challenge 04](3_trees/challenge_04) - [Challenge 05](3_trees/challenge_05) - #### Dynamic Programming - [Challenge 01](4_dynamic_programming/challenge_1) - [Challenge 02](4_dynamic_programming/challenge_2) - [Challenge 03](4_dynamic_programming/challenge_3) <file_sep>// // Created by <NAME> on 06/03/2022. // #include <iostream> #include <set> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; using std::set; long vectorSum(const set<long>& vec){ long sum = 0; for (long element: vec) { sum+=element; } return sum; } void findMaxCells(vector<long> cells, set<long> generated, int &maxCells, int cellsLength, int level){ long sum = vectorSum(generated); if(sum == 0 && generated.size() > maxCells){ maxCells = generated.size(); } if(level == cellsLength) return; findMaxCells(cells, generated,maxCells, cellsLength, level + 1); generated.insert(cells[level]); findMaxCells(cells, generated, maxCells,cellsLength, level + 1); } /// \IMPLEMENTATION DONE /// \TESTCASES PASSED int main() { int M,N; cin>>N>>M; vector<long> cells(N*M); for (int i = 0; i < N * M; ++i) { cin>>cells[i]; } int maxCells = 0; findMaxCells(cells, {}, maxCells,N*M,0); cout<<maxCells; } <file_sep>#include <iostream> #include <typeinfo> #include <typeindex> #include <unordered_map> #include <string> #include <memory> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; void generateTeam(vector<int> team, int teamSize,int index, vector<vector<int>> matrix, int& maxTeam){ if(team.size() !=0) { bool hasSyn = true; for(int i =0;i<team.size() - 1; i++){ for(int j = i+1;j<team.size();j++){ if(matrix[team[i]][team[j]] ==0) hasSyn = false; } } if(hasSyn && maxTeam < team.size()) { maxTeam = team.size(); }; } if(index == teamSize){ return; } generateTeam(team, teamSize, index +1, matrix, maxTeam); team.push_back(index); generateTeam(team, teamSize, index +1, matrix, maxTeam); } int main() { int teamSize; cin>>teamSize; int edgesNo; cin>>edgesNo; vector<vector<int>> matrix(teamSize, vector<int>(teamSize)); int val1, val2; for(int i = 0; i<edgesNo;i++){ cin>>val1>>val2; matrix[val1][val2] = 1; matrix[val2][val1] = 1; for(int j = 0;j<teamSize;j++){ if(i==j){ matrix[i][j] = 0; } } } vector<int> team; int maxTeam = 0; generateTeam(team, teamSize,0, matrix, maxTeam); cout<<maxTeam<<endl; return 0; } <file_sep>// // Created by <NAME> on 11/06/2021. // #include "iostream" #include "vector" #include <algorithm> int findMaxNumberOfOrders(const std::vector<long>& ordersValues, long noOfGrams){ int maxOrders = 0; long currentValue = 0; for (long ordersValue : ordersValues) { if(currentValue + ordersValue <= noOfGrams){ currentValue += ordersValue; maxOrders++; } else { break; } } return maxOrders; } int main() { int noOfOrders; long noOfGrams; std::cin>>noOfOrders>>noOfGrams; /// vector to hold each order's summed value std::vector<long> ordersValues(noOfOrders); long smallBurgerWeight, largeBurgerWeight; std::cin>>smallBurgerWeight>>largeBurgerWeight; for (int i = 0; i < noOfOrders; i++) { long noOfSmallBurgers, noOfLargeBurgers, orderValue; std::cin>>noOfSmallBurgers>>noOfLargeBurgers; orderValue = noOfSmallBurgers*smallBurgerWeight + noOfLargeBurgers*largeBurgerWeight; ordersValues[i] = orderValue; } /// sort the array in ascending order std::sort(ordersValues.begin(), ordersValues.end()); std::cout<<findMaxNumberOfOrders(ordersValues, noOfGrams); return 0; } <file_sep>cmake_minimum_required(VERSION 3.19) project(algorithms) set(CMAKE_CXX_STANDARD 17) add_executable(1_brute_force_ch01 1_brute_force/challenge_01/main.cpp) add_executable(1_brute_force_ch02 1_brute_force/challenge_02/main.cpp) add_executable(1_brute_force_ch03 1_brute_force/challenge_03/main.cpp) add_executable(1_brute_force_ch06 1_brute_force/challenge_06/main.cpp) add_executable(1_brute_force_ch07 1_brute_force/challenge_07/main.cpp) add_executable(1_brute_force_ch08 1_brute_force/challenge_08/main.cpp) add_executable(2_sorting 2_sorting/sort.cpp) add_executable(3_trees_ch01 3_trees/challenge_01/main.cpp) add_executable(3_trees_ch02 3_trees/challenge_02/main.cpp) add_executable(3_trees_ch03 3_trees/challenge_03/main.cpp) add_executable(3_trees_ch04 3_trees/challenge_04/main.cpp) add_executable(3_trees_ch05 3_trees/challenge_05/main.cpp) add_executable(4_dynamic_programming_ch01 4_dynamic_programming/challenge_1/main.cpp) add_executable(4_dynamic_programming_ch02 4_dynamic_programming/challenge_2/main.cpp) add_executable(4_dynamic_programming_ch03 4_dynamic_programming/challenge_3/main.cpp) add_executable(1_brute_force_ch09 1_brute_force/challenge_09/main.cpp) <file_sep>#include <vector> class SelectionSort { private: public: static void sort(int* list, int size) { int min; for(int i = 0 ; i < size-1 ; i++) { min = i; for (int j = i+1; j < size; j++) { if(list[j] < list[min]) { min = j; } } // swap list[min] with list[i] if(min != i) { int temp = list[i]; list[i] = list[min]; list[min] = temp; } } }; };<file_sep>// // Created by <NAME> on 07/05/2021. // #include "iostream" #include "vector" struct Node { int data; Node *left, *right, *parent; }; Node* createNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; return node; } int getTreeSize(Node *root){ /// get the tree size from the current node /// for opt. get it in treeSum if(root == nullptr){ return 0; } else{ return 1 + getTreeSize(root->left) + getTreeSize(root->right); } } // TODO need handling corner case where subtrees are not next to each other int treeSum(Node *root, int &count, int maxSize) { if (root == nullptr) return 0; /// using postOrder traversal to start from bottom first then going up int leftSum = treeSum(root->left, count, maxSize); int rightSum = treeSum(root->right, count, maxSize); /// if the sum of the left subtree is equal to right subtree and equal to zero, /// and if both has the same size => increment the counter if(leftSum == rightSum && leftSum != 0) { ///check if same size (-needs refactoring) and if greater than M int leftTreeSize = getTreeSize(root->left); int rightTreeSize = getTreeSize(root->right); if(leftTreeSize == rightTreeSize && leftTreeSize > maxSize){ count++; } } return leftSum + rightSum + root->data; } int isSameSumAndSize(Node *root, int maxSize) { int count = 0; treeSum(root,count ,maxSize); if (count > 0) return 1; return 0; } int main() { /// the number of nodes in the tree N, the size M and edges in the tree E. int N, M, E; std::cin>>N>>M; std::vector<Node*> nodes (N); for (int i = 0; i < N; i++) { int data; std::cin>>data; nodes[i] = createNode(data); } std::cin>>E; for (int i = 0; i < E; i++) { char child; int parentIndex, childIndex; std::cin>>child>>parentIndex>>childIndex; /// fill nodes vector with data from input if(child == 'L') nodes[parentIndex]->left = nodes[childIndex]; else nodes[parentIndex]->right = nodes[childIndex]; } int result = isSameSumAndSize(nodes[0], M); std::cout<<result; return 0; } <file_sep># [Measuring Christmas Tree](https://www.hackerrank.com/contests/cmpn302-fall2021-hw3/challenges/measuring) Santa is giving christmas trees with only two lengths X and Y. He needs to make sure that the tree length is exactly X or Y and for doing so he has a measuring tape but it has strange distances, it starts with 0 and ends with L and in the middle it has some numbers that represent distances. To measure distance D with the tape there should be a pair of numbers on the tape V1 and V2 such that V2 - V1 = D. Your task is to determine what is the minimum number of additional distances you need to add to the tape so that they can be used to measure the distances x and y. You are allowed to use unordered_map and unordered_set if needed *A perfect binary tree is a binary tree in which all interior nodes have two children and all leaves have the same depth or same level **Input Format** - The first line contains four positive space-separated integers N, L, X, Y — the number of distances on the measuring tape, the length of the measuring tape and the two allowed lengthes of the trees - The second line contains a sequence of n integers a1, a2, ..., an (0 = a1 < a2 < ... < an = l), where ai shows the distance between number i from the origin **Constraints** - (2 ≤ n ≤ 105, 2 ≤ l ≤ 109, 1 ≤ x < y ≤ l) **Output Format** print a single non-negative integer v — the minimum number of distances that you need to add on the tape. **Sample Input 0** ``` 3 250 185 230 0 185 250 ``` **Sample Output 0** ``` 1 ``` **Explanation 0** In the first sample it is impossible to initially measure the distance of 230 centimeters. For that it is enough to add a 20 centimeter mark or a 230 centimeter mark. **Sample Input 1** ``` 4 250 185 230 0 20 185 250 ``` **Sample Output 1** ``` 0 ``` <file_sep>#include <iostream> #include <typeinfo> #include <typeindex> #include <string> #include <fstream> #include <chrono> #include "./algorithms/insertion_sort.h" #include "./algorithms/selection_sort.h" #include "./algorithms/quick_sort.h" #include "./algorithms/merge_sort.h" using std::cin; using std::cout; using std::endl; using std::chrono::duration; using std::chrono::duration_cast; using std::chrono::high_resolution_clock; using std::chrono::milliseconds; int main(int argc, char **argv) { if (argc < 4) return -1; int algNum; char *inputFile; char *outputFile; char *timeFile; try { algNum = std::stoi((argv[1])); inputFile = argv[2]; outputFile = argv[3]; timeFile = argv[4]; } catch (std::exception const &e) { cout << "error : " << e.what() << endl; return -1; } std::fstream file; int *data = new int(); int size = 0; file.open(inputFile, std::fstream::in); if (file.is_open()) { std::string tp; while (getline(file, tp)) { data[size] = stoi(tp); size++; } file.close(); // close the file object. } else { cout << "error : " << "couldn't read data" << endl; return -1; } auto start = high_resolution_clock::now(); switch (algNum) { case 0: SelectionSort::sort(data, size); break; case 1: InsertionSort::sort(data, size); break; case 2: MergeSort::sort(data, 0, size); break; case 3: QuickSort::sort(data, 0, size); break; } auto end = high_resolution_clock::now(); /* Getting number of milliseconds as an integer. */ auto elapsed_seconds = duration_cast<milliseconds>(end - start); file.open(outputFile, std::fstream::out | std::fstream::trunc); if (file.is_open()) { for(int i =0; i < size; i++) { file << data[i] << std::endl; } file.close(); //close the file object. } else { cout << "error : " << "couldn't write sorted data" << endl; return -1; } file.open(timeFile, std::fstream::out | std::fstream::app); if (file.is_open()) { file << inputFile << " : " << elapsed_seconds.count() << "ms" << std::endl; file.close(); //close the file object. } else { cout << "error : " << "couldn't write time" << endl; return -1; } return 0; } <file_sep>// // Created by <NAME> on 11/06/2021. // #include "iostream" #include "vector" #include <algorithm> long findMinimumSteps(std::vector<long> blocks,int noOfBlocks){ long minSteps = 0; long minHeight = *std::min_element(blocks.begin(), blocks.end()); minSteps += minHeight; for (int i = 0; i < noOfBlocks; i++) { if (blocks[i] > minHeight) { if (i == noOfBlocks -1){ minSteps++; break; } for (int j = i+1; j < noOfBlocks; j++) { if (blocks[j] != blocks[i]){ minSteps++; i = j-1; break; } } } } return minSteps < noOfBlocks ? minSteps : noOfBlocks; } /// 7 test cases fail out of 21 int main() { int noOfBlocks; std::cin>>noOfBlocks; /// array to hold blocks, each block will be /// 1 m in width, and blocks[i] in height std::vector<long> blocks(noOfBlocks); for (int i = 0; i < noOfBlocks; i++) { std::cin>>blocks[i]; } std::cout<<findMinimumSteps(blocks, noOfBlocks); return 0; } <file_sep># [Dark streets](https://www.hackerrank.com/contests/cmpn302-fall2021-lab4/challenges/dark-streets) Bob fears the dark and unfortunately many streetlights in his neighborhood are broken. He wants to visit some of his friend today as he feels so lonely, so he needs some help. The streets are represented as a tree with root at node 1 and N Nodes, the leaves of the tree contains his friends. He needs to know which friend he can visit given that he can't take a path that have more than M consecutive dark streets. Count the number of friends he can visit. **Notes** : The tree is not binary, so the node may have multiple children, also it is not guaranteed that the edges will be given from parent to child so if node B has a parent A, the edge in the input could be B A or A B **Input Format** - The first line contains two integers, N and M — the number of nodes of the tree, and the maximum number of consecutive dark nodes - The second line contains n numbers either equals to 1 if the node is dark, or 0 otherwise. - Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the nodes of the tree, connected by an edge. - It is guaranteed that the given set of edges specifies a tree. **Constraints** - (2 ≤ n ≤ 10^5, 1 ≤ m ≤ n) **Output Format** The number of distinct leaves of the tree with a valid path **Sample Input 0** ``` 4 1 1 1 0 0 1 2 1 3 1 4 ``` **Sample Output 0** ``` 2 ``` **Sample Input 1** ``` 7 1 1 0 1 1 0 0 0 1 2 1 3 2 4 2 5 3 6 3 7 ``` **Sample Output 1** ``` 2 ``` <file_sep># [Full Synergy Team](https://www.hackerrank.com/contests/cmpn302-fall2021-lab1/challenges/full-synergy-team) You are a team coach and want to choose a team with the maximum full synergy possible. Players in your team are represented as vertices and synergy is represented as edges in an undirected graph. If there is an edge between two players, this means there is synergy between them. The team with maximum full synergy requires that each pair of players in the team has a synergy edge. You are required, given a graph, to output the size of the team satisfying the maximum full synergy constraint using non-optimized brute force solution. **Input Format** - The first line will contain N, the number of players (vertices). - The second line will contain E, the number of synergy edges (edges). - The next E lines will contain an edge each. Each line will contain two space-separated numbers representing the vertices connected with the edge. (Hint: you can input this numbers using cin normally. “cin >> var1 >> var2) **Constraints** - Number of vertices is from 1 to 17. - The output team size will vary between 1 to number of vertices. - Edges varies between 0 and (N*(N-1))/2 **Output Format** - The maximum size of a team in one line. **Sample Input 0** ``` 4 4 0 1 0 2 0 3 1 2 ``` **Sample Output 0** ``` 3 ``` **Explanation 0** This input corresponds to the following graph ![img.png](img.png)<file_sep># [A Project Team](https://www.hackerrank.com/contests/cmpn302-s2022-lab1/challenges/a-project-team) Given N student names, we want to form one project team of M students. It is required to print all possible combinations of students joining that team. You are given N unique characters representing the first character of each student name, It is required to print all possible combinations of strings of length M where each string contains the characters of its students. Strings should be printed in Lexicographic order, and the letters of the same string should be printed sorted too. Note: this problem is a combination problem not permutation (for example, team ABC and BAC are the same team). **Input Format** - one line containing N and M, space separated - one line containing N unique characters, space separated **Constraints** - N is from 1 to 20 - M is from 1 to 8 - N is larger than or equal M - the given characters are unique **Output Format** - print each string in a separate line, and strings are sorted in lexigraphical order **Sample Input 0** ``` 4 3 D C A B ``` **Sample Output 0** ``` ABC ABD ACD BCD ``` **Explanation 0** Note that there is only one string containing (A, B, C), which means that ABC and BAC are one. All strings are sorted and the letters in the same string are sorted too. <file_sep>#include <vector> class MergeSort { public: //TODO -- implement static void sort(int * list ,int start ,int end ) //end is length) { }; };<file_sep># [Carrots](https://www.hackerrank.com/contests/cmpn302-s2022-hw1/challenges/carrots-1) There are a Rabbit trying to collect the maximum number of carrots from a 3*3 grid that has: some cells containing carrots (positive cells), some cells containing more powerful rabbits that steal carrots (negative cells), and zero cells do not take or give carrots. In each jump, the rabbit can jump one step up, down, or in any of the four diagonals. The rabbit starts its journey from the top left cell and ends at the bottom left cell. The rabbit is forbidden to visit the same cell more than once in its journey. It is required to print the maximum number of carrots it can collect in its journey. Note: assume that if our rabbit has, for example, 5 carrots and passed by a cell of value -7, then the total carrots so far will be -2 (a negative number not zero) indicating that the two will be taken from it later. **Input Format** - 3 lines, each line represents a row and contains 3 numbers separated by spaces **Constraints** - cell values are from -1000 to 1000 **Output Format** - one line containing the maximum number of carrots the rabbit can collect in its journey **Sample Input 0** ``` 5 -1 -6 7 8 -7 6 -9 -8 ``` **Sample Output 0** ``` 25 ``` **Explanation 0** the path: 5 > 7 > -1 > 8 > 6 <file_sep>#include <vector> class InsertionSort { public: static void sort(int* list, int size) { int val, j; for (int i = 1; i < size; i++) { val = list[i]; j = i - 1; while (j>=0 && list[j] > val) { list[j + 1] = list[j]; j--; } list[j + 1] = val; } }; };<file_sep># [ZERO Sum Cells](https://www.hackerrank.com/contests/cmpn302-s2022-lab1/challenges/zero-sum-cells/problem) Given a 2D matrix of integers of size N*M, it is required to find the maximum number of cells that sum to 0 and do not have any duplicates. **Input Format** - one line containing N and M, space separated - the next N lines, each line contains M space separated numbers **Constraints** - N is from 1 to 4 - M is from 1 to 4 - cell values are from -10^9 to 10^9 **Output Format** - one line containing the maximum number of cells that sum to 0 and do not have any duplicates **Sample Input 0** ``` 3 3 3 -3 4 2 2 0 7 -2 -2 ``` **Sample Output 0** ``` 5 ``` **Explanation 0** The cells are: 3, -3, 2, 0, -2. Note that we cannot add the other 2, -2 because the chosen cells will be containing duplicates. **Sample Input 1** ``` 2 3 -3 0 3 2 1 0 ``` **Sample Output 1** ``` 4 ``` **Explanation 1** The cells: -3, 0, 2, 1. Note that -3, 0, 3 sum to zero but the length is 3 (less than 4). Note also that we cannot add the other 0 because of the duplicates condition.<file_sep># [Coin Game 6](https://www.hackerrank.com/contests/cmpn302-fall2021-lab1/challenges/coin-game-6) You are playing a game and you are given a collection of coins of size N where each coin has a value in pounds as an array of positive integers A [0...N-1]. You find a mission that requires you to collect exactly a total value of T pounds. Is it possible to take coins from A that sums to exactly T? You are required to answer the question above using non-optimized brute force solution. **Input Format** - The first line will contain T. - The second line will contain N, denoting the number of integers in the array A. - Each of the next N lines will contain an integer to build the array A. **Constraints** - Each coin A[i] can be taken once. - Range of N is from 1 to 25. - T value can be 0. **Output Format** - 1 if you can choose coins that sums to exactly T and 0 if you cannot. **Sample Input 0** ``` 10 4 2 1 5 1 ``` **Sample Output 0** ``` 0 ``` **Sample Input 1** ``` 10 3 5 2 3 ``` **Sample Output 1** ``` 1 ```<file_sep>#include <vector> class QuickSort{ public: static int _partition(int* list, int left,int right) { int pivot = list[right]; int storeIndex = left - 1; for (int i = left; i <= right -1; i++) { if(list[i] < pivot) { storeIndex++; //swap int temp = list[i]; list[i] = list[storeIndex]; list[storeIndex] = temp; } } int temp = list[storeIndex + 1]; list[storeIndex + 1] = list[right]; list[right] = temp; return storeIndex +1; }; static void sort(int* list, int left, int right) { if(left < right) { int pivot = _partition(list, left, right); sort(list, left, pivot - 1); sort(list, pivot +1 , right); } }; };
c99dbd168e0da83a25240e6f5af34e0ba9844c1d
[ "Markdown", "CMake", "C++", "Shell" ]
43
Shell
michaelsoliman1/Algorithms-DesignPatterns
68fc03c20dda72116dffc098ad14a025e68ee9b4
07df05f800bea5ace8f67104f42879ccf96f27ac
refs/heads/master
<repo_name>lai32290/nlw-proffy<file_sep>/mobile/README.md # Proffy Mobile ## How to Run Run the following command in the project folder terminal ``` # Moving into the mobile folder $ code mobile # Install the dependencies $ npm install # Run the server $ npm start ``` Now the terminal will provide a QR Code, install the Expo ([Android](https://play.google.com/store/apps/details?id=host.exp.exponent&hl=pt_BR) | [Iphone](https://apps.apple.com/br/app/expo-client/id982107779)) in your phone, and scan the QR Code to open the app using Expo. ## Screenshots ![Landing Page](../images/mobile-landing.jpg) ![Teacher List](../images/mobile-teacher-list.jpg) ![Teacher Register](../images/mobile-teacher-register.jpg) ![Favorites](../images/mobile-teacher-favorites.jpg)<file_sep>/README.md <h1 align="center"> <img src="images/web-landing.png?raw=true" alt="Web Landing Screenshot" /> Proffy </h1> Proffy is a platform to connect teacher and students, a place where people can choose what subject they want to teach/learn and what is the best day of the week they want to do it. ## Technologies Involved ### Backend - Node.js - Express - SQLite - Knex - TypeScript ### Frontend - React - TypeScript - React Router DOM - Axios ### Mobile - React Native - Axios ## How to Run - [Backend](server) - [Frontend](web) - [Mobile](mobile)<file_sep>/mobile/src/hooks/use-favorited.ts import { useEffect, useState, useCallback } from 'react'; import AsyncStorage from '@react-native-community/async-storage'; import { Teacher } from '../components/teacher-item'; function useFavorited(): [ Teacher[], any, any ] { const [ favorited, setFavorited ] = useState<Teacher[]>([]); const loadFavorited = useCallback(async () => { const response = await AsyncStorage.getItem('favorited'); let favorited = []; if (response) { favorited = JSON.parse(response); } setFavorited(favorited); }, [ setFavorited ]); useEffect(() => { loadFavorited(); }, [ loadFavorited ]); const updateFavorited = useCallback(async (favorited: Teacher[]) => { await AsyncStorage.setItem('favorited', JSON.stringify(favorited)); setFavorited(favorited); }, [ setFavorited ]); return [ favorited, updateFavorited, loadFavorited ]; } export default useFavorited;<file_sep>/server/README.md # Proffy Backend ## How to Run Run the following command in the project folder terminal ``` # Moving into the server folder $ code server # Install the dependencies $ npm install # Run the server $ npm start ``` In a new terminal, run the following command to create database and tables: ``` $ npm run knex:migrate ``` The server will be working in [http://localhost:3333](http://localhost:3333) <file_sep>/web/README.md # Proffy Frontend ## How to Run Run the following command in the project folder terminal ``` # Moving into the web folder $ code web # Install the dependencies $ npm install # Run the server $ npm start ``` Now the website is available in the [http://localhost:3000](http://localhost:3000) ## Screenshots ![Landing Page](../images/web-landing.png) ![Teacher List](../images/web-teacher-list.png) ![Teacher Register](../images/web-teacher-register.png)
bc45849469bbc62ba059e398b9c603a1af35c3da
[ "Markdown", "TypeScript" ]
5
Markdown
lai32290/nlw-proffy
febb7d13acb4ff41f1d895a621754d498f9abd36
3e96c6c6c2ef3e7d45455f62be87e36d8f06be1a
refs/heads/master
<repo_name>wilsonzlin/cabinet<file_sep>/src/client/_common/ui.ts import { Duration } from "luxon"; import { useEffect, useRef, useState } from "react"; export const useScreenDimensions = () => { const [height, setHeight] = useState(0); const [width, setWidth] = useState(0); useEffect(() => { const listener = () => { setHeight(document.documentElement.clientHeight); setWidth(document.documentElement.clientWidth); }; const EVENTS = ["orientationchange", "resize"]; for (const e of EVENTS) { window.addEventListener(e, listener, true); } return () => { for (const e of EVENTS) { window.removeEventListener(e, listener, true); } }; }, []); return { height, width }; }; export const useElemDimensions = (elem: HTMLElement | null | undefined) => { // Do not use elem.offset{Height,Width} for initialState, // as they'll be expensively called for every invocation of this function, // but discarded immediately by useState. const [height, setHeight] = useState(0); const [width, setWidth] = useState(0); const observer = useRef( new ResizeObserver((entries) => { for (const entry of entries) { setHeight(entry.contentRect.height); setWidth(entry.contentRect.width); } }) ); useEffect(() => { console.warn("WARN PERF: Reattaching ResizeObserver"); if (elem) { observer.current.observe(elem); return () => observer.current.unobserve(elem); } return; }, [elem]); return { height, width }; }; export const formatDur = (seconds: number | Duration) => { const dur = Duration.isDuration(seconds) ? seconds : Duration.fromMillis(seconds * 1000); return dur.toFormat(dur.as("hours") >= 1 ? "h:mm:ss" : "m:ss"); }; // https://stackoverflow.com/a/9039885/6249022. export const isIos = () => [ "iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod", ].includes(navigator.platform) || // iPad on iOS 13 detection (navigator.userAgent.includes("Mac") && "ontouchend" in document); const round = (n: number, places: number) => Math.round(n * 10 ** places) / 10 ** places; export const formatSize = (s: number) => { if (s < 900) { return `${s} B`; } s /= 1024; if (s < 900) { return `${round(s, 2)} KB`; } s /= 1024; if (s < 900) { return `${round(s, 2)} MB`; } s /= 1024; if (s < 900) { return `${round(s, 2)} GB`; } s /= 1024; return `${round(s, 2)} TB`; }; <file_sep>/src/util/fs.ts import maybeFileStats from "@xtjs/lib/js/maybeFileStats"; import { rename, writeFile } from "fs/promises"; import { basename, dirname, join } from "path"; const winattr = require("winattr"); type WindowsFileAttributes = { archive: boolean; hidden: boolean; system: boolean; readonly: boolean; }; const getWindowsFileAttributes = ( file: string ): Promise<WindowsFileAttributes> => new Promise((resolve, reject) => { winattr.get(file, (err: Error, attrs: WindowsFileAttributes) => { if (err) { reject(err); } else { resolve(attrs); } }); }); export const isHiddenFile = (path: string) => process.platform === "win32" ? getWindowsFileAttributes(path).then(({ hidden }) => hidden) : basename(path)[0] === "."; export class LazyP<T> { private called = false; private value: any; constructor(private readonly provider: () => Promise<T>) {} compute(): Promise<T> { if (this.called) { return this.value; } this.called = true; return (this.value = this.provider()); } } export type ComputedFile = { absPath: string; size: number; }; export const getFileMetadata = async (absPath: string) => { const stats = await maybeFileStats(absPath); if (stats && stats.size > 0) { return { size: stats.size, }; } return undefined; }; export class ComputedFileError extends Error {} export function computedFile( absPath: string, provider: (incompleteAbsPath: string) => Promise<unknown>, errorMsg: string ): Promise<ComputedFile>; export function computedFile( absPath: string, provider: (incompleteAbsPath: string) => Promise<unknown> ): Promise<ComputedFile | undefined>; export async function computedFile( absPath: string, provider: (incompleteAbsPath: string) => Promise<unknown>, // If provided, an exception will be thrown on failure. // If not provided, a marker file will be written to prevent any future attempts creating the same file, and undefined will be returned. errorMsg?: string ) { // Ensure incomplete path keeps extension to allow programs like ffmpeg to continue to autodetect output format. const incompleteAbsPath = join( dirname(absPath), `.incomplete_${basename(absPath)}` ); const failedAbsPath = join(dirname(absPath), `.failed_${basename(absPath)}`); if (await maybeFileStats(failedAbsPath)) { return undefined; } let meta; if (!(meta = await getFileMetadata(absPath))) { await provider(incompleteAbsPath); meta = await getFileMetadata(incompleteAbsPath); if (!meta) { if (errorMsg != undefined) { throw new ComputedFileError(errorMsg); } // If this fails, allow crash. await writeFile(failedAbsPath, ""); return undefined; } await rename(incompleteAbsPath, absPath); } return { absPath, size: meta.size, }; } <file_sep>/src/api/_common.ts import { Library } from "../library/model"; import { ApiOutput, Json } from "../server/response"; export type ApiCtx = { library: Library; // Path to scratch directory if available. scratch?: string; }; export type ApiFn = (ctx: ApiCtx, input: any) => Promise<ApiOutput>; export type ApiInput<A extends ApiFn> = Parameters<A>[1]; export type JsonApiOutput<A extends ApiFn> = ReturnType<A> extends Promise< Json<infer V> | undefined > ? V : never; <file_sep>/src/api/listFiles.ts import assertExists from "@xtjs/lib/js/assertExists"; import Dict from "@xtjs/lib/js/Dict"; import naturalOrdering from "@xtjs/lib/js/naturalOrdering"; import propertyComparator from "@xtjs/lib/js/propertyComparator"; import splitString from "@xtjs/lib/js/splitString"; import tokeniseForNaturalOrdering from "@xtjs/lib/js/tokeniseForNaturalOrdering"; import { sep } from "path"; import { Audio, Directory, DirEntry, File, Photo, Video, } from "../library/model"; import { ClientError, Json } from "../server/response"; import { ApiCtx } from "./_common"; export type ListedFolder = { type: "dir"; name: string; itemCount: number; }; type BaseListedFile = { path: string; name: string; size: number; modifiedMs: number; }; export type ListedAudio = BaseListedFile & { type: "audio"; duration: number; title?: string; author?: string; album?: string; genre?: string; track?: number; }; export type ListedPhoto = BaseListedFile & { type: "photo"; width: number; height: number; channels?: number; chromaSubsampling: string; colourSpace?: string; dpi?: number; format: string; orientation?: number; hasIccProfile?: boolean; isProgressive?: boolean; hasAlphaChannel?: boolean; }; export type ListedVideo = BaseListedFile & { type: "video"; width: number; height: number; duration: number; title?: string; author?: string; album?: string; genre?: string; track?: number; }; export type ListedMedia = ListedAudio | ListedVideo; type ResultsDirEntry = ListedFolder | ListedAudio | ListedPhoto | ListedVideo; type ResultsDir = { dir: string[]; entries: Array<ResultsDirEntry> }; export const listFilesApi = async ( ctx: ApiCtx, { path, filter, types, limit = Infinity, excludeFolders = false, subdirectories, }: { path: string[]; // Possible query parameters. filter?: string; types: ("audio" | "photo" | "video")[]; limit?: number; excludeFolders?: boolean; // Only valid when filter is also provided. subdirectories: boolean; } ): Promise< Json<{ results: ResultsDir[]; }> > => { const dir = await ctx.library.getDirectory(path); if (!dir) { throw new ClientError(404, "Directory not found"); } let totalResults = 0; const resultsByDir = new Dict<string, ResultsDirEntry[]>(); const visitDirEntry = async (e: DirEntry) => { if (totalResults > limit) { return; } const entries = resultsByDir.computeIfAbsent(e.dirRelPath(), () => []); if (e instanceof Directory && !subdirectories && !excludeFolders) { entries.push({ type: "dir", name: e.fileName(), itemCount: Object.keys(await e.entries.compute()).length, }); totalResults++; } else if (e instanceof File) { if (e instanceof Audio && types.includes("audio")) { entries.push({ type: "audio", path: e.relPath, name: e.fileName(), size: e.size, modifiedMs: e.modified.toMillis(), duration: e.duration(), author: e.metadata().artist, title: e.metadata().title, album: e.metadata().album, genre: e.metadata().genre, track: e.metadata().track, }); totalResults++; } else if (e instanceof Photo && types.includes("photo")) { entries.push({ type: "photo", path: e.relPath, name: e.fileName(), size: e.size, modifiedMs: e.modified.toMillis(), width: e.metadata.width, height: e.metadata.height, dpi: e.metadata.dpi, channels: e.metadata.channels, chromaSubsampling: e.metadata.chromaSubsampling, colourSpace: e.metadata.colourSpace, format: e.metadata.format, orientation: e.metadata.orientation, isProgressive: e.metadata.isProgressive, hasIccProfile: e.metadata.hasIccProfile, hasAlphaChannel: e.metadata.hasAlphaChannel, }); totalResults++; } else if (e instanceof Video && types.includes("video")) { entries.push({ type: "video", path: e.relPath, name: e.fileName(), size: e.size, modifiedMs: e.modified.toMillis(), width: e.width(), height: e.height(), duration: e.duration(), author: e.metadata().artist, title: e.metadata().title, album: e.metadata().album, genre: e.metadata().genre, track: e.metadata().track, }); totalResults++; } } }; if (filter) { if (subdirectories) { const ensureDirLoaded = async (dir: Directory) => { for (const e of Object.values(await dir.entries.compute())) { if (e instanceof Directory) { await ensureDirLoaded(e); } } }; await ensureDirLoaded(dir); } for (const relPath of await dir.search(filter, subdirectories)) { await visitDirEntry( assertExists(await ctx.library.getFile(relPath.join(sep))) ); } } else { for (const e of Object.values(await dir.entries.compute())) { await visitDirEntry(e); } } return new Json({ results: [...resultsByDir] .map(([dir, entries]) => ({ dir: splitString(dir, sep), entries: entries .map((entry) => ({ entry, tokens: tokeniseForNaturalOrdering(entry.name), })) .sort(propertyComparator("tokens", naturalOrdering)) .map(({ entry }) => entry), })) .sort(propertyComparator("dir")), }); }; <file_sep>/src/client/_common/search.ts export const parseSearchFilter = (raw: string) => { let subdirectories = false; raw = raw.trim(); if (raw.startsWith("~")) { subdirectories = true; raw = raw.slice(1).trim(); } // SQLite3 FTS5 trigram search requires at least 3 characters. if (raw.length <= 2) { return { filter: undefined, subdirectories: false }; } return { filter: raw, subdirectories }; }; <file_sep>/src/api/getFile.ts import mapValue from "@xtjs/lib/js/mapValue"; import assertExists from "@xtjs/lib/js/assertExists"; import mapDefined from "@xtjs/lib/js/mapDefined"; import maybeFileStats from "@xtjs/lib/js/maybeFileStats"; import { mkdir } from "fs/promises"; import { dirname, join } from "path"; import { Video } from "../library/model"; import { ClientError, Json, StreamFile } from "../server/response"; import { ff, getMp4CodecString } from "../util/media"; import { ApiCtx } from "./_common"; const streamVideoCapture = async ({ ctx, video, start, end, type, silent, }: { ctx: ApiCtx; video: Video; start?: number; end?: number; type?: string; silent: boolean; }) => { const { scratch } = ctx; if (!scratch) { throw new ClientError(404, "No scratch directory available"); } if ( start == undefined || start < 0 || start > video.duration() || end == undefined || end < 0 || end > video.duration() ) { throw new ClientError(400, "Bad range"); } const duration = end - start + 1; if (duration >= 60) { throw new ClientError(400, "Too long"); } const mime = { gif: "image/gif", low: "video/mp4", medium: "video/mp4", high: "video/mp4", original: "video/mp4", }[type ?? ""]; if (!mime) { throw new ClientError(400, "Invalid type"); } const audio = type != "gif" && !silent; const outputFile = join( scratch, video.relPath, `capture.${start}-${end}.${type}${audio ? `` : `.silent`}` ); await mkdir(dirname(outputFile), { recursive: true }); let outputFileStats = await maybeFileStats(outputFile); if (!outputFileStats) { await ff.convert({ input: { file: video.absPath(), start, duration, }, metadata: false, video: type == "gif" ? { codec: "gif", loop: true, fps: Math.min(10, video.fps()), resize: { width: Math.min(800, video.width()) }, } : { codec: "libx264", preset: "veryfast", crf: 18, fps: Math.min( type == "low" ? 10 : type == "medium" ? 30 : type == "high" ? 60 : Infinity, video.fps() ), resize: { width: Math.min( type == "low" ? 800 : type == "medium" ? 1280 : type == "high" ? 1920 : Infinity, video.width() ), }, }, audio: type != "gif" && audio, output: { format: type == "gif" ? "gif" : "mp4", file: outputFile, movflags: ["faststart"], }, }); outputFileStats = assertExists(await maybeFileStats(outputFile)); } return new StreamFile( outputFile, outputFileStats.size, mime, `${video.fileName()} (capture ${duration}s, ${type}${ audio ? "" : ", silent" })` ); }; export const getFileApi = async ( ctx: ApiCtx, { path, contentManifest, montageFrame, preview, segment, segmentGaplessMetadata, stream, thumbnail, capture, }: { path: string; contentManifest?: true; montageFrame?: number; preview?: true; segment?: { index: number; stream: "audio" | "video" }; segmentGaplessMetadata?: number; stream?: "audio" | "video"; thumbnail?: true; capture?: { start?: number; end?: number; type?: string; silent: boolean; }; } ) => { const file = await ctx.library.getFile(path); if (!file) { throw new ClientError(404, "File not found"); } if (capture) { if (!(file instanceof Video)) { throw new ClientError(400, "Capturing is only supported on videos"); } return await streamVideoCapture({ ctx, video: file, ...capture, }); } if (contentManifest) { if (!(file instanceof Video)) { throw new ClientError( 400, "Content manifests are only available for videos" ); } const content = await file.content.compute(); const montageFrames = file.montage.map((m) => m.time); if ("absPath" in content) { return new Json({ type: "src", montageFrames, }); } // Yes, these will start computation immediately and delay response, but this is OK given that getting the file/first segment is the immediate next request by the client anyway. const [audioCodecString, videoCodecString] = await Promise.all([ mapDefined(content.audio, (a) => (a.file ? a.file : a.segments[0].file) .compute() .then((f) => mapDefined(f, (f) => getMp4CodecString(f.absPath))) ), mapValue(content.video, (v) => (v.file ? v.file : v.segments[0].file) .compute() .then((f) => mapDefined(f, (f) => getMp4CodecString(f.absPath))) ), ]); return new Json({ type: "mse", montageFrames, audio: mapDefined(content.audio, (a) => (a.file ? "file" : "segments")), audioCodecString, segments: content.segments, video: content.video.file ? "file" : "segments", videoCodecString, }); } if (montageFrame != undefined) { if (!(file instanceof Video)) { throw new ClientError( 400, "Montage frames are only available for videos" ); } const frame = await file.montage .find((f) => f.time === montageFrame) ?.file.compute(); if (!frame) { throw new ClientError(404, "Frame not found"); } return new StreamFile(frame.absPath, frame.size); } if (preview) { if (!(file instanceof Video)) { throw new ClientError(400, "Previews only available for videos"); } const previewFile = await file.preview.compute(); if (!previewFile) { throw new ClientError(404, "No preview available"); } return new StreamFile(previewFile.absPath, previewFile.size, "video/mp4"); } if (segment != undefined) { if (!(file instanceof Video)) { throw new ClientError(400, "Segments only available for videos"); } const content = await file.content.compute(); if ("absPath" in content) { throw new ClientError(404, "Video does not have segments"); } const stream = content[segment.stream]; const s = stream?.segments?.[segment.index]; if (!s) { throw new ClientError(404, "Segment not found"); } const f = await s.file.compute(); return new StreamFile(f.absPath, f.size); } if (segmentGaplessMetadata != undefined) { if (!(file instanceof Video)) { throw new ClientError(400, "Segments only available for videos"); } const content = await file.content.compute(); if ("absPath" in content) { throw new ClientError(404, "Video does not have segments"); } const s = content.audio?.segments?.[segmentGaplessMetadata]; if (!s) { throw new ClientError(404, "Segment not found"); } const f = await s.file.compute(); return new Json({ gaplessMetadata: f.gaplessMetadata, }); } if (stream) { if (!(file instanceof Video)) { throw new ClientError(400, "Segments only available for videos"); } const content = await file.content.compute(); if ("absPath" in content) { throw new ClientError(404, "Video does not have separate streams"); } const s = await content[stream]?.file?.compute(); if (!s) { throw new ClientError(404, "Stream not available"); } return new StreamFile(s.absPath, s.size, `${stream}/mp4`); } if (thumbnail) { const thumbnailMeta = await file.thumbnail.compute(); if (!thumbnailMeta) { throw new ClientError(404, "No thumbnail available"); } return new StreamFile(thumbnailMeta.absPath, thumbnailMeta.size); } if (file instanceof Video) { const content = await file.content.compute(); if (!("absPath" in content)) { throw new ClientError(404, "Video must be accessed via segments"); } return new StreamFile(content.absPath, content.size); } return new StreamFile(file.absPath(), file.size); }; <file_sep>/src/library/search.ts import assertState from "@xtjs/lib/js/assertState"; import last from "@xtjs/lib/js/last"; import splitString from "@xtjs/lib/js/splitString"; import { sep } from "path"; import sqlite3 from "sqlite3"; // We use [].join(sep) instead of path.join(...[]) as path.join can cause "./". // We use sep instead of "/" as a platform could allow "/" in paths. export class FsSearch { private constructor(readonly db: sqlite3.Database) {} static new = () => new Promise<FsSearch>((resolve, reject) => { const db = new sqlite3.Database(":memory:", function (err) { if (err) { return reject(err); } console.debug("[FsSearch] Database opened"); db.exec( ` create virtual table fs using fts5 ( path, dir, name, tokenize="trigram" ) `, (err) => { if (err) { reject(err); } console.debug("[FsSearch] Table created"); resolve(new FsSearch(db)); } ); }); }); add = (relPath: string[]) => new Promise<void>((resolve, reject) => { assertState(relPath.length >= 1); this.db.run( ` insert into fs values (?, ?, ?) `, [relPath.join(sep), relPath.slice(0, -1).join(sep), last(relPath)], (err) => { if (err) { reject(err); } else { resolve(); } } ); }); query = (dir: string[], query: string, subdirs: boolean = false) => new Promise<string[][]>((resolve, reject) => { const where = []; const params = []; where.push(`name match ?`); params.push(`"${query.replaceAll('"', '""')}"`); if (subdirs) { if (dir.length) { where.push(`dir LIKE ? ESCAPE '*'`); // Use [...dir, ""].join(sep) instead of dir.join(sep) + sep in case sep needs to be escaped. // If dir.length == 0, [...dir, ""].join(sep) will result in "/" which is not what we want. params.push([...dir, ""].join(sep).replace(/[*%_]/g, "*$&") + "%"); } else { where.push("true"); } } else { where.push(`dir = ?`); params.push(dir.join(sep)); } this.db.all( ` select path from fs where ${where.join(" and ")} `, params, (err, rows) => { if (err) { reject(err); } else { resolve(rows.map((r) => splitString(r.path, sep))); } } ); }); } <file_sep>/src/main.ts #!/usr/bin/env node import mapDefined from "@xtjs/lib/js/mapDefined"; import { promises as fs, realpathSync } from "fs"; import * as sacli from "sacli"; import { Library } from "./library/model"; import { startServer } from "./server/server"; const rp = (p: string): string => realpathSync(p); const cli = sacli.Command.new() .optional("library", String) .optional("port", Number.parseInt) .optional("scratch", String) .optional("sslkey", String) .optional("sslcert", String) .optional("ssldh", String) .action( async ({ library = process.cwd(), scratch, port = 0, ssldh, sslcert, sslkey, }) => { const serverPort = await startServer({ library: await Library.init(library), port, scratch: mapDefined(scratch, rp), ssl: !sslkey || !sslcert ? undefined : { certificate: await fs.readFile(sslcert), key: await fs.readFile(sslkey), dhParameters: ssldh ? await fs.readFile(ssldh) : undefined, }, }); console.log(`Cabinet started on port ${serverPort}`); } ); cli.eval(process.argv.slice(2)); <file_sep>/README.md # Cabinet Quickly explore and view local photos, music, and videos in a browser over the network with a single command and zero configuration. - View and play all formats, even ones not browser- or streaming-friendly. - Works on any device with a modern browser; no app install needed. - Comes with a beautiful, smooth, glass-inspired UI, designed for all inputs. - Transparently detects, previews, transcodes, and caches, only when needed. ## Requirements - [Node.js](https://nodejs.org) - [Bento4](https://www.bento4.com) - [fdkaac](https://github.com/nu774/fdkaac) - [ffmpeg](https://ffmpeg.org) - Any modern browser ## Quick start ```bash npx @wzlin/cabinet ``` <details> <summary><strong>Advanced options</strong></summary> |Name|Default|Description| |---|---|---| |`--library`|Current working directory.|Absolute path to the folder containing photos and videos (including in subdirectories).| |`--port`|Random port assigned by OS.|Port to listen on.| |`--sslkey`||Absolute path to HTTPS private key file in PEM format. Required for HTTPS.| |`--sslcert`||Absolute path to HTTPS certificate file in PEM format. Required for HTTPS.| |`--ssldh`||Absolute path to HTTPS Diffie-Hellman parameters file. Optional for HTTPS.| </details> ## Installing `npx` downloads and runs the latest version on every invocation. This makes it convenient to occasionally run the server without having to worry about installing or updating, but might not be efficient when run often on a single machine. It's possible to install this npm package globally: ```bash npm i -g @wzlin/cabinet ``` Once installed, the server can be started without invoking `npx`: ```bash cabinet ``` npm creates executable aliases in the global bin folder. For the command to be found, ensure that the folder has been added to `PATH`. The folder's path can be found using `npm bin -g`. To update in the future: ```bash npm update -g @wzlin/cabinet ``` To uninstall: ```bash npm uninstall -g @wzlin/cabinet ``` <file_sep>/src/server/response.ts import parseRangeHeader from "@xtjs/lib/js/parseRangeHeader"; import FileType from "file-type"; import { createReadStream } from "fs"; import { PassThrough, pipeline, Readable } from "stream"; import { ServerReq, ServerRes } from "./server"; export class StreamFile { constructor( readonly path: string, readonly size: number, readonly mime?: string, readonly name?: string ) {} } export class ClientError { constructor(readonly status: number, readonly message: string) {} } export class Json<V> { constructor(readonly value: V) {} } export type ApiOutput = StreamFile | Json<any>; export const writeResponse = ( res: ServerRes, status: number, headers: { [name: string]: string | number }, data: string | Uint8Array | Readable ) => { const actualHeaders = Object.fromEntries( Object.entries(headers).map(([n, v]) => [n.toLowerCase(), v.toString()]) ); let src; if (typeof data == "string" || data instanceof Uint8Array) { const bytes = typeof data == "string" ? Buffer.from(data, "utf8") : data; if (actualHeaders["content-length"] == undefined) { actualHeaders["content-length"] = bytes.byteLength.toString(); } src = new PassThrough(); src.write(data); src.end(); } else { src = data; } res.writeHead(status, actualHeaders); pipeline(src, res, (err) => { if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { console.warn("Response stream error:", err); } }); }; const streamFile = async ( req: ServerReq, res: ServerRes, { name, mime, path, size, }: { path: string; size: number; name?: string; mime?: string; } ) => { // Every browser except Safari can handle media sent without Content-Type. But alas, // we have to implement this special code for the special browser. // This should not be too much of a performance drag, since we are going to stream the file anyway // (albeit not necessarily from the start). We don't enumerate MIMEs upon listing a directory // to avoid having to read lots of random sectors before the user can even start viewing a single file. if (mime == undefined) { mime = (await FileType.fromFile(path))?.mime; } let start: number; let end: number; const range = req.headers.range; if (typeof range == "string") { const parsed = parseRangeHeader(range, size); if (!parsed) { return res.writeHead(400).end(`Invalid range`); } start = parsed.start; end = parsed.end; } else { start = 0; end = size - 1; } const streamLength = end - start + 1; const headers: { [name: string]: string } = { "Accept-Ranges": "bytes", "Content-Length": streamLength.toString(), }; if (range) { headers["Content-Range"] = `bytes ${start}-${end}/${size}`; } if (name != undefined) { headers["Content-Disposition"] = `inline; filename="${name.replace( /[^a-zA-Z0-9-_'., ]/g, "_" )}"`; } if (mime != undefined) { headers["Content-Type"] = mime; } writeResponse( res, range ? 206 : 200, headers, createReadStream(path, { start, end }) ); }; export const applyResponse = async ( req: ServerReq, res: ServerRes, val: ApiOutput ) => { if (val instanceof StreamFile) { streamFile(req, res, val); } else { writeResponse( res, 200, { "Content-Type": "application/json", }, JSON.stringify(val.value) ); } }; <file_sep>/src/client/_common/api.ts // Escape some chars to allow insertion into CSS `url()`. export const apiGetPath = (apiName: string, input: object) => `/${apiName}?${encodeURIComponent(JSON.stringify(input)).replace( /[(')]/g, (paren) => "%" + paren.charCodeAt(0).toString(16) )}`; <file_sep>/src/api/_apis.ts import { getFileApi } from "./getFile"; import { listFilesApi } from "./listFiles"; export const APIS = { getFile: getFileApi, listFiles: listFilesApi, }; <file_sep>/src/server/server.ts import decodeUrlEncoded from "@xtjs/lib/js/decodeUrlEncoded"; import decodeUtf8 from "@xtjs/lib/js/decodeUtf8"; import readBufferStream from "@xtjs/lib/js/readBufferStream"; import splitString from "@xtjs/lib/js/splitString"; import * as http from "http"; import * as http2 from "http2"; import { AddressInfo } from "net"; import { Readable, Writable } from "stream"; import { APIS } from "../api/_apis"; import { ApiCtx, ApiFn } from "../api/_common"; import { Library } from "../library/model"; import { applyResponse, ClientError, writeResponse } from "./response"; declare const CLIENT_HTML: string; export type ServerReq = Readable & { url?: string; method?: string; headers: { [name: string]: string | string[] | undefined }; }; export type ServerRes = Writable & { writeHead(status: number, headers?: { [name: string]: string }): Writable; }; export const startServer = ({ library, port, scratch, ssl, }: { library: Library; port: number; scratch?: string; ssl?: { key: Buffer; certificate: Buffer; dhParameters?: Buffer; }; }) => new Promise<number>(async (onServerListening) => { const ctx: ApiCtx = { library, scratch, }; const requestHandler = async (req: ServerReq, res: ServerRes) => { const [pathname, queryString] = splitString(req.url ?? "", "?", 2); const apiName = pathname.slice(1); const api = (APIS as any)[apiName] as ApiFn; if (!api) { return writeResponse( res, 200, { "Content-Type": "text/html", }, CLIENT_HTML ); } let input; if (req.method == "GET") { input = JSON.parse(decodeUrlEncoded(queryString)); } else { const payloadBytes = await readBufferStream(req); input = JSON.parse(decodeUtf8(payloadBytes)); } let output; try { output = await api(ctx, input); } catch (e) { if (e instanceof ClientError) { return writeResponse( res, e.status, { "Content-Type": "text/plain", }, e.message ); } throw e; } await applyResponse(req, res, output); }; // Start server const server = ssl ? http2.createSecureServer( { allowHTTP1: true, cert: ssl.certificate, dhparam: ssl.dhParameters, key: ssl.key, }, requestHandler ) : http.createServer(requestHandler); server.listen(port, () => onServerListening((server.address() as AddressInfo).port) ); }); <file_sep>/src/library/model.ts import { ffprobeAudioStream, ffprobeFormat, ffprobeOutput, ffprobeVideoStream, } from "@wzlin/ff"; import assertExists from "@xtjs/lib/js/assertExists"; import exec from "@xtjs/lib/js/exec"; import filterValue from "@xtjs/lib/js/filterValue"; import last from "@xtjs/lib/js/last"; import map from "@xtjs/lib/js/map"; import mapDefined from "@xtjs/lib/js/mapDefined"; import numberGenerator from "@xtjs/lib/js/numberGenerator"; import pathExtension from "@xtjs/lib/js/pathExtension"; import splitString from "@xtjs/lib/js/splitString"; import { mkdir, readdir, readFile, realpath, stat, writeFile, } from "fs/promises"; import { DateTime } from "luxon"; import { EOL } from "os"; import { basename, dirname, join, sep } from "path"; import sharp from "sharp"; import { ComputedFile, computedFile, getFileMetadata, LazyP } from "../util/fs"; import { ff, GaplessMetadata, parseGaplessMetadata, queue, } from "../util/media"; import { BROWSER_SUPPORTED_MEDIA_CONTAINER_FORMATS, findSuitableContainer, MEDIA_EXTENSIONS, MSE_SUPPORTED_AUDIO_CODECS, MSE_SUPPORTED_VIDEO_CODECS, PHOTO_EXTENSIONS, } from "./format"; import { FsSearch } from "./search"; // Consider: // - HiDPI displays and zoomed-in viewports e.g. logical 180px is physical 360px. // - Tile lists with awkward width where 2 columns can't fit so only 1 ultra-wide column is possible. // - Bandwidth: a list of just 20 will require 20 x THUMB_SIZE network data and requests. const PREVIEW_SCALED_WIDTH = 500; const DATA_DIR_NAME = ".$Cabinet_data"; const dataDirForFile = (absPath: string) => join(dirname(absPath), DATA_DIR_NAME, basename(absPath)); const ensureDataDirForFile = async (absPath: string) => { const dir = dataDirForFile(absPath); await mkdir(dir, { recursive: true }); return dir; }; export abstract class DirEntry { constructor(readonly rootAbsPath: string, readonly relPath: string) {} absPath() { return join(this.rootAbsPath, this.relPath); } dirRelPath() { return filterValue(dirname(this.relPath), (p) => p != ".") ?? ""; } fileName() { return basename(this.relPath); } } export class Directory extends DirEntry { constructor( rootAbsPath: string, relPath: string, private readonly fsSearch: FsSearch ) { super(rootAbsPath, relPath); } async search(query: string, subdirs: boolean = false) { // Use splitString so that empty string results in an empty array, not `[""]`. return this.fsSearch.query(splitString(this.relPath, sep), query, subdirs); } entries = new LazyP(async () => { const names = await readdir(this.absPath()); const entries: { [name: string]: DirEntry } = Object.create(null); await Promise.all( names.map(async (f) => { if (f == DATA_DIR_NAME) { return; } const abs = join(this.absPath(), f); const rel = join(this.relPath, f); let entry: DirEntry; const stats = await stat(abs); if (stats.isDirectory()) { entry = new Directory(this.rootAbsPath, rel, this.fsSearch); } else if (stats.isFile()) { const modified = DateTime.fromMillis(stats.mtimeMs); const ext = pathExtension(f) ?? ""; if (MEDIA_EXTENSIONS.has(ext)) { let probeDataPath = join( await ensureDataDirForFile(abs), "probe.json" ); let probe: ffprobeOutput; try { probe = JSON.parse(await readFile(probeDataPath, "utf8")); } catch { try { probe = await ff.probe(abs); } catch (e) { console.warn(`Failed to probe ${abs}: ${e}`); // Invalid file. return; } await writeFile(probeDataPath, JSON.stringify(probe)); } const audio = probe.streams.find( (s): s is ffprobeAudioStream => s.codec_type === "audio" ); const video = probe.streams.find( (s): s is ffprobeVideoStream => s.codec_type === "video" ); if (video) { entry = new Video( this.rootAbsPath, rel, stats.size, modified, probe.format, video, audio ); } else if (audio) { entry = new Audio( this.rootAbsPath, rel, stats.size, modified, probe.format, audio ); } else { return; } } else if (PHOTO_EXTENSIONS.has(ext)) { await ensureDataDirForFile(abs); let metadata; try { metadata = await sharp(abs).metadata(); } catch { return; } const { format, height, width } = metadata; if ( format == undefined || height == undefined || width == undefined ) { return; } entry = new Photo(this.rootAbsPath, rel, stats.size, modified, { hasAlphaChannel: metadata.hasAlpha, channels: metadata.channels, chromaSubsampling: metadata.chromaSubsampling, colourSpace: metadata.space, dpi: metadata.density, format, hasIccProfile: metadata.hasProfile, height, isProgressive: metadata.isProgressive, orientation: metadata.orientation, width, }); } else { return; } } else { return; } if (entry instanceof File) { await this.fsSearch.add(entry.relPath.split(sep)); } entries[f] = entry; }) ); return entries; }); } export abstract class File extends DirEntry { abstract readonly thumbnail: LazyP<ComputedFile | undefined>; protected constructor( rootAbsPath: string, relPath: string, readonly size: number, readonly modified: DateTime ) { super(rootAbsPath, relPath); } protected dataDir() { return dataDirForFile(this.absPath()); } } export class Photo extends File { readonly thumbnail = new LazyP(() => computedFile(join(this.dataDir(), "thumbnail.jpg"), (thumbnailPath) => queue.add(() => sharp(this.absPath()) .resize({ fastShrinkOnLoad: true, width: PREVIEW_SCALED_WIDTH, withoutEnlargement: true, }) .jpeg({ quality: 50, }) .toFile(thumbnailPath) ) ) ); constructor( rootAbsPath: string, relPath: string, size: number, modified: DateTime, readonly metadata: { channels?: number; chromaSubsampling: string; colourSpace?: string; dpi?: number; format: string; hasAlphaChannel?: boolean; hasIccProfile?: boolean; height: number; isProgressive?: boolean; orientation?: number; width: number; } ) { super(rootAbsPath, relPath, size, modified); } } export abstract class Media extends File { protected constructor( rootAbsPath: string, relPath: string, size: number, modified: DateTime, protected readonly format: ffprobeFormat ) { super(rootAbsPath, relPath, size, modified); } duration() { return Number(this.format.duration); } // Many videos also use the same standard audio metadata tags. metadata(): { artist?: string; album?: string; genre?: string; title?: string; track?: number; } { return this.format.tags ?? {}; } } export class Audio extends Media { thumbnail = new LazyP(() => computedFile(join(this.dataDir(), "waveform.png"), (waveformAbsPath) => // https://trac.ffmpeg.org/wiki/Waveform and https://stackoverflow.com/questions/32254818/generating-a-waveform-using-ffmpeg. queue.add(() => exec( "ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-nostdin", "-i", this.absPath(), "-filter_complex", `aformat=channel_layouts=mono,showwavespic=s=${PREVIEW_SCALED_WIDTH}x${Math.round( PREVIEW_SCALED_WIDTH * 0.4 )}:colors=#969696`, "-frames:v", "1", waveformAbsPath ).status() ) ) ); constructor( rootAbsPath: string, relPath: string, size: number, modified: DateTime, format: ffprobeFormat, private readonly audioStream: ffprobeAudioStream ) { super(rootAbsPath, relPath, size, modified, format); } channels() { return this.audioStream.channels; } } export class Video extends Media { readonly montage = [ // Use frames from every 1m13s, except earlier or later than first/last 2s. These are arbitrary values. ...map(numberGenerator(2, this.duration() - 1, 73), (time) => ({ file: new LazyP(() => computedFile( join(this.dataDir(), `montage.${time}.jpg`), async (output) => { await ff.extractFrame({ input: this.absPath(), output, timestamp: time, scaleWidth: PREVIEW_SCALED_WIDTH, }); } ) ), time, })), ]; readonly content = new LazyP(async () => { // Prioritise any existing converted file, whether created by us or externally. // Assume it works and is better shaped for network streaming and browser viewing. const convertedWholeFilePath = join(this.dataDir(), "converted"); const externalFileMeta = await getFileMetadata(convertedWholeFilePath); if (externalFileMeta) { return { absPath: convertedWholeFilePath, size: externalFileMeta.size, }; } const container = this.format.format_name; const videoCodec = this.videoStream.codec_name; const audioCodec = this.audioStream?.codec_name; const containerConfig = BROWSER_SUPPORTED_MEDIA_CONTAINER_FORMATS.get(container); // True if specific audio and video codec combination in container supported by browser. const containerAndAVSupported = !!containerConfig?.videoCodecs.has(videoCodec) && (audioCodec == undefined || !!containerConfig?.audioCodecs.has(audioCodec)); if (containerAndAVSupported) { return { absPath: this.absPath(), size: this.size }; } // If we can find another container that the browser will support with this audio and video codec combination, we can quickly transmux instead of having to do complex, intensive, and lossy transcoding and segmenting with Media Source Extensions. const convertedContainer = findSuitableContainer(videoCodec, audioCodec); // If no suitable container found for existing video and audio codec, we can only transcode. if (convertedContainer != undefined) { return await computedFile( convertedWholeFilePath, (incompleteAbsPath) => ff.convert({ threads: 1, input: { file: this.absPath(), }, metadata: false, audio: true, video: true, output: { file: incompleteAbsPath, format: convertedContainer, }, }), "Failed to convert video to different container" ); } // If a video is relatively short, just convert entire video directly. if (this.duration() <= 160) { return await computedFile( convertedWholeFilePath, (incompleteAbsPath) => ff.convert({ threads: 1, input: { file: this.absPath(), }, metadata: false, // We need to convert both audio and video even if one is supported, // as container is different and may not support the existing A/V codec. audio: { codec: "aac" }, video: { codec: "libx264", crf: 18, vsync: "vfr", preset: "veryfast", }, output: { file: incompleteAbsPath, format: "mp4", }, }), "Failed to convert video" ); } // If we can convert an entire stream as a whole, we can quickly transmux and avoid complex segmenting. const mseAudioContainer = mapDefined(audioCodec, (c) => MSE_SUPPORTED_AUDIO_CODECS.get(c) ); const mseVideoContainer = mapDefined(videoCodec, (c) => MSE_SUPPORTED_VIDEO_CODECS.get(c) ); // Don't probe and use keyframes: // - Not consistent in duration between. // - Some broken and old formats don't have any or have extremely long durations between. // - Probing is slow and causes head-of-line blocking (i.e. probing entire file delays streaming even first few segments). const SEGMENT_DUR = 10; const segments: number[] = []; for ( let ts = 0; ts <= Math.max(0, this.duration() - SEGMENT_DUR); ts += SEGMENT_DUR ) { segments.push(ts); } return { segments, audio: mapDefined(audioCodec, () => mseAudioContainer ? { file: new LazyP(() => computedFile( join(this.dataDir(), `converted.audio`), (output) => ff.convert({ threads: 1, input: { file: this.absPath(), }, metadata: false, video: false, audio: true, output: { file: output, format: mseAudioContainer.format, // See video segment code for more info. movflags: [ "default_base_moof", "empty_moov", "faststart", ], }, }) ) ), } : { segments: segments.map((ts, i, a) => { const nextTs: number | undefined = a[i + 1]; return { start: ts, file: new LazyP(async () => { // This is result of several facts: // - Audio conversion is not fast enough to do entire file at once, especially for super long videos. // - Uncompressed audio codecs will take up significantly more space (think 10x instead of 10%). // - Compressed audio have padded silence at start and end that will cause noticeable skips/stutters during concatenated playback of segments. // - AAC can store padding metadata in MP4/M4A container format (but not AAC container). // - ffmpeg (as of 2021-06-30) cannot place this info in the container. // - fdkaac (a CLI for a superior AAC codec) can when container format chosen is M4A. // - The MIME specified to MediaSource must be audio/mp4, not audio/x-m4a. See official W3C spec for supported formats: https://www.w3.org/TR/mse-byte-stream-format-registry/#registry. For more details, see https://developer.mozilla.org/en-US/docs/Web/Media/Formats/codecs_parameter. // - Additionally, a codec string must be provided on Chrome-like browsers. This can be sourced using mp4info, part of Bento4. // - Notice: spec says FLAC and WAV are not supported. // TODO There is another gapless metadata format stored in edge + sgpd that is worth investigating to see if this flow can be simplified. See https://www.mail-archive.com/ffmpeg-devel@ffmpeg.org/msg95677.html. let gaplessMetadata: GaplessMetadata | undefined; const rawFile = await computedFile( join(this.dataDir(), `converted.audio.segment.${i}.raw`), (out) => ff.convert({ threads: 1, input: { file: this.absPath(), start: ts, // We extract slightly more than necessary to avoid errors and stutters // with minor gaps between segments during playback due to // rounding/precision, gapless metadata, etc. end: mapDefined(nextTs, (ts) => ts + 1), }, video: false, audio: { codec: "pcm", bits: 24, signedness: "s", endianness: "le", }, metadata: false, output: { format: "wav", file: out, }, }), "Failed to convert video audio segment to WAV" ); const fdkFile = await computedFile( join(this.dataDir(), `converted.audio.segment.${i}.fdk`), (out) => exec( "fdkaac", "-b", 192000, "-f", 0, "-G", 2, "-o", out, rawFile.absPath ).status(), "Failed to convert video audio segment using fdkaac" ); const probe = await ff.probe(fdkFile.absPath); const sampleRate = +assertExists( probe.streams.find( (s): s is ffprobeAudioStream => s.codec_type == "audio" ) ).sample_rate; gaplessMetadata = parseGaplessMetadata( await readFile(fdkFile.absPath, "ascii"), sampleRate ); const finalFile = await computedFile( join(this.dataDir(), `converted.audio.segment.${i}`), (out) => ff.convert({ threads: 1, input: { file: fdkFile.absPath, }, metadata: false, output: { file: out, format: "mp4", // See video segment code for more info. movflags: ["default_base_moof", "empty_moov"], }, }), "Failed to set movflags on video audio segment" ); return { ...finalFile, gaplessMetadata, }; }), }; }), } ), video: mseVideoContainer ? { file: new LazyP(() => computedFile(join(this.dataDir(), `converted.video`), (output) => ff.convert({ threads: 1, input: { file: this.absPath(), }, metadata: false, video: true, audio: false, output: { file: output, format: mseVideoContainer.format, // See video segment code for more info. movflags: ["default_base_moof", "empty_moov", "faststart"], }, }) ) ), } : { segments: segments.map((ts, i, a) => { const nextTs: number | undefined = a[i + 1]; return { start: ts, file: new LazyP(async () => { return await computedFile( join(this.dataDir(), `converted.video.segment.${i}`), async (segmentAbsPath) => { await ff.convert({ threads: 1, input: { file: this.absPath(), start: ts, end: nextTs, }, video: { vsync: "vfr", codec: "libx264", preset: "veryfast", crf: 18, }, audio: false, metadata: false, output: { // https://developer.mozilla.org/en-US/docs/Web/API/Media_Source_Extensions_API/Transcoding_assets_for_MSE. movflags: ["default_base_moof", "empty_moov"], format: "mp4", file: segmentAbsPath, }, }); }, "Failed to transcode video segment" ); }), }; }), }, }; }); readonly thumbnail = new LazyP(() => computedFile(join(this.dataDir(), "thumbnail.webp"), (thumbnailPath) => ff.extractFrame({ input: this.absPath(), output: thumbnailPath, timestamp: this.duration() * 0.5, scaleWidth: PREVIEW_SCALED_WIDTH, }) ) ); readonly preview = new LazyP(() => computedFile(join(this.dataDir(), "preview.mp4"), async (previewPath) => { const VIDEO_PARAMS = { codec: "libx264", crf: 23, fps: Math.min(24, this.fps()), preset: "veryfast", resize: { width: PREVIEW_SCALED_WIDTH }, } as const; const PART_SEC = 3; const PARTS = 8; if (this.duration() < PART_SEC * (PARTS + 2)) { await ff.convert({ threads: 1, input: { file: this.absPath(), }, metadata: false, video: VIDEO_PARAMS, audio: false, output: { file: previewPath, format: "mp4", movflags: ["faststart"], }, }); return; } const chapterLen = this.duration() / PARTS; const partFiles = []; const partFilesListFile = join(this.dataDir(), `preview.parts.txt`); const promises: Promise<any>[] = []; // Using the ffmpeg select filter is excruciatingly slow for a tiny < 1 minute output. // Manually seek and extract in parallel, and stitch at end. for (let i = 0; i < PARTS; i++) { const partFile = join(this.dataDir(), `preview.part.${i}`); partFiles.push(`file '${partFile.replaceAll("'", "'\\''")}'${EOL}`); const start = chapterLen * i + chapterLen / 2 - PART_SEC / 2; promises.push( computedFile(partFile, (output) => ff.convert({ threads: 1, input: { file: this.absPath(), start, duration: PART_SEC, }, metadata: false, video: VIDEO_PARAMS, audio: false, output: { file: output, format: "mp4", movflags: ["faststart"], }, }) ) ); } promises.push(writeFile(partFilesListFile, partFiles.join(""))); await Promise.all(promises); await ff.concat({ filesListFile: partFilesListFile, output: previewPath, }); }) ); constructor( rootAbsPath: string, relPath: string, size: number, modified: DateTime, format: ffprobeFormat, private readonly videoStream: ffprobeVideoStream, private readonly audioStream?: ffprobeAudioStream ) { super(rootAbsPath, relPath, size, modified, format); } fps() { const [num, denom] = splitString(this.videoStream.r_frame_rate, "/", 2).map( (n) => Number.parseInt(n, 10) ); return num / denom; } height() { return this.videoStream.height; } width() { return this.videoStream.width; } hasAudio() { return !!this.audioStream; } } export class Library { private constructor( private readonly root: Directory, private readonly fsSearch: FsSearch ) {} static async init(rootRaw: string) { const root = await realpath(rootRaw); const search = await FsSearch.new(); const rootDir = new Directory(root, "", search); return new Library(rootDir, search); } async getDirectory(path: string[]): Promise<Directory | undefined> { let cur: Directory = this.root; for (const component of path) { const entries = await cur.entries.compute(); const entry = entries[component]; if (!(entry instanceof Directory)) { return undefined; } cur = entry; } return cur; } async getFile(path: string): Promise<File | undefined> { const pathComponents = splitString(path, sep); const dir = await this.getDirectory(pathComponents.slice(0, -1)); const entries = await dir?.entries.compute(); const entry = entries?.[last(pathComponents)]; return entry instanceof File ? entry : undefined; } async search(relDir: string[], query: string, subdirs: boolean = false) { return this.fsSearch.query(relDir, query, subdirs); } } <file_sep>/src/util/media.ts import { Ff } from "@wzlin/ff"; import exec from "@xtjs/lib/js/exec"; import PromiseQueue from "@xtjs/lib/js/PromiseQueue"; import { execFile, spawn } from "child_process"; import os from "os"; // Leave 1 virtual core: // - Allow HTTP requests to continue to be processed. // - ffmpeg commands are already multithreaded, so utilising all cores is probably oversaturating the CPU. // - NOTE: It still won't prevent storage bottlenecks. export const queue = new PromiseQueue(os.cpus().length - 1); // TODO BUG @xtjs/lib/js/exec has bugs around heavy concurrent invocation causing lost stdout. It's also quite slow. Temporarily directly use built-in library. export const ff = new Ff({ runCommandWithoutStdout: (command, args) => queue.add( () => new Promise((resolve, reject) => { const proc = spawn(command, args, { stdio: ["ignore", "inherit", "inherit"], }); proc.on("error", reject); proc.on("exit", resolve); }) ), runCommandWithStdout: (command, args) => queue.add( () => new Promise((resolve, reject) => { execFile(command, args, (error, stdout) => { if (error) { reject(error); } else { resolve(stdout); } }); }) ), }); // We could use this in the future. export const webmSegment = ( input: string, start: number, end: number, output: string ) => ff.convert({ input: { file: input, start, end, }, video: { codec: "vp9", deadline: "realtime", cpuUsed: 8, multithreading: true, // Suggested values from https://developers.google.com/media/vp9/settings/vod/. mode: "constrained-quality", minBitrate: "9000K", targetBitrate: "18000K", maxBitrate: "26100K", }, audio: { codec: "libopus", }, metadata: false, output: { format: "webm", file: output, }, }); export type GaplessMetadata = { duration: number; start: number; end: number; }; // Sourced from https://developers.google.com/web/fundamentals/media/mse/seamless-playback. export const parseGaplessMetadata = ( bytesAsString: string, sampleRate: number ): GaplessMetadata | undefined => { const iTunesDataIndex = bytesAsString.indexOf("iTunSMPB"); if (iTunesDataIndex == -1) { return undefined; } const frontPaddingIndex = iTunesDataIndex + 34; const frontPadding = parseInt(bytesAsString.substr(frontPaddingIndex, 8), 16); const endPaddingIndex = frontPaddingIndex + 9; const endPadding = parseInt(bytesAsString.substr(endPaddingIndex, 8), 16); const sampleCountIndex = endPaddingIndex + 9; const realSamples = parseInt(bytesAsString.substr(sampleCountIndex, 16), 16); return { start: frontPadding / sampleRate, duration: realSamples / sampleRate, end: endPadding / sampleRate, }; }; export const getMp4CodecString = async (absPath: string) => { const out: { // Won't be set if invalid file. file?: { major_brand: string; minor_version: number; compatible_brands: Array<string>; fast_start: boolean; }; // Won't have any properties if invalid file. movie: { duration_ms?: number; duration?: number; time_scale?: number; fragments?: boolean; }; // Won't be set if invalid file. tracks?: Array<{ flags: number; flag_names: Array<string>; id: number; type: string; duration_ms: number; language: string; media: { sample_count: number; timescale: number; duration: number; duration_ms: number; }; sample_descriptions: Array<{ coding: string; coding_name: string; codecs_string: string; stream_type: number; stream_type_name: string; object_type: number; object_type_name: string; max_bitrate: number; average_bitrate: number; buffer_size: number; decoder_info: string; sample_rate: number; sample_size: number; channels: number; }>; }>; } = await exec("mp4info", "--format", "json", "--fast", absPath) .output() .then((r) => JSON.parse(r)); return out.tracks?.[0].sample_descriptions[0].codecs_string; }; <file_sep>/src/library/format.ts const PCM_CODECS = [ "pcm_s16be", "pcm_s16le", "pcm_s24be", "pcm_s24le", "pcm_s32be", "pcm_s32le", "pcm_s64be", "pcm_s64le", "pcm_s8", "pcm_u16be", "pcm_u16le", "pcm_u24be", "pcm_u24le", "pcm_u32be", "pcm_u32le", "pcm_u64be", "pcm_u64le", "pcm_u8", ]; export const MEDIA_EXTENSIONS = new Set([ "3gp", "aac", "avi", "flac", "flv", "gifv", "m2v", "m4v", "mka", "mkv", "mp3", "mp4", "mpeg", "mpg", "oga", "ogg", "ogv", "opus", "rm", "rmvb", "wav", "webm", "wmv", ]); export const PHOTO_EXTENSIONS = new Set([ "bmp", "gif", "jpeg", "jpg", "png", "svg", "tif", "tiff", "webp", ]); export const BROWSER_SUPPORTED_MEDIA_CONTAINER_FORMATS = new Map< string, { argValue?: string; audioCodecs: Set<string>; videoCodecs: Set<string>; } >([ [ "aac", { argValue: "alac", audioCodecs: new Set(["aac"]), videoCodecs: new Set(), }, ], [ "flac", { audioCodecs: new Set(["flac"]), videoCodecs: new Set(), }, ], // TODO Enable only when detected browser is supported. // [ // "matroska,webm", // { // argValue: "webm", // audioCodecs: new Set(["opus", "vorbis"]), // videoCodecs: new Set(["av1", "vp8", "vp9"]), // }, // ], [ "mov,mp4,m4a,3gp,3g2,mj2", { // Sources: // - https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers#mpeg-4_mp4 // - https://www.w3.org/2008/WebVideo/Fragments/wiki/State_of_the_Art/Containers argValue: "mp4", // flac, opus, vorbis in mp4 support is experimental by ffmpeg but technically supported by browser. audioCodecs: new Set(["aac", "alac", "mp3"]), videoCodecs: new Set(["av1", "h264", "vp9"]), }, ], [ "mp3", { audioCodecs: new Set(["mp3"]), videoCodecs: new Set(), }, ], // TODO Enable only when detected browser is supported. // [ // "ogg", // { // audioCodecs: new Set(["opus", "vorbis"]), // videoCodecs: new Set(["theora"]), // }, // ], [ "wav", { audioCodecs: new Set(PCM_CODECS), videoCodecs: new Set(), }, ], ]); export const findSuitableContainer = ( videoCodec?: string, audioCodec?: string ) => { for (const [k, v] of BROWSER_SUPPORTED_MEDIA_CONTAINER_FORMATS) { if ( (audioCodec == undefined || v.audioCodecs.has(audioCodec)) && (videoCodec == undefined || v.videoCodecs.has(videoCodec)) ) { return v.argValue ?? k; } } return undefined; }; // Map of MSE supported video codec to container. export const MSE_SUPPORTED_VIDEO_CODECS = new Map([ ["h264", { format: "mp4", mime: "video/mp4" }], // TODO Enable only if detected browser supports these. // "vp8", // "vp9", ]); // Map of MSE supported audio codec to container. export const MSE_SUPPORTED_AUDIO_CODECS = new Map([ // Browsers don't support AAC directly or in ALAC container for MSE. ["aac", { format: "mp4", mime: "audio/mp4" }], // TODO Enable only if detected browser supports these. // Most browsers don't support audio/mp4 with MP3. // Firefox doesn't support audio/mpeg but Chrome does. // ["mp3", {container: "mp3", mime: "audio/mpeg"}], // "opus", // "vorbis", ]);
ae38f04ba73fe1847708ee79a9a3b760690c4e6e
[ "JavaScript", "TypeScript", "Markdown" ]
16
TypeScript
wilsonzlin/cabinet
03e1a4e53645d293896bc36b22a6f1dcbbf88b22
8a6415e46574777ab3db72b412f688ec0e188c0c
refs/heads/master
<repo_name>Nadern96/TripReservation-<file_sep>/TripReserv/Trip/designTrip/apps.py from django.apps import AppConfig class DesigntripConfig(AppConfig): name = 'designTrip' <file_sep>/TripReserv/Trip/TripPackages/migrations/0005_auto_20190421_1421.py # Generated by Django 2.2 on 2019-04-21 12:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('TripPackages', '0004_auto_20190416_2252'), ] operations = [ migrations.AddField( model_name='city', name='image', field=models.ImageField(default='default.jpg', upload_to=''), ), migrations.AddField( model_name='place', name='brief', field=models.CharField(default='', max_length=1500), ), migrations.AddField( model_name='place', name='image', field=models.ImageField(default='default.jpg', upload_to=''), ), migrations.AddField( model_name='place', name='location', field=models.CharField(default='', max_length=1000, null=True), ), ] <file_sep>/TripReserv/Trip/designTrip/models.py from django.db import models from CustomUser.models import User class Program(models.Model): pass class DesignTrip(models.Model): status_choices = ( ('Requested','Requested'), ('onGoing','onGoing'), ('Done','Done'), ('Archieve','Archieve'), ) trip_type = models.CharField(max_length=50,blank=True) about_trip = models.CharField(max_length=50,blank=True) budget_from = models.IntegerField(blank=True,null=True) budget_to = models.IntegerField(blank=True,null=True) travel_with = models.CharField(max_length=50,blank=True) couple_question = models.CharField(max_length=50,blank=True) adult_number = models.IntegerField(blank=True) chidren_number = models.IntegerField(blank=True) exact_date = models.CharField(max_length=50,blank=True) arrival_date = models.DateField(blank=True,null=True) departure_date = models.DateField(blank=True,null=True) month = models.CharField(max_length=50,blank=True) period = models.CharField(max_length=50,blank=True) begin_trip =models.CharField(max_length=50,blank=True) agent_language = models.CharField(max_length=50,blank=True) agent_time = models.CharField(max_length=50,blank=True) agent_welcome = models.CharField(max_length=50,blank=True) agent_byebye = models.CharField(max_length=50,blank=True) agent_car = models.CharField(max_length=50,blank=True) agent_camera = models.CharField(max_length=50,blank=True) additional_info = models.TextField(max_length=1000,blank=True) user = models.ForeignKey(User,on_delete=models.CASCADE,blank=True) form_submitted_date = models.DateTimeField(auto_now_add=True,blank=True,null=True) status = models.CharField(max_length=20,blank=True,null=True,choices=status_choices) program = models.OneToOneField(Program,on_delete=models.CASCADE,blank=True,null=True) def __str__(self): return self.user.get_full_name() <file_sep>/TripReserv/Trip/TripPackages/static/js/base.js /*****************Places dropdown menu *******************************/ $('ul.navbar-nav li.dropdown').hover(function() { $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500); }, function() { $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500); }); /**********************************************************************/ /**********************************************************************/ // Get the modal var modal = document.getElementById('id01'); // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } // if user press escape button it will close the modal $(document).keyup(function(e) { if (e.key === "Escape") { // write your logic here. go_SignIn(); modal.style.display = "none"; } }); /************************************************************************/ var sign_in = document.getElementById('sign-in'); var sign_up = document.getElementById('sign-up'); var reset_pass = document.getElementById('reset-pass'); function go_SignUp(){ sign_in.style.display = "none"; reset_pass.style.display= "none"; sign_up.style.display = "block"; console.log("hello"); } function go_SignIn(){ sign_in.style.display = "block"; reset_pass.style.display= "none"; sign_up.style.display = "none"; console.log("hello"); } function go_resetPass(){ sign_in.style.display = "none"; reset_pass.style.display= "block"; sign_up.style.display = "none"; console.log("hello"); } function validate_form (form , pass1 , pass2 , error){ pass1 = document.getElementById(pass1).value; pass2 = document.getElementById(pass2).value; var valid; console.log(pass1); form = document.getElementById(form); if(pass1!=pass2){ valid = false; console.log("not valid"); console.log(document.getElementById(error).innerHTML); document.getElementById(error).innerHTML = "Passwords Don't Match"; return false; } console.log("valid"); return true; } /************ To make alert message disappear after ***********/ setTimeout(function(){$('.alert').fadeOut();}, 15000); <file_sep>/TripReserv/Trip/designTrip/migrations/0003_delete_designtrip.py # Generated by Django 2.2 on 2019-04-10 15:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('designTrip', '0002_auto_20190410_1647'), ] operations = [ migrations.DeleteModel( name='DesignTrip', ), ] <file_sep>/TripReserv/Trip/CustomUser/views.py from django.shortcuts import render,get_object_or_404,redirect from .models import User from designTrip.models import DesignTrip from TripPackages.models import City from django.http import HttpResponse def profile_render(request,user_id): user = get_object_or_404(User,id=user_id) designedTrips = DesignTrip.objects.filter(user=user) cities = City.objects.all() context = {'user':user, 'DesignedTrips':designedTrips,'cities':cities} return render(request,'user_profile.html', context) def cancel_request(request): trip_id = request.POST.get("trip_id",'') trip_request = get_object_or_404(DesignTrip,id=trip_id) user_id = trip_request.user.id trip_request.delete() return redirect('profile_render',user_id) def get_mobile(request,user_id): user = get_object_or_404(User,id=user_id) mobile = user.mobile return HttpResponse('%s' % mobile)<file_sep>/TripReserv/Trip/designTrip/form_save.py from .models import DesignTrip from CustomUser.models import User def DesignTrip_formSave(request,user,signUpFlag): design_form = DesignTrip() design_form.trip_type = request.POST.get('trip_type','') design_form.about_trip = request.POST.get('about_trip','') design_form.budget_from = request.POST.get('budget_from',0) design_form.budget_to = request.POST.get('budget_to',design_form.budget_from) design_form.travel_with = request.POST.get('people_question','') design_form.couple_question = request.POST.get('couple_question','') design_form.adult_number = request.POST.get('adult_number',1) design_form.chidren_number = request.POST.get('chidren_number',0) design_form.exact_date = request.POST.get('exact_date','') design_form.arrival_date = request.POST.get('arrival_date',None) design_form.departure_date = request.POST.get('departure_date',None) design_form.month = request.POST.get('month','') design_form.period = request.POST.get('period','') design_form.begin_trip = request.POST.get('whereTobeginTrip_question','') design_form.agent_language = request.POST.get('language_question','') design_form.agent_time = request.POST.get('guide_time','') design_form.agent_welcome = request.POST.get('welcome','') design_form.agent_byebye = request.POST.get('byebye_question','') design_form.agent_car = request.POST.get('car_question','') design_form.agent_camera = request.POST.get('camera_question','') design_form.additional_info = request.POST.get('additional_info','') design_form.status = "Requested" if signUpFlag: design_form.user = user else: design_form.user = request.user design_form.save() def User_SignUp(request): user = User() user.email = request.POST.get('email','') user.title = request.POST.get('title_question','') user.full_name = request.POST.get('first_name','') +" "+ request.POST.get('last_name','') user.country = request.POST.get('country_complete','') user.mobile = request.POST.get('mobile_complete','') user.birthday = request.POST.get('birthday',None) user.set_password(request.POST.get('password_signup','')) user.save() return user <file_sep>/TripReserv/Trip/TripPackages/models.py from django.db import models # Create your models here. class City (models.Model): name = models.CharField(max_length=100, default="") historical = models.BooleanField(default=False) local_culture = models.BooleanField(default=False) local_cusine = models.BooleanField(default=False) relaxation = models.BooleanField(default=False) about_city = models.TextField(default=" ") image = models.ImageField(null=False,default = 'default.jpg') def __str__(self): return self.name class Place (models.Model): name= models.CharField(max_length=250, default="") brief = models.CharField(max_length=1500,default="") about_place = models.TextField(default=" ") historical= 'historical' local_culture = 'local culture' local_cusine = 'local cusine' relaxation = 'relaxation' category_choices = ( (historical, 'historical'), (local_culture, 'local culture'), (local_cusine, 'local cusine'), (relaxation, 'relaxation'), ) category = models.CharField( max_length=50, choices=category_choices, default=historical, ) image = models.ImageField(null=False ,default = 'default.jpg') city = models.ForeignKey(City, on_delete=models.CASCADE) location = models.CharField(default = "" , max_length = 1000 ,null = True) def __str__(self): return self.name class Subscribed_user (models.Model): email = models.EmailField(max_length=70, null=True, blank=True, unique=True) <file_sep>/TripReserv/Trip/CustomUser/forms.py # accounts.forms.py from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User class UserAdminCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='<PASSWORD>', widget=forms.PasswordInput) password2 = forms.CharField(label='<PASSWORD> confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email','full_name',)#add all required fields to create an admin , note:you dont have to put the password def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["<PASSWORD>"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ password = ReadOnlyPasswordHashField() class Meta: model = User fields = ('email', 'password', 'full_name','active', 'admin','title','country','mobile','birthday') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial["password"] class RegisterForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email','full_name',)#add all required fields to create an admin , note:you dont have to put the password def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) user.active=False # not active (means cant login until confirmed) if commit: user.save() return user class LoginForm(forms.Form): email = forms.EmailField(label="Email") password = forms.CharField(widget=forms.PasswordInput) class SetPasswordForm(forms.Form): """ A form that lets a user change set their password without entering the old password """ error_messages = { 'password_mismatch': ("The two password fields didn't match."), } new_password1 = forms.CharField(label=("New password"), widget=forms.PasswordInput) new_password2 = forms.CharField(label=("New password confirmation"), widget=forms.PasswordInput) def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2<file_sep>/TripReserv/Trip/TripPackages/apps.py from django.apps import AppConfig class TrippackagesConfig(AppConfig): name = 'TripPackages' <file_sep>/TripReserv/Trip/designTrip/urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.design_form_render, name = "design_form_render"), path('check_email/',views.checkEmail,name='check_email'), path('ajax_check_auth/',views.check_auth,name="check_auth"), path('design_form_get/',views.design_form_get,name="design_form_get"), path('form_complete/',views.form_complete,name="form_complete"), ]<file_sep>/TripReserv/Trip/TripPackages/migrations/0004_auto_20190416_2252.py # Generated by Django 2.2 on 2019-04-16 20:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('TripPackages', '0003_place_year_in_school'), ] operations = [ migrations.RemoveField( model_name='place', name='year_in_school', ), migrations.AddField( model_name='place', name='category', field=models.CharField(choices=[('historical', 'historical'), ('local culture', 'local culture'), ('local cusine', 'local cusine'), ('relaxation', 'relaxation')], default='historical', max_length=50), ), ] <file_sep>/TripReserv/Trip/designTrip/migrations/0005_auto_20190410_1807.py # Generated by Django 2.2 on 2019-04-10 16:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('designTrip', '0004_designtrip'), ] operations = [ migrations.AlterField( model_name='designtrip', name='arrival_date', field=models.DateField(blank=True, null=True), ), migrations.AlterField( model_name='designtrip', name='departure_date', field=models.DateField(blank=True, null=True), ), ] <file_sep>/TripReserv/Trip/TripPackages/urls.py from django.contrib import admin from django.urls import path, include from . import views from TripPackages.views import PasswordResetConfirmView from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from django.conf.urls import url urlpatterns = [ path('', views.Home_view, name = "Home_view"), path('cities/<city>/', views.city_view, name='city_view'), path('about_us/', views.about_us, name='about_us'), #path('loginUser', views.login_user , name='login_user'), path('logout_user', views.logout_user , name='logout_user'), path('signUp', views.signUp , name='signUp'), path('login_page', views.login_page , name='login_page'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate_user_account, name='activate_user_account'), path('resetpass',views.password_reset,name='password_reset'), # url(r'^password_reset_confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', # views.password_reset_confirm, name='password_reset_confirm'), url(r'^account/reset_password_confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', PasswordResetConfirmView.as_view(),name='reset_password_confirm'), path('addSubUser',views.addSubUser.as_view() , name='addSubUser'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <file_sep>/TripReserv/Trip/designTrip/admin.py from django.contrib import admin from .models import DesignTrip,Program class DesignTripAdmin(admin.ModelAdmin): list_display = ('status','user','form_submitted_date', 'trip_type','about_trip','budget_from','budget_to','travel_with', 'couple_question','couple_question','adult_number','chidren_number', 'exact_date','arrival_date','departure_date','month','period', 'begin_trip','agent_language','agent_time', 'agent_welcome','agent_byebye','agent_car','agent_camera') fieldsets = ( ('Tab1', {'fields': ('status', 'user','program', 'trip_type','about_trip','budget_from','budget_to')}), ('Tab2', {'fields': ('travel_with', 'couple_question','adult_number','chidren_number', 'exact_date','arrival_date','departure_date','month','period')}), ('Tab3', {'fields': ('begin_trip','agent_language','agent_time', 'agent_welcome','agent_byebye','agent_car','agent_camera')}), ) search_fields = ('about_trip','form_submitted_date', 'trip_type','about_trip','travel_with', 'couple_question','couple_question','adult_number','chidren_number', 'exact_date','arrival_date','departure_date','month','period', 'begin_trip','agent_language','agent_time', 'agent_welcome','agent_byebye','agent_car','agent_camera','status') ordering = ['form_submitted_date'] list_filter = ('status',) actions = ['mark_ongoing','mark_requested','mark_Done','mark_archieve'] def mark_ongoing(self, request, queryset): rows_updated =queryset.update(status="onGoing") if rows_updated == 1: message_bit = "1 story was" else: message_bit = "%s stories were" % rows_updated self.message_user(request, "%s successfully marked as OnGoing." % message_bit) mark_ongoing.short_description = "Mark OnGoing" def mark_Done(self, request, queryset): rows_updated = queryset.update(status="Done") if rows_updated == 1: message_bit = "1 story was" else: message_bit = "%s stories were" % rows_updated self.message_user(request, "%s successfully marked as Done." % message_bit) mark_Done.short_description = "Mark Done" def mark_requested(self, request, queryset): rows_updated = queryset.update(status="Requested") if rows_updated == 1: message_bit = "1 story was" else: message_bit = "%s stories were" % rows_updated self.message_user(request, "%s successfully marked as Requested." % message_bit) mark_requested.short_description = "Mark Requested" def mark_archieve(self, request, queryset): rows_updated = queryset.update(status="Archieve") if rows_updated == 1: message_bit = "1 story was" else: message_bit = "%s stories were" % rows_updated self.message_user(request, "%s successfully marked as Archieve." % message_bit) mark_archieve.short_description = "Mark Archieve" admin.site.register(DesignTrip,DesignTripAdmin) admin.site.register(Program)<file_sep>/TripReserv/Trip/CustomUser/static/user_profile/js/user_profile.js // to get csrftoken and setup ajax with it function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) c_end = document.cookie.length; return unescape(document.cookie.substring(c_start,c_end)); } } return ""; } $(function () { $.ajaxSetup({ headers: { "X-CSRFToken": getCookie("csrftoken") } }); }); var input = document.querySelector("#phone"); var errorMsg = document.querySelector("#error-msg"); var validMsg = document.querySelector("#valid-msg"); var countryData = window.intlTelInputGlobals.getCountryData(); var addressDropdown = document.querySelector("#address-country"); // here, the index maps to the error code returned from getValidationError - see readme var errorMap = [ "Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"]; // initialise plugin var iti = window.intlTelInput(input, { nationalMode: true, utilsScript: "/static/user_profile/intl-tel-input-master/build/js/utils.js?1549804213570" }); // populate the country dropdown for (var i = 0; i < countryData.length; i++) { var country = countryData[i]; var optionNode = document.createElement("option"); optionNode.value = country.iso2; var textNode = document.createTextNode(country.name); optionNode.appendChild(textNode); addressDropdown.appendChild(optionNode); } // set it's initial value addressDropdown.value = iti.getSelectedCountryData().iso2; // listen to the telephone input for changes input.addEventListener('countrychange', function(e) { addressDropdown.value = iti.getSelectedCountryData().iso2; }); // listen to the address dropdown for changes addressDropdown.addEventListener('change', function() { iti.setCountry(this.value); }); /////for error and valid msgs var reset = function() { input.classList.remove("error"); errorMsg.innerHTML = ""; errorMsg.style.display = 'none'; validMsg.style.display = 'none'; }; // on blur: validate input.addEventListener('blur', function() { reset(); if (input.value.trim()) { if (iti.isValidNumber()) { //document.getElementById('mobile_complete').value = iti.getNumber(); validMsg.style.display = 'inline' } else { input.classList.add("error"); var errorCode = iti.getValidationError(); errorMsg.innerHTML = errorMap[errorCode]; errorMsg.style.display = 'inline'; } } }); // on keyup / change flag: reset input.addEventListener('change', reset); input.addEventListener('keyup', reset); function showhide(button,trip_id) { if(button.innerHTML == "<i id=\"showhideIcon"+String(trip_id)+"\" class=\"fas fa-plus\"></i> Show Full Details"){ button.innerHTML = "<i id=\"showhideIcon"+String(trip_id)+"\" class=\"fas fa-minus\"></i> Show Summary"; document.getElementById("summ_div"+String(trip_id)).style.display = "none"; document.getElementById("full_div"+String(trip_id)).style.display = "inline"; } else if(button.innerHTML == "<i id=\"showhideIcon"+String(trip_id)+"\" class=\"fas fa-minus\"></i> Show Summary"){ button.innerHTML = "<i id=\"showhideIcon"+String(trip_id)+"\" class=\"fas fa-plus\"></i> Show Full Details"; document.getElementById("full_div"+String(trip_id)).style.display = "none"; document.getElementById("summ_div"+String(trip_id)).style.display = "inline"; //for scrooling to show error var navOffset = 100; var div_postion = $("#summ_div"+String(trip_id)).offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 750); } } function cancelRequest(trip_id){ if(confirm("Are You Sure You Want to Cancel Trip Request ??")) { document.forms['cancel_request_form'].submit(); } } $( document ).ready(function() { });<file_sep>/TripReserv/Trip/TripPackages/migrations/0002_auto_20190416_1308.py # Generated by Django 2.2 on 2019-04-16 11:08 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('TripPackages', '0001_initial'), ] operations = [ migrations.AddField( model_name='city', name='about_city', field=models.TextField(default=' '), ), migrations.CreateModel( name='Place', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='', max_length=250)), ('about_place', models.TextField(default=' ')), ('city', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='TripPackages.City')), ], ), ] <file_sep>/TripReserv/Trip/designTrip/migrations/0007_designtrip_status.py # Generated by Django 2.2 on 2019-04-15 15:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('designTrip', '0006_designtrip_form_submitted_date'), ] operations = [ migrations.AddField( model_name='designtrip', name='status', field=models.CharField(blank=True, choices=[('Requested', 'Requested'), ('onGoing', 'onGoing'), ('Done', 'Done'), ('Archieve', 'Archieve')], max_length=20, null=True), ), ] <file_sep>/TripReserv/Trip/designTrip/migrations/0002_auto_20190410_1647.py # Generated by Django 2.2 on 2019-04-10 14:47 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('designTrip', '0001_initial'), ] operations = [ migrations.RenameField( model_name='designtrip', old_name='agent_byeby', new_name='agent_byebye', ), ] <file_sep>/TripReserv/Trip/requirements.txt apturl==0.5.2 asn1crypto==0.24.0 astroid==2.2.5 Brlapi==0.6.6 certifi==2019.3.9 chardet==3.0.4 command-not-found==0.3 confusable-homoglyphs==3.2.0 cryptography==2.1.4 cupshelpers==1.0 defer==1.0.6 defusedxml==0.5.0 distro-info===0.18ubuntu0.18.04.1 Django==2.2 django-allauth==0.39.1 django-registration==3.0 django-sendgrid==1.0.1 django-sendgrid-v5==0.8.0 django-widget-tweaks==1.4.3 future==0.17.1 gunicorn==19.9.0 httplib2==0.9.2 idna==2.8 isort==4.3.16 kazam==1.4.5 keyring==10.6.0 keyrings.alt==3.0 language-selector==0.1 launchpadlib==1.10.6 lazr.restfulclient==0.13.5 lazr.uri==1.0.3 lazy-object-proxy==1.3.1 louis==3.5.0 macaroonbakery==1.1.3 Mako==1.0.7 MarkupSafe==1.0 mccabe==0.6.1 netifaces==0.10.4 numpy==1.16.2 oauth==1.0.1 oauthlib==3.0.1 olefile==0.45.1 pandas==0.24.2 pexpect==4.2.1 Pillow==6.0.0 protobuf==3.0.0 pycairo==1.16.2 pycrypto==2.6.1 pycups==1.9.73 pygobject==3.26.1 PyJWT==1.7.1 pylint==2.3.1 pymacaroons==0.13.0 PyNaCl==1.1.2 pyRFC3339==1.0 python-apt==1.6.3+ubuntu1 python-dateutil==2.8.0 python-debian==0.1.32 python-http-client==3.1.0 python3-openid==3.1.0 pytz==2019.1 pyxdg==0.25 PyYAML==3.12 reportlab==3.4.0 requests==2.21.0 requests-oauthlib==1.2.0 requests-unixsocket==0.1.5 scipy==1.2.1 SecretStorage==2.3.1 sendgrid==6.0.4 simplejson==3.16.0 six==1.12.0 social-auth-app-django==3.1.0 social-auth-core==3.1.0 sqlparse==0.3.0 system-service==0.3 systemd-python==234 typed-ast==1.3.1 ubuntu-drivers-common==0.0.0 ufw==0.36 unattended-upgrades==0.1 urllib3==1.24.1 usb-creator==0.3.3 wadllib==1.3.2 wrapt==1.11.1 xkit==0.0.0 zope.interface==4.3.2 <file_sep>/TripReserv/Trip/TripPackages/views.py from django.shortcuts import render,redirect # Create your views here. from . models import City , Place , Subscribed_user from django.contrib.auth import authenticate, login , logout , get_user_model from CustomUser.forms import RegisterForm , LoginForm , SetPasswordForm from django.utils.http import is_safe_url from django.contrib import messages from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text #Email confirmation from django.conf import settings from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.core.mail import EmailMultiAlternatives from CustomUser.tokens import account_activation_token from django.urls import reverse from django.template.loader import render_to_string from django.core.mail import EmailMessage #reset pass from django.views.generic import * #for addSubUSer from django.urls import reverse_lazy def Home_view (request): cities = City.objects.all() context = { 'cities': cities } return render(request, 'TripPackages/Home.html', context) def city_view (request,city): places = Place.objects.all() places = places.filter(city__name=city) cities = City.objects.all() city = cities.filter(name=city) context = { "places": places, "cities": cities, "city" : city, } return render(request, 'TripPackages/City_template.html',context) def about_us (request): cities = City.objects.all() context = { 'cities': cities } return render(request, 'TripPackages/About_us.html', context) # def login_user(request): # if request.method == "POST": # email = request.POST['email'] # password = request.POST['<PASSWORD>'] # user = authenticate(email=email, password=<PASSWORD>) # if user is not None: # if user.is_active: # login(request, user) # request.session.set_expiry(10) # return redirect('Home_view') # return redirect('Home_view') def logout_user(request): logout(request) return redirect('Home_view') def login_page(request): form = LoginForm(request.POST or None) next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") remember_me = request.POST.get('remember_me') user = authenticate(request, username=email, password=<PASSWORD>) if user is not None: login(request, user) if not remember_me: request.session.set_expiry(0) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: messages.error(request,f'invalid email or password ,try again!') return redirect("/",{'messages':messages}) messages.error(request,f'invalid email or password ,try again!') return redirect(redirect_path,{'messages':messages}) User = get_user_model() def signUp(request): form = RegisterForm(request.POST or None) next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): form.save() full_name = form.cleaned_data.get('full_name') #### user = form.save(commit=False) current_site = get_current_site(request) mail_subject = 'Activate your AmieGoo! account.' message = render_to_string('accounts/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() messages.success(request,f'{full_name} Please confirm your email address to complete the registration!') ### try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path,{'messages':messages}) else: messages.error(request,f'Account is not created!') return redirect("/",{'messages':messages}) messages.error(request,f'This email address is already in use') return redirect(redirect_path,{'messages':messages}) def activate_user_account(request, uidb64=None, token=None): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except User.DoesNotExist: user = None if user and account_activation_token.check_token(user, token): user.active = True user.save() login(request, user) messages.success(request,f'Thank you for your email confirmation') return render(request,'TripPackages/Home.html') elif user.is_active: return redirect('Home_view') else: messages.error(request,f'Activation link is invalid!') return render(request,'TripPackages/Home.html') # password_reset: Form where the user submits the email address def password_reset(request): if request.method == "POST": email = request.POST.get('email') all_users = User.objects.all() user = all_users.filter(email=email) if not user.exists(): messages.error(request,f"invalid Email") return redirect("/",{'messages':messages}) user = user[0] full_name = user.full_name next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None #send email to that user current_site = get_current_site(request) mail_subject = 'Reset your Password' message = render_to_string('accounts/acc_forgot_pass.html', { 'full_name': full_name, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = email email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() messages.success(request,f'Please Check your Email!') ### try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path,{'messages':messages}) else: messages.error(request,f'Try Again') return redirect("/",{'messages':messages}) messages.error(request,f'Try Again') return redirect(redirect_path,{'messages':messages}) class PasswordResetConfirmView(FormView): template_name = "accounts/acc_reset_pass.html" success_url = '/' form_class = SetPasswordForm def post(self, request, uidb64=None, token=None, *arg, **kwargs): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ UserModel = get_user_model() form = self.form_class(request.POST) assert uidb64 is not None and token is not None # checked by URLconf try: uid = urlsafe_base64_decode(uidb64) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): if form.is_valid(): new_password= form.cleaned_data['new_password2'] user.set_password(new_password) user.save() messages.success(request, 'Password has been reset.') return self.form_valid(form) else: messages.error(request, 'Password reset has not been unsuccessful.') return self.form_invalid(form) else: messages.error(request,'The reset password link is no longer valid.') return redirect("/",{'messages':messages}) class addSubUser(CreateView): model = Subscribed_user fields = ['email'] success_url =reverse_lazy('Home_view') <file_sep>/TripReserv/Trip/TripPackages/static/js/Home.js //To filter where to go list on input change function filter() { var input, filter, ul, li, a, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); ul = document.getElementById("myUL"); li = ul.getElementsByTagName("li"); ul.style.display = ""; for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; txtValue = a.textContent || a.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].style.display = "none"; } } } //to hide list on input blur function myBlurFunc () { var ul = document.getElementById("myUL"); var li = ul.getElementsByTagName("li"); for (var i = 0; i < li.length; i++) { li[i].style.display = "none"; } } document.addEventListener("click", (evt) => { const flyoutElement = document.getElementById("myInput"); let targetElement = evt.target; // clicked element do { if (targetElement == flyoutElement) { // This is a click inside. Do nothing, just return. console.log("Clicked inside!"); return; } // Go up the DOM targetElement = targetElement.parentNode; } while (targetElement); // This is a click outside. myBlurFunc(); }); // to copy choosed li text to input function copyToinput (cityName) { var cityName = cityName.innerText; var input = document.getElementById("myInput"); input.value = cityName; } <file_sep>/TripReserv/Trip/designTrip/migrations/0008_auto_20190416_1526.py # Generated by Django 2.2 on 2019-04-16 13:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('designTrip', '0007_designtrip_status'), ] operations = [ migrations.RemoveField( model_name='designtrip', name='budget', ), migrations.AddField( model_name='designtrip', name='budget_from', field=models.IntegerField(blank=True, null=True), ), migrations.AddField( model_name='designtrip', name='budget_to', field=models.IntegerField(blank=True, null=True), ), ] <file_sep>/TripReserv/Trip/CustomUser/urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('id=<int:user_id>/', views.profile_render, name = "profile_render"), path('cancel_request/', views.cancel_request, name = "cancel_request"), path('id=<int:user_id>/get_mobile/', views.get_mobile, name = "get_mobile"), ]<file_sep>/TripReserv/Trip/TripPackages/admin.py from django.contrib import admin from .models import City , Place , Subscribed_user # Register your models here. admin.site.register(City) admin.site.register(Place) admin.site.register(Subscribed_user)<file_sep>/TripReserv/Trip/designTrip/views.py from django.shortcuts import render,get_object_or_404, redirect from CustomUser.models import User from django.http import HttpResponse from django.contrib.auth import authenticate, login , logout from .form_save import DesignTrip_formSave, User_SignUp from django.contrib import messages from django.utils.http import is_safe_url from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text #Email confirmation from django.conf import settings from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.core.mail import EmailMultiAlternatives from CustomUser.tokens import account_activation_token from django.urls import reverse from django.template.loader import render_to_string from django.core.mail import EmailMessage # Create your views here. def design_form_render(request): return render(request, 'design_form.html') def checkEmail(request): email = request.POST.get('emailValue', False) if email: numberOfEmail = User.objects.filter(email=email).count() if numberOfEmail != 0: id = User.objects.filter(email=email).values('id')[0]['id'] user = get_object_or_404(User, pk=id) if user.is_active: res = "There is already an AmieGoo account set up with this email address" else: res = "There is already an AmieGoo account set up with this email address But It Is Not Active Please Check Your Mail For Confirmation So You Can Make A Trip Request" else: res = "No account with this email found please Create an account" else: res = "" return HttpResponse('%s' % res) def check_auth(request): if request.user.is_authenticated: return HttpResponse('%s' % "yes") else: return HttpResponse('%s' % "no") # already signed in = 1 # have account = 2 # signed up = 3 complete_status = 0 def design_form_get(request): global complete_status email = request.POST.get('email','') if request.user.is_authenticated: DesignTrip_formSave(request,request.user,False) complete_status = 1 return redirect('form_complete') elif User.objects.filter(email=email).count() !=0: id = User.objects.filter(email=email).values('id')[0]['id'] user = get_object_or_404(User, pk=id) DesignTrip_formSave(request,user,True) complete_status = 2 return redirect('form_complete') else: user = User_SignUp(request) DesignTrip_formSave(request,user,True) complete_status = 3 #### for confirmation mail current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('TripPackages/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = request.POST.get('email','') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return redirect('form_complete') def form_complete(request): global complete_status if complete_status == 1: message = 'Your Trip Request Was Sent Successfully You Can See Your Request In Your Account' elif complete_status == 2: message = 'Your Trip Request Was Sent Successfully Please Login To See Your Account' elif complete_status == 3: message = 'Your Trip Request Was Sent Successfully And A Confirmation Mail Was Sent To Your Mail' return render(request,'form_Complete.html',{'message':message})<file_sep>/TripReserv/Trip/TripPackages/migrations/0003_place_year_in_school.py # Generated by Django 2.2 on 2019-04-16 20:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('TripPackages', '0002_auto_20190416_1308'), ] operations = [ migrations.AddField( model_name='place', name='year_in_school', field=models.CharField(choices=[('historical', 'historical'), ('local_culture', 'local_culture'), ('local_cusine', 'local_cusine'), ('relaxation', 'Senrelaxationior')], default='historical', max_length=2), ), ] <file_sep>/README.md # TripReservation- Trip Adviser and Reservation System developed with Django Apps : CustomUser App : to customize user model of django , go to model.py in that app , and add any attribute you want. <file_sep>/TripReserv/Trip/designTrip/static/design_form/js/design_form.js // to get csrftoken and setup ajax with it function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) c_end = document.cookie.length; return unescape(document.cookie.substring(c_start,c_end)); } } return ""; } $(function () { $.ajaxSetup({ headers: { "X-CSRFToken": getCookie("csrftoken") } }); }); /* --------------------------------------------------------------- Trip Type Filter -----------------------------------------------------------------*/ class City{ constructor(name, relaxation, historical, culture, cuisine,button,mobile_button,selected) { this.name = name; this.relaxation = relaxation; this.history = historical; this.culture = culture; this.cuisine = cuisine; this.button = button; this.button_mobile = mobile_button; this.selected = selected; } } var cities = []; var city = new City('cairo',false,true,true,true, document.getElementById('cairo'),document.getElementById('cairo_m'),false); cities.push(city); city = new City('alexandria',false,true,true,true, document.getElementById('alexandria'),document.getElementById('alexandria_m'),false); cities.push(city); city = new City('luxour',false,true,true,false, document.getElementById('luxour'),document.getElementById('luxour_m'),false); cities.push(city); city = new City('aswan',false,true,true,false, document.getElementById('aswan'),document.getElementById('aswan_m'),false); cities.push(city); city = new City('dahab',true,false,false,false, document.getElementById('dahab'),document.getElementById('dahab_m'),false); cities.push(city); city = new City('marsa_alam',true,false,true,false, document.getElementById('marsa_alam'),document.getElementById('marsa_alam_m'),false); cities.push(city); city = new City('siwa',true,false,true,false, document.getElementById('siwa'),document.getElementById('siwa_m'),false); cities.push(city); var relaxation = false; var historical = false; var culture = false ; var cuisine = false ; var trip_type = ""; var about_trip = ""; function change_filter(button) { var all_disappeared = true; if (button.className === "btn btn-outline-info type_btn" || button.className === "btn btn-outline-info type_btn mobile" ) { if(button.className === "btn btn-outline-info type_btn") button.className = "btn btn-info type_btn"; else if(button.className === "btn btn-outline-info type_btn mobile") button.className = "btn btn-info type_btn mobile"; if(button.id === "relaxation" || button.id === "relaxation_mobile") { relaxation = true; trip_type +="Relaxation-"; } else if(button.id === "historical" || button.id === "historical_mobile") { historical = true; trip_type +="Historical-"; } else if(button.id === "culture" || button.id === "culture_mobile") { culture = true; trip_type +="Local Culture-"; } else if(button.id === "cuisine" || button.id === "cuisine_mobile") { cuisine = true; trip_type +="Local Cuisine-"; } } else { if(button.className === "btn btn-info type_btn") button.className = "btn btn-outline-info type_btn"; else if(button.className === "btn btn-info type_btn mobile") button.className = "btn btn-outline-info type_btn mobile"; if(button.id === "relaxation" || button.id === "relaxation_mobile") { relaxation = false; trip_type =trip_type.replace("Relaxation-", ""); } else if(button.id === "historical" || button.id === "historical_mobile") { historical = false; trip_type =trip_type.replace("Historical-", ""); } else if(button.id === "culture" || button.id === "culture_mobile") { culture = false; trip_type =trip_type.replace("Local Culture-", ""); } else if(button.id === "cuisine" || button.id === "cuisine_mobile") { cuisine = false; trip_type =trip_type.replace("Local Cuisine-", ""); } } if (relaxation || historical || culture || cuisine) { for(var i =0; i<cities.length; i++){ cities[i].button.style.display = "none"; cities[i].selected = false; } } if (!relaxation && !historical && !culture && !cuisine) { for( i =0; i<cities.length; i++){ cities[i].button.style.display = "inline"; cities[i].selected = false; } } if(relaxation){ for( i =0; i<cities.length; i++){ if(cities[i].relaxation) { cities[i].button.style.display = "inline"; cities[i].selected = true; } } } if(historical){ for( i =0; i<cities.length; i++){ if(cities[i].history) { cities[i].button.style.display = "inline"; cities[i].selected = true; } } } if(culture){ for( i =0; i<cities.length; i++){ if(cities[i].culture) { cities[i].button.style.display = "inline"; cities[i].selected = true; } } } if(cuisine){ for( i =0; i<cities.length; i++){ if(cities[i].cuisine) { cities[i].button.style.display = "inline"; cities[i].selected = true; } } } /* for( i =0; i<cities.length; i++){ if(relaxation && !historical && !culture && !cuisine) //relaxation { if(cities[i].relaxation) cities[i].button.style.display = "inline"; } else if(relaxation && historical && !culture && !cuisine) //relaxation and historical { if(cities[i].relaxation && cities[i].history) cities[i].button.style.display = "inline"; } else if(relaxation && historical && culture && !cuisine) //relaxation and historical and culture { if(cities[i].relaxation && cities[i].history && cities[i].culture) cities[i].button.style.display = "inline"; } else if(relaxation && historical && culture && cuisine) //all { if(cities[i].relaxation && cities[i].history && cities[i].culture && cities[i].cuisine) cities[i].button.style.display = "inline"; } else if(!relaxation && historical && !culture && !cuisine) // historical { if(cities[i].history) cities[i].button.style.display = "inline"; } else if(!relaxation && historical && culture && !cuisine) //historical and culture { if(cities[i].history && cities[i].culture) cities[i].button.style.display = "inline"; } else if(!relaxation && historical && culture && cuisine) // historical and culture and cuisine { if(cities[i].history && cities[i].culture && cities[i].cuisine) cities[i].button.style.display = "inline"; } else if(!relaxation && !historical && culture && !cuisine) //culture { if(cities[i].culture) cities[i].button.style.display = "inline"; } else if(!relaxation && !historical && culture && cuisine) //culture and cuisine { if(cities[i].culture && cities[i].cuisine) cities[i].button.style.display = "inline"; } else if(!relaxation && !historical && !culture && cuisine) //cuisine { if(cities[i].cuisine) cities[i].button.style.display = "inline"; } else if(relaxation && !historical && culture && !cuisine) //relaxation and culture { if(cities[i].relaxation && cities[i].culture) cities[i].button.style.display = "inline"; } else if(relaxation && !historical && culture && cuisine) //relaxation and culture and cuisine { if(cities[i].relaxation && cities[i].culture && cities[i].cuisine) cities[i].button.style.display = "inline"; } else if(relaxation && !historical && !culture && cuisine) //relaxation and cuisine { if(cities[i].relaxation && cities[i].cuisine) cities[i].button.style.display = "inline"; } else if(!relaxation && historical && !culture && cuisine) // historical and cuisine { if(cities[i].history && cities[i].cuisine) cities[i].button.style.display = "inline"; } else if(relaxation && !historical && culture && cuisine) //relaxation and historical and cuisine { if(cities[i].relaxation && cities[i].history && cities[i].cuisine) cities[i].button.style.display = "inline"; } } */ for( i =0; i<cities.length; i++){ if(cities[i].button.style.display !== "none") { all_disappeared = false; break; } } if(all_disappeared){ document.getElementById('whereToGo').style.display = 'none'; } else { document.getElementById('whereToGo').style.display = 'inline'; } if(trip_type != ""){ document.getElementById('trip_type_error').style.display = 'none'; } } /* --------------------------------------------------------------- Tab change -----------------------------------------------------------------*/ var submitting = false; var authenticated = false; var currentTab = 0; // Current tab is set to be the first tab (0) showTab(currentTab); // Display the current tab function showTab(n) { // This function will display the specified tab of the form ... var x = document.getElementsByClassName("tab"); x[n].style.display = "block"; //To be on the top of the tab // ... and fix the Previous/Next buttons: if (n === 0) { document.getElementById("previous").style.display = "none"; } else { document.getElementById("previous").style.display = "inline"; } if (n === (x.length - 1)) { if(document.getElementById('signup_div').style.display === 'inline'){ document.getElementById("next").style.display = "inline"; document.getElementById("next").innerHTML = "Sign Up and Send Request"; } else{ document.getElementById("next").style.display = "none"; } } else { document.getElementById("next").style.display = "inline"; document.getElementById("next").innerHTML = "Next"; } //to display cities to begin from in tab 3 if(n===2){ for(var i=0;i<cities.length;i++){ document.getElementById(cities[i].name+"_tab3").style.display = 'none'; if(cities[i].selected){ document.getElementById(cities[i].name+"_tab3").style.display = "inline"; } if(!cities[i].selected) { document.getElementById(cities[i].name+"_in").checked = false; } } } if(n===2 &&authenticated){ document.getElementById("next").innerHTML = "Send Request"; } // ... and run a function that displays the correct step indicator: fixStepIndicator(n); var navOffset = 100; var div_postion = $("#title").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 750); // 1000 for scroll speed } function nextPrev(n) { // This function will figure out which tab to display var x = document.getElementsByClassName("tab"); // put it in the valid function when complete if(currentTab===3 && n===1 && isValid()){ document.getElementsByClassName("step")[currentTab].className += " finish"; if(document.getElementById('next').innerHTML === "Send Request"){ submitting = true; document.getElementsByClassName("step")[currentTab].className += " finish"; trip_type = trip_type.substr(0,trip_type.length-1); document.getElementById('trip_type').value = trip_type; about_trip = about_trip.substr(0,about_trip.length-1); document.getElementById('about_trip').value = about_trip; document.getElementById('country_complete').value = $('#address-country').find(":selected").text(); $("input[name=csrfmiddlewaretoken]").val(getCookie('csrftoken')); document.forms['design_form'].submit(); } else if(document.getElementById('next').innerHTML === "Sign Up and Send Request"){ submitting = true; document.getElementsByClassName("step")[currentTab].className += " finish"; trip_type = trip_type.substr(0,trip_type.length-1); document.getElementById('trip_type').value = trip_type; about_trip = about_trip.substr(0,about_trip.length-1); document.getElementById('about_trip').value = about_trip; document.getElementById('country_complete').value = $('#address-country').find(":selected").text(); $("input[name=csrfmiddlewaretoken]").val(getCookie('csrftoken')); document.forms['design_form'].submit(); } } else if(currentTab===2 && n===1 && authenticated && isValid()){ submitting = true; document.getElementsByClassName("step")[currentTab].className += " finish"; trip_type = trip_type.substr(0,trip_type.length-1); document.getElementById('trip_type').value = trip_type; about_trip = about_trip.substr(0,about_trip.length-1); document.getElementById('about_trip').value = about_trip; document.getElementById('country_complete').value = $('#address-country').find(":selected").text(); document.forms['design_form'].submit(); } else if(currentTab!==3 && n===1 && isValid()){ document.getElementsByClassName("step")[currentTab].className += " finish"; x[currentTab].style.display = "none"; currentTab = currentTab + n; showTab(currentTab); } else if(n===-1) { document.getElementsByClassName("step")[currentTab-1].classList.remove("finish"); x[currentTab].style.display = "none"; currentTab = currentTab + n; showTab(currentTab); } } function fixStepIndicator(n) { // This function removes the "active" class of all steps... var i, x = document.getElementsByClassName("step"); for (i = 0; i < x.length; i++) { x[i].className = x[i].className.replace(" active", ""); } //... and adds the "active" class to the current step: x[n].className += " active"; } function step_button(n) { // This function will figure out which tab to display var x = document.getElementsByClassName("tab"); if(n<currentTab){ x[currentTab].style.display = "none"; currentTab = n; showTab(n); } } $('.number').each(function () { $(this).number(); }); // function to get month for the next year in array to be in the drop list function monthList(){ var date = new Date(); var current_year = date.getFullYear(); var current_month = date.getMonth() + 2; // add one for index and one to be at the next month var monthlist = []; for(var i = 0;i<10;i++){ if(current_month ==1){ monthlist.push('January '+String(current_year)); current_month++; } else if(current_month ==2){ monthlist.push('February '+String(current_year)); current_month++; } else if(current_month ==3){ monthlist.push('March '+String(current_year)); current_month++; } else if(current_month ==4){ monthlist.push('April '+String(current_year)); current_month++; } else if(current_month ==5){ monthlist.push('May '+String(current_year)); current_month++; } else if(current_month ==6){ monthlist.push('June '+String(current_year)); current_month++; } else if(current_month ==7){ monthlist.push('July '+String(current_year)); current_month++; } else if(current_month ==8){ monthlist.push('August '+String(current_year)); current_month++; } else if(current_month ==9){ monthlist.push('September '+String(current_year)); current_month++; } else if(current_month ==10){ monthlist.push('October '+String(current_year)); current_month++; } else if(current_month ==11){ monthlist.push('November '+String(current_year)); current_month++; } else if(current_month ==12){ monthlist.push('December '+String(current_year)); current_month=1; current_year++; } } return monthlist; } var monthlist = monthList(); for(var i=0;i<10;i++){ document.getElementById("option"+String(i+1)).value = monthlist[i]; document.getElementById("option"+String(i+1)).innerHTML = monthlist[i]; } var period_options = ['Give me a suggestion','Less than a week','1 week','2 weeks', '3 weeks','More than 3 week']; for(var i=0;i<6;i++){ document.getElementById('op'+String(i+1)).value = period_options[i]; document.getElementById('op'+String(i+1)).innerHTML = period_options[i]; } //Display Only Date till today // var dtToday = new Date(); var month = dtToday.getMonth() + 1; // getMonth() is zero-based var day = dtToday.getDate(); var year = dtToday.getFullYear(); if(month < 10) month = '0' + month.toString(); if(day < 10) day = '0' + day.toString(); var maxDate = year + '-' + month + '-' + day; $('#arrival_date').attr('min', maxDate); document.getElementById('departure_date').disabled = true; function adjustDate(date) { if(!Date.parse(date.value)) { document.getElementById('departure_date').value = null; document.getElementById('departure_date').disabled = true; } else{ document.getElementById('departure_date').disabled = false; $('#departure_date').attr('min', date.value); } } function showQuestion(radio) { var questions = document.getElementsByClassName('variable_question') for(var i =0; i<questions.length;i++) { questions[i].style.display = 'none'; } // to reser hidden questions not so not go get to me at database document.getElementById('number_adult').value = 1; document.getElementById('number_children').value = 0; var couple_radios = $("input[name=couple_question]"); for(var i =0; i<couple_radios.length;i++) { couple_radios[i].checked = false; } if(radio.id === "couple"){ document.getElementById('couple_question').style.display = 'inline'; } else if(radio.id === "family" || radio.id === "friends"){ document.getElementById('number_people').style.display = 'inline'; } } function showQuestion2(radio) { var questions = document.getElementsByClassName('variable_question2') for(var i =0; i<questions.length;i++) { questions[i].style.display = 'none'; } document.getElementById('arrival_date').valueAsDate = null; document.getElementById('departure_date').valueAsDate = null; document.getElementById('arrival_date').disabled = true; document.getElementById('departure_date').disabled = true; document.getElementById('month').value = ""; document.getElementById('period').value = ""; if(radio.id === "date_yes"){ document.getElementById('exact_dates').style.display = 'inline'; document.getElementById('arrival_date').disabled = false; } else if(radio.id === "date_no") { document.getElementById('notSure_date').style.display = 'inline'; } } $( document ).ready(function() { document.getElementById('additional_info_textarea').value = ""; var radio = $("input:radio"); for(var i =0; i<radio.length;i++) { radio[i].checked = false; } var checkbox = $("input[type=checkbox]"); for(var i =0; i<checkbox.length;i++) { checkbox[i].checked = false; } var numbers = $("input[type=number]"); for(var i =0; i<numbers.length;i++) { numbers[i].value = 0; } document.getElementById('number_adult').value = 1; var dates = $("input[type=date]"); for(var i =0; i<dates.length;i++) { dates[i].valueAsDate = null; dates[i].disabled =true; } var text = $("input[type=text]"); for(var i =0; i<text.length;i++) { text[i].value ="" } var passwords = $("input[type=password]"); for(var i =0; i<passwords.length;i++) { passwords[i].value ="" } // to fix where to begin question render error var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; if(screenWidth<767){ document.getElementById('wheretobegin_div').classList.replace('col-2','col-md'); document.getElementById('guide_time_div').classList.replace('col-3','col-md'); document.getElementById('next').classList.add("btn-sm"); document.getElementById('previous').classList.add("btn-sm"); } //tab 4 icons document.getElementById('email_checked').style.display = 'none'; document.getElementById('loading').style.display = 'none'; document.getElementById('password_view_signup').style.display = 'none'; document.getElementById('password_view_signup2').style.display = 'none'; document.getElementById('email_input').value = ""; document.getElementById('address-country').value = ""; document.getElementById('email_input').value = ""; $.ajax({ type: "POST", url: 'ajax_check_auth/', success: function (auth) { if(auth==="yes") { document.getElementById('step4').style.display = "none"; authenticated = true; } else authenticated = false; } }); }); /* --------------------------------------------------------------- Function to remove error msg -----------------------------------------------------------------*/ function checkbox_error(pressed_checkbox){ var checkbox1 = document.getElementById('highlights'); var checkbox2 = document.getElementById('off_the_beaten_track'); if(checkbox1.checked || checkbox2.checked) { document.getElementById('about_trip_question_error').style.display = 'none'; document.getElementById('about_trip_question_error_mobile').style.display = 'none'; } if(pressed_checkbox.checked) about_trip += pressed_checkbox.value+"-"; else about_trip = about_trip.replace(pressed_checkbox.value+"-",""); } function budget_error(){ var budget_from = parseInt(document.getElementById('budget_from').value); var budget_to = parseInt(document.getElementById('budget_to').value); if(budget_from > budget_to){ document.getElementById('budget_to').value = budget_from; document.getElementById('budget_to').min = budget_from; } var budget_to = parseInt(document.getElementById('budget_to').value); if(budget_to > 0) document.getElementById('budget_error').style.display = 'none'; document.getElementById('budget_error_mobile').style.display = 'none'; } function Tab2_first_question(){ document.getElementById('people_question_error').style.display = 'none'; document.getElementById('people_question_error_mobile').style.display = 'none'; } function Tab2_couple_question(){ document.getElementById('couple_question_error').style.display = 'none'; document.getElementById('couple_question_error_mobile').style.display = 'none'; } function Tab2_number_question(){ var number_adult = document.getElementById('number_adult').value; var number_children = document.getElementById('number_children').value; if(number_adult>"1" || number_children>"0"){ document.getElementById('number_people_error').style.display = 'none'; document.getElementById('number_people_error_mobile').style.display = 'none'; } } function Tab2_exact_question(){ document.getElementById('exactTime_question_error').style.display = 'none'; document.getElementById('exactTime_question_error_mobile').style.display = 'none'; } function Tab2_notSure_questionDrop(){ var month_select = document.getElementById('month').value; var period_select = document.getElementById('period').value; if(month_select!="" && period_select!="") { document.getElementById('notSure_date_error').style.display = 'none'; document.getElementById('notSure_date_error_mobile').style.display = 'none'; } } function Tab2_calender(){ var arrival_date = document.getElementById('arrival_date').valueAsDate; var departure_date = document.getElementById('departure_date').valueAsDate; if(arrival_date!=null && departure_date!=null) { document.getElementById('exact_dates_error').style.display = 'none'; document.getElementById('exact_dates_error_mobile').style.display = 'none'; } } function Tab3_wheretobegin(){ document.getElementById('whereTobeginTrip_question_error').style.display = 'none'; document.getElementById('whereTobeginTrip_question_error_mobile').style.display = 'none'; } function Tab3_language(){ document.getElementById('language_question_error').style.display = 'none'; document.getElementById('language_question_error_mobile').style.display = 'none'; } function Tab3_agenttime(){ document.getElementById('guide_time_question_error').style.display = 'none'; document.getElementById('guide_time_question_error_mobile').style.display = 'none'; } function Tab3_welcome(){ document.getElementById('welcome_question_error').style.display = 'none'; document.getElementById('welcome_question_error_mobile').style.display = 'none'; } function Tab3_byebye(){ document.getElementById('byebye_question_error').style.display = 'none'; document.getElementById('byebye_question_error_mobile').style.display = 'none'; } function Tab3_car(){ document.getElementById('car_question_error').style.display = 'none'; document.getElementById('car_question_error_mobile').style.display = 'none'; } function Tab3_camera(){ document.getElementById('camera_question_error').style.display = 'none'; document.getElementById('camera_question_error_mobile').style.display = 'none'; } function Tab4_password_signup(password){ var reg = /^(.{0,7}|[^0-9]*)$/; var password2 = document.getElementById('password_input_signup2'); if(password.value!=="") document.getElementById('password_error').style.display = 'none'; if(reg.test(password.value) && password.value!==""){ if(password.value===password2.value){ document.getElementById('password_notStrong2').style.display = 'none'; } document.getElementById('password_notStrong').style.display = 'inline'; } else{ if(password.value===password2.value){ document.getElementById('password_notStrong2').style.display = 'none'; } document.getElementById('password_notStrong').style.display = 'none'; return true; } } function Tab4_password_signup2(password){ var password1 = document.getElementById('password_input_signup'); if(password.value!=="") document.getElementById('password_error2').style.display = 'none'; if(password1.value!==password.value){ document.getElementById('password_notStrong2').style.display = 'inline'; } else{ document.getElementById('password_notStrong2').style.display = 'none'; } } function Tab4_title(){ document.getElementById('title_question_error').style.display = 'none'; } function Tab4_first_name(first_name){ if(first_name.value!=="") document.getElementById('first_name_error').style.display = 'none'; } function Tab4_last_name(last_name){ if(last_name.value!=="") document.getElementById('last_name_error').style.display = 'none'; } function Tab4_country(country){ if(country.value!=="") document.getElementById('country_question_error').style.display = 'none'; } function Tab4_phone(phone){ if(phone.value!=="") document.getElementById('mobile_error').style.display = 'none'; } function Tab4_birthday(birthday){ if(birthday.valueAsDate!==null) document.getElementById('birthDay_question_error').style.display = 'none'; } /* --------------------------------------------------------------- Validation Function -----------------------------------------------------------------*/ function isValid(){ var valid = true; var ScreenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; // the or for all clients if(currentTab == 0){ var checkbox1 = document.getElementById('highlights'); var checkbox2 = document.getElementById('off_the_beaten_track'); var budget_from = parseInt(document.getElementById('budget_from').value); var budget_to = parseInt(document.getElementById('budget_to').value); // trip type question if(trip_type == ""){ if(ScreenWidth>767) { document.getElementById('trip_type_error').style.display = 'inline'; document.getElementById('trip_type_error_mobile').style.display = 'none'; } else { document.getElementById('trip_type_error').style.display = 'none'; document.getElementById('trip_type_error_mobile').style.display = 'inline'; } valid = false; //for scrooling to show error var navOffset = 100; var div_postion = $("#TripType").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); } //about trip question if(!checkbox1.checked && !checkbox2.checked) { if(ScreenWidth>767) { document.getElementById('about_trip_question_error').style.display = 'inline'; document.getElementById('about_trip_question_error_mobile').style.display = 'none'; } else { document.getElementById('about_trip_question_error').style.display = 'none'; document.getElementById('about_trip_question_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#about_trip_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); } valid = false; } //budget question if(budget_to === 0){ if(ScreenWidth>767) { document.getElementById('budget_error').style.display = 'inline'; document.getElementById('budget_error_mobile').style.display = 'none'; } else { document.getElementById('budget_error').style.display = 'none'; document.getElementById('budget_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#budget_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); } valid = false; } return valid ; } else if(currentTab == 1){ // first question var solo = document.getElementById('solo').checked; var couple = document.getElementById('couple').checked; var family = document.getElementById('family').checked; var friends = document.getElementById('friends').checked; if(!solo && !couple && !family && !friends) { if(ScreenWidth>767) { document.getElementById('people_question_error').style.display = 'inline'; document.getElementById('people_question_error_mobile').style.display = 'none'; } else { document.getElementById('people_question_error').style.display = 'none'; document.getElementById('people_question_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#people_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // second question when choose couple in first var couple_question = document.getElementById('') var vacation = document.getElementById('vacation').checked; var honey_moon = document.getElementById('honey_moon').checked; var other = document.getElementById('other').checked; if(!vacation && !honey_moon && !other && $('#couple_question').is(':visible')) { if(ScreenWidth>767) { document.getElementById('couple_question_error').style.display = 'inline'; document.getElementById('couple_question_error_mobile').style.display = 'none'; } else { document.getElementById('couple_question_error').style.display = 'none'; document.getElementById('couple_question_error_mobile').style.display = 'inline'; } //for scrolling to show error if(valid){ var navOffset = 100; var div_postion = $("#couple_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // numbers question when choose family or friends in first var adult_number = document.getElementById('number_adult').value; var children_number = document.getElementById('number_children').value; if(adult_number ==1 && children_number==0 && $('#number_people').is(':visible')) { if(ScreenWidth>767) { document.getElementById('number_people_error').style.display = 'inline'; document.getElementById('number_people_error_mobile').style.display = 'none'; } else { document.getElementById('number_people_error').style.display = 'none'; document.getElementById('number_people_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#number_people").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // question to check for exact date var date_yes = document.getElementById('date_yes').checked; var date_no = document.getElementById('date_no').checked; if(!date_yes && !date_no) { if(ScreenWidth>767) { document.getElementById('exactTime_question_error').style.display = 'inline'; document.getElementById('exactTime_question_error_mobile').style.display = 'none'; } else { document.getElementById('exactTime_question_error').style.display = 'none'; document.getElementById('exactTime_question_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#exactTime_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // question to check for exact date var month_select = document.getElementById('month').value; var period_select = document.getElementById('period').value; if((month_select =="" || period_select=="") && $('#notSure_date').is(':visible')) { if(ScreenWidth>767) { document.getElementById('notSure_date_error').style.display = 'inline'; document.getElementById('notSure_date_error_mobile').style.display = 'none'; } else { document.getElementById('notSure_date_error').style.display = 'none'; document.getElementById('notSure_date_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#notSure_date").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } var arrival_date = document.getElementById('arrival_date').valueAsDate; var departure_date = document.getElementById('departure_date').valueAsDate; if((arrival_date ==null || departure_date==null) && $('#exact_dates').is(':visible')) { if(ScreenWidth>767) { document.getElementById('exact_dates_error').style.display = 'inline'; document.getElementById('exact_dates_error_mobile').style.display = 'none'; } else { document.getElementById('exact_dates_error').style.display = 'none'; document.getElementById('exact_dates_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#exact_dates").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } return valid; } else if(currentTab == 2){ // first to check for where to begin trip var cario_in = document.getElementById('cairo_in').checked; var alexandria_in = document.getElementById('alexandria_in').checked; var luxour_in = document.getElementById('luxour_in').checked; var aswan_in = document.getElementById('aswan_in').checked; var dahab_in = document.getElementById('dahab_in').checked; var marsa_alam_in = document.getElementById('marsa_alam_in').checked; var siwa_in = document.getElementById('siwa_in').checked; if(!cario_in && !alexandria_in && !luxour_in && !aswan_in && !dahab_in && !marsa_alam_in && !siwa_in) { if(ScreenWidth>767) { document.getElementById('whereTobeginTrip_question_error').style.display = 'inline'; document.getElementById('whereTobeginTrip_question_error_mobile').style.display = 'none'; } else { document.getElementById('whereTobeginTrip_question_error').style.display = 'none'; document.getElementById('whereTobeginTrip_question_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#whereTobeginTrip_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // second to check for the guide language var english = document.getElementById('english').checked; var french = document.getElementById('french').checked; if(!english && !french) { if(ScreenWidth>767) { document.getElementById('language_question_error').style.display = 'inline'; document.getElementById('language_question_error_mobile').style.display = 'none'; } else { document.getElementById('language_question_error').style.display = 'none'; document.getElementById('language_question_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#language_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // third to check for the guide time var from9to5 = document.getElementById('from9to5').checked; var from5to12 = document.getElementById('from5to12').checked; var full_day = document.getElementById('full_day').checked; if(!from9to5 && !from5to12 && !full_day) { if(ScreenWidth>767) { document.getElementById('guide_time_question_error').style.display = 'inline'; document.getElementById('guide_time_question_error_mobile').style.display = 'none'; } else { document.getElementById('guide_time_question_error').style.display = 'none'; document.getElementById('guide_time_question_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#guide_time_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // forth to check if he want us to welcome him var welcome_yes = document.getElementById('welcome_yes').checked; var welcome_no = document.getElementById('welcome_no').checked; if(!welcome_yes && !welcome_no) { if(ScreenWidth>767) { document.getElementById('welcome_question_error').style.display = 'inline'; document.getElementById('welcome_question_error_mobile').style.display = 'none'; } else { document.getElementById('welcome_question_error_mobile').style.display = 'none'; document.getElementById('welcome_question_error').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#welcome_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // fifth to check if he want us to byebye him var byebye_yes = document.getElementById('byebye_yes').checked; var byebye_no = document.getElementById('byebye_no').checked; if(!byebye_yes && !byebye_no) { if(ScreenWidth>767) { document.getElementById('byebye_question_error').style.display = 'inline'; document.getElementById('byebye_question_error_mobile').style.display = 'none'; } else { document.getElementById('byebye_question_error').style.display = 'none'; document.getElementById('byebye_question_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#byebye_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // sixth to check if he want car var car_yes = document.getElementById('car_yes').checked; var car_no = document.getElementById('car_no').checked; if(!car_yes && !car_no) { if(ScreenWidth>767) { document.getElementById('car_question_error').style.display = 'inline'; document.getElementById('car_question_error_mobile').style.display = 'none'; } else { document.getElementById('car_question_error').style.display = 'none'; document.getElementById('car_question_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#car_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // seventh to check if he want a camera var camera_yes = document.getElementById('camera_yes').checked; var camera_no = document.getElementById('camera_no').checked; if(!camera_yes && !camera_no) { if(ScreenWidth>767) { document.getElementById('camera_question_error').style.display = 'inline'; document.getElementById('camera_question_error_mobile').style.display = 'none'; } else { document.getElementById('camera_question_error').style.display = 'none'; document.getElementById('camera_question_error_mobile').style.display = 'inline'; } //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#camera_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } return valid; } else if(currentTab == 3){ if(document.getElementById('signup_div').style.display==="inline"){ // password question var password_input_signup = document.getElementById('password_input_signup'); if(password_input_signup.value==="") { document.getElementById('password_error').style.display = 'inline'; //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#password_div_signup").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } else if(!password_IsStrong(password_input_signup)){ if(valid){ var navOffset = 100; var div_postion = $("#password_div_signup").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } //password 2 question var password_input_signup2 = document.getElementById('password_input_signup2'); if(password_input_signup2.value==="") { document.getElementById('password_error2').style.display = 'inline'; //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#password_div_signup2").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } else if(password_input_signup.value!==password_input_signup2.value){ document.getElementById('password_notStrong2').style.display = 'inline'; if(valid){ var navOffset = 100; var div_postion = $("#password_div_signup2").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // title question var ms = document.getElementById('ms').checked; var mr = document.getElementById('mr').checked; if(!ms && !mr) { document.getElementById('title_question_error').style.display = 'inline'; //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#title_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // first name question var first_name = document.getElementById('first_name').value; if(first_name==="") { document.getElementById('first_name_error').style.display = 'inline'; //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#name_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // lastname question var last_name = document.getElementById('last_name').value; if(last_name ==="") { document.getElementById('last_name_error').style.display = 'inline'; //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#name_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // country question var country = document.getElementById('address-country').value; if(country ==="") { document.getElementById('country_question_error').style.display = 'inline'; //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#country_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // phone question var phone = document.getElementById('phone').value; if(phone ==="") { document.getElementById('mobile_error').style.display = 'inline'; //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#country_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } else if(document.querySelector("#valid-msg").style.display!=="inline"){ if(valid){ var navOffset = 100; var div_postion = $("#country_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } // birthday question var birthday = document.getElementById('birthday').valueAsDate; if(birthday === null) { document.getElementById('birthDay_question_error').style.display = 'inline'; //for scrooling to show error if(valid){ var navOffset = 100; var div_postion = $("#birthDay_question").offset().top - navOffset; $('html, body').animate({ scrollTop: div_postion }, 1000); // 1000 for scroll speed } valid = false; } } return valid; } return valid; } // function to hide bugs when resizing window window.addEventListener('resize', function () { var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; // the or for all clients var mobile_errors = document.getElementsByClassName('error_message_mobile'); var windows_errors = document.getElementsByClassName('error_message'); if(screenWidth>767){ for(var i =0; i<windows_errors.length;i++) { if(mobile_errors[i].style.display==='inline') { mobile_errors[i].style.display ='none'; windows_errors[i].style.display = 'inline'; } } if( document.getElementById('wheretobegin_div').classList.contains("col-md")) document.getElementById('wheretobegin_div').classList.replace('col-md','col-3'); if( document.getElementById('guide_time_div').classList.contains("col-md")) document.getElementById('guide_time_div').classList.replace('col-md','col-3'); } else{ for(var i =0; i<windows_errors.length;i++) { if(windows_errors[i].style.display==='inline') { mobile_errors[i].style.display ='inline'; windows_errors[i].style.display = 'none'; } } if( document.getElementById('wheretobegin_div').classList.contains('col-3')) document.getElementById('wheretobegin_div').classList.replace('col-3','col-md'); if( document.getElementById('guide_time_div').classList.contains("col-3")) document.getElementById('guide_time_div').classList.replace('col-3','col-md'); } }); var input = document.querySelector("#phone"); var errorMsg = document.querySelector("#error-msg"); var validMsg = document.querySelector("#valid-msg"); var countryData = window.intlTelInputGlobals.getCountryData(); var addressDropdown = document.querySelector("#address-country"); // here, the index maps to the error code returned from getValidationError - see readme var errorMap = [ "Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"]; // initialise plugin var iti = window.intlTelInput(input, { nationalMode: true, utilsScript: "../static/design_form/intl-tel-input-master/build/js/utils.js?1549804213570" }); // populate the country dropdown for (var i = 0; i < countryData.length; i++) { var country = countryData[i]; var optionNode = document.createElement("option"); optionNode.value = country.iso2; var textNode = document.createTextNode(country.name); optionNode.appendChild(textNode); addressDropdown.appendChild(optionNode); } // set it's initial value addressDropdown.value = iti.getSelectedCountryData().iso2; // listen to the telephone input for changes input.addEventListener('countrychange', function(e) { addressDropdown.value = iti.getSelectedCountryData().iso2; }); // listen to the address dropdown for changes addressDropdown.addEventListener('change', function() { iti.setCountry(this.value); }); /////for error and valid msgs var reset = function() { input.classList.remove("error"); errorMsg.innerHTML = ""; errorMsg.style.display = 'none'; validMsg.style.display = 'none'; }; // on blur: validate input.addEventListener('blur', function() { reset(); if (input.value.trim()) { if (iti.isValidNumber()) { document.getElementById('mobile_complete').value = iti.getNumber(); validMsg.style.display = 'inline' } else { input.classList.add("error"); var errorCode = iti.getValidationError(); errorMsg.innerHTML = errorMap[errorCode]; errorMsg.style.display = 'inline'; } } }); // on keyup / change flag: reset input.addEventListener('change', reset); input.addEventListener('keyup', reset); /// fucntion to toggle password function toggle_password(img){ var password_signup = document.getElementById('password_input_signup'); var password_signup2 = document.getElementById('password_input_signup2'); if(img.id==="password_view_signup"){ password_signup.type = "password"; document.getElementById('password_view_signup').style.display = 'none'; document.getElementById('password_hide_signup').style.display = 'inline'; } else if(img.id==="password_hide_signup"){ password_signup.type = "text"; document.getElementById('password_view_signup').style.display = 'inline'; document.getElementById('password_hide_signup').style.display = 'none'; } else if(img.id==="password_view_signup2"){ password_signup2.type = "password"; document.getElementById('password_view_signup2').style.display = 'none'; document.getElementById('password_hide_signup2').style.display = 'inline'; } else if(img.id==="password_hide_signup2"){ password_signup2.type = "text"; document.getElementById('password_view_signup2').style.display = 'inline'; document.getElementById('password_hide_signup2').style.display = 'none'; } } function validateEmail(emailField){ var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; if (reg.test(emailField.value) == false) { document.getElementById('invalid_email').style.display = 'inline'; return false; } document.getElementById('invalid_email').style.display = 'none'; return true; } //function to check for user auth to not enter tab 3 if auth // not to enter ajax function 2 times var in_ajax = 0; function checkEmail(){ var email = document.getElementById('email_input'); if(validateEmail(email)){ // code to check for mail with ajax emailValue = email.value; if ((emailValue != "") && (in_ajax != 1)) { in_ajax = 1; document.getElementById('checkButton_div').style.display="none"; document.getElementById('loading').style.display="inline"; $("#email_info").load('check_email/', {emailValue}, function(email_info) { showSubTab(email_info); in_ajax = 0; }); } } } /// function on change email function hide_divs(){ document.getElementById('signup_div').style.display = "none"; document.getElementById('email_checked').style.display = 'none'; document.getElementById('checkButton_div').style.display = 'inline'; document.getElementById('next').style.display = 'none'; //elemets reset document.getElementById('email_info').innerHTML = ""; document.getElementById('password_input_signup').value = ""; document.getElementById('password_input_signup2').value = ""; document.getElementById('ms').checked = false; document.getElementById('mr').checked = false; document.getElementById('first_name').value = ""; document.getElementById('last_name').value = ""; document.getElementById('address-country').value = ""; document.getElementById('phone').value = ""; document.getElementById('birthday').valueAsDate = null; } function password_IsStrong(password){ // regular expersion for invalid password var reg = /^(.{0,7}|[^0-9]*)$/; if(reg.test(password.value)){ document.getElementById('password_notStrong').style.display = 'inline'; return false; } else{ document.getElementById('password_notStrong').style.display = 'none'; return true; } } function showSubTab(email_info){ if(email_info ==="There is already an AmieGoo account set up with this email address"){ document.getElementById('signup_div').style.display = "none"; document.getElementById('next').style.display = 'inline'; document.getElementById('next').innerHTML = 'Send Request'; document.getElementById('checkButton_div').style.display = 'none'; document.getElementById('loading').style.display = "none"; document.getElementById('email_checked').style.display = 'inline'; } else if(email_info ==="No account with this email found please Create an account") { document.getElementById('signup_div').style.display = "inline"; document.getElementById('next').style.display = 'inline'; document.getElementById('next').innerHTML = 'Sign Up and Send Request'; document.getElementById('checkButton_div').style.display = 'none'; document.getElementById('loading').style.display = "none"; document.getElementById('email_checked').style.display = 'inline'; document.getElementById('birthday').disabled = false; } else if(email_info==="There is already an AmieGoo account set up with this email address But It Is Not Active Please Check Your Mail For Confirmation So You Can Make A Trip Request"){ document.getElementById('signup_div').style.display = "none"; document.getElementById('next').style.display = 'none'; document.getElementById('checkButton_div').style.display = 'none'; document.getElementById('loading').style.display = "none"; document.getElementById('email_checked').style.display = 'inline'; } } window.onbeforeunload = function() { if(submitting) return; else return confirm('Are You Sure You Want To Leave The Form Before Sending Request ?'); };<file_sep>/TripReserv/Trip/designTrip/migrations/0001_initial.py # Generated by Django 2.2 on 2019-04-10 14:34 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='DesignTrip', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('trip_type', models.CharField(blank=True, max_length=50)), ('about_trip', models.CharField(blank=True, max_length=50)), ('budget', models.IntegerField(blank=True)), ('travel_with', models.CharField(blank=True, max_length=50)), ('couple_question', models.CharField(blank=True, max_length=50)), ('adult_number', models.IntegerField(blank=True)), ('chidren_number', models.IntegerField(blank=True)), ('exact_date', models.CharField(blank=True, max_length=50)), ('arrival_date', models.DateField(blank=True)), ('departure_date', models.DateField(blank=True)), ('month', models.CharField(blank=True, max_length=50)), ('period', models.CharField(blank=True, max_length=50)), ('begin_trip', models.CharField(blank=True, max_length=50)), ('agent_language', models.CharField(blank=True, max_length=50)), ('agent_time', models.CharField(blank=True, max_length=50)), ('agent_welcome', models.CharField(blank=True, max_length=50)), ('agent_byeby', models.CharField(blank=True, max_length=50)), ('agent_car', models.CharField(blank=True, max_length=50)), ('agent_camera', models.CharField(blank=True, max_length=50)), ('additional_info', models.TextField(blank=True, max_length=1000)), ], ), ]
436a4330047d3cc75a6af43661a3099896c3c7ae
[ "JavaScript", "Python", "Text", "Markdown" ]
30
Python
Nadern96/TripReservation-
5a78136cb36d23f67ef375e976b452fc7365bc53
f20fbe5bc7dcd31ed1c94f783ae34973e86440ba
refs/heads/master
<repo_name>jude1997felix/Music-Classification<file_sep>/README.md # Music-Classification A project was to classify a set of 200 songs into like or dislike by the user based on the previous interest of songs of the user. The models used to classify are ### 1. Logistic Regression ### 2. Linear Discriminant Analysis ### 3. Quadratic Discriminant Analysis ### 4. KNN ### 5. Decision Tree Classifier ### 6. Random Forest Classifier The best accuracy was obtained for Random forest classifier model. <file_sep>/music_classification.py import matplotlib import matplotlib.pyplot as plt from sklearn.grid_search import GridSearchCV from sklearn.model_selection import KFold # import KFold from sklearn.metrics import classification_report def load_train_data(): '''Returns training dataset as dataframe, input features X and target classes y''' train_df = pd.read_csv('training_data.csv') X = train_df.iloc[:,0:13] y = train_df['label'] return train_df, X, y def train_model_for_submission(train_df, model,scaled=False): '''Trains the model on whole training data and returns the trained model''' X = train_df.iloc[:,0:13] y = train_df['label'] if scaled: X = normalise_data(X) clf = model.fit(X, y) return clf def predict_for_submission(model, scaled=False): '''Predicts the labels for data in submission file using the trained model as input and returns the predicted labels''' test_df = pd.read_csv('songs_to_classify.csv') if scaled: test_df = normalise_data(test_df) y_pred = model.predict(test_df.to_numpy()) return y_pred def validate_model1(input_features, target, model, splits): '''Function which splits the data into n folds and validates the model performance''' kf = KFold(n_splits=splits, random_state=None, shuffle=True) for train_index, test_index in kf.split(input_features): X_train, X_test = input_features.iloc[train_index], input_features.iloc[test_index] y_train, y_test = target.iloc[train_index], target.iloc[test_index] clf = model.fit(X_train, y_train) y_pred = clf.predict(X_test) report = classification_report(y_test, y_pred) print(report) # print(pd.crosstab(np.array(y_pred), np.array(y_test)), '\n') print("=====================================================================") return report def validate_model(input_features, target, model, splits): '''Function which splits the data into n folds and validates the model performance''' kf = KFold(n_splits=splits, random_state=None, shuffle=True) for train_index, test_index in kf.split(input_features): X_train, X_test = input_features.iloc[train_index], input_features.iloc[test_index] y_train, y_test = target.iloc[train_index], target.iloc[test_index] clf = model.fit(X_train, y_train) y_pred = clf.predict(X_test) report = classification_report(y_test, y_pred) print(report) print(pd.crosstab(np.array(y_pred), np.array(y_test)), '\n') print("=====================================================================") from sklearn import preprocessing def normalise_data(X): x = X.values #returns a numpy array min_max_scaler = preprocessing.MinMaxScaler() x_scaled = min_max_scaler.fit_transform(x) X_scaled = pd.DataFrame(x_scaled) return X_scaled def evaluateKNN(train_df, y): iterations = 50 splits = 3 results = [] for k in range(iterations): clf = KNeighborsClassifier(n_neighbors=k+1) kf = KFold(n_splits=splits, random_state=None, shuffle=True) split_list=[] for train_index, test_index in kf.split(train_df): X_train, X_test = train_df.iloc[train_index], train_df.iloc[test_index] y_train, y_test = y.iloc[train_index], y.iloc[test_index] clf = model.fit(X_train, y_train) y_pred = clf.predict(X_test) split_list.append(np.mean(y_pred != y_test)) results.append(split_list) # Plotting the misclassification rate as a scatter plot for 3 folds import matplotlib.pyplot as plt mis1 = [] mis2 = [] mis3 = [] for i in range(50): mis1.append(results[i][0]) mis2.append(results[i][1]) mis3.append(results[i][2]) # for fold 1 K = np.linspace(1,50,50) plt.plot(K, mis1, '.') plt.ylabel("Misclassification") plt.xlabel("Number of neighbors") plt.show() # for fold 2 K = np.linspace(1,50,50) plt.plot(K, mis2, '.') plt.ylabel("Misclassification") plt.xlabel("Number of neighbors") plt.show() # for fold 3 K = np.linspace(1,50,50) plt.plot(K, mis3, '.') plt.ylabel("Misclassification") plt.xlabel("Number of neighbors") plt.show() # KNN on raw data evaluateKNN(X, y) # KNN for normalised data evaluateKNN(X_scaled, y) model = LogisticRegression(solver='lbfgs',penalty='l2', class_weight='balanced') print(model) validate_model(X,y, model, 3) # logistic regression model model = LogisticRegression(solver='liblinear', penalty='l1', class_weight='balanced') model = train_model_for_submission(train_df, model) predicted_values = predict_for_submission(model) # Scatter plot for the label vs speechiess train_df.plot.scatter(x='label',y='speechiness'); # Scatter plot for the label vs danceability train_df.plot.scatter(x='label',y='danceability'); # Scatter plot for the label vs acousticness train_df.plot.scatter(x='label',y='acousticness'); # Scatter plot for the label vs speechiness vs danceability vs acousticness sns.set() cols = ['label','speechiness','danceability','acousticness'] sns.pairplot(train_df[cols], height = 5) plt.show(); #Random Forest classifier model for the raw data train_df = pd.read_csv('training_data.csv') X = train_df.iloc[:,0:13] y = train_df['label'] model= RandomForestClassifier(n_estimators=500,min_samples_split=25) print(model) validate_model(X,y, model, 3) # Random Forest classifier model for the normalized data X_scaled = normalise_data(X) model= RandomForestClassifier(n_estimators=500,min_samples_split=25) print(model) validate_model(X_scaled,y, model, 3) # Random Forest classifier model for the raw data with new features model= RandomForestClassifier(n_estimators=500,min_samples_split=20) print(model) validate_model(X_new,y, model, 3) # Random Forest classifier model for the normalized data with the new features X_scaled_new= normalise_data(X_new) model= RandomForestClassifier(n_estimators=500,min_samples_split=20) print(model) validate_model(X_scaled_new,y, model, 3) #Pandas profiling to find the weightage of the attributes from pandas_profiling import ProfileReport profile = ProfileReport(df, title='Pandas Profiling Report', html={'style':{'full_width':True}}) # Decision Tree Classifier for raw data model= tree.DecisionTreeClassifier(max_depth=2) print(model) validate_model(X_new,y, model, 3) #Decision Tree Classifier for normalised data X_scaled=normalise_data(X) model= tree.DecisionTreeClassifier(max_depth=2) print(model) validate_model(X_scaled,y, model, 3) # LDA model on raw data from sklearn.discriminant_analysis import LinearDiscriminantAnalysis X = train_df.iloc[:,0:13] y = train_df['label'] model = LinearDiscriminantAnalysis() print(model) validate_model(X,y, model, 3) # LDA for normalised data from sklearn.discriminant_analysis import LinearDiscriminantAnalysis X = train_df.iloc[:,0:13] y = train_df['label'] X_scaled = normalise_data(X) model = LinearDiscriminantAnalysis() print(model) validate_model(X_scaled,y, model, 3) # QDA for raw data from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis X = train_df.iloc[:,0:13] y = train_df['label'] model = QuadraticDiscriminantAnalysis() print(model) validate_model(X,y, model, 3) # QDA for normalised data from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis X = train_df.iloc[:,0:13] y = train_df['label'] X_scaled = normalise_data(X) model = QuadraticDiscriminantAnalysis() print(model) validate_model(X_scaled,y, model, 3)
0bf19bb8a37cf93c94f36092b6349ce5c545a5f5
[ "Markdown", "Python" ]
2
Markdown
jude1997felix/Music-Classification
fa2b1f1037d6f938d1b7a43b15f958f718423f43
d581469f748220dfac94d1f2067335e0f272a93b
refs/heads/master
<repo_name>Felix-lx/webpack-vue-practice<file_sep>/01base/src/main.js console.log(111); import './js/demo1' import {fn} from './js/demo2' fn() import './less/index.less' import obj from './js/demo3' console.log(obj.name,obj.age,obj.gender); <file_sep>/01base/src/js/demo2.js export const fn = ()=>{console.log("我是demo2");} <file_sep>/01base/src/js/demo3.js const name = 'Felix' const age = 26 const gender = 'man' export default { name, age, gender }<file_sep>/02webpackVue/src/router/index.js import Vue from 'vue' import VueRouter from 'vue-router' import Component1 from '../components/component1.vue' import Component2 from '../components/component2.vue' Vue.use(VueRouter) const router = new VueRouter({ routes:[ {path:'/component1',component:Component1}, {path:'/component2',component:Component2} ] }) export default router<file_sep>/01base/src/js/demo1.js const fn = ()=>{console.log("我是demo.js文件,看到我说明导出成功了");} fn()
03ad95b209833ba820ecefd83bf0ad38bb360fe9
[ "JavaScript" ]
5
JavaScript
Felix-lx/webpack-vue-practice
80a6aff503ff52532fb88b1377b49996135ef2ad
6787b129d6917b759a2001a13eb92eb9c1b476a9
refs/heads/main
<repo_name>saivivek7495/Predicting-Customer-Churn_Neural-Networks_Deep-Learning<file_sep>/helper.py from sklearn.metrics import confusion_matrix, roc_curve, auc import matplotlib.pyplot as plt # Function to compute the metrics def compute_metrics(train_pred, y_train, test_pred, y_test): # Confusion matrix for train predictions confmat = confusion_matrix(y_train, train_pred) print('Train metrics') print('Confusion matrix') print(confmat) print("----------------------------------------------") TP = confmat[0,0] TN = confmat[1,1] FN = confmat[0,1] FP = confmat[1,0] Total = TP + TN + FP + FN # Accuracy: Overall, how often is the classifier correct? Accuracy = (TP+TN)/Total # Misclassification Rate: Overall, how often is it wrong? # equivalent to 1 minus Accuracy also known as "Error Rate" Misclassification_Rate = (FP+FN)/Total # True Positive Rate: When it's actually yes, how often does it predict yes? # also known as "Sensitivity" or "Recall" Actual_Yes = TP + FN Recall = TP/Actual_Yes # False Positive Rate: When it's actually no, how often does it predict yes? Actual_No = TN + FP FPR = FP/Actual_No # True Negative Rate: When it's actually no, how often does it predict no? # equivalent to 1 minus False Positive Rate, also known as "Specificity" TNR = TN/Actual_No # Precision: When it predicts yes, how often is it correct? Predicted_Yes = TP + FP Precission = TP/Predicted_Yes # Prevalence: How often does the yes condition actually occur in our sample? Prevalance = Actual_Yes / Total # F1 Score f1 = 2 * (Precission * Recall) / (Precission + Recall) print('Accuracy: ', Accuracy) print('Precission: ', Precission) print('Recall: ', Recall) print('F1 Score: ', f1) print("") print("==============================================") print("") # Confusion matrix for train predictions confmat = confusion_matrix(y_test, test_pred) print('Test metrics') print('Confusion matrix') print(confmat) print("----------------------------------------------") TP = confmat[0,0] TN = confmat[1,1] FN = confmat[0,1] FP = confmat[1,0] Total = TP + TN + FP + FN # Accuracy: Overall, how often is the classifier correct? Accuracy = (TP+TN)/Total # Misclassification Rate: Overall, how often is it wrong? # equivalent to 1 minus Accuracy also known as "Error Rate" Misclassification_Rate = (FP+FN)/Total # True Positive Rate: When it's actually yes, how often does it predict yes? # also known as "Sensitivity" or "Recall" Actual_Yes = TP + FN Recall = TP/Actual_Yes # False Positive Rate: When it's actually no, how often does it predict yes? Actual_No = TN + FP FPR = FP/Actual_No # True Negative Rate: When it's actually no, how often does it predict no? # equivalent to 1 minus False Positive Rate, also known as "Specificity" TNR = TN/Actual_No # Precision: When it predicts yes, how often is it correct? Predicted_Yes = TP + FP Precission = TP/Predicted_Yes # Prevalence: How often does the yes condition actually occur in our sample? Prevalance = Actual_Yes / Total # F1 Score f1 = 2 * (Precission * Recall) / (Precission + Recall) print('Accuracy: ', Accuracy) print('Precission: ', Precission) print('Recall: ', Recall) print('F1 Score: ', f1) # Function to draw plot for the train and validation accuracies def accuracy_plot(history): plt.clf() # Clears the figure history_dict = history.history acc_values = history_dict['accuracy'] val_acc_values = history_dict['val_accuracy'] epochs = range(1, len(acc_values) + 1) plt.plot(epochs, acc_values, label='Training accuracy') plt.plot(epochs, val_acc_values, label='Validation accuracy') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Function to draw plot for the train and validation loss def loss_plot(history): plt.clf() # Clears the figure history_dict = history.history acc_values = history_dict['loss'] val_acc_values = history_dict['val_loss'] epochs = range(1, len(acc_values) + 1) plt.plot(epochs, acc_values, label='Training loss') plt.plot(epochs, val_acc_values, label='Validation loss') plt.title('Training and validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show()<file_sep>/Telecom_Churn_NN.py #!/usr/bin/env python # coding: utf-8 # In[1]: # DEEP LEARNING_ANN_MODULE END PROJECT : PREDICTING CUSTOMER CHURN FOR A TELECOM COMPANY # The current challenge, is to develop a Deep learning based engine that predicts customers who are likely to churn. # In[2]: # Importing Neccessary Libraries import pandas as pd import numpy as np import os from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import confusion_matrix, roc_curve, auc import tensorflow as tf from keras.regularizers import l2 from keras.models import Sequential # Sequential model is a linear stack of layers from keras.layers import Dense, Dropout, BatchNormalization from keras.utils import to_categorical from keras import optimizers from keras.callbacks import Callback from keras import backend as K import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) # In[3]: #fix random seed for reproducibility #Seed function is used to save the state of a random function, so that it can generate same random numbers on multiple executions of the code np.random.seed(123) tf.set_random_seed(123) #tf.random.set_seed(123) # In[4]: #Get current working directory PATH = os.getcwd() # In[5]: # Set the Working directory os.chdir(PATH) # In[6]: # Loading the data Telcochurn = pd.read_csv("Telcochurn.csv",header=0) # In[7]: # Exploratory Data Analysis and Preprocessing # 1) Identification of Varibales and Datatypes # In[8]: Telcochurn.dtypes # In[9]: print(Telcochurn.shape) # In[10]: #Display the columns Telcochurn.columns # In[11]: #Display the index Telcochurn.index # In[12]: Telcochurn.head() # In[13]: # Summary Statistics and Distribution of the Columns Telcochurn.describe() # In[14]: Telcochurn.describe(include = 'object' ) # In[15]: # 2) Non - Graphical Univariate Analysis #Distribution of dependent variable Telcochurn.Churn.value_counts() # In[16]: Telcochurn.Churn.value_counts(normalize = True)*100 # In[17]: Telcochurn.SeniorCitizen.value_counts() # In[18]: Telcochurn[Telcochurn.Churn == 'Yes'].InternetService.value_counts(normalize = True)*100 # In[19]: Telcochurn[Telcochurn.Churn == 'Yes'].Contract.value_counts(normalize = True)*100 # In[20]: # People having Month-to-month Contract are about 88 % who are churning out. #Customer is impacted by the Monthly Charges you offer # In[21]: Telcochurn[Telcochurn.Churn == 'Yes'].PaymentMethod.value_counts(normalize = True)*100 # In[22]: Telcochurn[Telcochurn.Churn == 'Yes'].tenure.value_counts(normalize = True)*100 # In[23]: Telcochurn.isnull().sum() # In[24]: #Convert all the attributes to appropriate type- Data type conversion # In[25]: Telcochurn['SeniorCitizen'] = Telcochurn['SeniorCitizen'].map({1:'yes', 0:'no'}) # In[26]: Telcochurn.dtypes # In[27]: Telcochurn.TotalCharges # In[28]: Telcochurn.TotalCharges.values # In[29]: Telcochurn.MonthlyCharges.values # In[30]: # Convert pandas.Series from dtype object to float, and errors to nans/ invalid parsing will be set as na pd.to_numeric(Telcochurn.TotalCharges, errors = 'coerce') # In[31]: pd.to_numeric(Telcochurn.TotalCharges, errors = 'coerce').isnull() # In[32]: Telcochurn[pd.to_numeric(Telcochurn.TotalCharges, errors = 'coerce').isnull()] # In[33]: Telcochurn = Telcochurn[Telcochurn.TotalCharges != ' '] # In[34]: pd.to_numeric(Telcochurn.TotalCharges) # In[35]: Telcochurn['TotalCharges'] = pd.to_numeric(Telcochurn.TotalCharges) # In[36]: Telcochurn.dtypes # In[37]: #Telcochurn[Telcochurn['TotalCharges'].isnull()] # Wherever the value is set to True it will return those rows # Drop These rows # In[38]: Telcochurn.shape # In[39]: Telcochurn.iloc[488] # In[40]: Telcochurn.isnull().sum() # In[41]: Telcochurn.drop('customerID',axis = 1,inplace = True) # In[42]: Telcochurn.reset_index() # In[43]: #Telcochurn.dropna(inplace = True) # In[44]: Telcochurn.dtypes # In[45]: Telcochurn.nunique() # In[46]: for column in Telcochurn: print(f'{column} : {Telcochurn[column].unique()}') # In[47]: for col in ['gender', 'SeniorCitizen', 'Partner', 'Dependents', 'PhoneService', 'MultipleLines', 'InternetService', 'OnlineSecurity', 'OnlineBackup', 'DeviceProtection', 'TechSupport', 'StreamingTV', 'StreamingMovies', 'Contract', 'PaperlessBilling', 'PaymentMethod','Churn']: Telcochurn[col] = Telcochurn[col].astype('category') # In[48]: Telcochurn.dtypes # In[49]: #Telcochurn['Churn'] = Telcochurn['Churn'].map({'Yes': 1,'No':0}) # In[50]: #Telcochurn['Churn'].value_counts() # In[51]: # YOUR CODE HERE #Telco_X_train = Telcochurn_new.drop(['Churn'], axis = 1) #Telco_y_train = Telcochurn_new["Churn"] # In[52]: #type(Telco_y_train) # In[53]: cat_columns = list(Telcochurn.select_dtypes('category').columns) num_columns = list(Telcochurn.columns.difference(cat_columns)) # In[54]: cat_columns # In[55]: num_columns # In[56]: # Convert categorical columns in dummies. Using the 'pd.get_dummies' method. Telcochurn_cat_dummy = pd.get_dummies(columns = cat_columns, data = Telcochurn[cat_columns], prefix = cat_columns, prefix_sep = "_", drop_first = True) # In[57]: Telcochurn_cat_dummy.dtypes # In[58]: Telcochurn_cat_dummy.head() # In[59]: Telcochurn_cat_dummy.shape # In[60]: Telcochurn_cat_dummy.dtypes # In[61]: # YOUR CODE HERE # Impute numerical columns # Apply label encoder to each column with categorical data #num_imputer = SimpleImputer() #imputed_X_train = pd.DataFrame(num_imputer.fit_transform(X_train[numerical_columns]), # columns = numerical_columns) #imputed_X_test = pd.DataFrame(num_imputer.transform(X_test[numerical_columns]), #columns = numerical_columns) # In[62]: #from sklearn.preprocessing import MinMaxScaler #scaler = MinMaxScaler() #Telcochurn_num = pd.DataFrame(scaler.fit_transform(Telcochurn[num_columns]), #columns = num_columns) # In[63]: #scale = StandardScaler() # In[64]: #scale.fit(Telcochurn[num_columns]) # In[65]: #Telcochurn_std = pd.DataFrame(scale.transform(Telcochurn[num_columns]), #columns = num_columns) # In[66]: #Telcochurn_std.dtypes # In[67]: Telcochurn_num = Telcochurn[num_columns] # In[68]: Telcochurn_num.dtypes # In[69]: pd.concat([Telcochurn_num,Telcochurn_cat_dummy], axis=1) # In[70]: Final_Telcochurn = pd.concat([Telcochurn_cat_dummy,Telcochurn_num], axis = 1) # In[71]: Final_Telcochurn.shape # In[72]: Final_Telcochurn.dtypes # In[73]: Final_Telcochurn.isnull().sum().sum() # In[74]: Final_Telcochurn.dropna(axis = 0) # In[75]: Final_Telcochurn.isnull().sum().sum() # In[76]: # Train and Validation Split & performing preprocessing appropriately on each of them X, y = Final_Telcochurn.loc[:,Final_Telcochurn.columns!='Churn_Yes'].values, Final_Telcochurn.loc[:,'Churn_Yes'].values X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.3, random_state=123) # In[77]: print(X_train.shape) print(X_valid.shape) # In[78]: print(pd.value_counts(y_train)) print(pd.value_counts(y_valid)) # In[79]: print(pd.value_counts(y_train)/y_train.size * 100) print(pd.value_counts(y_valid)/y_valid.size * 100) # In[80]: Final_Telcochurn.dtypes # In[81]: scale = StandardScaler() scale.fit(X_train) X_train_std = scale.transform(X_train) X_valid_std = scale.transform(X_valid) # In[82]: np.random.seed(123) tf.set_random_seed(123) # In[83]: from keras import models from keras import layers # In[84]: Telco_NN = models.Sequential() # Telco_NN.add(layers.Dense(25, input_shape=(X_train_std.shape[1], ), activation='relu', kernel_initializer='glorot_normal')) # Telco_NN.add(layers.Dense(20, activation='relu', kernel_initializer='glorot_normal')) # Telco_NN.add(layers.Dense(1, activation='sigmoid', kernel_initializer='glorot_normal')) # In[85]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') # In[86]: from keras import optimizers # In[87]: get_ipython().system('pip install PyPi') # In[88]: get_ipython().system('pip install helper') # In[89]: #from helper import accuracy_plot, loss_plot, compute_metrics # In[90]: Telco_NN.summary() # In[91]: Telco_NN.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # In[92]: get_ipython().run_cell_magic('time', '', 'Telco_NN_Model = Telco_NN.fit(X_train_std, \n y_train, \n epochs=100,\n batch_size= 32, \n validation_split=0.2, \n shuffle=True)') # In[96]: print(Telco_NN_Model.history.keys()) # In[97]: accuracy_plot(Telco_NN_Model) # In[98]: loss_plot(Telco_NN_Model) # In[99]: Telco_NN_Model_Train__pred = Telco_NN.predict_classes(X_train_std) Telco_NN_Model_Test_pred = Telco_NN.predict_classes(X_valid_std) # In[100]: import helper # In[101]: os.getcwd() # In[102]: #from helper.py import accuracy_plot, loss_plot, compute_metrics # In[103]: #!wget -c https://raw.githubusercontent.com/udacity/deep-learning-v2-pytorch/master/intro-to-pytorch/helper.py #import helper # In[104]: from sklearn.metrics import confusion_matrix, roc_curve, auc import matplotlib.pyplot as plt # Function to compute the metrics def compute_metrics(train_pred, y_train, test_pred, y_test): # Confusion matrix for train predictions confmat = confusion_matrix(y_train, train_pred) print('Train metrics') print('Confusion matrix') print(confmat) print("----------------------------------------------") TP = confmat[0,0] TN = confmat[1,1] FN = confmat[0,1] FP = confmat[1,0] Total = TP + TN + FP + FN # Accuracy: Overall, how often is the classifier correct? Accuracy = (TP+TN)/Total # Misclassification Rate: Overall, how often is it wrong? # equivalent to 1 minus Accuracy also known as "Error Rate" Misclassification_Rate = (FP+FN)/Total # True Positive Rate: When it's actually yes, how often does it predict yes? # also known as "Sensitivity" or "Recall" Actual_Yes = TP + FN Recall = TP/Actual_Yes # False Positive Rate: When it's actually no, how often does it predict yes? Actual_No = TN + FP FPR = FP/Actual_No # True Negative Rate: When it's actually no, how often does it predict no? # equivalent to 1 minus False Positive Rate, also known as "Specificity" TNR = TN/Actual_No # Precision: When it predicts yes, how often is it correct? Predicted_Yes = TP + FP Precission = TP/Predicted_Yes # Prevalence: How often does the yes condition actually occur in our sample? Prevalance = Actual_Yes / Total # F1 Score f1 = 2 * (Precission * Recall) / (Precission + Recall) print('Accuracy: ', Accuracy) print('Precission: ', Precission) print('Recall: ', Recall) print('F1 Score: ', f1) print("") print("==============================================") print("") # Confusion matrix for train predictions confmat = confusion_matrix(y_test, test_pred) print('Test metrics') print('Confusion matrix') print(confmat) print("----------------------------------------------") TP = confmat[0,0] TN = confmat[1,1] FN = confmat[0,1] FP = confmat[1,0] Total = TP + TN + FP + FN # Accuracy: Overall, how often is the classifier correct? Accuracy = (TP+TN)/Total # Misclassification Rate: Overall, how often is it wrong? # equivalent to 1 minus Accuracy also known as "Error Rate" Misclassification_Rate = (FP+FN)/Total # True Positive Rate: When it's actually yes, how often does it predict yes? # also known as "Sensitivity" or "Recall" Actual_Yes = TP + FN Recall = TP/Actual_Yes # False Positive Rate: When it's actually no, how often does it predict yes? Actual_No = TN + FP FPR = FP/Actual_No # True Negative Rate: When it's actually no, how often does it predict no? # equivalent to 1 minus False Positive Rate, also known as "Specificity" TNR = TN/Actual_No # Precision: When it predicts yes, how often is it correct? Predicted_Yes = TP + FP Precission = TP/Predicted_Yes # Prevalence: How often does the yes condition actually occur in our sample? Prevalance = Actual_Yes / Total # F1 Score f1 = 2 * (Precission * Recall) / (Precission + Recall) print('Accuracy: ', Accuracy) print('Precission: ', Precission) print('Recall: ', Recall) print('F1 Score: ', f1) # Function to draw plot for the train and validation accuracies def accuracy_plot(history): plt.clf() # Clears the figure history_dict = history.history acc_values = history_dict['accuracy'] val_acc_values = history_dict['val_accuracy'] epochs = range(1, len(acc_values) + 1) plt.plot(epochs, acc_values, label='Training accuracy') plt.plot(epochs, val_acc_values, label='Validation accuracy') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Function to draw plot for the train and validation loss def loss_plot(history): plt.clf() # Clears the figure history_dict = history.history acc_values = history_dict['loss'] val_acc_values = history_dict['val_loss'] epochs = range(1, len(acc_values) + 1) plt.plot(epochs, acc_values, label='Training loss') plt.plot(epochs, val_acc_values, label='Validation loss') plt.title('Training and validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() # In[105]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') # In[106]: compute_metrics(Telco_NN_Model_Train__pred, y_train, Telco_NN_Model_Test_pred, y_valid) # In[107]: # Using auto encoders, get deep features for the same input, and using the deep features, build and tune to a good model # and observe the performance # Derive new non-linear features using autoencoder # In[108]: from keras.models import Sequential, Model from keras.layers import Dense, Input # In[109]: # The size of encoded and actual representations encoding_dim = 16 # this is the size of our encoded representations actual_dim = X_train_std.shape[1] # In[110]: # Input placeholder input_attrs = Input(shape=(actual_dim,)) # "encoded" is the encoded representation of the input encoded = Dense(encoding_dim, activation='relu')(input_attrs) # "decoded" is the lossy reconstruction of the input decoded = Dense(actual_dim, activation='sigmoid')(encoded) # In[111]: # this model maps an input to its reconstruction autoencoder = Model(input_attrs, decoded) # In[112]: print(autoencoder.summary()) # In[113]: autoencoder.compile(optimizer='adam', loss='binary_crossentropy') # In[114]: autoencoder.fit(X_train_std, X_train_std, epochs=100) # In[115]: # this model maps an input to its encoded representation encoder = Model(input_attrs, encoded) # In[116]: print(encoder.summary()) # In[117]: X_train_nonLinear_features = encoder.predict(X_train_std) X_test_nonLinear_features = encoder.predict(X_valid_std) # In[118]: X_train_nonLinear_features[1:2,:] # In[119]: encoder.get_weights() # In[123]: # Combining new non-linear features to X_train and X_test respectively # In[124]: X_train = np.concatenate((X_train_std, X_train_nonLinear_features), axis=1) X_test = np.concatenate((X_valid_std, X_test_nonLinear_features), axis=1) # In[125]: #Perceptron Model Building with both actual and non-linear features # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: #type(Telcochurn_num) # In[ ]: #Telcochurn_num.head() # In[ ]: #cat_attr_label = list(Telcochurn_new[['InternetService', 'Contract', 'PaymentMethod']]) # In[ ]: #cat_attr_label # In[ ]: #cat_attr_onehot = list(Telcochurn_new[['gender','SeniorCitizen','Partner','Dependents','PhoneService','MultipleLines','OnlineSecurity','OnlineBackup','DeviceProtection','TechSupport','StreamingTV','StreamingMovies','PaperlessBilling','Churn']]) # In[ ]: #cat_attr_onehot # In[ ]: <file_sep>/README.md # Predicting-Customer-Churn_Neural-Networks_Deep Learning AI for Decision Modelling_Project which involves to develop a deep learning based engine that predicts customers who are likely to churn. PROJECT : PREDICTING CUSTOMER CHURN FOR A TELECOM COMPANY PROBLEM TYPE: CLASSIFICATION Domain: Telecommunication (I)Problem Statement : The major problem of Telecom companies is customer churn (loss of a customer to a competitor). The acquisition of a new customer is very expensive compared to retention of existing customers. Small percentage of reduction in churn improves huge margins to Telecom companies. The companies perform various target marketing activities or reward customer through offers and incentives, to retain a customer if he is identified before he churns. The current challenge, is to develop a deep learning based engine that predicts customers who are likely to churn. Metric: Accuracy (II) Data Description : Data presented contains attributes related to users’ information, the usage plans, charges billed, payment method etc, and the target column of interest is if the user has churned out or not. The task is to build a predictive model that can predict user ratings with reasonably good accuracy and sensitivity. (III) Approach/Strategy : i. Loaded the data and understood it; You will observe that its predictors belong to three different types, numeric/integer, categorical. ii. Exploratory analysis to analyse the data. iii. Did necessary type conversions. iv. Columns like CustomerID can be removed from the analysis. v. Split the data into train and validation sets and performing preprocessing appropriately on each of them. • Dealt with missing values • On numeric data : applied standardisation technique, preferably using standard scaler. • On categorical data: Applied one-hot encoding/label encoding as appropriate. vi. Built deep neural net model, compiled and fitted the model. Tuned it to improve validation accuracy/recall. Observed the performance vii. Using auto encoders, got deep features for the same input, and using the deep features, built and tuned it to a good model and observed the performance viii.Also, as there is class imbalance in the data, and recall, being an important metric for this problem is highly effected by the imbalance, tried to work on mitigating the effect of class imbalance. Explored parameters like class weight while fitting the model, and analysed the performance.
717619cd981c5d7492b34010162cc821b09244b8
[ "Markdown", "Python" ]
3
Python
saivivek7495/Predicting-Customer-Churn_Neural-Networks_Deep-Learning
8f2de75a3c5cb1e28a830edec3683b30da2ea406
47d02eb861c9421d95a49c165410949e5f4c92ed
refs/heads/master
<file_sep>import { Component } from '@angular/core'; import { FormBuilder, FormControl, Validators } from '@angular/forms'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { fileToUpload: File = null; constructor(private fb: FormBuilder, private http: HttpClient) { } userForm = this.fb.group({ name: new FormControl(''), email: new FormControl('', Validators.email), }) handleFileInput(files: FileList) { this.fileToUpload = files.item(0); } onSubmit(formValue) { const formData: FormData = new FormData(); formData.append('profilePic', this.fileToUpload, this.fileToUpload.name); formData.append('name', formValue.name); formData.append('email', formValue.email); console.log(formValue); console.log(formData); this.http.post('http://localhost:3000/api/product/create-user', formData).subscribe(result => { console.log(result); }, err => { console.error(err); }); } }
14c3248b036564867b19e1f60e556165e2170273
[ "TypeScript" ]
1
TypeScript
sreenivasarajiv/global-mantra-demo
8e82cae91ba810a2e359390180a004d7dafa0d52
6c69da7e9cd789c134452f1355d4c2fbab52b69c
refs/heads/main
<repo_name>garrettroth/Metaverse-Sicariis<file_sep>/README.md # Metaverse-Sicariis The Sicarrii are known to be the first organized cloak and dagger assassin group, their goal was to free the Judean people from Roman Occupation. They were succussesful due to the tools and resources at their disposal. This repository is meant to be a tool box for those ready to dive into the Metaverse and gain their freedom. Tool Box: 1.) Coin Market Cap - This program allows you to pull the top 100 cryptocurrencies by Marketcap 2.) Twitter_api - This program allows you to search for x number of tweets from a choosen topic. <file_sep>/twitter_api.py import tweepy from tweepy import OAuthHandler import re class TwitterClient(object): ''' Twitter Class for grabbing Tweets ''' def __init__(self): ''' Initialization Method ''' #Keys and Tokens from the Twitter Dev Console consumer_key = 'osoPe1vbrjL6hi83pPaT99JcZ' consumer_secret = '<KEY>' access_token = '<KEY>' access_token_secret = '<KEY>' #Attempt Authentication try: #Create OAuthhandler object self.auth = OAuthHandler(consumer_key,consumer_secret) #Set access token and secret self.auth.set_access_token(access_token,access_token_secret) #Create tweepy API object to fetch tweets self.api = tweepy.API(self.auth) except: print("Error Authentication Failed") def clean_tweet(self, tweet): ''' Utility function to clean tweet text by removing links, special characters using simple regex statements ''' return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split()) def get_tweets(self, query, count = 1): ''' Main Function to fetch tweets and parse them ''' #Empty list to store parsed tweets tweets = [] try: #call twitter api to fetch tweets fetch_tweets = self.api.search(q=query,count = count) #parsing tweets one by one for tweet in fetch_tweets: print(tweet) #empty dictionary to store required params of tweet parsed_tweet = {} #saving text of tweet parsed_tweet['text'] = tweet.text #appending parsed tweet to tweets list if tweet.retweet_count > 0: #if tweet has a retweet, ensure that is is append only once. if parsed_tweet not in tweets: tweets.append(parsed_tweet) else: tweets.append(parsed_tweet) #return parsed tweet return tweets except tweepy.TweepError as e: #print error print("Error : " + str(e)) def main(): #Creating Object of twitter client class api = TwitterClient() #calling function to get tweets tweets = api.get_tweets(query = 'Cryptocurrency', count = 1) #print tweets print(tweets) #running program main()
3de26610573401457170585493f2e15dac6fa5ee
[ "Markdown", "Python" ]
2
Markdown
garrettroth/Metaverse-Sicariis
181d1b4e5cb68026a3d58f944024dfc019b85ef3
6018a975e66a21a12c0d9de5b10e2007d69c9ce0
refs/heads/master
<file_sep>import requests import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import style import statistics import math import pylab as pl from scipy.stats import lognorm style.use('ggplot') day_before = input("how many days you need for API?: ") #Days for API cRs = input("What is your Collateral amount? ") #amount for Collateral day_number = int(input("Enter a day numbers you want: ")) #number of days you want for simulations cAmount = float(cRs.split()[0]) #print(cAmount) collaterals=[] for i in range(len(cRs.split())): collaterals.append(float(cRs.split()[i])) print(collaterals) ## Get prices from API r=requests.get('https://api.coingecko.com/api/v3/coins/ethereum/market_chart?vs_currency=usd&days=' + day_before) prices = [x[1] for x in r.json()['prices']] returns=[] for i in range(len(prices)-1): returns.append(math.log((prices[i+1]/prices[i]))) last_price=prices[-1] first_money= cAmount / prices[-1] #first_money is the factor of collateral amount to last price of ETH print(first_money) first_moneys=[] for i in range(len(collaterals)): first_moneys.append( collaterals[i] / prices[-1]) print(first_moneys) daily_vol= statistics.stdev(returns) daily_avr= statistics.mean(returns) daily_var= statistics.variance(returns) daily_drift=daily_avr+(daily_var/2) #print("This is average of ETH history prices",daily_avr) #print("This is standar diviation of ETH history prices",daily_vol) drift = daily_drift #print("This is drift of the ETH prices",daily_drift) temprory=0 numberSimulation=1000 simulation_df = pd.DataFrame() final_prices=[] final_price_for_onepointfive_dollar=[] ##difference=[] blackCoinZero=[] logReturn=[] positives=[] redBellowOne=[] leverages=[] littleDrop=[] fulllevrage=[] ###################################################################### ###################################################################### ######## For different Collaterals################################ ###################################################################### ###################################################################### blackCoinZeroS=[[] for i in range(len(collaterals))] positivesS=[[] for i in range(len(collaterals))] redBellowOneS=[[] for i in range(len(collaterals))] leveragesS=[[] for i in range(len(collaterals))] littleDropS=[[] for i in range(len(collaterals))] fulllevrageS=[[] for i in range(len(collaterals))] ###################################################################### for i in range(numberSimulation): count=0 daily_vol= statistics.stdev(returns) daily_avr= statistics.mean(returns) daily_var= statistics.variance(returns) daily_drift=daily_avr+(daily_var/2) drift = daily_drift price_series=[] shock = drift + daily_vol * np.random.normal() price= last_price * math.exp(shock) price_series.append(price) for y in range(day_number): if count == day_number-1: break shock = drift + daily_vol * np.random.normal() price= price_series[count] * math.exp(shock) price_series.append(price) count += 1 simulation_df[i]=price_series ## final_prices is the price of all simulations on the last day of estimations final_prices.append(price_series[len(price_series)-1]) final_price_for_onepointfive_dollar.append(first_money * price_series[len(price_series)-1]) ## Log of the outcomes of each simulation on day nth (100) logReturn.append(math.log(first_money * price_series[len(price_series)-1])) alpha=(first_money * price_series[len(price_series)-1]) ##difference.append((first_money * price_series[len(price_series)-1])-1) ##### In this part we assume that for cAmount (collateral) investment we have outcomes and then choose the simulaion results with : ##### 1. outcomes lower than 1USD as redBellowOne ##### 2. outcomes lesser and equal to one as blackCoinZero (In this part black coin is equal to zero) ##### 3. outcomes that are higher than 1USD has a value for blackcoin --> positives if ((first_money * price_series[len(price_series)-1]) < 1): redBellowOne.append((first_money * price_series[len(price_series)-1])) if ((first_money * price_series[len(price_series)-1]) > 1 and (first_money * price_series[len(price_series)-1]) < cAmount ): littleDrop.append((first_money * price_series[len(price_series)-1])) if ((first_money * price_series[len(price_series)-1]) <= 1): blackCoinZero.append((first_money * price_series[len(price_series)-1])) else: positives.append((first_money * price_series[len(price_series)-1])) if ((first_money * price_series[len(price_series)-1]) >= cAmount): temprory=(first_money * price_series[len(price_series)-1]) leverages.append((cAmount*temprory -1)/(cAmount*temprory -temprory)) if ((first_money * price_series[len(price_series)-1]) >= 1): temprory=(first_money * price_series[len(price_series)-1]) fulllevrage.append((cAmount*temprory -1)/(cAmount*temprory -temprory)) ################################################################################ for w in range(len(collaterals)): if ((first_moneys[w] * price_series[len(price_series)-1]) < 1): redBellowOneS[w].append((first_moneys[w] * price_series[len(price_series)-1])) if ((first_moneys[w] * price_series[len(price_series)-1]) > 1 and (first_moneys[w] * price_series[len(price_series)-1]) < collaterals[w] ): littleDropS[w].append((first_moneys[w] * price_series[len(price_series)-1])) if ((first_moneys[w] * price_series[len(price_series)-1]) <= 1): blackCoinZeroS[w].append((first_moneys[w] * price_series[len(price_series)-1])) else: positivesS[w].append((first_moneys[w] * price_series[len(price_series)-1])) if ((first_moneys[w] * price_series[len(price_series)-1]) >= collaterals[w]): temprory=(first_moneys[w] * price_series[len(price_series)-1]) leveragesS[w].append((collaterals[w]*temprory -1)/(collaterals[w]*temprory -temprory)) if ((first_moneys[w] * price_series[len(price_series)-1]) >= 1): temprory=(first_moneys[w] * price_series[len(price_series)-1]) fulllevrageS[w].append((collaterals[w]*temprory -1)/(collaterals[w]*temprory -temprory)) rednumber=len(redBellowOne) redmean=statistics.mean(redBellowOne) redexpected= ((redmean * rednumber)+ (1000 - rednumber))/1000 blackexpected= ((1000-rednumber)*((statistics.mean(positives))-1))/1000 print("The mean of last day outcomes is:",statistics.mean(final_price_for_onepointfive_dollar)) print("The stantard deviation of the last day outcomes is:",statistics.stdev(final_price_for_onepointfive_dollar)) print("Number of cases that Blackcoin is zero:",len(blackCoinZero)) print("Number of cases that Redcoin is bellow one dollar is:",len(redBellowOne)) print("The mean of Redcoins bellow one dollar is:",statistics.mean(redBellowOne)) print("The STdev of Redcoins bellow one dollar is:",statistics.stdev(redBellowOne)) print("Expected Value of Redcoins is:",redexpected) print("Expected Value of Blackcoins is:",blackexpected) print("The mean of Leverage of Blackcoin is:",statistics.mean(leverages)) print("The stantard deviation of Leverage is:",statistics.stdev(leverages)) print("The mean of fulllevrage Leverage of Blackcoin for non-zero Blackcoin cases is:",statistics.mean(fulllevrage)) print("The stantard deviation of fulllevrage of Blackcoin for non-zero Blackcoin cases is:",statistics.stdev(fulllevrage)) print("Number of cases for a little drop in ETH is:",len(littleDrop)) print("The mean of cases for a little drop in ETH is:",statistics.mean(littleDrop)) print("The stantard deviation of cases for a little drop in ETH is:",statistics.stdev(littleDrop)) print("#################################################") print("#################################################") ########################################################################################## ########################################################################################## ################# For multi collateral ############################################### ########################################################################################## ########################################################################################## rednumbers=[] redmeans=[] redexpecteds=[] blackexpecteds=[] for i in range(len(collaterals)): rednumbers.append(len(redBellowOneS[i])) redmeans.append(statistics.mean(redBellowOneS[i])) redexpecteds.append(((redmeans[i] * rednumbers[i])+ (1000 - rednumbers[i]))/1000) blackexpecteds.append(((1000-rednumbers[i])*((statistics.mean(positivesS[i]))-1))/1000) print("Number of cases that Blackcoin is zero:",len(blackCoinZeroS[i])) print("Number of cases that Redcoin is bellow one dollar is:",len(redBellowOneS[i])) print("The mean of Redcoins bellow one dollar is:",statistics.mean(redBellowOneS[i])) print("The STdev of Redcoins bellow one dollar is:",statistics.stdev(redBellowOneS[i])) print("Expected Value of Redcoins is:",redexpecteds[i]) print("Expected Value of Blackcoins is:",blackexpecteds[i]) print("The mean of Leverage of Blackcoin is:",statistics.mean(leveragesS[i])) print("The stantard deviation of Leverage is:",statistics.stdev(leveragesS[i])) print("The mean of fulllevrage Leverage of Blackcoin for non-zero Blackcoin cases is:",statistics.mean(fulllevrageS[i])) print("The stantard deviation of fulllevrage of Blackcoin for non-zero Blackcoin cases is:",statistics.stdev(fulllevrageS[i])) print("Number of cases for a little drop in ETH is:",len(littleDropS[i])) print("The mean of cases for a little drop in ETH is:",statistics.mean(littleDropS[i])) print("The stantard deviation of cases for a little drop in ETH is:",statistics.stdev(littleDropS[i])) print("#################################################") print("#################################################") ######################################################################################### ######################################################################################### standar_div = statistics.stdev(final_price_for_onepointfive_dollar) miangin = statistics.mean(final_price_for_onepointfive_dollar) new_drift= miangin + (standar_div**2)/2 -cAmount disti=lognorm([standar_div],loc=new_drift) man=np.linspace(0,6,100) fig20= plt.figure() plt.hist(logReturn, density=False, bins=50) fig0= plt.figure() plt.hist(final_price_for_onepointfive_dollar, density=False, bins=50) pl.plot(man,disti.pdf(man)*100) fig= plt.figure() plt.plot(simulation_df) ##fig2= plt.figure() ##plt.plot(final_price_for_onepointfive_dollar) ##fig3= plt.figure() ##plt.plot(difference) fig10= plt.figure() plt.hist(leverages, density=False, bins=100) plt.show() ##fig4= plt.figure() ##plt.plot(blackCoinZero) ##plt.show() <file_sep># Monte-Carlo Python 3 code. ask you for how many days you need prediction and after that you will receive the output figure.
836e476023b4e99bef21ae4b876aabd6b849e63a
[ "Markdown", "Python" ]
2
Python
GreatSoshiant/Monte-Carlo
ebfdb0502250859554abe4baeb64fca0855daecc
980a9278c0453ada2ba8730600edef8dc757f95b