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>############################################################ # Undergraduate Research - <NAME> # Imports ############################################################ import numpy as np import torch from pytorch_pretrained_bert import BertTokenizer, BertModel, BertForMaskedLM import contextlib import sys ############################################################ # Helper Functions ############################################################ def loadTrainingSentences(file_path): commandTypeToSentences = {} with open(file_path, 'r') as fin: for line in fin: line = line.rstrip('\n') if len(line.strip()) == 0 or "##" == line.strip()[0:2]: continue commandType, command = line.split(' :: ') commandType = commandType[:-9] if commandType not in commandTypeToSentences: commandTypeToSentences[commandType] = [command] else: commandTypeToSentences[commandType].append(command) return commandTypeToSentences # The following structure is useful for supressing print statements class PrintsToOuterSpace(object): def write(self, x): pass @contextlib.contextmanager def noStdOut(): save_stdout = sys.stdout sys.stdout = PrintsToOuterSpace() yield sys.stdout = save_stdout ############################################################ # Intent Detection ############################################################ def cosineSimilarity(vector1, vector2): return np.dot(vector1, vector2)/(np.linalg.norm(vector1) * np.linalg.norm(vector2)) class Bert: def __init__(self): self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') # Load pre-trained model (weights) self.model = BertModel.from_pretrained('bert-base-uncased') # Put the model in "evaluation" mode, meaning feed-forward operation. self.model.eval() self.storedResults = None self.wordEmbeddings = {} def generateWordEmbeddings(self): sent = "[CLS] Turn your lights off. [SEP]" word = "off" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn your lights on. [SEP]" word = "on" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Lights off. [SEP]" word = "off" self.wordEmbeddings["off4"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Lights on. [SEP]" word = "on" self.wordEmbeddings["on4"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Lights out. [SEP]" word = "out" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn on holoemitter. [SEP]" word = "on" self.wordEmbeddings["on3"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn off holoemitter. [SEP]" word = "off" self.wordEmbeddings["off3"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Set your lights to maximum intensity. [SEP]" word = "maximum" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Set your lights to minimum intensity. [SEP]" word = "minimum" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Increase the blue value of your back LED by 50%. [SEP]" word = "increase" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Decrease the blue value of your back LED by 50%. [SEP]" word = "decrease" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Add 100 to the red value of your front LED. [SEP]" word = "add" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Minus 100 to the red value of your front LED. [SEP]" word = "minus" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Waddle off. [SEP]" word = "off" self.wordEmbeddings["off2"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Waddle on. [SEP]" word = "on" self.wordEmbeddings["on2"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn your back light green. [SEP]" word = "back" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn your front light green. [SEP]" word = "front" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Change your back LED to be green. [SEP]" word = "back" self.wordEmbeddings["back2"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Change your front LED to be green. [SEP]" word = "front" self.wordEmbeddings["front2"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Blink your logic display. [SEP]" word = "blink" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Dim your lights holoemitter. [SEP]" word = "dim" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Increase your speed by 50 percent. [SEP]" word = "percent" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) ## start of driving words sent = "[CLS] Set your front light red. [SEP]" word = "set" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Change the blue value of your front LED by 20%. [SEP]" word = "change" self.wordEmbeddings["set3"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Set speed to be 20%. [SEP]" word = "set" self.wordEmbeddings["set2"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Go faster. [SEP]" word = "faster" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Go slower. [SEP]" word = "slower" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn left. [SEP]" word = "left" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn right. [SEP]" word = "right" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn forward. [SEP]" word = "forward" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn backward. [SEP]" word = "backward" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Start rolling left. [SEP]" word = "left" self.wordEmbeddings["left2"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Start rolling right. [SEP]" word = "right" self.wordEmbeddings["right2"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Start rolling forward. [SEP]" word = "forward" self.wordEmbeddings["forward2"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Start rolling backward. [SEP]" word = "backward" self.wordEmbeddings["backward2"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] There is a bug to your left, run away! [SEP]" word = "left" self.wordEmbeddings["left3"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] There is a bug to your right, run away! [SEP]" word = "right" self.wordEmbeddings["right3"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] There is a bug ahead of you, run away! [SEP]" word = "ahead" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] There is a bug behind you, run away! [SEP]" word = "behind" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Go back. [SEP]" word = "back" self.wordEmbeddings["behind2"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Go ahead. [SEP]" word = "ahead" self.wordEmbeddings["ahead2"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn back. [SEP]" word = "back" self.wordEmbeddings["behind3"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn around. [SEP]" word = "around" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Go left. [SEP]" word = "go" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn left. [SEP]" word = "turn" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn to heading 30 degrees. [SEP]" word = "turn" self.wordEmbeddings["turn2"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn around. [SEP]" word = "turn" self.wordEmbeddings["turn3"] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Head left. [SEP]" word = "head" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Start rolling forward. [SEP]" word = "start" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Stop rolling. [SEP]" word = "stop" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Halt. [SEP]" word = "halt" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Start continuous roll. [SEP]" word = "continuous" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Go forward for 2 feet. [SEP]" word = "feet" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Go forward for 2 seconds. [SEP]" word = "seconds" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) sent = "[CLS] Turn to heading 30 degrees. [SEP]" word = "heading" self.wordEmbeddings[word] = self.wordEmbeddingNewSentence(sent, word) def wordEmbeddingNewSentence(self, sent, word): tokenized_text = self.tokenizer.tokenize(sent) indexed_tokens = self.tokenizer.convert_tokens_to_ids(tokenized_text) segments_ids = [1] * len(tokenized_text) tokens_tensor = torch.tensor([indexed_tokens]) segments_tensors = torch.tensor([segments_ids]) with torch.no_grad(): encoded_layers, _ = self.model(tokens_tensor, segments_tensors) token_embeddings = torch.stack(encoded_layers, dim=0) token_embeddings = torch.squeeze(token_embeddings, dim=1) token_embeddings = token_embeddings.permute(1,0,2) sum_vec = torch.sum(token_embeddings[tokenized_text.index(word)][-4:], dim = 0).numpy() return sum_vec def contextWordSim(self, word, sentWord): if sentWord not in self.tokenized_text: return 0 # bert tokenization works differently, for common words they are all in sum_vec = torch.sum(self.token_embeddings[self.tokenized_text.index(sentWord)][-4:], dim = 0).numpy() if word == "off": return max(cosineSimilarity(self.wordEmbeddings["off"], sum_vec), cosineSimilarity(self.wordEmbeddings["off2"], sum_vec), cosineSimilarity(self.wordEmbeddings["off3"], sum_vec), cosineSimilarity(self.wordEmbeddings["off4"], sum_vec)) if word == "on": return max(cosineSimilarity(self.wordEmbeddings["on"], sum_vec), cosineSimilarity(self.wordEmbeddings["on2"], sum_vec), cosineSimilarity(self.wordEmbeddings["on3"], sum_vec), cosineSimilarity(self.wordEmbeddings["on4"], sum_vec)) if word == "front": return max(cosineSimilarity(self.wordEmbeddings["front"], sum_vec), cosineSimilarity(self.wordEmbeddings["front2"], sum_vec)) if word == "back": return max(cosineSimilarity(self.wordEmbeddings["back"], sum_vec), cosineSimilarity(self.wordEmbeddings["back2"], sum_vec)) if word == "left": return max(cosineSimilarity(self.wordEmbeddings["left"], sum_vec), cosineSimilarity(self.wordEmbeddings["left2"], sum_vec), cosineSimilarity(self.wordEmbeddings["left3"], sum_vec)) if word == "right": return max(cosineSimilarity(self.wordEmbeddings["right"], sum_vec), cosineSimilarity(self.wordEmbeddings["right2"], sum_vec), cosineSimilarity(self.wordEmbeddings["right3"], sum_vec)) if word == "forward": return max(cosineSimilarity(self.wordEmbeddings["forward"], sum_vec), cosineSimilarity(self.wordEmbeddings["forward2"], sum_vec)) if word == "backward": return max(cosineSimilarity(self.wordEmbeddings["backward"], sum_vec), cosineSimilarity(self.wordEmbeddings["backward2"], sum_vec)) if word == "ahead": return max(cosineSimilarity(self.wordEmbeddings["ahead"], sum_vec), cosineSimilarity(self.wordEmbeddings["ahead"], sum_vec)) if word == "behind": return max(cosineSimilarity(self.wordEmbeddings["behind"], sum_vec), cosineSimilarity(self.wordEmbeddings["behind2"], sum_vec), cosineSimilarity(self.wordEmbeddings["behind3"], sum_vec)) if word == "turn": return max(cosineSimilarity(self.wordEmbeddings["turn"], sum_vec), cosineSimilarity(self.wordEmbeddings["turn2"], sum_vec), cosineSimilarity(self.wordEmbeddings["turn3"], sum_vec)) if word == "set": return max(cosineSimilarity(self.wordEmbeddings["set"], sum_vec), cosineSimilarity(self.wordEmbeddings["set2"], sum_vec), cosineSimilarity(self.wordEmbeddings["set3"], sum_vec)) if word in self.wordEmbeddings: return cosineSimilarity(self.wordEmbeddings[word], sum_vec) print("This world has not had a contextualized word embedding yet. See the method generateWordEmbeddings in the Bert class of r2d2_bert.py for more details.") return 0 def bertSentenceEncode(self, sentences): if type(sentences) is not list: sentences = [ sentences ] returnedEmbeddings = [] for sentence in sentences: marked_text = "[CLS] " + sentence + " [SEP]" self.tokenized_text = self.tokenizer.tokenize(marked_text) # Tokenize our sentence with the BERT tokenizer. indexed_tokens = self.tokenizer.convert_tokens_to_ids(self.tokenized_text) segments_ids = [1] * len(self.tokenized_text) tokens_tensor = torch.tensor([indexed_tokens]) segments_tensors = torch.tensor([segments_ids]) with torch.no_grad(): encoded_layers, _ = self.model(tokens_tensor, segments_tensors) # the following is only needed for creating word embeddings, but better to do it here instead of individually for each word token_embeddings = torch.stack(encoded_layers, dim=0) token_embeddings = torch.squeeze(token_embeddings, dim=1) self.token_embeddings = token_embeddings.permute(1,0,2) # Use the second to last bert layer for word embeddings token_vecs = encoded_layers[11][0] # Calculate the average of all token vectors in the sentence. sentence_embedding = torch.mean(token_vecs, dim=0) returnedEmbeddings.append(sentence_embedding.numpy()) return np.array(returnedEmbeddings) def sentenceToEmbeddings(self, commandTypeToSentences): '''Returns a tuple of sentence embeddings and an index-to-(sentence, category) dictionary. Inputs: commandTypeToSentences: A dictionary in the form returned by loadTrainingSentences. Each key is a string '[category]' which maps to a list of the sentences belonging to that category. Let m = number of sentences. Let n = dimension of vectors. Returns: a tuple (sentenceEmbeddings, indexToSentence) sentenceEmbeddings: A mxn numpy array where m[i:] containes the embedding for sentence i. indexToSentence: A dictionary with key: index i, value: (sentence, category). ''' indexToSentence = {} i = 0 for category in commandTypeToSentences: sentences = commandTypeToSentences[category] for sentence in sentences: indexToSentence[i] = (sentence, category) i += 1 sentenceEmbeddings = self.bertSentenceEncode([indexToSentence[j][0] for j in range(i)]) return sentenceEmbeddings, indexToSentence def createSentenceEmbeddings(self, file_path): commandTypeToSentences = loadTrainingSentences(file_path) sentenceEmbeddings, indexToSentence = self.sentenceToEmbeddings(commandTypeToSentences) self.storedResults = (sentenceEmbeddings, indexToSentence, commandTypeToSentences) return commandTypeToSentences def getCategory(self, sentence): '''Returns the supposed category of 'sentence'. Inputs: sentence: A sentence file_path: path to a file containing r2d2 commands Returns: a string 'command', where 'command' is the category that the sentence should belong to. ''' commandEmbedding = self.bertSentenceEncode(sentence) sentenceEmbeddings, indexToSentence, commandTypeToSentences = self.storedResults sortList = [] for i in range(sentenceEmbeddings.shape[0]): similarity = cosineSimilarity(commandEmbedding, sentenceEmbeddings[i, :]) sortList.append((i, similarity)) similarSentences = sorted(sortList, key = lambda x: x[1], reverse = True) closestSentences = [x[0] for x in similarSentences] commandDict = {} for category in commandTypeToSentences: commandDict[category] = 0 commandDict[indexToSentence[closestSentences[0]][1]] += 1 commandDict[indexToSentence[closestSentences[1]][1]] += 0.5 commandDict[indexToSentence[closestSentences[2]][1]] += 0.5 commandDict[indexToSentence[closestSentences[3]][1]] += 0.2 commandDict[indexToSentence[closestSentences[4]][1]] += 0.2 # print(commandDict) # print("Closest sentence was: " + indexToSentence[closestSentences[0]][0]) # print(cosineSimilarity(commandEmbedding, sentenceEmbeddings[closestSentences[0], :])) if cosineSimilarity(commandEmbedding, sentenceEmbeddings[closestSentences[0], :]) < 0.73: return "no" return max(commandDict, key=commandDict.get)<file_sep>TO RUN: Make sure you install the pytorch bert library: pip install pytorch-pretrained-bert Then, move all the files in the bertR2 folder over to the sphero-project/src directory, and run the R2D2 setup instructions. If you decide to use audio, you need to run: export GOOGLE_APPLICATION_CREDENTIALS="/[Path to sphero-project/src]/credentials.json" before running the audio_io.py script. You can change the R2D2 id in robot_com and audio_io, but with the connection parsing functionality, you shouldn't need to :).
25565c417d4ed69d5683d0f500c00f5a5bf10aee
[ "Python", "Text" ]
2
Python
jyzhang111/bertR2
126f691dbca09d3c3bc3fea328bcf62da99962c3
131361a32306892384295de5242569d91ace02ae
refs/heads/master
<file_sep>class Slingshot{ constructor(BodyA,pointB){ var options={ bodyA : BodyA, pointB : pointB, length : 0, stiffness : 0.01 } this.slingImage1 = loadImage("sprites/sling1.png") this.slingImage2 = loadImage("sprites/sling2.png") this.slingImage3 = loadImage("sprites/sling3.png") this.sling = Matter.Constraint.create(options) World.add(world,this.sling) } display(){ if(this.sling.bodyA){ //line(this.sling.bodyA.position.x,this.sling.bodyA.position.y,this.sling.pointB.x,this.sling.pointB.y) var startpoint = this.sling.bodyA.position var endpoint = this.sling.pointB if(startpoint.x < 200){ line(startpoint.x-20,startpoint.y,endpoint.x-10,endpoint.y) line(startpoint.x-20,startpoint.y,endpoint.x+30,endpoint.y) image(this.slingImage3,startpoint.x-30,startpoint.y-10,15,30) } else{ line(startpoint.x+20,startpoint.y,endpoint.x-10,endpoint.y) line(startpoint.x+20,startpoint.y,endpoint.x+30,endpoint.y) image(this.slingImage3,startpoint.x+20,startpoint.y-10,15,30) } } strokeWeight(10) stroke(48,22,8) image(this.slingImage1,200,20) image(this.slingImage2,170,20) } Fly(){ this.sling.bodyA=null } Attach(body){ this.sling.bodyA=body } }
ce2d804695a733f4e24867847b4ad8eb22ece770
[ "JavaScript" ]
1
JavaScript
Aadishshele/Angry-birds-constrained-bodies-
74db870a4deb4e1a4d6d7d8c5a6f11ce1ece7fef
7c1acc14598dcdc970ca1526167cf3d137c37cc6
refs/heads/master
<repo_name>CentrychOS/centrych-support<file_sep>/etc/profile.d/skype-mesa.sh # mask bug when using skype (possibly others) on 64bit systems w/Nvidia drivers ARCH=`dpkg --print-architecture` if [ "$ARCH" = "amd64" ] && \ [ -e /usr/lib/i386-linux-gnu/mesa/libGL.so.1 ] ; then LD_PRELOAD=$LD_PRELOAD:/usr/lib/i386-linux-gnu/mesa/libGL.so.1 export LD_PRELOAD fi <file_sep>/usr/bin/autostart-kde #!/bin/sh # autostart-kde - Conditionally starts KDE services at login. # # Copyright (C) 2013,2014 Centrych Systems LLC # Author: <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it only under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation. You are not permitted # to use, modify, republish, or redistribute this program under any # other version of the GNU General Public License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # On Debian systems the full text of the GNU General Public License can # be found in the `/usr/share/common-licenses/GPL-2' file. # #=============================================================================== RCFILE=~/.kde/share/config/kalarmrc if [ -e ${RCFILE} ] ; then if grep -iq "AutoStart=true" ${RCFILE} ; then kalarm --tray fi fi RCFILE=~/.kde/share/config/nepomukserverrc if [ -e ${RCFILE} ] ; then if grep -iq "Start Nepomuk=true" ${RCFILE} ; then if [ -e /usr/bin/nepomukcontroller ] ; then nepomukcontroller sleep 1 fi if [ -e /usr/bin/nepomukserver ] ; then exec nepomukserver fi fi fi RCFILE=~/.kde/share/config/kwalletrc if [ -e ${RCFILE} ] ; then if grep -iq "Launch Manager=true" ${RCFILE} ; then if [ -e /usr/bin/kwalletd ] ; then /usr/bin/kwalletd fi fi fi RCFILE=~/.kde/share/config/kgpgrc if [ -e ${RCFILE} ] ; then if grep -iq "Autostart=true" ${RCFILE} ; then if [ -e /usr/bin/kgpg ] ; then /usr/bin/kgpg fi fi fi <file_sep>/src/rootstat.c /* ** rootstat - returns status of the root account. ** ** Copyright (C) 2013,2014 Centrych Systems LLC ** Author: <NAME> <<EMAIL>> ** ** This program is free software; you can redistribute it and/or modify ** it only under the terms of the GNU General Public License Version 2 ** as published by the Free Software Foundation. You are not permitted ** to use, modify, republish, or redistribute this program under any ** other version of the GNU General Public License. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. ** ** On Debian systems the full text of the GNU General Public License can ** be found in the `/usr/share/common-licenses/GPL-2' file. **/ #include <pwd.h> #include <shadow.h> #include <stdlib.h> int main(int argc, char *argv[]) { struct passwd *pw; struct spwd *spwd; int ret = 1; if((pw = getpwnam("root")) == NULL) printf("WARN: no root entry in /etc/passwd.\n"); else if((spwd = getspnam("root")) == NULL) printf("WARN: no root entry in /etc/shadow.\n"); else if(spwd->sp_pwdp == NULL) printf("WARN: root account password field is NULL.\n"); else if(spwd->sp_pwdp[0] == '\0') printf("WARN: root account disabled with empty password field.\n"); else if(spwd->sp_pwdp[0] == '!' || spwd->sp_pwdp[0] == '*') printf("root account disabled.\n"); else { printf("root account enabled.\n"); ret = 0; } return (ret); } <file_sep>/usr/bin/show-xfce4-panel #!/bin/sh # show-xfce4-panel - Briefly displays a hidden Xfce panel. # # Copyright (C) 2013,2014 Centrych Systems LLC # Author: <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it only under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation. You are not permitted # to use, modify, republish, or redistribute this program under any # other version of the GNU General Public License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # On Debian systems the full text of the GNU General Public License can # be found in the `/usr/share/common-licenses/GPL-2' file. # #=============================================================================== # # NOTE: In Centrych this is tied to the <Left_Super><Escape> hotkey. STATE=`xfconf-query -c xfce4-panel -p /panels/panel-0/autohide` if [ "$STATE" = "true" ] ; then xfconf-query -c xfce4-panel -p /panels/panel-0/autohide -s false xfconf-query -c xfce4-panel -p /panels/panel-0/autohide -s true fi <file_sep>/usr/bin/configure-vesafb #!/bin/sh # # configures GRUB with "best" (closest) VESA mode to the current display # resolution. # # Copyright (C) 2013,2014 Centrych Systems LLC # Author: <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it only under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation. You are not permitted # to use, modify, republish, or redistribute this program under any # other version of the GNU General Public License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # On Debian systems the full text of the GNU General Public License can # be found in the `/usr/share/common-licenses/GPL-2' file. # #=============================================================================== # # Exits with an error if no suitable VESA resolution was found. EID=`id -u` if [ "$EID" -ne 0 ] ; then echo "$0: must be executed as root" >&2 exit 1 fi case "$1" in enable) STATE=yes FB="y" ;; disable) STATE=no FB="n" ;; *) echo "$0: called with unknown argument \`$1'" >&2 exit 1 ;; esac best_res="0" disp_res=$(xdpyinfo | grep -oE 'dimensions:\s+[0-9]+x[0-9]+' | \ grep -oE '[0-9]+x[0-9]+$') dw=$(echo $disp_res | grep -oE '^[0-9]+') dh=$(echo $disp_res | grep -oE '[0-9]+$') # widest res xw="0" xh="0" # tallest res yh="0" yw="0" TEMP=`mktemp /tmp/vesa-XXXXXX` hwinfo --framebuffer 2>/dev/null | grep 'Mode ' >${TEMP} exec 0<${TEMP} while read i ; do vesa_res=$(echo $i | grep -oE ':\s+[0-9]+x[0-9]+' | \ grep -oE '[0-9]+x[0-9]+$') if [ "$vesa_res" = "$disp_res" ] ; then # exact match best_res="$vesa_res" break fi vw=$(echo $vesa_res | grep -oE '^[0-9]+') vh=$(echo $vesa_res | grep -oE '[0-9]+$') if [ "$vw" -le "$dw" ] && [ "$vh" -le "$dh" ] ; then if [ "$xw" -le "$vw" ] && [ "$xh" -le "$vh" ] ; then xw="$vw" xh="$vh" fi if [ "$yh" -le "$vh" ] && [ "$yw" -le "$vw" ] ; then yh="$vh" yw="$vw" fi fi done rm ${TEMP} if [ "$best_res" = "0" ] ; then if [ "$yh" -eq "$dh" ] ; then best_res="${yw}x${yh}" elif [ "$xw" -eq "$dw" ] ; then best_res="${xw}x${xh}" elif [ "$yh" -eq "$xh" ] ; then if [ "$xw" -gt "$yw" ] ; then best_res="${xw}x${xh}" else best_res="${yw}x${yh}" fi elif [ $(($dh - $yh)) -lt $(($dh - $xh)) ] ; then best_res="${yw}x${yh}" else best_res="${xw}x${xh}" fi fi if [ "$best_res" = "0" ] ; then echo "ERROR: no suitable VESA resolution found" exit 1 else echo "configuring GRUB for VESA resolution: $best_res" fi GRUB=/etc/default/grub if [ "$FB" = "y" ] ; then if grep -iq '^.*GRUB_CMDLINE_LINUX_DEFAULT=.*$' ${GRUB} ; then if ! grep -iq '^GRUB_CMDLINE_LINUX_DEFAULT=.*video=vesafb.*$' \ ${GRUB} ; then sed -i 's/^.*\(GRUB_CMDLINE_LINUX_DEFAULT="[^"]*\)"$/\1 video=vesafb"/g' ${GRUB} fi else cat >>${GRUB} <<EOF GRUB_CMDLINE_LINUX_DEFAULT="video=vesafb" EOF fi if grep -iq '^.*GRUB_GFXMODE=.*$' ${GRUB} ; then sed -i "s/^.*GRUB_GFXMODE.*$/GRUB_GFXMODE=$best_res/g" ${GRUB} else cat >>${GRUB} <<EOF GRUB_GFXMODE=$best_res EOF fi if grep -iq '^.*GRUB_GFXPAYLOAD_LINUX=.*$' ${GRUB} ; then sed -i 's/^.*GRUB_GFXPAYLOAD_LINUX.*$/GRUB_GFXPAYLOAD_LINUX=keep/g' \ ${GRUB} else cat >>${GRUB} <<EOF GRUB_GFXPAYLOAD_LINUX=keep EOF fi if grep -iq '^GRUB_TERMINAL=.*$' ${GRUB} ; then sed -i 's/^GRUB_TERMINAL\(.*\)$/#GRUB_TERMINAL\1/g' \ ${GRUB} fi else sed -i 's/^\(GRUB_CMDLINE_LINUX_DEFAULT=".*\)video=vesafb\(.*"\)$/\1\2/g' \ ${GRUB} if grep -iq '^GRUB_GFXMODE=.*$' ${GRUB} ; then sed -i 's/^GRUB_GFXMODE\(.*\)$/#GRUB_GFXMODE\1/g' \ ${GRUB} fi if grep -iq '^GRUB_GFXPAYLOAD_LINUX=.*$' ${GRUB} ; then sed -i 's/^GRUB_GFXPAYLOAD_LINUX\(.*\)$/#GRUB_GFXPAYLOAD_LINUX\1/g' \ ${GRUB} fi fi cat >/etc/initramfs-tools/conf.d/splash <<EOF FRAMEBUFFER=$FB EOF update-grub update-initramfs -u exit 0 <file_sep>/usr/bin/ident-agent-info #!/bin/sh # ident-agent-info - Creates identity agent info files for current user. # # Copyright (C) 2013,2014 Centrych Systems LLC # Author: <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it only under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation. You are not permitted # to use, modify, republish, or redistribute this program under any # other version of the GNU General Public License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # On Debian systems the full text of the GNU General Public License can # be found in the `/usr/share/common-licenses/GPL-2' file. # #=============================================================================== HOST=`hostname -s` GNOME_KEYRING_FILE=~/.config/gnome-keyring-info-${HOST} SSH_AGENT_FILE=~/.config/ssh-agent-info-${HOST} GPG_AGENT_FILE=~/.gnupg/gpg-agent-info-${HOST} # These variables indicate that the GNOME keyring is running. [ -f ${GNOME_KEYRING_FILE} ] && rm -f ${GNOME_KEYRING_FILE} GNOME_KEYRING_PKCS= if [ "x$GNOME_KEYRING_PID" != "x" ] ; then if ! kill -0 ${GNOME_KEYRING_PID} ; then unset GNOME_KEYRING_CONTROL unset GNOME_KEYRING_PID else if [ -S "${GNOME_KEYRING_CONTROL}/pkcs11" ] ; then GNOME_KEYRING_PKCS="${GNOME_KEYRING_CONTROL}/pkcs11" fi cat >${GNOME_KEYRING_FILE} <<EOF GNOME_KEYRING_CONTROL=$GNOME_KEYRING_CONTROL GNOME_KEYRING_PID=$GNOME_KEYRING_PID GNOME_KEYRING_PKCS=$GNOME_KEYRING_PKCS export GNOME_KEYRING_CONTROL GNOME_KEYRING_PID GNOME_KEYRING_PKCS EOF fi fi # These variables are created by either GNOME keyring or ssh-agent. [ -f ${SSH_AGENT_FILE} ] && rm -f ${SSH_AGENT_FILE} if [ "x$SSH_AGENT_PID" != "x" ] ; then if ! kill -0 ${SSH_AGENT_PID} ; then unset SSH_AUTH_SOCK unset SSH_AGENT_PID else cat >${SSH_AGENT_FILE} <<EOF SSH_AUTH_SOCK=$SSH_AUTH_SOCK SSH_AGENT_PID=$SSH_AGENT_PID export SSH_AUTH_SOCK SSH_AGENT_PID EOF fi fi # This variable is created by either GNOME keyring or gpg-agent. # Skip if the later, it creates this file when it starts. if ! ps -u $USER | grep -q gpg-agent ; then [ ! -d ~/.gnupg ] && mkdir ~/.gnupg [ -f ${GPG_AGENT_FILE} ] && rm -f ${GPG_AGENT_FILE} if [ "x$GPG_AGENT_INFO" != "x" ] ; then if [ ! -e ${GPG_AGENT_INFO%%:*} ] ; then unset GPG_AGENT_INFO else cat >${GPG_AGENT_FILE} <<EOF GPG_AGENT_INFO=$GPG_AGENT_INFO export GPG_AGENT_INFO EOF fi fi fi <file_sep>/usr/bin/configure-discard #!/bin/sh # # configures discard and fstrim cron job for solid state disks using # LVM with or without full disk encryption. # # Copyright (C) 2013,2014 Centrych Systems LLC # Author: <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it only under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation. You are not permitted # to use, modify, republish, or redistribute this program under any # other version of the GNU General Public License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # On Debian systems the full text of the GNU General Public License can # be found in the `/usr/share/common-licenses/GPL-2' file. # #=============================================================================== # # This script expects the SSD to have been configured using one of the # Centrych guided partitioning methods during installation. # # No other use is supported by Centrych. EID=`id -u` if [ "$EID" -ne 0 ] ; then echo "$0: must be executed as root" >&2 exit 1 fi case "$1" in enable) STATE=yes ;; disable) STATE=no ;; *) echo "$0: called with unknown argument \`$1'" >&2 exit 1 ;; esac if [ ! -e /etc/centrych/install.conf ] ; then echo "$0: /etc/centrych/install.conf missing" >&2 exit 1 fi . /etc/centrych/install.conf if [ "$STATE" = 'yes' ] ; then if [ "x$SSD_DISK" != "x" ] ; then drive=${SSD_DISK##*=} echo "disk: $SSD_DISK, drive: $drive" if hdparm -I /dev/$drive | grep -q "Solid State Device" ; then if [ -e /etc/lvm/lvm.conf ] ; then if grep -iq 'issue_discards = 0' /etc/lvm/lvm.conf ; then echo "modifying: /etc/lvm/lvm.conf" sed -i 's/issue_discards = 0/issue_discards = 1/g' \ /etc/lvm/lvm.conf fi fi if [ -e /etc/crypttab ] ; then if grep -q "${drive}[0-9]_crypt.*luks\$" /etc/crypttab ; then echo "modifying: /etc/crypttab" sed -i "s/^\(${drive}[0-9]_crypt.*luks\)\$/\1,discard/g" \ /etc/crypttab fi fi else echo "$0: /dev/$drive is not a SSD" >&2 fi else echo "$0: SSD was not used during installation" >&2 fi if [ ! -e /etc/cron.weekly/ssd-trim ] ; then echo "daily cron job created" cat >/etc/cron.weekly/ssd-trim <<EOF #! /bin/bash set -e [ -x /usr/sbin/ssd-trim ] || exit 0 ssd-trim >>/var/log/ssd-trim.log EOF chmod +x /etc/cron.weekly/ssd-trim fi elif [ "$STATE" = 'no' ] ; then if [ -e /etc/lvm/lvm.conf ] ; then if grep -iq 'issue_discards = 1' /etc/lvm/lvm.conf ; then echo "modifying: /etc/lvm/lvm.conf" sed -i 's/issue_discards = 1/issue_discards = 0/g' /etc/lvm/lvm.conf fi fi if [ -e /etc/crypttab ] ; then if grep -q "${drive}[0-9]_crypt.*luks\$" /etc/crypttab ; then echo "modifying: /etc/crypttab" sed -i "s/^\(${drive}[0-9]_crypt.*\),discard\$/\1/g" \ /etc/crypttab fi fi if [ -e /etc/cron.weekly/ssd-trim ] ; then echo "daily cron job removed" rm /etc/cron.weekly/ssd-trim fi else echo "$0: unexpected state: $STATE" >&2 exit 1 fi exit 0 <file_sep>/etc/init.d/checkroot #!/bin/sh # checkroot - check state of root account, create root-enabled file if enabled. # Copyright (C) 2013,2014 Centrych Systems LLC ### BEGIN INIT INFO # Provides: checkroot # Required-Start: $local_fs $remote_fs # Required-Stop: $local_fs $remote_fs # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Check status of local root account ### END INIT INFO FILE=/etc/centrych/root-enabled case $1 in start) [ -e ${FILE} ] && rm ${FILE} if grep -q '^+:' /etc/passwd; then # NIS in use, root password assumed. RET=0 else /usr/bin/rootstat >/dev/null 2>&1 RET=$? fi [ "$RET" -eq "0" ] && touch ${FILE} ;; stop | force-reload | restart) ;; *) ;; esac exit 0 <file_sep>/src/kwif4.cc /*- * Copyright © 2009, 2010 * <NAME> <<EMAIL>> * Copyright © 2009 * <NAME> <<EMAIL>> * * Provided that these terms and disclaimer and all copyright notices * are retained or reproduced in an accompanying document, permission * is granted to deal in this work without restriction, including un‐ * limited rights to use, publicly perform, distribute, sell, modify, * merge, give away, or sublicence. * * This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to * the utmost extent permitted by applicable law, neither express nor * implied; without malicious intent or gross negligence. In no event * may a licensor, author or contributor be held liable for indirect, * direct, other damage, loss, or other issues arising in any way out * of dealing in the work, even if advised of the possibility of such * damage or existence of a defect, except proven that it results out * of said person’s immediate fault when using the work as intended. *- * KWallet interface file for Qt 4 and KDE 4 */ #include <qstring.h> #include <kaboutdata.h> #include <kapplication.h> #include <kcmdlineargs.h> #include <kwallet.h> #include "kwalletcli.h" extern "C" char *getenv(const char *); extern "C" char *strdup(const char *); extern "C" const char __rcsid_kwif[] = "$MirOS: contrib/hosted/tg/code/kwalletcli/kwif4.cc,v 1.2 2010/01/11 15:34:31 tg Exp $"; extern "C" int kw_io(const char *fld, const char *ent, const char **pwp, const char *vers) { int rv; QString localwallet, qfld, qent, qpw; KWallet::Wallet *wallet; char *env_DISPLAY; if (pwp == NULL) return (KWE_ABORT); /* very basic protection against kdeinit4 errors */ if (!(env_DISPLAY = getenv("DISPLAY")) || !*env_DISPLAY) return (KWE_NOWALLET); qfld = QString::fromUtf8(fld); qent = QString::fromUtf8(ent); if (*pwp != NULL) qpw = QString::fromUtf8(*pwp); /* this is ridiculous */ KAboutData aboutData("kwalletcli", 0, ki18n("KWallet CLI"), vers); KCmdLineArgs::init(&aboutData); KApplication app(false); localwallet = KWallet::Wallet::LocalWallet(); wallet = KWallet::Wallet::openWallet(localwallet, 0); if (!wallet) { rv = KWE_NOWALLET; goto out; } if (!wallet->hasFolder(qfld)) { if (*pwp == NULL) { rv = KWE_NOFOLDER; goto out; } wallet->createFolder(qfld); } if (!wallet->setFolder(qfld)) { rv = KWE_ERRFOLDER; goto out; } if (*pwp == NULL) { if (!wallet->hasEntry(qent)) { rv = KWE_NOENTRY; goto out; } qpw = ""; if (wallet->readPassword(qent, qpw)) { rv = KWE_ERRENTRY; goto out; } rv = KWE_OK_GET; *pwp = strdup((const char *)qpw.toUtf8().data()); } else { if (wallet->writePassword(qent, qpw)) { rv = KWE_ERR_SET; goto out; } rv = KWE_OK_SET; } out: delete wallet; return (rv); } <file_sep>/usr/bin/rootcheck #!/bin/sh # rootcheck - check state of root account, create root-enabled file if enabled. # # Copyright (C) 2013,2014 Centrych Systems LLC # Author: <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it only under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation. You are not permitted # to use, modify, republish, or redistribute this program under any # other version of the GNU General Public License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # On Debian systems the full text of the GNU General Public License can # be found in the `/usr/share/common-licenses/GPL-2' file. # #=============================================================================== FILE=/etc/centrych/root-enabled EID=`id -u` [ "$EID" -eq 0 ] && [ -e ${FILE} ] && rm ${FILE} if grep -q '^+:' /etc/passwd; then echo "NIS in use, root password assumed." RET=0 else /usr/bin/rootstat RET=$? fi [ "$EID" -eq 0 ] && [ "$RET" -eq "0" ] && touch ${FILE} exit $RET <file_sep>/usr/bin/configure-suspend #!/bin/sh # sets the state the suspend menu item in the Xfce4 panel. # # Copyright (C) 2013,2014 Centrych Systems LLC # Author: <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it only under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation. You are not permitted # to use, modify, republish, or redistribute this program under any # other version of the GNU General Public License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # On Debian systems the full text of the GNU General Public License can # be found in the `/usr/share/common-licenses/GPL-2' file. # #=============================================================================== EID=`id -u` if [ "$EID" -ne 0 ] ; then echo "$0: must be executed as root" >&2 exit 1 fi case "$1" in enable) STATE=yes ;; disable) STATE=no ;; *) echo "$0: called with unknown argument \`$1'" >&2 exit 1 ;; esac cat > /etc/polkit-1/localauthority/50-local.d/com.ubuntu.suspend.pkla <<EOF [Suspend] Identity=unix-user:* Action=org.freedesktop.upower.suspend ResultActive=$STATE EOF <file_sep>/src/main.c /*- * Copyright © 2009, 2011 * <NAME> <<EMAIL>> * * Provided that these terms and disclaimer and all copyright notices * are retained or reproduced in an accompanying document, permission * is granted to deal in this work without restriction, including un‐ * limited rights to use, publicly perform, distribute, sell, modify, * merge, give away, or sublicence. * * This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to * the utmost extent permitted by applicable law, neither express nor * implied; without malicious intent or gross negligence. In no event * may a licensor, author or contributor be held liable for indirect, * direct, other damage, loss, or other issues arising in any way out * of dealing in the work, even if advised of the possibility of such * damage or existence of a defect, except proven that it results out * of said person’s immediate fault when using the work as intended. */ #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include "kwalletcli.h" const char __rcsid_main_c[] = "$MirOS: contrib/hosted/tg/code/kwalletcli/main.c,v 1.10 2011/04/09 22:24:32 tg Exp $"; #define WOCTET_MASK (0x7FFFFF80) #define WOCTET_VALUE (0x0000EF80) #define iswoctet(wc) (((wc) & WOCTET_MASK) == WOCTET_VALUE) int main(int argc, char *argv[]) { int ch, rv, quiet = 0; const char *kw_folder = NULL, *kw_entry = NULL, *kw_pass = NULL, *fmts; char *vers; while ((ch = getopt(argc, argv, "e:f:hPp:qV")) != -1) { switch (ch) { case 'e': kw_entry = optarg; break; case 'f': kw_folder = optarg; break; case 'P': { char *cp; size_t n = 65536; ssize_t cnt; if ((kw_pass = cp = malloc(n--)) == NULL) abort(); do { cnt = read(STDIN_FILENO, cp, n); if (cnt == -1) { if (errno == EINTR) continue; break; } else if (cnt == 0) break; n -= cnt; cp += cnt; } while (n); *cp = '\0'; break; } case 'p': kw_pass = optarg; break; case 'q': quiet = 1; break; case 'V': if (!quiet) fprintf(stderr, "%s\n%s\n%s\n", __rcsid_main_c, __rcsid_kwif, KWALLETCLI_H); return (0); case 'h': default: usage: fprintf(stderr, "Usage: kwalletcli -f folder" " -e entry [-P | -p writepassword]\n"); return (2); } } if ((argc - optind) || !kw_folder || !kw_entry) goto usage; if (asprintf(&vers, "%s %s %s", __rcsid_main_c, __rcsid_kwif, KWALLETCLI_H) == -1) vers = NULL; if (kw_pass) { unsigned int wc; size_t n; char *dst, *cp; const char *src = kw_pass; /* recode kw_pass from binary/utf-8 to safe utf-8 */ if ((dst = cp = malloc(strlen(kw_pass) * 3 + 1)) == NULL) abort(); do { n = utf_8to32(src, &wc); if (n == UTFCONV_ERROR || iswoctet(wc)) { /* assert: 0x80 <= *src <= 0xFF */ wc = *((const unsigned char *)src); wc |= WOCTET_VALUE; n = 1; } src += n; n = utf_32to8(dst, wc); dst += n; } while (wc); kw_pass = cp; } if (quiet) fclose(stderr); rv = kw_io(kw_folder, kw_entry, &kw_pass, vers ? vers : ""); switch (rv) { case KWE_OK_GET: { unsigned int wc; size_t n; char *dst, *cp; const char *src = kw_pass; /* recode kw_pass from safe utf-8 to binary/utf-8 */ if ((dst = cp = malloc(strlen(kw_pass) + 1)) == NULL) abort(); do { n = utf_8to32(src, &wc); if (n == UTFCONV_ERROR) /* should never happen */ goto print_kw_pass; src += n; if (iswoctet(wc)) { wc &= 0xFF; *((unsigned char *)dst++) = wc; } else { n = utf_32to8(dst, wc); dst += n; } } while (wc); kw_pass = cp; print_kw_pass: printf("%s", kw_pass); break; } case KWE_NOWALLET: if (!quiet) fprintf(stderr, "cannot open wallet\n"); break; case KWE_NOFOLDER: fmts = "folder '%s' does not exist\n"; if (0) /* FALLTHROUGH */ case KWE_ERRFOLDER: fmts = "cannot open folder '%s'\n"; if (!quiet) fprintf(stderr, fmts, kw_folder); break; case KWE_NOENTRY: fmts = "entry '%s' does not exist in folder '%s'\n"; if (0) /* FALLTHROUGH */ case KWE_ERRENTRY: fmts = "error reading entry '%s' from folder '%s'\n"; if (0) /* FALLTHROUGH */ case KWE_ERR_SET: fmts = "error writing entry '%s' to folder '%s'\n"; if (!quiet) fprintf(stderr, fmts, kw_entry, kw_folder); break; case KWE_OK_SET: rv = 0; break; case KWE_ABORT: if (!quiet) fprintf(stderr, "internal error\n"); default: fflush(NULL); abort(); } return (rv); } <file_sep>/usr/bin/root-shell #!/bin/sh # root-shell - open a root login. # # Copyright (C) 2013,2014 Centrych Systems LLC # Author: <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it only under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation. You are not permitted # to use, modify, republish, or redistribute this program under any # other version of the GNU General Public License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # On Debian systems the full text of the GNU General Public License can # be found in the `/usr/share/common-licenses/GPL-2' file. # #=============================================================================== # # allows xfce4 or gnome terminals, uses xfce4 if another terminal is set. TerminalEmulator=xfce4-terminal if [ -e /etc/centrych/root-enabled ] ; then if [ -e ${HOME}/.config/xfce4/helpers.rc ] ; then . ${HOME}/.config/xfce4/helpers.rc if [ "$TerminalEmulator" != gnome-terminal ] && \ [ "$TerminalEmulator" != xfce4-terminal ] ; then TerminalEmulator=xfce4-terminal fi fi ${TerminalEmulator} --title "Root Shell" --command "su -" else echo "ERROR: root account is not enabled." exit 1 fi exit 0 <file_sep>/etc/profile.d/clean-goutputstream.sh # Clean HOME directory of spurious goutputstream files. if [ "x$HOME" != "x" ] ; then for i in ${HOME}/.goutputstream-?????? ; do [ -f ${i} ] && rm ${i} done fi <file_sep>/Makefile #!/usr/bin/make -f all: $(MAKE) -C src rootstat $(MAKE) -C src gnome-keyring-query $(MAKE) -C src pam-keyring-tool $(MAKE) -C src kwalletcli install: mkdir -pv $(DESTDIR) cp -a etc usr $(DESTDIR)/. mv src/rootstat $(DESTDIR)/usr/bin mv src/gnome-keyring-query $(DESTDIR)/usr/bin mv src/pam-keyring-tool $(DESTDIR)/usr/bin mv src/kwalletcli $(DESTDIR)/usr/bin # remove some remaining files find $(DESTDIR) -type f -iname "*.in" | xargs rm -f # vim:ts=4 <file_sep>/usr/bin/configure-autologin #!/bin/sh # # disables or enables autologin for a user. # # Copyright (C) 2013,2014 Centrych Systems LLC # Author: <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it only under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation. You are not permitted # to use, modify, republish, or redistribute this program under any # other version of the GNU General Public License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # On Debian systems the full text of the GNU General Public License can # be found in the `/usr/share/common-licenses/GPL-2' file. # #=============================================================================== EID=`id -u` if [ "$EID" -ne 0 ] ; then echo "$0: must be executed as root" >&2 exit 1 fi if [ -d /home/.ecryptfs/$USER ] ; then echo "$0: autologin prohibited with encrypted home directory" >&2 exit 1 fi if [ ! -f /etc/lightdm/lightdm.conf ] ; then echo "$0: /etc/lightdm/lightdm.conf missing" >&2 exit 1 fi if [ ! -x /usr/lib/lightdm/lightdm-set-defaults ] ; then echo "$0: /usr/lib/lightdm/lightdm-set-defaults missing" >&2 exit 1 fi case "$1" in enable) ;; disable) ;; *) echo "$0: called with unknown argument \`$1'" >&2 exit 1 ;; esac if cat /etc/passwd | grep -q "^${2}\:" ; then sed -e '/#\?pam-service=.*/d' -i /etc/lightdm/lightdm.conf sed -e '/#\?autologin-user.*/d' -i /etc/lightdm/lightdm.conf case "$1" in enable) adduser $2 autologin /usr/lib/lightdm/lightdm-set-defaults --keep-old --autologin=$2 cat >>/etc/lightdm/lightdm.conf <<EOF autologin-user-timeout=0 pam-service=lightdm-autologin EOF ;; disable) deluser $2 autologin cat >>/etc/lightdm/lightdm.conf <<EOF pam-service=lightdm EOF ;; esac else echo "$0: user not found." >&2 exit 1 fi exit <file_sep>/src/charconv.c /*- * Copyright © 2011 * <NAME> <<EMAIL>> * * Provided that these terms and disclaimer and all copyright notices * are retained or reproduced in an accompanying document, permission * is granted to deal in this work without restriction, including un‐ * limited rights to use, publicly perform, distribute, sell, modify, * merge, give away, or sublicence. * * This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to * the utmost extent permitted by applicable law, neither express nor * implied; without malicious intent or gross negligence. In no event * may a licensor, author or contributor be held liable for indirect, * direct, other damage, loss, or other issues arising in any way out * of dealing in the work, even if advised of the possibility of such * damage or existence of a defect, except proven that it results out * of said person’s immediate fault when using the work as intended. */ #include <stdlib.h> #include "kwalletcli.h" const char __rcsid_charconv_c[] = "$MirOS: contrib/hosted/tg/code/kwalletcli/charconv.c,v 1.3 2011/04/09 22:33:49 tg Exp $"; /* From MirOS: contrib/hosted/tg/code/any2utf8/wide.c,v 1.1 2009/08/02 17:12:07 tg Exp */ size_t utf_32to8(char *dst, unsigned int wc) { unsigned char *cp = (unsigned char *)dst; unsigned int count; if (wc > 0x7FFFFFFF) /* beyond UTF-8 */ abort(); if (wc < 0x80) { count = 0; *cp++ = wc; } else if (wc < 0x0800) { count = 1; *cp++ = (wc >> 6) | 0xC0; } else if (wc < 0x00010000) { count = 2; *cp++ = (wc >> 12) | 0xE0; } else if (wc < 0x00200000) { count = 3; *cp++ = (wc >> 18) | 0xF0; } else if (wc < 0x04000000) { count = 4; *cp++ = (wc >> 24) | 0xFC; } else { count = 5; *cp++ = (wc >> 30) | 0xFE; } while (count) *cp++ = ((wc >> (6 * --count)) & 0x3F) | 0x80; return ((size_t)((char *)cp - dst)); } size_t utf_8to32(const char *src, unsigned int *dst) { const unsigned char *s = (const unsigned char *)src; unsigned int wc, count = 0; unsigned char c; wc = *s++; if (wc < 0xC2 || wc >= 0xFE) { if (wc >= 0x80) return (UTFCONV_ERROR); } else if (wc < 0xE0) { count = 1; /* one byte follows */ wc = (wc & 0x1F) << 6; } else if (wc < 0xF0) { count = 2; /* two bytes follow */ wc = (wc & 0x0F) << 12; } else if (wc < 0xF8) { count = 3; /* three bytes follow */ wc = (wc & 0x07) << 18; } else if (wc < 0xFC) { count = 4; /* four bytes follow */ wc = (wc & 0x03) << 24; } else /* (wc < 0xFE) */ { count = 5; /* five bytes follow */ wc = (wc & 0x01) << 30; } while (count) { if (((c = *s++) & 0xC0) != 0x80) return (UTFCONV_ERROR); wc |= (c & 0x3F) << (6 * --count); if (!count) break; if (wc < (1U << (5 * count + 6))) return (UTFCONV_ERROR); } if (wc == 0xFFFE || wc == 0xFFFF || wc > 0x7FFFFFFF || (wc >= 0xD800 && wc <= 0xDFFF)) return (UTFCONV_ERROR); *dst = wc; return ((size_t)((const char *)s - src)); } <file_sep>/src/Makefile #!/usr/bin/make -f rootstat: gcc -o rootstat rootstat.c gnome-keyring-query: ifeq ($(DEB_HOST_ARCH),amd64) gcc -c -I /usr/include/gnome-keyring-1 -I /usr/include/glib-2.0 \ -I /usr/lib/x86_64-linux-gnu/glib-2.0/include gnome-keyring-query.c else gcc -c -I /usr/include/gnome-keyring-1 -I /usr/include/glib-2.0 \ -I /usr/lib/i386-linux-gnu/glib-2.0/include gnome-keyring-query.c endif gcc gnome-keyring-query.o -o gnome-keyring-query \ -lgnome-keyring -lglib-2.0 pam-keyring-tool: ifeq ($(DEB_HOST_ARCH),amd64) gcc -c -I /usr/include/gnome-keyring-1 -I /usr/include/glib-2.0 \ -I /usr/lib/x86_64-linux-gnu/glib-2.0/include pam-keyring-tool.c else gcc -c -I /usr/include/gnome-keyring-1 -I /usr/include/glib-2.0 \ -I /usr/lib/i386-linux-gnu/glib-2.0/include pam-keyring-tool.c endif gcc pam-keyring-tool.o -o pam-keyring-tool \ -lpam -lgnome-keyring -lglib-2.0 kwalletcli: g++ -I/usr/include/qt4 -I/usr/include/qt4/QtCore -D_GNU_SOURCE -O2 \ -c -o kwif4.o kwif4.cc gcc -I/usr/include/qt4 -I/usr/include/qt4/QtCore -D_GNU_SOURCE -O2 \ -c -o charconv.o charconv.c gcc -I/usr/include/qt4 -I/usr/include/qt4/QtCore -D_GNU_SOURCE -O2 \ -c -o main.o main.c g++ ${LDFLAGS} -o kwalletcli kwif4.o charconv.o main.o -lkdeui \ -lkdecore -lQtCore <file_sep>/usr/bin/ident-check #!/bin/bash # ident-check - Checks status of identity agents and brower password stores. # # Copyright (C) 2013,2014 Centrych Systems LLC # Author: <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it only under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation. You are not permitted # to use, modify, republish, or redistribute this program under any # other version of the GNU General Public License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # On Debian systems the full text of the GNU General Public License can # be found in the `/usr/share/common-licenses/GPL-2' file. # #=============================================================================== # ensure identify agent info is current. ident-agent-info echo "Identity agent environment variables" echo "====================================" echo "GNOME_KEYRING_CONTROL: $GNOME_KEYRING_CONTROL" echo "GNOME_KEYRING_PKCS: $GNOME_KEYRING_PKCS" echo "GNOME_KEYRING_PID: $GNOME_KEYRING_PID" echo "SSH_AUTH_SOCK: $SSH_AUTH_SOCK" echo "SSH_AGENT_PID: $SSH_AGENT_PID" echo "GPG_AGENT_INFO: $GPG_AGENT_INFO" echo "" echo -n "Default GNOME " pam-keyring-tool --get-default echo "" SSH_AGENT_FILE=~/.config/ssh-agent-info-${HOST} if [ -e ${SSH_AGENT_FILE} ] ; then if cat ${SSH_AGENT_FILE} | grep -q SSH_ASKPASS ; then echo "Identities in ssh-agent" echo "=======================" ssh-add -l echo "" fi fi echo "Permissions of GNOME keyring file(s)" echo "====================================" if [ -d ~/.gnome2/keyrings ] ; then cd ~/.gnome2/keyrings for i in * ; do [ -f ${i} ] && ls -l ${i} done cd - >/dev/null fi echo "" echo "Permissions of kwallet file(s)" echo "==============================" if [ -d ~/.kde/share/apps/kwallet ] ; then cd ~/.kde/share/apps/kwallet for i in * ; do [ -f ${i} ] && ls -l ${i} done cd - >/dev/null fi echo "" echo "Permissions of GnuPG keyring file(s)" echo "====================================" if [ -d ~/.gnupg ] ; then cd ~/.gnupg for i in *.gpg ; do [ -f ${i} ] && ls -l ${i} done cd - >/dev/null fi echo "" echo "Permissions of SSH private key file(s)" echo "======================================" if [ -d ~/.ssh ] ; then cd ~/.ssh for i in id{entity,_dsa,_rsa,_ecdsa} ; do [ -f ${i} ] && ls -l ${i} done cd - >/dev/null fi echo "" echo "Chrome local passwords" echo "======================" if [ -e ~/.config/google-chrome/Default/Login\ Data ] ; then sqlite3 $HOME/.config/google-chrome/Default/Login\ Data \ 'SELECT username_value, password_value FROM logins;' echo "END passwords list" else echo "plaintext password store not found." fi echo "" echo "Chromium local passwords" echo "========================" if [ -e ~/.config/chromium/Default/Login\ Data ] ; then sqlite3 $HOME/.config/chromium/Default/Login\ Data \ 'SELECT username_value, password_value FROM logins;' echo "END passwords list" else echo "plaintext password store not found." fi echo "" <file_sep>/src/pam-keyring-tool.c /* pam-keyring-tool.c - utility for manipulating keyrings. Copyright (C) 2004 <NAME> The Gnome Keyring Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The Gnome Keyring Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the Gnome Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Author: <NAME> <<EMAIL>> */ #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <glib.h> #include <glib/gprintf.h> #include <gnome-keyring.h> /* ============================ PASSWORD_SIZE =============================== */ const size_t PASSWORD_SIZE = 1024; char *getpass(const char *); /* ============================ stdin_getpass () ============================= */ /* SIDE AFFECTS: at most size - 1 characters are read from stream and placed * in stdinpass; terminating carriage return in s is removed * OUTPUT: copy of stdinpass */ static char *stdin_getpass(void) { char stdinpass[PASSWORD_SIZE]; size_t len; /* * if no error is reported from fgets() and string at least contains * the newline that ends the password, then replace the newline with * a null terminator. */ if ( fgets(stdinpass, PASSWORD_SIZE, stdin) != NULL) { if ((len = strlen(stdinpass)) > 0) { if(stdinpass[len-1] == '\n') stdinpass[len - 1] = 0; } } return g_strdup(stdinpass); } /* ============================ get_pass () ============================= */ /* INPUT: pointer to a password prompt, and a gboolean for use stdin option * SIDE AFFECT: pass is filled with an authentication token * OUTPUT: if error NULL else pointer to pass */ static gchar *get_pass(const gchar *prompt, gboolean opt_use_stdin) { char *pass = NULL; if (opt_use_stdin) { pass = stdin_getpass(); } else { pass = getpass(prompt); } return (pass); } /* ============================ pam_keyring_create () =============================== */ /* INPUT: name, the name of the keyring to create * SIDE AFFECT: the keyring has been created * OUTPUT: GnomeKeyringResult */ static GnomeKeyringResult pam_keyring_create(gchar *keyring, gchar *password) { GnomeKeyringResult result; assert(keyring != NULL); if (password == NULL) { g_fprintf(stderr, "pam-keyring-tool: error reading password\n"); result = GNOME_KEYRING_RESULT_BAD_ARGUMENTS; goto _return; } result = gnome_keyring_create_sync(keyring, password); _return: return result; } /* ============================ pam_keyring_set_default () =========================== */ /* INPUT: name, the name of the keyring to set as the default * SIDE AFFECT: the keyring has been set to the default * OUTPUT: GnomeKeyringResult */ static GnomeKeyringResult pam_keyring_set_default(gchar *keyring) { GnomeKeyringResult result; assert(keyring != NULL); result = gnome_keyring_set_default_keyring_sync(keyring); return result; } /* ============================ pam_keyring_get_default () =========================== */ /* SIDE AFFECT: the name of the keyring is set to the default that is returned * OUTPUT: GnomeKeyringResult */ static GnomeKeyringResult pam_keyring_get_default(gchar **keyring) { char *name; GnomeKeyringResult result; result = gnome_keyring_get_default_keyring_sync(&name); if (result == GNOME_KEYRING_RESULT_OK) { *keyring = g_strdup(name); g_free(name); } return result; } /* ============================ pam_keyring_unlock () =============================== */ /* INPUT: name, the name of the keyring to unlock, boolean of how to get password * SIDE AFFECT: the keyring is unlocked * OUTPUT: GnomeKeyringResult */ static GnomeKeyringResult pam_keyring_unlock(char *keyring, gboolean opt_use_stdin) { GnomeKeyringResult result; char *password = NULL; assert(keyring != NULL); password = get_pass( "Password:", opt_use_stdin); if (password == NULL) { g_fprintf(stderr, "pam-keyring-tool: error reading authtok\n"); result = GNOME_KEYRING_RESULT_IO_ERROR; goto _return; } result = gnome_keyring_unlock_sync(keyring, password); if ( result == GNOME_KEYRING_RESULT_NO_SUCH_KEYRING ) { result = pam_keyring_create(keyring, password); } memset(password, 0x0, sizeof(password)); _return: return result; } static gboolean opt_unlock_keyring = FALSE; static gboolean opt_getdefault_keyring = FALSE; static gboolean opt_use_stdin = FALSE; static char *keyring = NULL; GOptionEntry entries[] = { { "unlock", 'u', 0, G_OPTION_ARG_NONE, &opt_unlock_keyring, "Unlock Keyring", NULL }, { "get-default", 'g', 0, G_OPTION_ARG_NONE, &opt_getdefault_keyring, "Get Default Keyring", NULL }, { "use-stdin", 's', 0, G_OPTION_ARG_NONE, &opt_use_stdin, "Use stdin for Password Prompt", NULL }, { "keyring", 0, 0, G_OPTION_ARG_STRING, &keyring, "Name of Keyring", "name" }, { NULL } }; int main(int argc, char *argv[], char *env[]) { gchar *error = NULL; GOptionContext *ctx; ctx = g_option_context_new(""); g_option_context_add_main_entries(ctx, entries, NULL); g_option_context_parse(ctx, &argc, &argv, NULL); g_option_context_free(ctx); if (opt_getdefault_keyring || !keyring) { if (pam_keyring_get_default(&keyring) != GNOME_KEYRING_RESULT_OK) { error = "error retrieving default keyring"; goto _error; } if (opt_getdefault_keyring) { g_fprintf(stdout, "keyring: %s\n", keyring); goto _exit; } if ( !keyring) { keyring = "default"; pam_keyring_set_default(keyring); } } if (opt_unlock_keyring && ! opt_getdefault_keyring) { if (pam_keyring_unlock(keyring, opt_use_stdin) != GNOME_KEYRING_RESULT_OK) { error = g_strdup_printf("error unlocking the %s keyring", keyring); goto _error; } goto _exit; } _error: if (error) { g_fprintf(stderr, "pam-keyring-tool: %s\n", error); } else { g_fprintf(stderr, "pam-keyring-tool: only one keyring action my be specified on the commandline\n"); } exit(EXIT_FAILURE); _exit: exit(EXIT_SUCCESS); } <file_sep>/usr/lib/os-probes/mounted/35centrych #!/bin/sh # Test for LSB systems. set -e . /usr/share/os-prober/common.sh partition="$1" dir="$2" type="$3" lsb_field () { file="$1" field="$2" grep ^"$field" "$file" | cut -d = -f 2 | sed 's/^"//' | sed 's/"$//' | sed 's/:/ /g' } file="$dir/etc/centrych-release" if [ ! -e "$file" ]; then exit 1 fi release=$(lsb_field "$file" DISTRIB_RELEASE) if [ -z "$release" ]; then release=$(lsb_field "$file" DISTRIB_CODENAME) fi description=$(lsb_field "$file" DISTRIB_DESCRIPTION) if [ -z "$description" ]; then description=$(lsb_field "$file" DISTRIB_CODENAME) fi if [ -n "$description" ]; then if [ -n "$release" ]; then long="$description ($release)" else long="$description" fi else exit 1 fi short=$(lsb_field "$file" DISTRIB_ID | sed 's/ //g') if [ -z "$short" ]; then short="UnknownLSB" fi label="$(count_next_label "$short")" result "$partition:$long:$label:linux" exit 0 <file_sep>/usr/bin/configure-browser-password #!/bin/sh # set password-store for chrome/chromium # # Copyright (C) 2013,2014 Centrych Systems LLC # Author: <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it only under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation. You are not permitted # to use, modify, republish, or redistribute this program under any # other version of the GNU General Public License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # On Debian systems the full text of the GNU General Public License can # be found in the `/usr/share/common-licenses/GPL-2' file. # #=============================================================================== ERROR="no" case "$1" in chrome) SRC="/usr/share/applications/google-chrome.desktop" DST="google-chrome.desktop" CMD="/opt/google/chrome/google-chrome" ;; chromium) SRC="/usr/share/applications/chromium-browser.desktop" DST="chromium-browser.desktop" CMD="chromium-browser" ;; *) ERROR="yes" ;; esac case "$2" in gnome|kwallet|basic) ;; *) ERROR="yes" ;; esac if [ "$ERROR" = "yes" ] ; then echo "Usage:" >&2 echo " $0 chrome|chromium basic|gnome|kwallet" >&2 exit 1 fi mkdir -p $HOME/.local/share/xfce4/helpers case "$1" in chrome) if [ ! -e $SRC ] ; then if id -Gn | grep -q sudo ; then sudo apt-get -q --yes install google-chrome-stable else echo "Please install the google-chrome-stable package, then re-run this script." exit 1 fi fi ;; chromium) if [ ! -e $SRC ] ; then if id -Gn | grep -q sudo ; then sudo apt-get -q --yes install chromium-browser else echo "Please install the chromium-browser package, then re-run this script." exit 1 fi fi ;; esac if [ -e $SRC ] ; then cp $SRC $HOME/.local/share/applications cp /usr/share/xfce4/helpers/$DST $HOME/.local/share/xfce4/helpers else echo "$0: $1 browser not found" >&2 exit 1 fi if [ "$2" != "basic" ] ; then sed -i "s|Exec=${CMD}|Exec=${CMD} --password-store=${2}|g" \ $HOME/.local/share/applications/$DST sed -i "s/=%B/=%B --password-store=${2}/g" \ $HOME/.local/share/xfce4/helpers/$DST fi
7d4192e76d46e7f29bfa1d2103bd2c6c5b2bb47d
[ "C", "Makefile", "C++", "Shell" ]
22
Shell
CentrychOS/centrych-support
31bfb85ff23536245a4efbe6d010915a9c63df34
580d0b65be6a3b65d644d38b217657a9e5421025
refs/heads/master
<repo_name>iKrishneel/sample_programs<file_sep>/rag/backup/main.cpp #include <boost/graph/adjacency_list.hpp> #include <boost/tuple/tuple.hpp> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <boost/config.hpp> #include <iostream> #include <vector> #include <string> #include <set> using namespace std; using namespace cv; const char *name[] = { "Jeanie", "Debbie", "Rick", "John", "Amanda", "Margaret", "Benjamin" }; struct VertexProperty { int v_index; const char* v_name; VertexProperty( int i = -1, const char* name = "default") : v_index(i), v_name(name) {} }; typedef boost::property<boost::edge_weight_t, float> EdgeProperty; typedef typename boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, VertexProperty, EdgeProperty> Graph; typedef typename boost::graph_traits< Graph>::adjacency_iterator AdjacencyIterator; typedef typename boost::property_map< Graph, boost::vertex_index_t>::type IndexMap; typedef typename boost::graph_traits< Graph>::edge_descriptor EdgeDescriptor; typedef typename boost::property_map< Graph, boost::edge_weight_t>::type EdgePropertyAccess; typedef typename boost::property_traits<boost::property_map< Graph, boost::edge_weight_t>::const_type>::value_type EdgeValue; typedef typename boost::graph_traits< Graph>::vertex_iterator VectorIterator; typedef typename boost::graph_traits< Graph>::vertex_descriptor VertexDescriptor; /** * updating the graph */ void updateRAG(const Graph &graph, int index) { boost::graph_traits<Graph>::vertex_iterator i, end; for (tie(i, end) = vertices(graph); i != end; ++i) { std::cout << "- Graph Property: " << graph[*i].v_index << "\t" << graph[*i].v_name << std::endl; } } /** * Create and process the graph */ void regionMergingGraph() { Graph graph; /* add vertices to the graph */ VertexDescriptor Jeanie = add_vertex(VertexProperty(0, name[0]), graph); VertexDescriptor Debbie = add_vertex(VertexProperty(1, name[1]), graph); VertexDescriptor Rick = add_vertex(VertexProperty(2, name[2]), graph); VertexDescriptor John = add_vertex(VertexProperty(3, name[3]), graph); VertexDescriptor Amanda = add_vertex(VertexProperty(4, name[4]), graph); VertexDescriptor Margaret = add_vertex(VertexProperty(5, name[5]), graph); VertexDescriptor Benjamin = add_vertex(VertexProperty(6, name[6]), graph); /* add edges to the vertices in the graph*/ add_edge(Jeanie, Debbie, EdgeProperty(0.5f), graph); add_edge(Jeanie, Rick, EdgeProperty(0.2f), graph); add_edge(Jeanie, John, EdgeProperty(-0.1f), graph); add_edge(Debbie, Amanda, EdgeProperty(-0.3f), graph); add_edge(Rick, Margaret, EdgeProperty(0.4f), graph); add_edge(John, Benjamin, EdgeProperty(0.6f), graph); IndexMap index_map = get(boost::vertex_index, graph); EdgeDescriptor e_descriptor; EdgePropertyAccess edge_weights = get(boost::edge_weight, graph); VectorIterator i, end; std::set<VertexDescriptor> to_remove; for (tie(i, end) = vertices(graph); i != end; i++) { std::cout << name[get(index_map, *i)]; AdjacencyIterator ai, a_end; tie(ai, a_end) = adjacent_vertices(*i, graph); if (ai == a_end) { std::cout << " has no children"; } else { std::cout << " is the parent of "; } for (; ai != a_end; ++ai) { bool found = false; tie(e_descriptor, found) = edge(*i, *ai, graph); if (found) { EdgeValue edge_val = boost::get( boost::edge_weight, graph, e_descriptor); float weights_ = edge_val; if (weights_ > 0.0f) { AdjacencyIterator aI, aEnd; tie(aI, aEnd) = adjacent_vertices(*ai, graph); for (; aI != aEnd; aI++) { EdgeDescriptor ed; bool located; tie(ed, located) = edge(*aI, *ai, graph); if (located && *aI != *i) { add_edge( get(index_map, *i), get(index_map, *aI), graph); } std::cout << "\n DEBUG: " << *i << " " << *ai << " " << *aI << " \n"; } std::cout << graph[*ai].v_index << ": " << graph[*ai].v_name << " " << *ai << " "; to_remove.insert(*ai); clear_vertex(*ai, graph); // remove_vertex(*ai, graph); } } }std::cout << "\n" << std::endl; } for(std::set<VertexDescriptor>::iterator it = to_remove.begin(); it != to_remove.end(); ++it) { VertexDescriptor vd = *it; clear_vertex(vd, graph); remove_vertex(vd, graph); } updateRAG(graph, 0); std::cout << "\nGraph Size: " << num_vertices(graph) << std::endl; } /** * */ int main(int argc, const char *argv[]) { regionMergingGraph(); exit(-1); cv::Mat image = cv::Mat::zeros(480, 640, CV_8UC3); Rect rect = Rect(64, 96, 256, 96); rectangle(image, rect, Scalar(0, 255, 0), -1); int width = 64; int height = 48; vector<Mat> patches; int _num_element = (image.rows/height) * (image.cols/width); Mat centroid = Mat(_num_element, 2, CV_32F); int y = 0; for (int j = 0; j < image.rows; j += height) { for (int i = 0; i < image.cols; i += width) { Rect_<float> _rect = Rect_<float>(i, j, width, height); if (_rect.x + _rect.width <= image.cols && _rect.y + _rect.height <= image.rows) { Mat roi = image(_rect); patches.push_back(roi); Point2f _center = Point2f(_rect.x + _rect.width/2, _rect.y + _rect.height/2); // centroid.push_back(_center); centroid.at<float>(y, 0) = _center.x; centroid.at<float>(y++, 1) = _center.y; } } } cv::flann::KDTreeIndexParams indexParams(5); cv::flann::Index kdtree(centroid, indexParams); Mat index; Mat dist; kdtree.knnSearch(centroid, index, dist, 4, cv::flann::SearchParams(64)); imshow("image", image); waitKey(0); return EXIT_SUCCESS; } <file_sep>/cc_labeling/main.cpp #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stdlib.h> #include <stdio.h> #include <ctime> #include <functional> using namespace cv; #include "connected.h" #include "contour_thinning.h" /** * function to label the binary image using connected component analysis */ void cvLabelImageRegion(const cv::Mat &in_img, cv::Mat &labelMD) { if (in_img.empty()) { std::cout << "Input image Empty!!!" << std::endl; return; } int width = in_img.cols; int height = in_img.rows; unsigned char *_img = new unsigned char[height*width]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { _img[i + (j * width)] = in_img.at<uchar>(j, i); } } const unsigned char *img = (const unsigned char *)_img; unsigned char *out_uc = new unsigned char[width*height]; ConnectedComponents *connectedComponent = new ConnectedComponents(3); connectedComponent->connected< unsigned char, unsigned char, std::equal_to<unsigned char>, bool>( img, out_uc, width, height, std::equal_to<unsigned char> (), false); labelMD = cv::Mat(in_img.size(), CV_32F); for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { labelMD.at<float>(j, i) = static_cast<float>( out_uc[i + (j * width)]); } } free(_img); free(out_uc); free(connectedComponent); } void cvMorphologicalOperations( const cv::Mat &img, cv::Mat &erosion_dst) { if (img.empty()) { return; } int erosion_size = 3; int erosion_const = 2; int erosion_type = MORPH_ELLIPSE; cv::Mat element = cv::getStructuringElement( erosion_type, cv::Size(erosion_const * erosion_size + sizeof(char), erosion_const * erosion_size + sizeof(char)), cv::Point(erosion_size, erosion_size)); cv::dilate(img, erosion_dst, element); cv::imshow("Errode Image", erosion_dst); } /** * */ void cvGetImageGrid( const cv::Mat &img, std::vector<cv::Mat> &img_cells, cv::Size cell_size = cv::Size(80, 60)) { if (img.empty()) { return; } img_cells.clear(); Mat img_ = img.clone(); cvtColor(img_, img_, CV_GRAY2BGR); for (int j = 0; j < img.rows; j += cell_size.height) { for (int i = 0; i < img.cols; i += cell_size.width) { cv::Rect_<int> rect = cv::Rect_<int>( i, j, cell_size.width, cell_size.height); if (rect.x + rect.width <= img.cols && rect.y + rect.height <= img.rows) { cv::Mat roi = img(rect); img_cells.push_back(roi); cv::rectangle(img_, rect, cv::Scalar(0, 255, 0), 2); } else { continue; } } } cv::imshow("grid map", img_); } void colorRegion(const cv::Mat &labelMD, cv::Mat &regionMD) { cv::RNG rng(12345); cv::Scalar color[100]; for (int i = 0; i < 100; i++) { color[i] = cv::Scalar( rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); } regionMD = cv::Mat(labelMD.size(), CV_8UC3); for (int j = 0; j < labelMD.rows; j++) { for (int i = 0; i < labelMD.cols; i++) { int lab = (int)labelMD.at<float>(j, i); regionMD.at<cv::Vec3b>(j, i)[0] = color[lab].val[0]; regionMD.at<cv::Vec3b>(j, i)[1] = color[lab].val[1]; regionMD.at<cv::Vec3b>(j, i)[2] = color[lab].val[2]; } } } int main(int argc, char *argv[]) { std::clock_t start; double duration; start = std::clock(); cv::Mat image = cv::imread("../edge.jpg", 0); if (image.empty()) { std::cout << "NO IMAGE READ..." << std::endl; } for (int j = 0; j < image.rows; j++) { for (int i = 0; i < image.cols; i++) { if (static_cast<int>(image.at<uchar>(j, i)) > 20) { image.at<uchar>(j, i) = 255; } else { image.at<uchar>(j, i) = 0; } } } cv::Rect rect(260, 180, 80, 60); cv::Mat img = image; cvMorphologicalOperations(img, img); thinning(img); std::vector<cv::Mat> img_cells; cvGetImageGrid(img, img_cells); Mat colorMapMD = Mat(image.size(), CV_8UC3); for (int i = 0; i < img_cells.size(); i++) { Mat roi = img_cells[i].clone(); cv::Mat labelMD; cvLabelImageRegion(roi, labelMD); cv::Mat regionMD; colorRegion(labelMD, regionMD); cv::imshow("label", regionMD); // } duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC; std::cout<<"printf: "<< duration << std::endl; cv::cvtColor(image, image, CV_GRAY2BGR); cv::rectangle(image, rect, cv::Scalar(0,255,0), 2); cv::imshow("image", image); cv::waitKey(0); return 0; } <file_sep>/pca_rot/back-up/main.cpp #include <iostream> #include <math.h> #include <ctime> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include "Object_Boundary.h" #include "RGBD_Image_Processing.h" #include "contour_thinning.h" using namespace std; using namespace cv; const cv::Scalar colorRangeMIN = cv::Scalar(0, 56, 5); const cv::Scalar colorRangeMAX = cv::Scalar(64, 119, 103); double getOrientation(vector<Point> &, Mat &); void getObjectROI(Mat &); void computeImageGradient(Mat &); void colorFilterTrackerBar(Mat &); void colorFilter(Mat &, cv::Scalar, cv::Scalar, bool = false); void getImageContours(Mat &, int = 30); void estimateDOGEdge(Mat &); void imageMorphologicalOp(Mat &, bool = true); RGBDImageProcessing * img_proc = new RGBDImageProcessing(); Mat original_img; int main(int argc, char *argv[]) { Mat image; if(argc < 2) { image = imread("../pca_test1.jpg", 1); } else { image = imread(argv[1], 1); } if(image.empty()) { std::cout << "No Image Found...." << std::endl; return -1; } const int downsample_ = 2; cv::resize(image, image, cv::Size(image.cols/downsample_, image.rows/downsample_)); original_img = image.clone(); getObjectROI(image); Mat img_bw; //cvtColor(image, img_bw, CV_BGR2GRAY); colorFilter(image, colorRangeMIN, colorRangeMAX, false); //colorFilterTrackerBar(image); cvtColor(image, img_bw, CV_BGR2GRAY); //estimateDOGEdge(img_bw); computeImageGradient(img_bw); //img_proc->lineDetection(image); Mat c_out; Mat img_gray; //cv::threshold(img_bw, img_gray, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU); cvtColor(image, image, CV_BGR2GRAY); //img_proc->extractImageContour(image, c_out, true); /* Dilate and errode*/ //getImageContours(original_img); vector<Vec4i> lines; cv::HoughLinesP(img_bw, lines, 1, CV_PI/180 , 20, 5, 5); imshow("input", image); waitKey(); //! Find all the contours in the thresholded image vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(img_bw, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_NONE); Mat img = image.clone(); for (size_t i = 0; i < contours.size(); ++i) { //! Calculate the area of each contour double area = contourArea(contours[i]); //! Ignore contours that are too small or too large if (area < 1e2 || 1e5 < area) { continue; } else { //! Draw each contour only for visualisation purposes drawContours(img, contours, i, CV_RGB(255, 0, 0), 2, 8, hierarchy, 0); //! Find the orientation of each shape getOrientation(contours[i], img); } } cv::imshow("img_bw", img_bw); cv::imshow("orig", img); cv::waitKey(0); return 0; } /** * */ double getOrientation(vector<Point> &pts, Mat &img) { //Construct a buffer used by the pca analysis Mat data_pts = Mat(pts.size(), 2, CV_64FC1); for (int i = 0; i < data_pts.rows; ++i) { data_pts.at<double>(i, 0) = pts[i].x; data_pts.at<double>(i, 1) = pts[i].y; } //Perform PCA analysis PCA pca_analysis(data_pts, Mat(), CV_PCA_DATA_AS_ROW); //Store the position of the object Point pos = Point(pca_analysis.mean.at<double>(0, 0), pca_analysis.mean.at<double>(0, 1)); //Store the eigenvalues and eigenvectors vector<Point2d> eigen_vecs(2); vector<double> eigen_val(2); for (int i = 0; i < 2; ++i) { eigen_vecs[i] = Point2d(pca_analysis.eigenvectors.at<double>(i, 0), pca_analysis.eigenvectors.at<double>(i, 1)); eigen_val[i] = pca_analysis.eigenvalues.at<double>(0, i); } // Draw the principal components circle(img, pos, 3, CV_RGB(255, 0, 255), 2); line(img, pos, pos + 0.02 * Point(eigen_vecs[0].x * eigen_val[0], eigen_vecs[0].y * eigen_val[0]) , CV_RGB(0, 255, 0)); line(img, pos, pos + 0.02 * Point(eigen_vecs[1].x * eigen_val[1], eigen_vecs[1].y * eigen_val[1]) , CV_RGB(0, 0, 255)); return atan2(eigen_vecs[0].y, eigen_vecs[0].x); } /** * */ void computeImageGradient(Mat &image) { GaussianBlur(image, image, Size(5,5), 1); Mat src_gray = image.clone(); /* Mat xsobel, ysobel; Sobel(image, xsobel, CV_32F, 1, 0, 5); Sobel(image, ysobel, CV_32F, 0, 1, 1); Mat Imag, Iang; //! Angle and Maginitue cartToPolar(xsobel, ysobel, Imag, Iang, true); normalize(Imag, Imag, 0, 1, NORM_MINMAX, -1, Mat()); const int angle_ = 360; add(Iang, Scalar(angle_), Iang, Iang < angle_); add(Iang, Scalar(-angle_), Iang, Iang >= angle_); normalize(Iang, Iang, 0, 1, NORM_MINMAX, -1, Mat()); Mat cb; multiply(Imag, Iang, cb); imshow("Mag", Imag); imshow("ang", Iang); imshow("weight", cb); */ int scale = 1; int delta = 0; int ddepth = CV_16S; /// Generate grad_x and grad_y Mat grad_x, grad_y; Mat grad; Mat abs_grad_x, abs_grad_y; /// Gradient X //Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT ); Sobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT ); convertScaleAbs( grad_x, abs_grad_x ); /// Gradient Y //Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT ); Sobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT ); convertScaleAbs( grad_y, abs_grad_y ); /// Total Gradient (approximate) addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad ); grad = grad * 2; //getImageContours(grad); imageMorphologicalOp(grad); imshow( "gradient", grad ); waitKey(); } /** * User defined object region via bounding box plot */ void getObjectROI(Mat &image) { ObjectBoundary *obj_roi = new ObjectBoundary(); Rect rect = obj_roi->cvGetobjectBoundary(image); Mat img = Mat::zeros(image.rows, image.cols, image.type()); for (int j = 0; j < image.rows; j++) { for (int i = 0; i < image.cols; i++) { if(i > (rect.x - 1) && i < (rect.x + rect.width + 1) && j > (rect.y - 1) && j < (rect.y + rect.height + 1)) { img.at<Vec3b>(j,i) = image.at<Vec3b>(j,i); } } } image = img.clone(); } /** * */ void colorFilter(Mat &image, Scalar colorMin, Scalar colorMax, bool isFind) { if(isFind) { colorFilterTrackerBar(image); } else { Mat dst; cv::inRange(image, colorMin, colorMax, dst); //cv::bitwise_and(img, dst, outimg); for (int j = 0; j < image.rows; j++) { for (int i = 0; i < image.cols; i++) { if((float)dst.at<uchar>(j,i) == 0) { image.at<Vec3b>(j,i)[0] = 0; image.at<Vec3b>(j,i)[1] = 0; image.at<Vec3b>(j,i)[2] = 0; } } } } } /** * */ int min_valR = 0; int max_valR = 256; int min_valG = 0; int max_valG = 256; int min_valB = 0; int max_valB = 256; Mat dst; Mat img; string window_name = "Result"; void threshCallBack(int, void*) { dst = img.clone(); Scalar lowerb = Scalar(min_valB, min_valG, min_valR); Scalar upperb = Scalar(max_valB, max_valG, max_valR); cv::inRange(img, lowerb, upperb, dst); Mat outimg = img.clone(); //cv::bitwise_and(img, dst, outimg); for (int j = 0; j < img.rows; j++) { for (int i = 0; i < img.cols; i++) { if((float)dst.at<uchar>(j,i) == 0) { outimg.at<Vec3b>(j,i)[0] = 0; outimg.at<Vec3b>(j,i)[1] = 0; outimg.at<Vec3b>(j,i)[2] = 0; } } } imshow( window_name, dst ); imshow("out", outimg); } void colorFilterTrackerBar(Mat &image) { img = image.clone(); namedWindow("Result", CV_WINDOW_AUTOSIZE); createTrackbar("Red Min", window_name, &min_valR, 256); createTrackbar("Red Max", window_name, &max_valR, 256); createTrackbar("Green Min", window_name, &min_valG, 256); createTrackbar("Green Max", window_name, &max_valG, 256); createTrackbar("Blue Min", window_name, &min_valB, 256); createTrackbar("Blue Max", window_name, &max_valB, 256); //cvtColor(image, img, CV_BGR2HSV); int c; while(true) { threshCallBack(0,0); c = waitKey( 20 ); if( (char)c == 27 ) { break; } } } /** * estimate the image contours */ void getImageContours(Mat &image, int contour_thresh) { if(image.empty() || image.type() != CV_8UC1) { std::cout << "Image is empty" << std::endl; return; } vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(image, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); Mat drawImg; cvtColor(image, drawImg, CV_GRAY2BGR); for (int i = 0; i < contours.size(); i++) { if(cv::contourArea(contours[i]) > contour_thresh) { drawContours(drawImg, contours, i, Scalar(255, 0, 255), 2, 8, hierarchy, 0, Point()); } } imshow("Image Contours", drawImg); } void estimateDOGEdge(Mat &image) { Mat img1, img2; GaussianBlur(image, img1, Size(3,3), 0); GaussianBlur(image, img2, Size(17,17), 0); Mat edgeMap = img1 - img2; imshow("Edge", edgeMap); waitKey(0); } /** * Function to create a binary image for any pixel not equal to zero */ void cvCreateBinaryImage(Mat image, Mat &img_bw, int lowerb = 0) { img_bw = Mat::zeros(image.size(), CV_8UC1); for (size_t j = 0; j < image.rows; j++) { for (size_t i = 0; i < image.cols; i++) { if(static_cast<int>(image.at<uchar>(j,i)) > lowerb) { img_bw.at<uchar>(j,i) = 255; } } } } /** * compute the pixel edge directional orientation */ void computeEdgeTangentOrientation(Mat &image, std::vector<std::vector<cv::Point> > &contours_tangent, std::vector<std::vector<cv::Point> > &contours) { #define BIN (6) const int ANGLE (180/BIN); std::vector<std::vector<cv::Point> > orientation_bin(BIN); for (int j = 0; j < contours_tangent.size(); j++) { for (int i = 0; i < contours_tangent[j].size(); i++) { /*compute the angle*/ float angle_ = 0.0f; if( contours_tangent[j][i].x == 0) { angle_ = 90.0f; } else { angle_ = atan(contours_tangent[j][i].y/contours_tangent[j][i].x) * (180/CV_PI); } int w_bin = (static_cast<int>(angle_) / ANGLE) + ((BIN - 1)/2); orientation_bin[w_bin].push_back(contours[j][i]); } } for (int j = 0; j < orientation_bin.size(); j++) { Mat img = image.clone();//Mat::zeros(image.size(), CV_8UC3); for (int i = 1; i < orientation_bin[j].size(); i++) { //circle(img, orientation_bin[j][i], 3, Scalar(255,0,255), //-1); line(img, orientation_bin[j][i-1], orientation_bin[j][i], Scalar(0,255,0), 2); } //imshow("Cluster of lines", img); //waitKey(); } } /** * Compute the image pixel tanget on the contour. * "http://en.wikipedia.org/wiki/Finite_difference#Forward.2C_backward.2C_and_central_differences"" */ void computeEdgeTangent(Mat &image, std::vector<std::vector<cv::Point> > &contours) { cvtColor(image, image, CV_GRAY2BGR); std::vector<std::vector<cv::Point> > tangents; for (int j = 0; j < contours.size(); j++) { std::vector<cv::Point> tangent; /* estimate the first tangent line*/ cv::Point2f edge_pt = contours[j].front(); cv::Point2f edge_tngt = contours[j].back() - contours[j].at(1); tangent.push_back(edge_tngt); //cv::line(image, edge_pt + edge_tngt, edge_pt - edge_tngt, cv::Scalar(0,0,255), 2); const int neighbor_pts = 0; if(contours[j].size() > sizeof(short)) { for (int i = sizeof(char) + neighbor_pts; i < contours[j].size() - sizeof(char) - neighbor_pts; i++) { edge_pt = contours[j][i]; edge_tngt = contours[j][i-1-neighbor_pts] - contours[j][i+1+neighbor_pts]; tangent.push_back(edge_tngt); //cv::line(image, edge_pt + edge_tngt, edge_pt - edge_tngt, cv::Scalar(0,0,255), 2); } } tangents.push_back(tangent); } /* compute the tangent orientation */ computeEdgeTangentOrientation(image, tangents, contours); std::vector<cv::Point> selected_pts; //! memory to hold the point //! where gradient changes const float tangent_range = 0.01f; for (int j = 0; j < tangents.size(); j++) { if(tangents[j].size() < 2) { continue; } for (int i = sizeof(char); i < tangents[j].size(); i++) { float y1 = tangents[j][i].y; float x1 = tangents[j][i].x; float y0 = tangents[j][i-1].y; float x0 = tangents[j][i-1].x; float tang1 = 0.0f; float tang0 = 0.0f; if(x1 != 0) { tang1 = y1/x1; } if(x0 != 0) { tang0 = y0/x0; } //std::cout << "Tanget: " << tang1 << "\tAngle: " << atan2(y1,x1) * 180/CV_PI << std::endl; //if(tang1 > -tangent_range && tang1 < tangent_range) if((tang1 >= 0.0f && tang0 < 0.0f) || (tang1 < 0.0f && tang0 >= 0.0f)) { selected_pts.push_back(contours[j][i]); //selected_pts.push_back(contours[j][i-1]); circle(original_img, contours[j][i], 2, Scalar(255, 0, 0), 1); circle(original_img, contours[j][i], 5, Scalar(0,255,0), 2); circle(original_img, contours[j][i-1], 2, Scalar(255, 0, 0), 1); circle(original_img, contours[j][i-1], 5, Scalar(0,255,0), 2); /* circle(image, contours[j][i], 2, Scalar(255, 0, 0), -1); circle(image, contours[j][i], 5, Scalar(0,0,255), 2); circle(image, contours[j][i-1], 2, Scalar(255, 0, 0), -1); circle(image, contours[j][i-1], 5, Scalar(0,0,255), 2); */ cv::line(image, contours[j][i-1], contours[j][i], Scalar(0,255,0), 2); } } //cv::imshow("masked", image); //waitKey(); } cv::imshow("masked", image); cv::imshow("tangent", original_img); cv::waitKey(); } /** * */ void branchEstimation(Mat &img_bw) { /* get the image contour by fitering the small contour region */ cv::Mat canny_out; int contour_area_thresh = 100; img_proc->extractImageContour(img_bw, canny_out, true, contour_area_thresh); std::vector<std::vector<cv::Point> > contours; img_proc->getContour(contours); computeEdgeTangent(img_bw, contours); } /** * Adequate image smoothing */ void imageMorphologicalOp(cv::Mat &src, bool is_errode) { cv::Mat erosion_dst; int erosion_size = 5; int erosion_const = 2; cv::Mat dilation_dst; int dilation_size = 1; int dilation_const = 2; int erosion_type = MORPH_ELLIPSE; cv::Mat element = cv::getStructuringElement(erosion_type, cv::Size(erosion_const * erosion_size + 1, erosion_const * erosion_size + 1), cv::Point(erosion_size, erosion_size )); cv::GaussianBlur(src, src, cv::Size(7, 7), 0); cv::erode( src, erosion_dst, element ); //erosion_dst = erosion_dst * 4; /* dilate the image by same factor as erosion*/ int dilation_type = MORPH_ELLIPSE; cv::Mat d_element = cv::getStructuringElement(dilation_type, cv::Size(dilation_const * dilation_size + 1, dilation_const * dilation_size + 1), cv::Point(dilation_size, dilation_size)); //dilate( erosion_dst, dilation_dst, d_element ); //erosion_dst = dilation_dst; /*convert the eroded image to binary*/ Mat img_bw; cvCreateBinaryImage(erosion_dst, img_bw); std::clock_t start; double duration; start = std::clock(); cv::Mat bw = img_bw.clone(); thinning(bw); cv::imshow("dst", bw); duration = (std::clock() - start) / (double)CLOCKS_PER_SEC; std::cout << "Time " << duration << std::endl; waitKey(); /* estimate the branch */ branchEstimation(img_bw); erosion_const = 3; element = cv::getStructuringElement(erosion_type, cv::Size(erosion_const * erosion_size + 1, erosion_const * erosion_size + 1), cv::Point(erosion_size, erosion_size )); //cv::erode(img_bw, img_bw, element ); //imshow("lines", img_lines); imshow("image", src); imshow( "Erosion Demo", erosion_dst ); imshow("Binary", img_bw); waitKey(); } <file_sep>/python_tutorial/pca_tutorials/pca.py #!/usr/bin/env python #tutorial from : http://sebastianraschka.com/Articles/2014_pca_step_by_step.html import numpy as np import numpy from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import proj3d # generating random dataset np.random.seed(1) # random seed for consistency mu_vec1 = np.array([0,0,0]) cov_mat1 = np.array([[1,0,0],[0,1,0],[0,0,1]]) class1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20).T assert class1_sample.shape == (3,20), "The matrix has not the dimensions 3x20" mu_vec2 = np.array([1,1,1]) cov_mat2 = np.array([[1,0,0],[0,1,0],[0,0,1]]) class2_sample = np.random.multivariate_normal(mu_vec2, cov_mat2, 20).T assert class1_sample.shape == (3,20), "The matrix has not the dimensions 3x20" # ploting fig = plt.figure(figsize=(8,8)) ax = fig.add_subplot(111, projection='3d') plt.rcParams['legend.fontsize'] = 10 ax.plot(class1_sample[0,:], class1_sample[1,:], class1_sample[2,:], 'o', markersize=8, color='blue', alpha=0.5, label='class1') ax.plot(class2_sample[0,:], class2_sample[1,:], class2_sample[2,:], '^', markersize=8, alpha=0.5, color='red', label='class2') plt.title('Samples for class 1 and class 2') ax.legend(loc='upper right') # concatenate the dataset all_samples = np.concatenate((class1_sample, class2_sample), axis=1) assert all_samples.shape == (3,40), "NO 3 x 40 matrix" # computing the d-dim mean vector mean_x = np.mean(all_samples[0,:]) mean_y = np.mean(all_samples[1,:]) mean_z = np.mean(all_samples[2,:]) mean_vector = np.array([[mean_x], [mean_y], [mean_z]]) print 'Mean Vector: \n', mean_vector #compute the scatter matrix scatter_matrix = np.zeros((3, 3)) for i in range(all_samples.shape[1]): scatter_matrix += (all_samples[:,i].reshape(3,1) - mean_vector).dot( (all_samples[:,i].reshape(3,1) - mean_vector).T) a = all_samples[:,i].reshape(3,1) - mean_vector print a print a.T print a.dot(a.T) print '\nScatter Matrix:\n', scatter_matrix #computing the covariance matrix which is alternative to the scatter matrix #their eigenspaces will be identical (identical eigenvectors, only the eigenvalues are scaled differently by a constant factor). cov_mat = np.cov([all_samples[0,:], all_samples[1,:], all_samples[2,:]]) print '\nCovariance matrix: \n', cov_mat # computing eigenvectors and eigenvalues #eigenvector and eigenvalue from the scatter matrix eig_val_sc, eig_vec_sc = np.linalg.eig(scatter_matrix) #eigenvector and eigenvalues from the covariance eig_val_cov, eig_vec_cov = np.linalg.eig(cov_mat) for i in range(len(eig_val_sc)): eigvec_sc = eig_vec_sc[:,i].reshape(1, 3).T eigvec_cov = eig_vec_cov[:, i].reshape(1, 3).T assert eigvec_sc.all() == eigvec_cov.all(), 'Eigenvectors are not identical' print'\nEigenvector {}: \n{}'.format(i+1, eigvec_sc) print'\nEigenvector {}: \n{}'.format(i+1, eigvec_cov) print'Eigenvalue {} from scatter matrix: {}'.format(i+1, eig_val_sc[i]) print'Eigenvalue {} from covariance matrix: {}'.format(i+1, eig_val_cov[i]) print'Scaling factor: ', eig_val_sc[i]/eig_val_cov[i] print 40 * '-' # check that the eigenvector and eigenvalues for i in range(len(eig_val_sc)): eigv = eig_vec_sc[:,i].reshape(1,3).T np.testing.assert_array_almost_equal(scatter_matrix.dot(eigv), eig_val_sc[i] * eigv, decimal=6, err_msg='', verbose=True) #visualizing the eigenvectors from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import proj3d from matplotlib.patches import FancyArrowPatch class Arrow3D(FancyArrowPatch): def __init__(self, xs, ys, zs, *args, **kwargs): FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs) self._verts3d = xs, ys, zs def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0],ys[0]),(xs[1],ys[1])) FancyArrowPatch.draw(self, renderer) fig = plt.figure(figsize=(7,7)) ax = fig.add_subplot(111, projection='3d') ax.plot(all_samples[0,:], all_samples[1,:], all_samples[2,:], 'o', markersize=8, color='green', alpha=0.2) ax.plot([mean_x], [mean_y], [mean_z], 'o', markersize=10, color='red', alpha=0.5) for v in eig_vec_sc.T: a = Arrow3D([mean_x, v[0]+mean_x], [mean_y, v[1]+mean_y], [mean_z, v[2]+mean_z], mutation_scale=20, lw=3, arrowstyle="-|>", color="r") ax.add_artist(a) ax.set_xlabel('x_values') ax.set_ylabel('y_values') ax.set_zlabel('z_values') plt.title('Eigenvectors') # plt.show() #projecting the feature space via PCA onto a smaller subspace, where the eigenvectors will form the axes of this new feature subspace. , the eigenvectors only define the directions of the new axis, since they have all the same unit length 1, which we can confirm by the following code: for ev in eig_vec_sc: numpy.testing.assert_array_almost_equal(1.0, np.linalg.norm(ev)) # instead of 'assert' because of rounding errors # ranking the eigenvector using the eigenvalues and chose k highest eigenvalues # Make a list of (eigenvalue, eigenvector) tuples eig_pairs = [(np.abs(eig_val_sc[i]), eig_vec_sc[:,i]) for i in range(len(eig_val_sc))] # Sort the (eigenvalue, eigenvector) tuples from high to low eig_pairs.sort() eig_pairs.reverse() # Visually confirm that the list is correctly sorted by decreasing eigenvalues for i in eig_pairs: print(i[0]) <file_sep>/pixel_classification/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project( main ) find_package( OpenCV REQUIRED ) find_package(OpenMP) if (OPENMP_FOUND) set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") endif() add_executable( main main.cpp ) target_link_libraries( main ${OpenCV_LIBS} ${OPENMP_LIBS}) <file_sep>/pca_rot/RGBD_Image_Processing.cpp // // Color Histogram Descriptors.cpp // Handheld Object Tracking // // Created by <NAME> on 11/11/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #include "RGBD_Image_Processing.h" /** * Function to extract the lines */ void RGBDImageProcessing::lineDetection(Mat &image, vector<Vec2f> &s_lines, double langle, double hangle) { vector<Vec2f> lines; Mat dst; this->extractImageContour(image, dst, true); //! detect the lines HoughLines(dst, lines, sizeof(char), CV_PI/180, 100); cvtColor(image, image, CV_GRAY2BGR); for (size_t i = 0; i < lines.size(); i++) { float rho = lines[i][0]; float theta = lines[i][1]; if(theta > (CV_PI / 180.0 * hangle) || theta < (CV_PI / 180.0 * langle)) { Point pt1, pt2; double a = cos(theta); double b = sin(theta); double x0 = a * rho; double y0 = b * rho; pt1.x = cvRound (x0 + 1000 * (-b)); pt1.y = cvRound (y0 + 1000 * (a)); pt2.x = cvRound (x0 - 1000 * (-b)); pt2.y = cvRound (y0 - 1000 * (a)); line(image, pt1, pt2, Scalar(0,255,0), 2, CV_AA); s_lines.push_back(lines[i]); } } imshow("Hough Line", image); } /** * Function to extract the image contour */ void RGBDImageProcessing::extractImageContour(Mat &image, Mat &canny_out, bool isContour, int contour_thresh) { if(!image.data) { //ROS_ERROR("No Input Image Found"); } else { vector<Vec4i> hierarchy; //GaussianBlur(image, image, Size(7, 7), 0); Mat img = image.clone(); if(img.type() != CV_8UC1) { cvtColor(img, img, CV_BGR2GRAY); } Canny(img, canny_out, 5, 50, 5, true); if(isContour) { std::vector<std::vector<cv::Point> > _contour; Mat contImg;// = cv::Mat::zeros(image.size(), CV_8U); cvtColor(image, contImg, CV_GRAY2BGR); findContours(canny_out, _contour, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_TC89_KCOS, Point(0, 0)); for (int i = 0; i < _contour.size(); i++) { if(cv::contourArea(_contour[i]) > contour_thresh) { this->contours.push_back(_contour[i]); drawContours(contImg, _contour, i, Scalar(0, 255, 0), 1, 8, hierarchy, 0, Point()); } else { //! #NOTE CHANGE THE ALGORITHM TO COPY ON CONTOUR REGION drawContours(image, _contour, i, Scalar(0, 0, 0), CV_FILLED, 8, hierarchy, 0, Point()); } //imshow("Contours", contImg); //waitKey(); } imshow("Contours", contImg); std::cout << "Contour Size: " << this->contours.size() << std::endl; //imshow("Canny Image", canny_out); } } } /** * Function to compute image line extraction on the roi */ void RGBDImageProcessing::roiLineDetection(Mat &image, Rect rect) { if(image.empty()) { //ROS_ERROR("No image to extract ROI line detection"); return; } Mat roi = image(rect); //lineDetection(roi); imshow("roi line", roi); } void RGBDImageProcessing::getContour(std::vector<std::vector<cv::Point> > &img_contour) { img_contour.clear(); img_contour = this->contours; } <file_sep>/pca_rot/Object_Boundary.h // // Object Boundary.h // Handheld Object Tracking // // Created by <NAME> on 3/11/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #ifndef __Handheld_Object_Tracking__Object_Boundary__ #define __Handheld_Object_Tracking__Object_Boundary__ #include <iostream> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> using namespace std; using namespace cv; typedef struct cvMouseParam{ Point x; Point y; const char* winName; Mat image; }cvMouseParam; class ObjectBoundary { private: /** * Mouse callback function that allows user to specify the * initial object region. * Parameters are as specified in OpenCV documentation. */ static void cvMouseCallback(int event, int x, int y, int flags, void* param){ cvMouseParam *p = (cvMouseParam*)param; Mat clone; static int pressed = false; if (!p->image.data) { cout << "No Image Found in MouseCallback" << endl; return; } if (event == CV_EVENT_LBUTTONDOWN) { p->x.x = x; p->x.y = y; pressed = true; } //! on left button press, remember first corner of rectangle around object else if (event == CV_EVENT_LBUTTONUP){ p->y.x = x; p->y.y = y; clone = p->image.clone(); rectangle(clone, p->x, p->y, Scalar(0,255,0), 2); imshow(p->winName, clone); // cvDestroyWindow(p->winName); pressed = false; } //! on mouse move with left button down, draw rectangle else if (event == CV_EVENT_MOUSEMOVE && flags & CV_EVENT_FLAG_LBUTTON){ clone = p->image.clone(); rectangle(clone, p->x, p->y, Scalar(0,255,0),2); imshow(p->winName, clone); // cvDestroyWindow(p->winName); } } cvMouseParam *mouseParam; public: Rect cvGetobjectBoundary(const Mat &); ObjectBoundary(); }; #endif /* defined(__Handheld_Object_Tracking__Object_Boundary__) */ <file_sep>/openMP/main.cpp #include <iostream> #include <cmath> #include <ctime> #ifdef _OPENMP #include <omp.h> #endif #include <set> int main(int argc, char *argv[]) { std::clock_t start; double duration; start = std::clock(); const int aSize = 256000; double sinTable[aSize]; #pragma omp parallel { #pragma omp for for (int n = 0; n < aSize; ++n) { sinTable[n] = std::sin(2 * M_PI * n / aSize); } } duration = (std::clock() - start) / static_cast<double>(CLOCKS_PER_SEC); std::cout<<"printf: "<< duration <<'\n'; return 0; } <file_sep>/region_growing/rgrow.c #include <stdlib.h> #include <stdio.h> #include <opencv/cv.h> #include <opencv/highgui.h> typedef struct { unsigned char r; unsigned char g; unsigned char b; } Color; typedef struct PosList { int x; int y; struct PosList *next; } PosList; int colordiff(Color a, Color b) { int dr, dg, db; dr = (int) ((a.r < b.r) ? (b.r - a.r) : (a.r - b.r)); dg = (int) ((a.g < b.g) ? (b.g - a.g) : (a.g - b.g)); db = (int) ((a.b < b.b) ? (b.b - a.b) : (a.b - b.b)); return dr + dg + db; } PosList * newnode(int x, int y) { PosList *pos; pos = (PosList *) malloc(sizeof(PosList)); pos->x = x; pos->y = y; pos->next = NULL; return pos; } void delnode(PosList **pos) { free(*pos); *pos = NULL; } void pl_push(PosList **list, PosList *pos) { pos->next = *list; *list = pos; } PosList * pl_pop(PosList **list) { PosList *pos; pos = *list; *list = (*list)->next; return pos; } void dellist(PosList **list) { PosList *a, *b; a = *list; while (a != NULL) { b = a->next; delnode(&a); a = b; } } int contains(PosList *list, int x, int y) { while (list != NULL) { if (list->x == x && list->y == y) return 1; list = list->next; } return 0; } void rgrow(IplImage *source, IplImage *dest, Color color, int threshold) { PosList *list_n; PosList *node_r; PosList *list_r; Color curcolor; int x, y; int sx, sy; int dx, dy; int offset; int mindiff, curdiff; #ifdef REC CvVideoWriter *writer; CvSize size; IplImage *frame; int i; #endif #ifdef REC size = cvSize(dest->width, dest->height); frame = cvCreateImage(size, IPL_DEPTH_8U, 3); writer = cvCreateVideoWriter("rgrow.avi", CV_FOURCC('M', 'J', 'P', 'G'), 15.0, size, 1); #endif mindiff = 255 * 3; for (y = 0; y < source->height; y++) { for (x = 0; x < source->width; x++) { offset = y * source->width * 3 + x * 3; curcolor.b = source->imageData[offset]; curcolor.g = source->imageData[offset + 1]; curcolor.r = source->imageData[offset + 2]; curdiff = colordiff(color, curcolor); if (curdiff < mindiff) { sx = x; sy = y; mindiff = curdiff; } dest->imageData[y * dest->width + x] = 0; } } list_n = newnode(sx, sy); list_r = NULL; while (list_n != NULL) { sx = list_n->x; sy = list_n->y; pl_push(&list_r, pl_pop(&list_n)); for (dy = -1; dy <= 1; dy++) { for (dx = -1; dx <= 1; dx++) { if (dx == 0 && dy == 0) continue; if (dx != 0 && dy != 0) continue; if (sx + dx == -1 || sx + dx == source->width || sy + dy == -1 || sy + dy == source->height) break; if (contains(list_n, sx + dx, sy + dy)) continue; if (contains(list_r, sx + dx, sy + dy)) continue; offset = (sy + dy) * source->width * 3 + (sx + dx) * 3; curcolor.b = source->imageData[offset]; curcolor.g = source->imageData[offset + 1]; curcolor.r = source->imageData[offset + 2]; curdiff = colordiff(color, curcolor); if (curdiff <= threshold) pl_push(&list_n, newnode(sx + dx, sy + dy)); } if (dx < 2) break; } } #ifdef REC cvCvtColor(dest, frame, CV_GRAY2BGR); cvWriteFrame(writer, frame); i = 0; #endif node_r = list_r; while (node_r != NULL) { dest->imageData[node_r->y * dest->width + node_r->x] = 255; #ifdef REC if (i % 100 == 0) { cvCvtColor(dest, frame, CV_GRAY2BGR); cvWriteFrame(writer, frame); } i++; #endif node_r = node_r->next; } dellist(&list_r); #ifdef REC cvReleaseVideoWriter(&writer); #endif } int main(int argc, char *argv[]) { IplImage *source = NULL; IplImage *dest = NULL; char *infile, *outfile; int64 t0, t1; double tps, deltatime; Color color; int threshold; if (argc != 7) { puts("Usage: rgrow in out r g b threshold"); return EXIT_FAILURE; } infile = argv[1]; outfile = argv[2]; color.r = (unsigned char) strtol(argv[3], NULL, 0); color.g = (unsigned char) strtol(argv[4], NULL, 0); color.b = (unsigned char) strtol(argv[5], NULL, 0); threshold = (int) strtol(argv[6], NULL, 0); source = cvLoadImage(infile, CV_LOAD_IMAGE_COLOR); if (source == NULL) { printf("Could not load image \"%s\".\n", infile); return EXIT_FAILURE; } dest = cvCreateImage(cvSize(source->width, source->height), IPL_DEPTH_8U, 1); t0 = cvGetTickCount(); rgrow(source, dest, color, threshold); t1 = cvGetTickCount(); tps = cvGetTickFrequency() * 1.0e6; deltatime = (double) (t1 - t0) / tps; cvSaveImage(outfile, dest, 0); printf("%dx%d image processed in %.3f seconds.\n", source->width, source->height, deltatime); cvReleaseImage(&source); cvReleaseImage(&dest); return EXIT_SUCCESS; } <file_sep>/openmp/atomic.cpp #include <omp.h> #include <iostream> float work1(int i) { return 1.0 * i; } float work2(int i) { return 2.0 * i; } void atomic_example(float *x, float *y, int *index, int n) { int i; #pragma omp parallel shared(x, y, index, n) private(i) { #pragma omp for schedule(guided) for (i = 0; i < n; i++) { #pragma omp atomic x[index[i]] += work1(i); y[i] += work2(i); std::cout << i << std::endl; } std::cout << omp_get_thread_num() << std::endl; } } int main(int argc, char *argv[]) { float x[1000]; float y[1000]; int index[1000]; int i; int N = 10; for (i = 0; i < N; i++) { index[i] = i %N; y[i] = 0.0; } for (i = 0; i < N; i++) { x[i] = 0.0; } atomic_example(x, y, index, N); for (i = 0; i < N; i++) { std::cout << x[i] << "\t" << y[i] << "\t" << index[i]<< std::endl; } return 0; } <file_sep>/pointers/main.cpp #include <iostream> int main(int argc, char *argv[]) { int *p = new int; int q = *p; // q = 5; *p = 20; std::cout << *p << "\t" << q << std::endl; return 0; } <file_sep>/openmp/barrier.cpp #include <omp.h> #include <iostream> void work(int n) { std::cout << n << std::endl; } void sub3(int n) { work(n); std::cout << "no barrier" << std::endl; #pragma omp barrier { work(n); std::cout << "THREAD COUNT: " << omp_get_thread_num() << "\t" << n << std::endl; } } void sub2(int k) { #pragma omp parallel shared(k) { sub3(k); if (omp_get_thread_num() == 0) { std::cout << "sub2(.) Threads: " << omp_get_num_threads() << std::endl; } } } void sub1(int n) { int i; #pragma omp parallel private(i) shared(n) { #pragma omp for schedule(guided) nowait for (i = 0; i < n; i++) { sub2(i); // std::cout << omp_get_thread_num() << std::endl; } // if (omp_get_thread_num() == 0) { // std::cout << "sub1(.) Threads: " << omp_get_num_threads() // << std::endl; // } } } int main(int argc, char *argv[]) { // sub1(10); sub2(2); // sub3(2); return 0; } /** * The BARRIER will bind to the nearest PARALLEL region */ <file_sep>/openmp/critial.cpp #include <omp.h> #include <iostream> int main(int argc, char *argv[]) { int x; x = 0; #pragma omp parallel shared(x) { #pragma omp critical x = x + 1; std::cout << "THREAD: " << omp_get_thread_num() << " " << x << std::endl; } /* end of parallel section */ std::cout << "\n" << x << std::endl; } /** * CRITICAL allows executation of one thread at a time */ <file_sep>/python_tutorial/numpy_py.py from numpy import * def main(): print 'Executing main program....\n' a = arange(15).reshape(3,5) print a b = array([20, 30, 40, 50]) print a.shape print a.dtype.name print a.itemsize print a.size print b if __name__ == '__main__': main() <file_sep>/sklearn/gaussian_navie_bayes/gnb.py #!/usr/bin/env python from sklearn import datasets from sklearn.naive_bayes import GaussianNB import numpy as np import cPickle import math #iris = datasets.load_iris() iris = None with open('my_dumped_classifier.pkl', 'rb') as fid: iris = cPickle.load(fid) gnb1 = GaussianNB() gnb2 = GaussianNB() gnb3 = GaussianNB() gnb4 = GaussianNB() #target = np.where(iris.target, 2, 1) # 2 class target = iris.target gnb1.fit(iris.data[:, 0].reshape(150,1), target) gnb2.fit(iris.data[:, 1].reshape(150,1), target) gnb3.fit(iris.data[:, 2].reshape(150,1), target) gnb4.fit(iris.data[:, 3].reshape(150,1), target) #y_pred = gnb.predict(iris.data) index = 100 y_prob1 = gnb1.predict_proba(iris.data[index,0].reshape(1,1)) y_prob2 = gnb2.predict_proba(iris.data[index,1].reshape(1,1)) y_prob3 = gnb3.predict_proba(iris.data[index,2].reshape(1,1)) y_prob4 = gnb4.predict_proba(iris.data[index,3].reshape(1,1)) # with open('my_dumped_classifier.pkl', 'wb') as fid: # cPickle.dump(iris, fid) #print y_prob1, "\n", y_prob2, "\n", y_prob3, "\n", y_prob4 , "\n" #print y_prob1 + y_prob2 + y_prob3 + y_prob4 priori = 0.5 prob1 = math.log(y_prob1[:,1] * priori/y_prob1[:,0] * priori, 2) prob2 = math.log(y_prob2[:,1] * priori/y_prob2[:,0] * priori, 2) prob3 = math.log(y_prob3[:,1] * priori/y_prob3[:,0] * priori, 2) prob4 = math.log(y_prob4[:,1] * priori/y_prob4[:,0] * priori, 2) # pos = y_prob1[:,1] + y_prob2[:,1] + y_prob3[:,1] + y_prob4[:,1] # neg = y_prob1[:,0] + y_prob2[:,0] + y_prob3[:,0] + y_prob4[:,0] # print pos # print neg #y_prob = prob1 * prob2 * prob3 * prob4 #print "\n", y_prob, "\n" gnb = GaussianNB() gnb.fit(iris.data, iris.target) #y_prob = np.zeros(shape=(1,3), dtype="float") y_prob = gnb.predict_proba(iris.data[45:55]) y_prob = np.around(y_prob, 3) print y_prob , "\n" print np.sum(y_prob, axis=0) <file_sep>/lccp_segmentation/CMakeLists.txt cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project(lccp_segmentation) find_package(PCL 1.7 REQUIRED) include_directories ("${PROJECT_SOURCE_DIR}") include_directories(${PCL_INCLUDE_DIRS}) link_directories(${PCL_LIBRARY_DIRS}) add_definitions(${PCL_DEFINITIONS}) set(HEADER_FILES main.cpp lccp_segmentation.cpp ${PROJECT_SOURCE_DIR}/lccp_segmentation.h) add_executable (main main.cpp) target_link_libraries (main ${PCL_LIBRARIES}) <file_sep>/connect_component_labeling/main.cpp // Copyright (C) 2015 by #include <opencv2/opencv.hpp> #include <iostream> class UnionFind { struct Node { int parent; int rank; }; private: Node *node; public: explicit UnionFind(int N); int findUF(int x); void unionUF(int x, int y); }; /** * */ UnionFind::UnionFind(int N) { this->node = new Node[N]; for (int i = 0; i < N; i++) { this->node[i].parent = i; this->node[i].rank = 0; } } /** * */ int UnionFind::findUF(int x) { if (x != this->node[x].parent) { this->node[x].parent = this->findUF(this->node[x].parent); } return this->node[x].parent; } /** * */ void UnionFind::unionUF(int x, int y) { int xroot = this->findUF(x); int yroot = this->findUF(y); if (xroot == yroot) { return; } if (this->node[xroot].rank < this->node[yroot].rank) { this->node[xroot].parent = yroot; } else if (this->node[xroot].rank > this->node[yroot].rank) { this->node[yroot].parent = xroot; } else { this->node[yroot].parent = xroot; this->node[xroot].rank = ++this->node[xroot].rank; } } int main(int argc, char *argv[]) { return 0; } <file_sep>/change_detection/octree_change_detection.cpp #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/openni_grabber.h> #include <pcl/io/openni_grabber.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/octree/octree.h> #include <pcl/filters/extract_indices.h> #include <pcl/console/parse.h> enum { REDDIFF_MODE, ONLYDIFF_MODE, MODE_COUNT }; class OpenNIChangeViewer { public: OpenNIChangeViewer (double resolution, int mode, int noise_filter) : viewer ("PCL OpenNI Viewer") { octree = new pcl::octree::OctreePointCloudChangeDetector<pcl::PointXYZRGBA>(resolution); mode_ = mode; noise_filter_ = noise_filter; } void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr &cloud) { std::cerr << cloud->points.size() << " -- "; // assign point cloud to octree octree->setInputCloud (cloud); // add points from cloud to octree octree->addPointsFromInputCloud (); std::cerr << octree->getLeafCount() << " -- "; boost::shared_ptr<std::vector<int> > newPointIdxVector (new std::vector<int>); // get a vector of new points, which did not exist in previous buffer octree->getPointIndicesFromNewVoxels (*newPointIdxVector, noise_filter_); std::cerr << newPointIdxVector->size() << std::endl; pcl::PointCloud<pcl::PointXYZRGBA>::Ptr filtered_cloud; switch (mode_) { case REDDIFF_MODE: filtered_cloud.reset (new pcl::PointCloud<pcl::PointXYZRGBA> (*cloud)); filtered_cloud->points.reserve(newPointIdxVector->size()); for (std::vector<int>::iterator it = newPointIdxVector->begin (); it != newPointIdxVector->end (); ++it) filtered_cloud->points[*it].rgba = 255<<16; if (!viewer.wasStopped()) viewer.showCloud (filtered_cloud); break; case ONLYDIFF_MODE: filtered_cloud.reset (new pcl::PointCloud<pcl::PointXYZRGBA>); filtered_cloud->points.reserve(newPointIdxVector->size()); for (std::vector<int>::iterator it = newPointIdxVector->begin (); it != newPointIdxVector->end (); ++it) filtered_cloud->points.push_back(cloud->points[*it]); if (!viewer.wasStopped()) viewer.showCloud (filtered_cloud); break; } // switch buffers - reset tree octree->switchBuffers (); } void run () { pcl::Grabber* interface = new pcl::OpenNIGrabber(); boost::function<void (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)> f = boost::bind (&OpenNIChangeViewer::cloud_cb_, this, _1); boost::signals2::connection c = interface->registerCallback (f); interface->start (); while (!viewer.wasStopped()) { boost::this_thread::sleep(boost::posix_time::seconds(1)); } interface->stop (); } pcl::octree::OctreePointCloudChangeDetector<pcl::PointXYZRGBA> *octree; pcl::visualization::CloudViewer viewer; int mode_; int noise_filter_; }; int main (int argc, char* argv[]) { std::cout << "Syntax is " << argv[0] << " [-r octree resolution] [-d] [-n noise_filter intensity] \n"; int mode = REDDIFF_MODE; int noise_filter = 7; double resolution = 0.01; pcl::console::parse_argument (argc, argv, "-r", resolution); pcl::console::parse_argument (argc, argv, "-n", noise_filter); if (pcl::console::find_argument (argc, argv, "-d")>0) { mode = ONLYDIFF_MODE; } OpenNIChangeViewer v (resolution, mode, noise_filter); v.run (); return 0; } <file_sep>/sorting/main.cpp #include <opencv2/core/core.hpp> #include <iostream> #include <string> // #include <multimap> #include <vector> #include <map> #include <utility> #include <algorithm> void sortvector() { std::vector<std::pair<int, std::vector<int> > > list; std::vector<int> a; a.push_back(1); a.push_back(5); std::vector<int> b; b.push_back(1); b.push_back(5); b.push_back(6); std::vector<int> c; c.push_back(2); c.push_back(3); c.push_back(4); std::vector<int> d; d.push_back(1); std::vector<int> e; e.push_back(3); std::vector<int> f; f.push_back(2); f.push_back(3); list.push_back(std::pair<int, std::vector<int> >(2, a)); list.push_back(std::pair<int, std::vector<int> >(3, b)); list.push_back(std::pair<int, std::vector<int> >(1, c)); list.push_back(std::pair<int, std::vector<int> >(4, d)); list.push_back(std::pair<int, std::vector<int> >(6, e)); list.push_back(std::pair<int, std::vector<int> >(5, f)); std::sort(list.begin(), list.end()); for (int i = 0; i < list.size(); i++) { std::cout << list[i].first << "\t< "; for (int j = 0; j < list[i].second.size(); j++) { std::cout << list[i].second.at(j) << ", "; } std::cout << " >\n" << std::endl; } } int main(int argc, char *argv[]) { std::map<int, std::vector<int> > list; std::vector<int> a; a.push_back(1); a.push_back(5); std::vector<int> b; b.push_back(1); b.push_back(5); b.push_back(6); std::vector<int> c; c.push_back(2); c.push_back(3); c.push_back(4); std::vector<int> d; d.push_back(1); std::vector<int> e; e.push_back(3); std::vector<int> f; f.push_back(2); f.push_back(3); list[2] = a; // list[3] = b; // list[1] = c; // list[4] = d; // list[6] = e; // list[5] = f; int j = 2; for (int i = 0; i < list.find(j)->second.size(); i++) { int val = list.find(j)->second.at(i); std::cout << val << " "; } std::cout << "\n" << std::endl; return 0; } <file_sep>/pca_rot/build.old/build.sh make est_return_val=$? if [ "$est_return_val" -ne "0" ]; then echo -e "\e[96mCompilation failed with error code [$est_return_val]\e[0m" exit 1 fi ./main "../uimg5.jpg" <file_sep>/python_tutorial/opencv_py.py #!/usr/bin/python import cv2 def webcam(): cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() img = cv2.resize(frame, (640, 480)) img = cv2.flip(img, 1) cv2.imshow('frame', img) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() def main(): print 'In main..' img = cv2.imread("../../man.jpg") img = cv2.resize(img, (320, 240)) cv2.imshow("image", img) cv2.waitKey(0) if __name__ == '__main__': #main() webcam() <file_sep>/gfpfh/CMakeLists.txt cmake_minimum_required(VERSION 2.6 FATAL_ERROR) project(gfpfh) find_package(PCL 1.5 REQUIRED) include_directories(${PCL_INCLUDE_DIRS}) link_directories(${PCL_LIBRARY_DIRS}) add_definitions(${PCL_DEFINITIONS}) add_executable (main main.cpp) target_link_libraries (main ${PCL_LIBRARIES})<file_sep>/rag/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project( region_grow ) find_package( OpenCV REQUIRED) find_package(Boost 1.40 COMPONENTS program_options REQUIRED) include_directories(${Boost_INCLUDE_DIR}) add_executable( main main.cpp ) target_link_libraries( main ${OpenCV_LIBS} ${Boost_LIBRARIES}) <file_sep>/optical_flow/main.cpp // // main.cpp // Motion Estimation // // Created by <NAME> on 12/9/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #include <opencv2/opencv.hpp> #include <opencv2/opencv_modules.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> #include <opencv2/video/tracking.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/nonfree/features2d.hpp> #include <opencv2/legacy/legacy.hpp> #include <opencv2/videostab/videostab.hpp> #include <opencv2/videostab/global_motion.hpp> #include <opencv2/videostab/optical_flow.hpp> #include <opencv2/video/video.hpp> #include <iostream> using namespace cv; using namespace std; using namespace videostab; void buildImagePyramid(const Mat &, vector<Mat> &); void getOpticalFlow(const Mat &, const Mat &, vector<Point2f> &, vector<Point2f> &, vector<uchar> &); void drawFlowField(Mat &, vector<Point2f> &, vector<Point2f> &); string float2string(float); void opticalFlowFromFile(); void computeAffineTransformation( const vector<Point2f> &, const vector<Point2f> &); #define FEATURE_COUNT 500 int main(int argc, const char * argv[]) { opticalFlowFromFile(); return 0; } // compute descriptor void computeKeyPoints( vector<Point2f> &points, vector<KeyPoint> &keypoints) { for (int i = 0; i < points.size(); i++) { Point2f pt = points[i]; if (pt.x > 0 && pt.x < 640 && pt.y > 0 && pt.y < 40) { KeyPoint kp; kp.pt = points[i]; kp.size = 8.0f; keypoints.push_back(kp); } } } void opticalFlowFromFile() { Mat img1 = imread( "frame0000.jpg"); Mat img2 = imread( "frame0001.jpg"); vector<Point2f> nextPts; vector<Point2f> prevPts; vector<Point2f> backPts; GaussianBlur(img1, img1, Size(1, 1), 1); GaussianBlur(img2, img2, Size(1, 1), 1); Mat gray, grayPrev; cvtColor(img1, grayPrev, CV_BGR2GRAY); cvtColor(img2, gray, CV_BGR2GRAY); // goodFeaturesToTrack(grayPrev, prevPts, FEATURE_COUNT, 0.001, // 0.1); Ptr<FeatureDetector> detector_h = FeatureDetector::create("FAST"); Ptr<FeatureDetector> detector_f = FeatureDetector::create("STAR"); vector<KeyPoint> keypoints_prev; detector_h->detect(grayPrev, keypoints_prev); vector<KeyPoint> keypoints_prevf; detector_f->detect(grayPrev, keypoints_prevf); keypoints_prev.insert(keypoints_prev.end(), keypoints_prevf.begin(), keypoints_prevf.end()); for (int i = 0; i < keypoints_prev.size(); i++) { prevPts.push_back(keypoints_prev[i].pt); } // do forward backward vector<uchar> status; vector<uchar> status_back; getOpticalFlow(img2, img1, nextPts, prevPts, status); getOpticalFlow(img1, img2, backPts, nextPts, status_back); std::vector<float> fb_err; for (int i = 0; i < prevPts.size(); i++) { cv::Point2f v = backPts[i] - prevPts[i]; fb_err.push_back(sqrt(v.dot(v))); } float THESHOLD = 25; for (int i = 0; i < status.size(); i++) { status[i] = (fb_err[i] <= THESHOLD) & status[i]; } vector<KeyPoint> keypoints_next; for (int i = 0; i < prevPts.size(); i++) { Point2f ppt = prevPts[i]; Point2f npt = nextPts[i]; double distance = cv::norm(cv::Mat(ppt), cv::Mat(npt)); if (status[i] && distance > 10) { KeyPoint kp; kp.pt = nextPts[i]; kp.size = keypoints_prev[i].size; keypoints_next.push_back(kp); } } // drawing Mat copyimg = img1.clone(); drawKeypoints(copyimg, keypoints_next, copyimg); imshow("key", copyimg); // compute current keypoints vector<KeyPoint>keypoints_cur; detector_h->detect(img2, keypoints_cur); vector<KeyPoint>keypoints_curf; detector_f->detect(img2, keypoints_curf); keypoints_cur.insert(keypoints_cur.end(), keypoints_curf.begin(), keypoints_curf.end()); // extract keyponts around good region vector<KeyPoint> keypoints_around_region; for (int i = 0; i < keypoints_cur.size(); i++) { Point2f cur_pt = keypoints_cur[i].pt; for (int j = 0; j < keypoints_next.size(); j++) { Point2f est_pt = keypoints_next[j].pt; double distance = cv::norm(cv::Mat(cur_pt), cv::Mat(est_pt)); if (distance < 10) { keypoints_around_region.push_back(keypoints_cur[i]); } } } Mat copyimg2 = img2.clone(); drawKeypoints(copyimg2, keypoints_cur, copyimg2); imshow("key_cur", copyimg2); Mat copyimgg = img2.clone(); drawKeypoints(copyimgg, keypoints_around_region, copyimgg); imshow("key_good", copyimgg); Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create("ORB"); Mat descriptor_cur; descriptor->compute(img2, keypoints_around_region, descriptor_cur); Mat descriptor_prev; descriptor->compute(img1, keypoints_prev, descriptor_prev); cv::Ptr<cv::DescriptorMatcher> descriptorMatcher = cv::DescriptorMatcher::create("BruteForce-Hamming(2)"); std::vector<std::vector<cv::DMatch> > matchesAll; descriptorMatcher->knnMatch(descriptor_cur, descriptor_prev, matchesAll, 2); std::vector<DMatch> match1; std::vector<DMatch> match2; for (int i=0; i < matchesAll.size(); i++) { match1.push_back(matchesAll[i][0]); match2.push_back(matchesAll[i][1]); } std::vector< DMatch > good_matches; for (int i = 0; i < matchesAll.size(); i++) { if (match1[i].distance < 0.9 * match2[i].distance) { good_matches.push_back(match1[i]); } } Mat img_matches1, img_matches2; drawMatches(img2, keypoints_around_region, img1, keypoints_prev, good_matches, img_matches1); /*drawMatches(img2, keypoints_around_region, img1, keypoints_prev, match2, img_matches2); */ imshow("matches1", img_matches1); // imshow("matches2", img_matches2); waitKey(); } void buildImagePyramid( const Mat &frame, vector<Mat> &pyramid) { Mat gray = frame.clone(); Size winSize = Size(5, 5); int maxLevel = 5; bool withDerivative = true; buildOpticalFlowPyramid( gray, pyramid, winSize, maxLevel, withDerivative, BORDER_REFLECT_101, BORDER_CONSTANT, true); } void getOpticalFlow( const Mat &frame, const Mat &prevFrame, vector<Point2f> &nextPts, vector<Point2f> &prevPts, vector<uchar> &status) { Mat gray, grayPrev; cvtColor(prevFrame, grayPrev, CV_BGR2GRAY); cvtColor(frame, gray, CV_BGR2GRAY); vector<Mat> curPyramid; vector<Mat> prevPyramid; buildImagePyramid(frame, curPyramid); buildImagePyramid(prevFrame, prevPyramid); // vector<uchar> status; vector<float> err; nextPts.clear(); status.clear(); nextPts.resize(prevPts.size()); status.resize(prevPts.size()); err.resize(prevPts.size()); Size winSize = Size(5, 5); int maxLevel = 3; TermCriteria criteria = TermCriteria( TermCriteria::COUNT+TermCriteria::EPS, 30, 0.001); int flags = 1; calcOpticalFlowPyrLK( prevPyramid, curPyramid, prevPts, nextPts, status, err, winSize, maxLevel, criteria, flags); // Mat iFrame = frame.clone(); Mat iFrame = prevFrame.clone(); drawFlowField(iFrame, nextPts, prevPts); } void drawFlowField(Mat &frame, vector<Point2f> &nextPts, vector<Point2f> &prevPts){ vector<Point2f> good_match; vector<Point2f> good_match_prev; for (int i = 0 ; i < nextPts.size(); i++) { double angle = atan2((double)(prevPts[i].y - nextPts[i].y),(double)(prevPts[i].x - nextPts[i].x)); double lenght = sqrt((double)pow(prevPts[i].y - nextPts[i].y, 2) + (double)pow((double)(prevPts[i].x - nextPts[i].x), 2)); // std::cout << lenght << std::endl; if (lenght > 0) { good_match.push_back(nextPts[i]); good_match_prev.push_back(prevPts[i]); Point iBig = Point(prevPts[i].x - 1 * lenght * cos(angle), prevPts[i].y - 1 * lenght * sin(angle)); line(frame, prevPts[i], iBig, Scalar(255, 0, 255)); //!Draw the arrow on the line line(frame, Point2f(iBig.x + 1 * cos( angle + CV_PI/4), iBig.y + 1 * sin( angle + CV_PI/4)), iBig, Scalar(255, 0, 255)); line(frame, Point2f(iBig.x + 1 * cos( angle - CV_PI/4), iBig.y + 1 * sin(angle - CV_PI/4)), iBig, Scalar(255, 0, 255)); } } // nextPts.clear(); // prevPts.clear(); // prevPts = good_match_prev; // nextPts = good_match; imshow("flow", frame); } void computeAffineTransformation(const vector<Point2f> &nextPts, const vector<Point2f> &prevPts){ cout << nextPts.size() << " " << prevPts.size() << endl; Mat affine = estimateRigidTransform(nextPts, prevPts, true); cout << endl << affine << endl << endl; } string float2string(float c_frame){ std::string frame_num; std::stringstream out; out << c_frame; frame_num = out.str(); return frame_num; } <file_sep>/libsvm/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project( libsvm ) find_package( OpenCV REQUIRED ) include_directories ("${PROJECT_SOURCE_DIR}") set(HEADER_FILES main.cpp svm.cpp ${PROJECT_SOURCE_DIR}/svm.h) add_executable(main ${HEADER_FILES}) target_link_libraries( main ${OpenCV_LIBS} )<file_sep>/pca_rot/build.old/main_1.cpp #include <iostream> #include <math.h> #include <fstream> #include <ctime> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include "Object_Boundary.h" #include "RGBD_Image_Processing.h" #include "contour_thinning.h" using namespace std; using namespace cv; const cv::Scalar colorRangeMIN = cv::Scalar(0, 56, 5); const cv::Scalar colorRangeMAX = cv::Scalar(64, 119, 103); double getOrientation(vector<Point> &, Mat &); void getObjectROI(Mat &); void computeImageGradient(Mat &); void colorFilterTrackerBar(Mat &); void colorFilter(Mat &, cv::Scalar, cv::Scalar, bool = false); void getImageContours(Mat &, int = 30); void estimateDOGEdge(Mat &); void imageMorphologicalOp(Mat &, bool = true); RGBDImageProcessing * img_proc = new RGBDImageProcessing(); Mat original_img; int main(int argc, char *argv[]) { Mat image; if(argc < 2) { image = imread("../pca_test1.jpg", 1); } else { image = imread(argv[1], 1); } if(image.empty()) { std::cout << "No Image Found...." << std::endl; return -1; } const int downsample_ = 1; cv::resize(image, image, cv::Size(image.cols/downsample_, image.rows/downsample_)); original_img = image.clone(); getObjectROI(image); Mat img_bw; //cvtColor(image, img_bw, CV_BGR2GRAY); colorFilter(image, colorRangeMIN, colorRangeMAX, false); //colorFilterTrackerBar(image); cvtColor(image, img_bw, CV_BGR2GRAY); //estimateDOGEdge(img_bw); computeImageGradient(img_bw); //img_proc->lineDetection(image); Mat c_out; Mat img_gray; //cv::threshold(img_bw, img_gray, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU); cvtColor(image, image, CV_BGR2GRAY); //img_proc->extractImageContour(image, c_out, true); /* Dilate and errode*/ //getImageContours(original_img); vector<Vec4i> lines; cv::HoughLinesP(img_bw, lines, 1, CV_PI/180 , 20, 5, 5); imshow("input", image); waitKey(); //! Find all the contours in the thresholded image vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(img_bw, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_NONE); Mat img = image.clone(); for (size_t i = 0; i < contours.size(); ++i) { //! Calculate the area of each contour double area = contourArea(contours[i]); //! Ignore contours that are too small or too large if (area < 1e2 || 1e5 < area) { continue; } else { //! Draw each contour only for visualisation purposes drawContours(img, contours, i, CV_RGB(255, 0, 0), 2, 8, hierarchy, 0); //! Find the orientation of each shape getOrientation(contours[i], img); } } cv::imshow("img_bw", img_bw); cv::imshow("orig", img); cv::waitKey(0); return 0; } /** * */ double getOrientation(vector<Point> &pts, Mat &img) { //Construct a buffer used by the pca analysis Mat data_pts = Mat(pts.size(), 2, CV_64FC1); for (int i = 0; i < data_pts.rows; ++i) { data_pts.at<double>(i, 0) = pts[i].x; data_pts.at<double>(i, 1) = pts[i].y; } //Perform PCA analysis PCA pca_analysis(data_pts, Mat(), CV_PCA_DATA_AS_ROW); //Store the position of the object Point pos = Point(pca_analysis.mean.at<double>(0, 0), pca_analysis.mean.at<double>(0, 1)); //Store the eigenvalues and eigenvectors vector<Point2d> eigen_vecs(2); vector<double> eigen_val(2); for (int i = 0; i < 2; ++i) { eigen_vecs[i] = Point2d(pca_analysis.eigenvectors.at<double>(i, 0), pca_analysis.eigenvectors.at<double>(i, 1)); eigen_val[i] = pca_analysis.eigenvalues.at<double>(0, i); } // Draw the principal components circle(img, pos, 3, CV_RGB(255, 0, 255), 2); line(img, pos, pos + 0.02 * Point(eigen_vecs[0].x * eigen_val[0], eigen_vecs[0].y * eigen_val[0]) , CV_RGB(0, 255, 0)); line(img, pos, pos + 0.02 * Point(eigen_vecs[1].x * eigen_val[1], eigen_vecs[1].y * eigen_val[1]) , CV_RGB(0, 0, 255)); return atan2(eigen_vecs[0].y, eigen_vecs[0].x); } /** * */ void computeImageGradient(Mat &image) { GaussianBlur(image, image, Size(5,5), 1); Mat src_gray = image.clone(); /* Mat xsobel, ysobel; Sobel(image, xsobel, CV_32F, 1, 0, 5); Sobel(image, ysobel, CV_32F, 0, 1, 1); Mat Imag, Iang; //! Angle and Maginitue cartToPolar(xsobel, ysobel, Imag, Iang, true); normalize(Imag, Imag, 0, 1, NORM_MINMAX, -1, Mat()); const int angle_ = 360; add(Iang, Scalar(angle_), Iang, Iang < angle_); add(Iang, Scalar(-angle_), Iang, Iang >= angle_); normalize(Iang, Iang, 0, 1, NORM_MINMAX, -1, Mat()); Mat cb; multiply(Imag, Iang, cb); imshow("Mag", Imag); imshow("ang", Iang); imshow("weight", cb); */ int scale = 1; int delta = 0; int ddepth = CV_16S; /// Generate grad_x and grad_y Mat grad_x, grad_y; Mat grad; Mat abs_grad_x, abs_grad_y; /// Gradient X //Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT ); Sobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT ); convertScaleAbs( grad_x, abs_grad_x ); /// Gradient Y //Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT ); Sobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT ); convertScaleAbs( grad_y, abs_grad_y ); /// Total Gradient (approximate) addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad ); grad = grad * 2; //getImageContours(grad); imageMorphologicalOp(grad); imshow( "gradient", grad ); waitKey(); } /** * User defined object region via bounding box plot */ void getObjectROI(Mat &image) { ObjectBoundary *obj_roi = new ObjectBoundary(); Rect rect = obj_roi->cvGetobjectBoundary(image); Mat img = Mat::zeros(image.rows, image.cols, image.type()); for (int j = 0; j < image.rows; j++) { for (int i = 0; i < image.cols; i++) { if(i > (rect.x - 1) && i < (rect.x + rect.width + 1) && j > (rect.y - 1) && j < (rect.y + rect.height + 1)) { img.at<Vec3b>(j,i) = image.at<Vec3b>(j,i); } } } image = img.clone(); } /** * */ void colorFilter(Mat &image, Scalar colorMin, Scalar colorMax, bool isFind) { if(isFind) { colorFilterTrackerBar(image); } else { Mat dst; cv::inRange(image, colorMin, colorMax, dst); //cv::bitwise_and(img, dst, outimg); for (int j = 0; j < image.rows; j++) { for (int i = 0; i < image.cols; i++) { if((float)dst.at<uchar>(j,i) == 0) { image.at<Vec3b>(j,i)[0] = 0; image.at<Vec3b>(j,i)[1] = 0; image.at<Vec3b>(j,i)[2] = 0; } } } } } /** * */ int min_valR = 0; int max_valR = 256; int min_valG = 0; int max_valG = 256; int min_valB = 0; int max_valB = 256; Mat dst; Mat img; string window_name = "Result"; void threshCallBack(int, void*) { dst = img.clone(); Scalar lowerb = Scalar(min_valB, min_valG, min_valR); Scalar upperb = Scalar(max_valB, max_valG, max_valR); cv::inRange(img, lowerb, upperb, dst); Mat outimg = img.clone(); //cv::bitwise_and(img, dst, outimg); for (int j = 0; j < img.rows; j++) { for (int i = 0; i < img.cols; i++) { if((float)dst.at<uchar>(j,i) == 0) { outimg.at<Vec3b>(j,i)[0] = 0; outimg.at<Vec3b>(j,i)[1] = 0; outimg.at<Vec3b>(j,i)[2] = 0; } } } imshow( window_name, dst ); imshow("out", outimg); } void colorFilterTrackerBar(Mat &image) { img = image.clone(); namedWindow("Result", CV_WINDOW_AUTOSIZE); createTrackbar("Red Min", window_name, &min_valR, 256); createTrackbar("Red Max", window_name, &max_valR, 256); createTrackbar("Green Min", window_name, &min_valG, 256); createTrackbar("Green Max", window_name, &max_valG, 256); createTrackbar("Blue Min", window_name, &min_valB, 256); createTrackbar("Blue Max", window_name, &max_valB, 256); //cvtColor(image, img, CV_BGR2HSV); int c; while(true) { threshCallBack(0,0); c = waitKey( 20 ); if( (char)c == 27 ) { break; } } } /** * estimate the image contours */ void getImageContours(Mat &image, int contour_thresh) { if(image.empty() || image.type() != CV_8UC1) { std::cout << "Image is empty" << std::endl; return; } vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(image, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); Mat drawImg; cvtColor(image, drawImg, CV_GRAY2BGR); for (int i = 0; i < contours.size(); i++) { if(cv::contourArea(contours[i]) > contour_thresh) { drawContours(drawImg, contours, i, Scalar(255, 0, 255), 2, 8, hierarchy, 0, Point()); } } imshow("Image Contours", drawImg); } void estimateDOGEdge(Mat &image) { Mat img1, img2; GaussianBlur(image, img1, Size(3,3), 0); GaussianBlur(image, img2, Size(17,17), 0); Mat edgeMap = img1 - img2; imshow("Edge", edgeMap); waitKey(0); } /** * Function to create a binary image for any pixel not equal to zero */ void cvCreateBinaryImage(Mat image, Mat &img_bw, int lowerb = 0) { img_bw = Mat::zeros(image.size(), CV_8UC1); for (size_t j = 0; j < image.rows; j++) { for (size_t i = 0; i < image.cols; i++) { if(static_cast<int>(image.at<uchar>(j,i)) > lowerb) { img_bw.at<uchar>(j,i) = 255; } } } } /** * compute the pixel edge directional orientation */ void computeEdgeCurvatureOrientation(std::vector<std::vector<cv::Point> > &contours_tangent, std::vector<std::vector<cv::Point> > &contours, std::vector<std::vector<float> > &orientation_) { for (int j = 0; j < contours_tangent.size(); j++) { std::vector<float> ang; for (int i = 0; i < contours_tangent[j].size(); i++) { float angle_ = 0.0f; if( contours_tangent[j][i].x == 0) { angle_ = 90.0f; } else { angle_ = atan2(contours_tangent[j][i].y, contours_tangent[j][i].x) * (180/CV_PI); } ang.push_back(static_cast<float>(angle_)); } orientation_.push_back(ang); ang.clear(); } } /** * Compute the image pixel curvature on the pixel edges. * "http://en.wikipedia.org/wiki/Finite_difference#Forward.2C_backward.2C_and_central_differences"" */ void computeEdgeCurvature(std::vector<std::vector<cv::Point> > &contours, std::vector<std::vector<cv::Point> > &tangents, std::vector<std::vector<float> > &orientation_, std::vector<cv::Point> &hcurvature_pts) { for (int j = 0; j < contours.size(); j++) { std::vector<cv::Point> tangent; /* estimate the first tangent line*/ cv::Point2f edge_pt = contours[j].front(); cv::Point2f edge_tngt = contours[j].back() - contours[j].at(1); tangent.push_back(edge_tngt); const int neighbor_pts = 0; if(contours[j].size() > sizeof(short)) { for (int i = sizeof(char) + neighbor_pts; i < contours[j].size() - sizeof(char) - neighbor_pts; i++) { edge_pt = contours[j][i]; edge_tngt = contours[j][i-1-neighbor_pts] - contours[j][i+1+neighbor_pts]; tangent.push_back(edge_tngt); } } tangents.push_back(tangent); } /* compute the tangent orientation */ computeEdgeCurvatureOrientation(tangents, contours, orientation_); for (int j = 0; j < tangents.size(); j++) { if(tangents[j].size() < 2) { continue; } for (int i = sizeof(char); i < tangents[j].size() - sizeof(char); i++) { float y1 = tangents[j][i+1].y; float x1 = tangents[j][i+1].x; float y0 = tangents[j][i-1].y; float x0 = tangents[j][i-1].x; float tang1 = 0.0f; float tang0 = 0.0f; if(x1 != 0) { tang1 = y1/x1; } if(x0 != 0) { tang0 = y0/x0; } if((tang1 >= 0.0f && tang0 < 0.0f) || (tang1 < 0.0f && tang0 >= 0.0f)) { if((abs(tang0 - tang1) < 0.5f) || (abs(tang1 - tang0) < 0.5f)) { continue; } hcurvature_pts.push_back(contours[j][i]); //hcurvature_pts.push_back(contours[j][i-1]); circle(original_img, contours[j][i], 2, Scalar(255, 0, 0), 1); circle(original_img, contours[j][i], 5, Scalar(0,255,0), 2); //circle(original_img, contours[j][i-1], 2, Scalar(255, 0, 0), 1); //circle(original_img, contours[j][i-1], 5, Scalar(0,255,0), 2); //circle(image, contours[j][i], 1, Scalar(0,0,255), 2); //circle(image, contours[j][i-1], 2, Scalar(0,0,255), 2); } } } cv::imshow("tangent", original_img); } /** * function to filter points by within some set radius */ void filterPoints(std::vector<cv::Point> &hcurvature_pts, const int radius_ = 10) { // filter very close high curvature region for (int i = 0; i < hcurvature_pts.size(); i++) { cv::Point cur_pt = hcurvature_pts[i]; for (int j = 0; j < hcurvature_pts.size(); j++) { if(i != j) { cv::Point nn_pt = hcurvature_pts[j]; float r = cv::norm(nn_pt - cur_pt); if(r <= radius_) { hcurvature_pts.erase(hcurvature_pts.begin() + j); } } } } /* Mat image = img_bw.clone(); cvtColor(image, image, CV_GRAY2BGR); for (int i = 0; i < hcurvature_pts.size(); i++) { circle(image, hcurvature_pts[i], 2, Scalar(255,0,255),-1); } imshow("hc", image); */ } /** * Function to estimate the junction in the image silhouette when * passed with the normal vector and the high curvature data */ void cvJunctionEstimation(Mat &img_bw, std::vector<std::vector<cv::Point> > &contours_, std::vector<std::vector<cv::Point> > &tangents_, std::vector<std::vector<float> > &orientation_, std::vector<cv::Point> &hcurvature_pts) { Mat image = img_bw.clone(); cvtColor(image, image, CV_GRAY2BGR); const int threshold_ = 20; const int radius_ = 5; std::vector<cv::Point> j_points; RGBDImageProcessing *tmp = new RGBDImageProcessing(); for(int i = 0; i < hcurvature_pts.size(); i++) { Mat testImg = Mat::zeros(img_bw.size(), img_bw.type()); circle(testImg, hcurvature_pts[i], 10, Scalar(255), 1); Mat mask; cv::bitwise_and(img_bw, testImg, mask); int whitePix = cv::countNonZero(mask > 0); //Mat canny_out; // tmp->extractImageContour(mask, canny_out, false); // contours_.clear(); // tmp->getContour(contours_); //std::cout << "Contour Size: " << contours_.size() << std::endl; if(whitePix > threshold_) { j_points.push_back(hcurvature_pts[i]); } //imshow("Mask", mask); //waitKey(); } //filterPoints(hcurvature_pts, 15); /* const float ANGLE = 360; const int radius_ = 10; std::vector<cv::Point> j_points; for (int k = 0; k < hcurvature_pts.size(); k++) { cv::Point center_ = hcurvature_pts[k]; //circle(image, center_, 4, Scalar(0,255,0)); int counter_ = 0; for (int j = 0; j < static_cast<int>(ANGLE); j++) { float angle_ = j * static_cast<float>(CV_PI/static_cast<float>(ANGLE/2.0f)); cv::Point2f test_points = cv::Point2f(static_cast<float>(center_.x) + (radius_ * cos(angle_)), static_cast<float>(center_.y) + (radius_ * sin(angle_))); for (int i = 0; i < contours_.size(); i++) { double tst = cv::pointPolygonTest(contours_[i], test_points, false); // std::cout << "Test: " << tst << std::endl; // circle(image, test_points, 2, Scalar(0,255,0)); // imshow("plot", image); // waitKey(0); if(static_cast<int>(tst) > -1) { // circle(image, test_points, 4, Scalar(0,255,0)); //std::cout << tst <<"\t Counter Value:" << counter_ << std::endl; counter_++; //break; } } //imshow("plot", image); //waitKey(0); } if(counter_ > 100) { //std::cout << counter_ << std::endl; j_points.push_back(center_); } } // for (int i = 0; i < hcurvature_pts.size(); i++) { // circle(image, hcurvature_pts[i], 2, Scalar(0,255,255),-1); // } */ for (int i = 0; i < j_points.size(); i++) { circle(image, j_points[i], 2, Scalar(255,0,255),-1); } imshow("hc", image); } /** * Function to perform contour estimation on the silhouette contour / * and smooth the contour based on the pre-set threshold. */ void branchEstimation(Mat &img_bw) { /* get the image contour by fitering the small contour region */ imshow("input", img_bw); cv::Mat canny_out; int contour_area_thresh = 150; img_proc->extractImageContour(img_bw, canny_out, true, contour_area_thresh); std::vector<std::vector<cv::Point> > contours; img_proc->getContour(contours); // compute the edge orientation and high curvature points std::vector<std::vector<cv::Point> > tangents; std::vector<std::vector<float> > orientation_; std::vector<cv::Point> hcurvature_pts; computeEdgeCurvature(contours, tangents, orientation_, hcurvature_pts); // junction estimation cvJunctionEstimation(img_bw, contours, tangents, orientation_, hcurvature_pts); cv::imshow("skeleton", img_bw); cv::waitKey(); } /** * Adequate image smoothing */ void imageMorphologicalOp(cv::Mat &src, bool is_errode) { cv::Mat erosion_dst; int erosion_size = 5; int erosion_const = 2; int erosion_type = MORPH_ELLIPSE; cv::Mat element = cv::getStructuringElement(erosion_type, cv::Size(erosion_const * erosion_size + 1, erosion_const * erosion_size + 1), cv::Point(erosion_size, erosion_size )); const int smooth_window = 7; const int smooth_sigma = 0; cv::GaussianBlur(src, src, cv::Size(smooth_window, smooth_window), smooth_sigma); cv::erode( src, erosion_dst, element ); //erosion_dst = erosion_dst * 4; /*convert the eroded image to binary*/ Mat img_bw; cvCreateBinaryImage(erosion_dst, img_bw); thinning(img_bw); /* estimate the branch */ branchEstimation(img_bw); imshow("image", src); imshow( "Erosion Demo", erosion_dst ); imshow("Binary", img_bw); waitKey(); } /* { Mat s_line = img_bw.clone(); Mat xsobel, ysobel; Sobel(s_line, xsobel, CV_32F, 1, 0, 5); Sobel(s_line, ysobel, CV_32F, 0, 1, 1); Mat Imag, Iang; //! Angle and Maginitue cartToPolar(xsobel, ysobel, Imag, Iang, false); normalize(Imag, Imag, 0, 1, NORM_MINMAX, -1, Mat()); Mat copy_sline = s_line.clone(); cvtColor(copy_sline, copy_sline, CV_GRAY2BGR); for (int j = 0; j < s_line.rows; j++) { for (int i = 0; i < s_line.cols; i++) { float angle = Iang.at<float>(j,i); if(angle == 0.0f && (int)s_line.at<uchar>(j,i) !=0) { //std::cout << "Angle: " << Iang.at<float>(j,i) << std::endl; float r = Imag.at<float>(j,i); std::cout << r << "\tangle " << angle << std::endl; line(copy_sline, Point(i,j), Point(i + r*sin(angle) * 50, j + r*cos(angle) * 50), Scalar(0,255,0), 1); } } } normalize(Imag, Imag, 0, 1, NORM_MINMAX, -1, Mat()); imshow("line Orientation", Iang); imshow("mag", Imag); imshow("lines", copy_sline); waitKey(); } */ <file_sep>/optical_flow/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project( optical_flow ) find_package( OpenCV REQUIRED ) add_executable( main main.cpp ) add_executable( fback fback.cpp ) target_link_libraries( main ${OpenCV_LIBS} ) target_link_libraries( fback ${OpenCV_LIBS} ) <file_sep>/sklearn/svm/sklearn_svm.py # /usr/bin/env python import numpy as np from sklearn.svm import SVC from sklearn.externals import joblib def svm_trainer(): X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) y = np.array([1, 1, 2, 2]) clf = SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma='auto', kernel='linear', max_iter=-1, probability=True, random_state=None, shrinking=True, tol=0.001, verbose=False) clf.fit(X, y) joblib.dump(clf, 'svm.pkl') print len(X) print len(y) def svm_predictor(fvector): fvector = np.reshape(fvector,-1,1) clf = joblib.load('svm.pkl') #response = clf.predict(fvector) response = clf.predict_proba(fvector) clf.classes_ print response print clf.predict_log_proba def svm_option(opt, fvect=[]): if opt == 'TRAIN': svm_trainer() return 0 elif opt == 'PREDICT': return svm_predictor(fvect) def numpy_array_convertor(fvect, lvect): print 'num' if __name__ == "__main__": svm_option('TRAIN') fvector = np.array(([1.8, -1]), dtype=float) sample = np.reshape(fvector, (1,-1)) svm_option('PREDICT', sample) <file_sep>/opencv_python/mark_image.py #!/usr/bin/env python import numpy as np import cv2 is_drawing = False mode = True ix, iy = -1, -1 img= np.zeros((512,512,3), np.uint8) def mouse_event(event, x, y, flags, param): global ix, iy, drawing_mode global is_drawing drawing = is_drawing if event == cv2.EVENT_LBUTTONDOWN: drawing = True print 'Drawing' ix, iy = x, y elif event == cv2.EVENT_MOUSEMOVE: if drawing == True: if mode == True: cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1) elif event == cv2.EVENT_LBUTTONUP: drawing = False if mode == True: cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1) print 'FINISH', ix, iy def read_images(path_text): image_lists = [] with open(path_text, 'r') as f: for line in f: pth = line.split() image = cv2.imread(pth[0]) image_lists.append(image) return image_lists def draw_bounding_box(image_lists): cv2.namedWindow('image') cv2.setMouseCallback('image', mouse_event) global img img = image_lists[0] cv2.imshow('image',img) #for i in image_lists: #cv2.imshow('image', i) cv2.waitKey(0) cv2.destroyAllWindows() def main(): image_lists = read_images('text.txt') draw_bounding_box(image_lists) if __name__ == "__main__": main() <file_sep>/pca_rot/RGBD_Image_Processing.h // // RGBD_Image_Processing.h // boundary_estimation // // Created by <NAME> on 3/11/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #ifndef __boundary_estimation__RGBD_Image_Processing__ #define __boundary_estimation__RGBD_Image_Processing__ #include <iostream> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> using namespace std; using namespace cv; class RGBDImageProcessing { private: //! downsampling scale size int downSample; //! Path to the template string template_path__; //! memeory to hold the region of the detected object vector<Rect> object_region__; vector<vector<Point> > contours; public: RGBDImageProcessing(int dw_sm = sizeof(char), const int thresh_ = 4) : downSample(dw_sm) { object_region__.clear(); } void extractImageContour(Mat &, Mat &, bool = false, int = 30); void lineDetection(Mat &, vector<Vec2f> &, double = 20, double = 160); void roiLineDetection(Mat &, Rect); void getContour(std::vector<std::vector<cv::Point> > &); }; #endif /* defined(__boundary_estimation__RGBD_Image_Processing__) */ <file_sep>/graph-theory/breadth-first-search/main.cpp #include <iostream> /** * Tree structure */ struct Node { int info; // data on this node Node *next; // Pointer to the next subtree }; class Graph { private: int n; // number of vertices in the graph int **A; public: explicit Graph(const int = 2); bool isConnected(int, int); void addEdge(int, int); void BFS(int); }; /** * constructor */ Graph::Graph(const int size) { int i, j; if (size < 2) { this->n = 2; } this->n = size; this->A = new int*[this->n]; for (int i = 0; i < this->n; i++) { this->A[i] = new int[this->n]; } for (int j = 0; j < this->n; j++) { for (int i = 0; i < this->n; i++) { this->A[j][i] = 0; } } } /** * check if two verices are connected by an edge @param u vertex @oaran v vertex */ bool Graph::isConnected(int u, int v) { return(this->A[u-1][v-1] == sizeof(char)); } /** * add an edge E to the graph G */ void Graph::addEdge(int u, int v) { this->A[u-1][v-1] = this->A[v-1][u-1] = sizeof(char); } /** * main function */ int main(int argc, char *argv[]) { return 0; } <file_sep>/opencv_xml/main.cpp #include <opencv2/core/core.hpp> #include <iostream> #include <string> void writeFile(cv::FileStorage &fs) { // std::string classifername = "cv::SVM"; std::string classiferpath = "~/.ros/svm.xml"; fs << "TrainerInfo" << "{"; fs << "trainer_type" << "cv::SVM"; fs << "trainer_path" << classiferpath; fs << "}"; fs << "FeatureInfo" << "{"; fs << "HOG" << 1; fs << "LBP" << 1; fs << "SIFT" << 0; fs << "SURF" << 0; fs << "COLOR_HISTOGRAM" << 0; fs << "}"; fs << "SlidingWindowInfo" << "{"; fs << "window_x" << 32; fs << "window_y" << 64; fs << "}"; fs << "TrainingDatasetDirectory" << "{"; fs << "object_dataset" << "~/.ros/"; fs << "nonobject_dataset" << "~/.ros/"; fs << "}"; } void readFile(cv::FileStorage &fs) { if (!fs.isOpened()) { std::cout << "Empty File..." << std::endl; return; } cv::FileNode n = fs["TrainerInfo"]; std::string ttype = n["trainer_type"]; std::string tpath = n["trainer_path"]; std::cout << ttype << std::endl; std::cout << tpath << std::endl; n = fs["FeatureInfo"]; int hog = n["HOG"]; int lbp = n["LBP"]; std::cout << hog << std::endl; std::cout << lbp << std::endl; n = fs["SlidingWindowInfo"]; int swindow_x = static_cast<int>(n["window_x"]); int swindow_y = static_cast<int>(n["window_y"]); n = fs["TrainingDatasetDirectory"]; std::string pfile = n["object_dataset"]; std::string nfile = n["nonobject_dataset"]; std::cout << swindow_x << " " << swindow_y << std::endl; std::cout << pfile << " \n" << nfile << std::endl; } int main(int argc, char *argv[]) { std::string filename = "trainer_manifest.xml"; cv::FileStorage fs = cv::FileStorage(filename, cv::FileStorage::WRITE); writeFile(fs); fs.release(); std::cout << "READIND \n" << std::endl; cv::FileStorage rfs; rfs.open(filename, cv::FileStorage::READ); readFile(rfs); return 0; } <file_sep>/openMP/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(openMP) find_package( OpenCV REQUIRED ) find_package(OpenMP) if (OPENMP_FOUND) set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") endif() add_executable( main main.cpp ) target_link_libraries(main ${OpenCV_LIBS} ${OPENMP_LIBS})<file_sep>/plane_segmentation/main.cpp #include <iostream> #include <exception> using namespace std; #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/visualization/mouse_event.h> #include <pcl/visualization/point_picking_event.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/features/normal_3d.h> #include <pcl/features/pfh.h> #include <pcl/features/vfh.h> #include <pcl/features/fpfh.h> #include <pcl/visualization/histogram_visualizer.h> #include <pcl/sample_consensus/sac_model_sphere.h> #include <pcl/sample_consensus/ransac.h> #include <pcl/filters/project_inliers.h> #include <pcl/surface/convex_hull.h> #include <pcl/segmentation/extract_polygonal_prism_data.h> #include <pcl/filters/extract_indices.h> typedef pcl::PointXYZRGB PointT; vector<int> pcl_indices; //! Variable to hold the selected PCL indices pcl::PointCloud<PointT>::Ptr gCloud (new pcl::PointCloud<PointT>); //********************************************************************************************************************** void saveSelectedPointCloud (); void pointAreaCallBack (const pcl::visualization::AreaPickingEvent &, void *); pcl::PointCloud<pcl::Normal>::Ptr computeSurfaceNormal (pcl::PointCloud<PointT>::Ptr); void pointFeatureHistogram(const pcl::PointCloud<PointT>::Ptr, pcl::PointCloud<pcl::Normal>::Ptr ); void viewPointFeatureHistorgram(pcl::PointCloud<PointT>::Ptr, pcl::PointCloud<pcl::Normal>::Ptr); void fastPointFeatureHistogram(pcl::PointCloud<PointT>::Ptr, pcl::PointCloud<pcl::Normal>::Ptr); Eigen::VectorXf pclModelSphere(pcl::PointCloud<PointT>::Ptr); pcl::PointCloud<PointT>::Ptr planeSegmentation(pcl::PointCloud<PointT>::Ptr); //********************************************************************************************************************** int main (int argc, const char* argv[]) { pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>); try { //pcl::io::loadPCDFile<PointT> ("/home/krishneel/Desktop/home.pcd", *cloud); //pcl::io::loadPCDFile<PointT> ("/home/krishneel/Desktop/Program/readPCL/selected_cloud.pcd", *cloud); pcl::io::loadPCDFile<PointT> ("/home/krishneel/Desktop/Program/readPCL/tomato2.pcd", *cloud); } catch (exception &e){ std::cout << "ERROR..." << e.what ()<< std::endl; } *gCloud = *cloud; Eigen::Vector3f translation = Eigen::Vector3f (0,0,0.5); Eigen::Quaternionf rotation = Eigen::Quaternionf::Identity (); pcl::visualization::PCLVisualizer pclVisual ("Visual"); pclVisual.setBackgroundColor (0,0,0); pclVisual.addPointCloud (cloud, "first"); pclVisual.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "first"); pclVisual.addCoordinateSystem (1.0); pclVisual.initCameraParameters (); //! Compute the surface normal pcl::PointCloud<pcl::Normal>::Ptr sNormal = computeSurfaceNormal (cloud); pclVisual.addPointCloudNormals<PointT, pcl::Normal> (cloud, sNormal, 10, 0.03, "normals"); std::cout << "Surface Normal: " << sNormal->size() << std::endl; for (int i = 0; i < sNormal->size(); i++) { std::cout << "Curvature: " << sNormal->points[i].curvature << "\t Axis: " << sNormal->points[i].normal_x << " " << sNormal->points[i].normal_y << " " << sNormal->points[i].normal_z << " " << sNormal->points[i].curvature<<std::endl; } pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal> ()); normals = sNormal; //pointFeatureHistogram(cloud, normals); //fastPointFeatureHistogram(cloud, normals); //viewPointFeatureHistorgram(cloud, normals); /*Eigen::VectorXf model_coefficients = pclModelSphere(cloud); pcl::ModelCoefficients sphere; sphere.values.resize(4); sphere.values[0] = model_coefficients[0]; sphere.values[1] = model_coefficients[1]; sphere.values[2] = model_coefficients[2]; sphere.values[3] = model_coefficients[3]; pclVisual.addSphere(sphere);*/ while(!pclVisual.wasStopped ()) { //pclVisual.showCloud (cloud); pclVisual.spinOnce (100); boost::this_thread::sleep (boost::posix_time::microseconds (100000)); } return 0; } //********************************************************************************************************************** //! Function to segment the table top //**********************************************************************************************************************\ pcl::PointCloud<PointT>::Ptr planeSegmentation(pcl::PointCloud<PointT>::Ptr cloud) { pcl::PointIndicesConstPtr plane_inliers; pcl::ModelCoefficientsConstPtr plane_coefficients; /* Cloud Points belonging to the object*/ pcl::PointCloud<PointT>::Ptr cloud_object; pcl::PointCloud<PointT>::Ptr plane_projected; pcl::ProjectInliers<PointT> proj; proj.setInputCloud(cloud); proj.setIndices(plane_inliers); proj.setModelCoefficients(plane_coefficients); proj.filter(*plane_projected); /* Estimation of Convex hull of projection */ pcl::PointCloud<PointT>::Ptr plane_hull; pcl::ConvexHull<PointT> hull; hull.setInputCloud(plane_projected); hull.reconstruct(*plane_hull); pcl::PointIndices object_inliers; pcl::ExtractPolygonalPrismData<PointT> prism; prism.setHeightLimits(0.01, 0.5); prism.setInputCloud(cloud); prism.setInputPlanarHull(plane_hull); prism.segment(object_inliers); /* Extract the object point cloud */ pcl::ExtractIndices<PointT> extract_object_indices; extract_object_indices.setInputCloud(cloud); extract_object_indices.setIndices(boost::make_shared<const pcl::PointIndices> (object_inliers)); extract_object_indices.filter(*cloud_object); return (cloud_object); } //********************************************************************************************************************** void saveSelectedPointCloud () { //cout << "Indices Size: " << pcl_indices.size () << "\t Cloud Size: " << gCloud->size () << endl; pcl::PointCloud<PointT>::Ptr nCloud (new pcl::PointCloud<PointT>); for (int i = 0; i < pcl_indices.size (); i++) { int index = pcl_indices.at (i); nCloud->push_back (gCloud->at (index)); cout << "PCL Value # " << gCloud->at (index) << "\t " << nCloud->points[i] << endl; } cout << endl << "Indices Size: " << pcl_indices.size () << "\tCopied Size: " << nCloud->size () << endl; pcl::io::savePCDFileASCII ("/home/krishneel/Desktop/readPCL/selected_cloud.pcd", *nCloud); } //********************************************************************************************************************** void pointAreaCallBack (const pcl::visualization::AreaPickingEvent &aEvent, void *viewer_void) { std::vector<int> indices; aEvent.getPointsIndices (indices); pcl_indices.insert (pcl_indices.end(), indices.begin (), indices.end ()); //std::cout << "Vector Size: " << indices.size () << std::endl; saveSelectedPointCloud (); } //********************************************************************************************************************** //! Function to compute and return the surface normal of the point cloud //********************************************************************************************************************** pcl::PointCloud<pcl::Normal>::Ptr computeSurfaceNormal (pcl::PointCloud<PointT>::Ptr cloud) { pcl::NormalEstimation<PointT, pcl::Normal>sNormal; sNormal.setInputCloud (cloud); pcl::search::KdTree<PointT>::Ptr tree (new pcl::search::KdTree<PointT>()); sNormal.setSearchMethod (tree); pcl::PointCloud<pcl::Normal>::Ptr cloud_normal (new pcl::PointCloud<pcl::Normal>); sNormal.setRadiusSearch (0.03); sNormal.compute (*cloud_normal); return cloud_normal; } //********************************************************************************************************************** //! Function to compute the point feature histogram //********************************************************************************************************************** void pointFeatureHistogram(const pcl::PointCloud<PointT>::Ptr cloud, pcl::PointCloud<pcl::Normal>::Ptr normals) { pcl::PFHEstimation<PointT, pcl::Normal, pcl::PFHSignature125> pfh; pfh.setInputCloud(cloud); pfh.setInputNormals(normals); pcl::search::KdTree<PointT>::Ptr tree(new pcl::search::KdTree<PointT>()); pfh.setSearchMethod(tree); pcl::PointCloud<pcl::PFHSignature125>::Ptr pfhs (new pcl::PointCloud<pcl::PFHSignature125> ()); pfh.setRadiusSearch(0.01); pfh.compute(*pfhs); std::cout << "Size........... " << cloud->size() << "\t" << pfhs->points.size() << std::endl; for (int i = 0; i < pfhs->size(); i++) { for(int j = 0; j < 125; j++) { std::cout << pfhs->points[i].histogram[j] << " " ; } std::cout << std::endl; } } //********************************************************************************************************************** //! Function to compute Viewpoint Feature histogram //********************************************************************************************************************** void viewPointFeatureHistorgram(pcl::PointCloud<PointT>::Ptr cloud, pcl::PointCloud<pcl::Normal>::Ptr normals) { pcl::VFHEstimation<PointT, pcl::Normal, pcl::VFHSignature308> vfh; vfh.setInputCloud(cloud); vfh.setInputNormals(normals); pcl::search::KdTree<PointT>::Ptr tree (new pcl::search::KdTree<PointT> ()); vfh.setSearchMethod(tree); pcl::PointCloud<pcl::VFHSignature308>::Ptr vfhs (new pcl::PointCloud<pcl::VFHSignature308> ()); vfh.compute(*vfhs); for(int j = 0; j < vfhs->size(); j++) { for (int i = 0; i < 308; i++) { std::cout << vfhs->points[j].histogram[i] << " "; } } std::cout << "\n\nVFH: " << vfhs->points.size() << "\t" << cloud->size() << std::endl; } //********************************************************************************************************************** //! Function to compute fast point feature histogram //********************************************************************************************************************** void fastPointFeatureHistogram(pcl::PointCloud<PointT>::Ptr cloud, pcl::PointCloud<pcl::Normal>::Ptr normals) { pcl::FPFHEstimation<PointT, pcl::Normal, pcl::FPFHSignature33> fpfh; fpfh.setInputCloud(cloud); fpfh.setInputNormals(normals); pcl::search::KdTree<PointT>::Ptr tree (new pcl::search::KdTree<PointT>); fpfh.setSearchMethod(tree); pcl::PointCloud<pcl::FPFHSignature33>::Ptr fpfhs (new pcl::PointCloud<pcl::FPFHSignature33> ()); fpfh.setRadiusSearch(0.01); fpfh.compute(*fpfhs); std::cout << "FPFH :" << fpfhs->points.size() << "\tCloud Size: " << cloud->size() << endl; for (int i = 0; i < fpfhs->points.size(); i++) { for (int j = 0; j < 33; j++) { std::cout << fpfhs->points[i].histogram[j] << " "; } cout << endl << endl; } } //********************************************************************************************************************** //! Function to fit a sphere model to the cloud points //********************************************************************************************************************** Eigen::VectorXf pclModelSphere(pcl::PointCloud<PointT>::Ptr cloud) { pcl::SampleConsensusModelSphere<PointT>::Ptr modelSphere (new pcl::SampleConsensusModelSphere<PointT> (cloud, false)); pcl::RandomSampleConsensus<PointT> ransac (modelSphere); Eigen::VectorXf model_coefficients; ransac.setDistanceThreshold(0.005); ransac.computeModel(); ransac.getModelCoefficients(model_coefficients); std::cout << "Model Coefficient:\n " << model_coefficients << std::endl; return model_coefficients; } <file_sep>/libsvm/main.cpp // Copyright (C) 2015 by <NAME> // Function to wrap OpenCV cv::Mat type features to LibSVM type // "svm_problem" // The example is taken from // http://docs.opencv.org/doc/tutorials/ml/introduction_to_svm/introduction_to_svm.html #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <svm.h> #include <iostream> #include <string> struct svm_problem libSVMWrapper( const cv::Mat &feature_mat, const cv::Mat &label_mat, const svm_parameter &param) { if (feature_mat.rows != label_mat.rows) { std::cout << "--TRAINING SET IS NOT EQUIVALENT.." << std::endl; std::_Exit(EXIT_FAILURE); } svm_problem svm_prob_vector; const int feature_lenght = static_cast<int>(feature_mat.rows); const int feature_dimensions = static_cast<int>(feature_mat.cols); svm_prob_vector.l = feature_lenght; svm_prob_vector.y = new double[feature_lenght]; svm_prob_vector.x = new svm_node*[feature_lenght]; for (int i = 0; i < feature_lenght; i++) { svm_prob_vector.x[i] = new svm_node[feature_dimensions]; } for (int j = 0; j < feature_lenght; j++) { svm_prob_vector.y[j] = static_cast<double>(label_mat.at<float>(j, 0)); for (int i = 0; i < feature_dimensions; i++) { svm_prob_vector.x[j][i].index = i + 1; svm_prob_vector.x[j][i].value = static_cast<double>( feature_mat.at<float>(j, i)); } svm_prob_vector.x[j][feature_dimensions].index = -1; } return svm_prob_vector; } int main(int argc, char *argv[]) { float labels[4] = {1.0, 1.0, -1.0, -1.0}; cv::Mat labelsMat(4, 1, CV_32FC1, labels); float trainingData[4][2] = {{501, 10}, {255, 10}, {501, 255}, {10, 501}}; cv::Mat trainingDataMat(4, 2, CV_32FC1, trainingData); svm_parameter param; param.svm_type = C_SVC; param.kernel_type = LINEAR; param.degree = 3; param.gamma = 0; param.coef0 = 0; param.nu = 0.5; param.cache_size = 100; param.C = 1; param.eps = 1e-6; param.p = 0.1; param.shrinking = 1; param.probability = 1; param.nr_weight = 0; param.weight_label = NULL; param.weight = NULL; svm_problem svm_prob_vector = libSVMWrapper( trainingDataMat, labelsMat, param); struct svm_model *model = new svm_model; if (svm_check_parameter(&svm_prob_vector, &param)) { std::cout << "ERROR" << std::endl; } else { model = svm_train(&svm_prob_vector, &param); } bool is_compute_probability = true; std::string model_file_name = "svm"; bool save_model = true; if (save_model) { try { svm_save_model(model_file_name.c_str(), model); std::cout << "Model file Saved Successfully..." << std::endl; } catch(std::exception& e) { std::cout << e.what() << std::endl; } } bool is_probability_model = svm_check_probability_model(model); int svm_type = svm_get_svm_type(model); int nr_class = svm_get_nr_class(model); // number of classes double *prob_estimates = new double[nr_class]; cv::Vec3b green(0, 255, 0); cv::Vec3b blue(255, 0, 0); int width = 512, height = 512; cv::Mat image = cv::Mat::zeros(height, width, CV_8UC3); for (int i = 0; i < image.rows; ++i) { for (int j = 0; j < image.cols; ++j) { cv::Mat sampleMat = (cv::Mat_<float>(1, 2) << j, i); int dims = sampleMat.cols; svm_node* test_pt = new svm_node[dims]; for (int k = 0; k < dims; k++) { test_pt[k].index = k + 1; test_pt[k].value = static_cast<double>(sampleMat.at<float>(0, k)); } test_pt[dims].index = -1; float response = 0.0f; if (is_probability_model && is_compute_probability) { response = svm_predict_probability(model, test_pt, prob_estimates); } else { response = svm_predict(model, test_pt); } /* std::cout << "Predict: " << prob << std::endl; for (int y = 0; y < nr_class; y++) { std::cout << prob_estimates[y] << " "; }std::cout << std::endl; */ if (prob_estimates[0] > 0.5 || response == 1) { image.at<cv::Vec3b>(i, j) = green; } else if (prob_estimates[1] >= 0.5 || response == -1) { image.at<cv::Vec3b>(i, j) = blue; } } } cv::imshow("image", image); cv::waitKey(0); return 0; } <file_sep>/cc_labeling/connected.cpp #include "connected.h" template<class Tin, class Tlabel, class Comparator, class Boolean> int ConnectedComponents::connected( const Tin *img, Tlabel *labelimg, int width, int height, Comparator SAME, Boolean K8_connectivity) { label_image(img, labelimg, width, height, SAME, K8_connectivity); return relabel_image(labelimg, width, height); } template<class Tin, class Tlabel, class Comparator, class Boolean> void ConnectedComponents::label_image( const Tin *img, Tlabel *labelimg, int width, int height, Comparator SAME, const Boolean K8_CONNECTIVITY) { const Tin *row = img; const Tin *last_row = 0; struct Label_handler { Label_handler(const Tin *img, Tlabel *limg) : piximg(img), labelimg(limg) {} Tlabel &operator()(const Tin *pixp) { return labelimg[pixp-piximg]; } const Tin *piximg; Tlabel *labelimg; } label(img, labelimg); clear(); label(&row[0]) = new_label(); for (int c = 1, r = 0; c < width; ++c) { if (SAME(row[c], row[c-1])) { label(&row[c]) = label(&row[c-1]); } else { label(&row[c]) = new_label(); } } for (int r = 1; r < height; ++r) { last_row = row; row = &img[width*r]; if (SAME(row[0], last_row[0])) label(&row[0]) = label(&last_row[0]); else label(&row[0]) = new_label(); for (int c = 1; c < width; ++c) { int mylab = -1; if (SAME(row[c], row[c-1])) mylab = label(&row[c-1]); for (int d = (K8_CONNECTIVITY ? -1 : 0); d < 1; ++d) { if (SAME(row[c], last_row[c+d])) { if (mylab >= 0) { merge(mylab, label(&last_row[c+d])); } else { mylab = label(&last_row[c+d]); } } } if (mylab >= 0) { label(&row[c]) = static_cast<Tlabel>(mylab); } else { label(&row[c]) = new_label(); } if (K8_CONNECTIVITY && SAME(row[c-1], last_row[c])) { merge(label(&row[c-1]), label(&last_row[c])); } } } } template<class Tlabel> int ConnectedComponents::relabel_image( Tlabel *labelimg, int width, int height) { int newtag = 0; for (int id = 0; id < labels.size(); ++id) { if (is_root_label(id)) { labels[id].tag = newtag++; } } for (int i = 0; i < width*height; ++i) { labelimg[i] = labels[root_of(labelimg[i])].tag; } return newtag; } <file_sep>/rag/backup/main1.cpp #include <boost/graph/adjacency_list.hpp> #include <boost/tuple/tuple.hpp> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <boost/config.hpp> #include <iostream> #include <vector> #include <string> using namespace std; using namespace cv; class RAG { #define THRESHOLD (0.5) private: typedef boost::property<boost::vertex_index_t, int> VertexProperty; typedef boost::property<boost::edge_weight_t, float> EdgeProperty; // the graph structure boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS, VertexProperty, EdgeProperty> graph; // prototype for edge descriptor typedef typename boost::graph_traits< boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, VertexProperty, EdgeProperty> >::edge_descriptor EdgeDescriptor; // prototype to handle the edge values typedef typename boost::property_traits<boost::property_map< boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, VertexProperty, EdgeProperty>, boost::edge_weight_t>::const_type>::value_type EdgeValue; // prototype for vertex descriptor boost::graph_traits< boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, VertexProperty, EdgeProperty> >::vertex_descriptor VertexDescriptor; // prototype for vertex iteration typedef typename boost::graph_traits< boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, VertexProperty, EdgeProperty> >::vertex_iterator VertexIterator; // prototype to accessing adjacent vertices typedef typename boost::graph_traits< boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, VertexProperty, EdgeProperty> >::adjacency_iterator AdjacencyIterator; void concatenateRegion( const cv::Mat &, const cv::Point2i &, cv::Mat &); void computeHistogram(const Mat &, Mat &, bool = true); public: // RAG(); void generateRAG( const vector<cv::Mat> &, const Mat &, const Mat &); bool mergeRegionRAG( const std::vector<cv::Mat> &, const Mat &); }; void RAG::generateRAG( const vector<cv::Mat> &patches, const Mat &neigbours, const Mat &centroids) { if (neigbours.empty() || centroids.empty()) { std::cout << "Error" << std::endl; return; } if (neigbours.rows == centroids.rows) { int icounter = 0; for (int j = 0; j < neigbours.rows; j++) { int c_index = j; // static_cast<int>(neigbours.at<uchar>(j, 0)); add_vertex(c_index, this->graph); Mat pHist; this->computeHistogram(patches[c_index], pHist); for (int i = 0; i < neigbours.cols; i++) { int n_index = static_cast<int>(neigbours.at<uchar>(j, i)); Mat nHist; this->computeHistogram(patches[n_index], nHist); float distance = 0.0f; // get weight function distance = static_cast<float>( compareHist(pHist, nHist, CV_COMP_BHATTACHARYYA)); add_edge(c_index, n_index, EdgeProperty(distance), this->graph); } } } std::cout << "Graph Size: " << num_vertices(this->graph) << std::endl; } bool RAG::mergeRegionRAG( const vector<cv::Mat> &patches, const Mat &centroids) { if (num_vertices(this->graph) == 0 || patches.empty()) { std::cout << "ERROR: Empty Graph" << std::endl; return false; } boost::property_map<boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, VertexProperty, EdgeProperty>, boost::vertex_index_t >::type vertex_index_map = get(boost::vertex_index, this->graph); VertexIterator vIter_begin, vIter_end; EdgeDescriptor e_descriptor; AdjacencyIterator aIter_begin, aIter_end; cv::Mat segmented_image = Mat::zeros(480, 640, CV_8UC3); for (tie(vIter_begin, vIter_end) = vertices(this->graph); vIter_begin != vIter_end; ++vIter_begin) { tie(aIter_begin, aIter_end) = adjacent_vertices( *vIter_begin, this->graph); for (; aIter_begin != aIter_end; ++aIter_begin) { bool found; tie(e_descriptor, found) = edge( *vIter_begin, *aIter_begin, this->graph); if (found) { EdgeValue edge_val = boost::get( boost::edge_weight, this->graph, e_descriptor); float e_weights = edge_val; if (e_weights > THRESHOLD) { // merge the regions int x_ = centroids.at<float>(static_cast<int>(*vIter_begin), 0); int y_ = centroids.at<float>(static_cast<int>(*vIter_begin), 1); cv::Point2i centr(x_, y_); this->concatenateRegion( patches[*vIter_begin], centr, segmented_image); x_ = centroids.at<float>(static_cast<int>(*aIter_begin), 0); y_ = centroids.at<float>(static_cast<int>(*aIter_begin), 1); centr = cv::Point2i(x_, y_); this->concatenateRegion( patches[*aIter_begin], centr, segmented_image); /* Direct all the edges to the new vertex and than * delete the other vertex */ AdjacencyIterator aI; AdjacencyIterator aEnd; tie(aI, aEnd) = adjacent_vertices(*vIter_begin, this->graph); for (; aI != aEnd; aI++) { EdgeDescriptor ed; bool located = false; tie(ed, located) = edge(*aI, *aIter_begin, this->graph); if (located && *aI != *vIter_begin) { EdgeValue ev = boost::get( boost::edge_weight, this->graph, ed); /*add_edge(*aI, *vIter_begin, EdgeProperty(static_cast<float>(ev)), this->graph);*/ std::cout << "Vertex: " << *aI << " " << get(vertex_index_map, *aEnd) << "\n"; } } // clear_vertex(*aIter_begin, this->graph); // remove_vertex(*aIter_begin, this->graph); std::cout << "Common: " << e_descriptor << std::endl; // clear_vertex(*aIter_begin, this->graph); // remove_vertex(*aIter_begin, this->graph); } } } } if (segmented_image.data) { imshow("RAG", segmented_image); } } /** * function to merge the 2 given node and the corresponding regions */ void RAG::concatenateRegion( const cv::Mat &n_region, const cv::Point2i &centroids, cv::Mat &out_img) { int x_off = centroids.x - n_region.cols/2; int y_off = centroids.y - n_region.rows/2; for (int j = 0; j < n_region.rows; j++) { for (int i = 0; i < n_region.cols; i++) { out_img.at<cv::Vec3b>(y_off + j, x_off + i) = n_region.at<cv::Vec3b>(j, i); } } } void RAG::computeHistogram(const Mat &src, Mat &hist, bool isNormalized) { Mat hsv; cvtColor(src, hsv, CV_BGR2HSV); int hBin = 16; int sBin = 16; int histSize[] = {hBin, sBin}; float h_ranges[] = {0, 180}; float s_ranges[] = {0, 256}; const float* ranges[] = {h_ranges, s_ranges}; int channels[] = {0, 1}; calcHist(&hsv, 1, channels, Mat(), hist, 2, histSize, ranges, true, false); if (isNormalized) { normalize(hist, hist, 0, 1, NORM_MINMAX, -1, Mat()); } } int main(int argc, const char *argv[]) { // boostSampleGraph(); // exit(-1); cv::Mat image = cv::Mat(480, 640, CV_8UC3, Scalar(255, 255, 255)); Rect rect = Rect(64, 96, 256, 96); rectangle(image, rect, Scalar(0, 255, 0), -1); int width = 64; int height = 48; vector<Mat> patches; int _num_element = (image.rows/height) * (image.cols/width); Mat centroid = Mat(_num_element, 2, CV_32F); int y = 0; for (int j = 0; j < image.rows; j += height) { for (int i = 0; i < image.cols; i += width) { Rect_<float> _rect = Rect_<float>(i, j, width, height); if (_rect.x + _rect.width <= image.cols && _rect.y + _rect.height <= image.rows) { Mat roi = image(_rect); patches.push_back(roi); Point2f _center = Point2f(_rect.x + _rect.width/2, _rect.y + _rect.height/2); // centroid.push_back(_center); centroid.at<float>(y, 0) = _center.x; centroid.at<float>(y++, 1) = _center.y; } } } cv::flann::KDTreeIndexParams indexParams(5); cv::flann::Index kdtree(centroid, indexParams); Mat index; Mat dist; kdtree.knnSearch(centroid, index, dist, 4, cv::flann::SearchParams(64)); RAG rag; rag.generateRAG(patches, index, centroid); rag.mergeRegionRAG(patches, centroid); imshow("image", image); waitKey(0); return EXIT_SUCCESS; } <file_sep>/openmp/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(openmp) find_package(OpenMP) if (OPENMP_FOUND) set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") endif() add_executable(hello_world hello_world.cpp ) target_link_libraries( hello_world ${OPENMP_LIBS} ) add_executable(for_loop for_loop.cpp ) target_link_libraries( for_loop ${OPENMP_LIBS}) add_executable(section section.cpp ) target_link_libraries( section ${OPENMP_LIBS}) add_executable(work_sharing_single work_sharing_single.cpp) target_link_libraries( work_sharing_single ${OPENMP_LIBS}) add_executable(critial critial.cpp) target_link_libraries( critial ${OPENMP_LIBS}) add_executable(barrier barrier.cpp) target_link_libraries( barrier ${OPENMP_LIBS}) add_executable(atomic atomic.cpp) target_link_libraries( atomic ${OPENMP_LIBS})<file_sep>/friends/main.cpp #include <iostream> using namespace std; class Square; class Rectangle { int width, height; public: int area () {return (width * height);} void convert(Square a); private: int x; }; class Square:public Rectangle { friend class Rectangle; private: int side; public: explicit Square(int a) : side(a) {x = 19;} }; void Rectangle::convert(Square a) { width = a.side; height = a.side; } int main() { Rectangle rect; Square sqr(4); sqr.convert(sqr); std::cout << sqr.area() << std::endl; rect.convert(sqr); cout << rect.area() << "\n"; return 0; } <file_sep>/python_tutorial/loop_py.py #!/usr/bin/python Money = 2000 def addMoney(): global Money Money += 2 def main(): print Money addMoney() print Money if __name__ == '__main__': main() <file_sep>/region_growing/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project( region_grow ) find_package( OpenCV REQUIRED ) add_executable( rgrow rgrow.c ) target_link_libraries( rgrow ${OpenCV_LIBS} ) <file_sep>/rag/backup/main4.cpp #include <boost/graph/adjacency_list.hpp> #include <boost/tuple/tuple.hpp> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <boost/config.hpp> #include <iostream> #include <vector> #include <string> using namespace std; using namespace cv; enum family { Jeanie, Debbie, Rick, John, Amanda, Margaret, Benjamin, N }; const char *name[] = { "Jeanie", "Debbie", "Rick", "John", "Amanda", "Margaret", "Benjamin" }; typedef boost::property<boost::vertex_index_t, int> vertex_property; typedef boost::property<boost::edge_weight_t, float> edge_property; typedef typename boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS, vertex_property, edge_property> Graph; typedef typename boost::graph_traits< Graph>::adjacency_iterator AdjacencyIterator; typedef typename boost::property_map< Graph, boost::vertex_index_t >::type IndexMap; typedef typename boost::graph_traits< Graph>::edge_descriptor EdgeDescriptor; typedef typename boost::property_map< Graph, boost::edge_weight_t>::type EdgePropertyAccess; typedef typename boost::property_traits<boost::property_map< Graph, boost::edge_weight_t>::const_type>::value_type EdgeValue; typedef typename boost::graph_traits< Graph>::vertex_iterator VectorIterator; /** * updating the graph */ bool updateRAG(const Graph &graph, int index) { boost::graph_traits<Graph>::vertex_iterator i, end; IndexMap index_map = get(boost::vertex_index, graph); for (tie(i, end) = vertices(graph); i != end; ++i) { // std::cout << name[get(index_map, *i)]; std::cout << get(index_map, *i) << std::endl; } return false; } /** * Create and process the graph */ void boostSampleGraph() { /* actual graph structure */ Graph graph; /* add vertices to the graph */ add_vertex(Jeanie, graph); add_vertex(Debbie, graph); add_vertex(Rick, graph); add_vertex(John, graph); add_vertex(Amanda, graph); add_vertex(Margaret, graph); add_vertex(Benjamin, graph); // add_vertex(N, graph); /* add edges to the vertices in the graph*/ add_edge(Jeanie, Debbie, edge_property(0.5f), graph); add_edge(Jeanie, Rick, edge_property(0.2f), graph); add_edge(Jeanie, John, edge_property(0.1f), graph); add_edge(Debbie, Amanda, edge_property(0.3f), graph); add_edge(Rick, Margaret, edge_property(0.4f), graph); add_edge(John, Benjamin, edge_property(0.6f), graph); // add_edge(Benjamin, Benjamin, edge_property(0.7f), graph); IndexMap index_map = get(boost::vertex_index, graph); EdgeDescriptor e_descriptor; EdgePropertyAccess edge_weights = get(boost::edge_weight, graph); VectorIterator i, end; bool continue_merging_flag = true; while (continue_merging_flag) { tie(i, end) = vertices(graph); AdjacencyIterator ai, a_end; tie(ai, a_end) = adjacent_vertices(*i, graph); for (; ai != a_end; ++ai) { bool found = false; tie(e_descriptor, found) = edge(*i, *ai, graph); if (found) { EdgeValue edge_val = boost::get( boost::edge_weight, graph, e_descriptor); float weights_ = edge_val; if (weights_ > 0.3f) { AdjacencyIterator aI, aEnd; tie(aI, aEnd) = adjacent_vertices(*ai, graph); for (; aI != aEnd; aI++) { EdgeDescriptor ed; bool located; tie(ed, located) = edge(*aI, *ai, graph); if (located && *aI != *i) { add_edge(*i, *aI, graph); } std::cout << "\n DEBUG: " << *i << " " << *ai << " " << *aI << " "; } std::cout << std::endl; clear_vertex(*ai, graph); remove_vertex(*ai, graph); // std::cout << "Graph Size: " // << num_vertices(graph) << std::endl; continue_merging_flag = updateRAG(graph, 0); } } } } for (tie(i, end) = vertices(graph); i != end; ++i) { std::cout << name[get(index_map, *i)]; AdjacencyIterator ai, a_end; tie(ai, a_end) = adjacent_vertices(*i, graph); if (ai == a_end) { std::cout << " has no children"; } else { std::cout << " is the parent of "; } for (; ai != a_end; ++ai) { bool found = false; tie(e_descriptor, found) = edge(*i, *ai, graph); if (found) { EdgeValue edge_val = boost::get( boost::edge_weight, graph, e_descriptor); float weights_ = edge_val; if (weights_ > 0.3f) { // - remove and merge AdjacencyIterator aI, aEnd; tie(aI, aEnd) = adjacent_vertices(*ai, graph); for (; aI != aEnd; aI++) { EdgeDescriptor ed; bool located; tie(ed, located) = edge(*aI, *ai, graph); if (located && *aI != *i) { add_edge(*i, *aI, graph); // get(index_map, *i), get(index_map, *aI), graph); } std::cout << "\n DEBUG: " << *i << " " << *ai << " " << *aI << " "; /* clear_vertex(*ai, graph); // remove_vertex(*ai, graph); std::cout << "\n DEBUG2: " << *i << " " << *ai << " " << *aI << " "; */ } std::cout << std::endl; clear_vertex(*ai, graph); remove_vertex(*ai, graph); // std::cout << "Graph Size: " // << num_vertices(graph) << std::endl; updateRAG(graph, 0); } } // ai = tmp; // std::cout << name[get(index_map, *ai)]; // if (boost::next(ai) != a_end) { // std::cout << ", "; // } } std::cout << std::endl << std::endl; } std::cout << "\nGraph Size: " << num_vertices(graph) << std::endl; } /** * */ int main(int argc, const char *argv[]) { boostSampleGraph(); exit(-1); cv::Mat image = cv::Mat::zeros(480, 640, CV_8UC3); Rect rect = Rect(64, 96, 256, 96); rectangle(image, rect, Scalar(0, 255, 0), -1); int width = 64; int height = 48; vector<Mat> patches; int _num_element = (image.rows/height) * (image.cols/width); Mat centroid = Mat(_num_element, 2, CV_32F); int y = 0; for (int j = 0; j < image.rows; j += height) { for (int i = 0; i < image.cols; i += width) { Rect_<float> _rect = Rect_<float>(i, j, width, height); if (_rect.x + _rect.width <= image.cols && _rect.y + _rect.height <= image.rows) { Mat roi = image(_rect); patches.push_back(roi); Point2f _center = Point2f(_rect.x + _rect.width/2, _rect.y + _rect.height/2); // centroid.push_back(_center); centroid.at<float>(y, 0) = _center.x; centroid.at<float>(y++, 1) = _center.y; } } } cv::flann::KDTreeIndexParams indexParams(5); cv::flann::Index kdtree(centroid, indexParams); Mat index; Mat dist; kdtree.knnSearch(centroid, index, dist, 4, cv::flann::SearchParams(64)); imshow("image", image); waitKey(0); return EXIT_SUCCESS; } <file_sep>/cc_labeling/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project( cc_labeling ) find_package( OpenCV REQUIRED ) include_directories ( "${PROJECT_SOURCE_DIR}"/connected.h "${PROJECT_SOURCE_DIR}"/contour_thinning.h) add_executable( main main.cpp #connected.cpp ) target_link_libraries( main ${OpenCV_LIBS} ${PROJECT_SOURCE_DIR} ) <file_sep>/pixel_classification/main.cpp #include <opencv2/core/core.hpp> #include <opencv2/opencv.hpp> #include <omp.h> #include <iostream> #include <string> cv::Mat readImage(std::string path) { cv::Mat image = cv::imread(path, 1); if (image.empty()) { std::cout << "NO IMAGE" << std::endl; exit(-1); } return image; } double likelihood(double distance, double w) { return (1.0 / (1 + w *(std::pow(distance/255, 2)))); } double classifyPixel(const cv::Vec3b pixel, const cv::Mat model) { if (model.empty()) { return 0.0; } double max_likelihood = 0; #pragma omp parallel for shared(max_likelihood) collapse(2) for (int j = 0; j < model.rows; j++) { for (int i = 0; i < model.cols; i++) { double m = 0.0; for (int k = 0; k < 3; k++) { double v = likelihood(pixel.val[k] - model.at<cv::Vec3b>( j, i)[k], 0.50); m += v; } if (m/3 > max_likelihood) { max_likelihood = m; } } } return max_likelihood; } int main(int argc, char *argv[]) { cv::Mat model = readImage(argv[1]); cv::Mat image = readImage(argv[2]); cv::Mat probablity = cv::Mat::zeros(image.size(), CV_8UC3); #pragma omp parallel for collapse(2) for (int j = 0; j < image.rows; j++) { for (int i = 0; i < image.cols; i++) { double p = classifyPixel(image.at<cv::Vec3b>(j, i), model); probablity.at<cv::Vec3b>(j, i)[0] = p * 255; probablity.at<cv::Vec3b>(j, i)[1] = p * 255; probablity.at<cv::Vec3b>(j, i)[2] = p * 255; } } cv::imshow("probability-map", probablity); cv::waitKey(0); return 0; } <file_sep>/sklearn/array/array_tut.py #!/usr/bin/env python import numpy import numpy as np import rospy from sklearn.svm import SVC from sklearn.externals import joblib def object_classifier_train(fvect, lvect): clf = SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, kernel='linear', max_iter=-1, probability=True, random_state=None, shrinking=True, tol=0.001, verbose=False) clf.fit(fvect, lvect) joblib.dump(clf, 'svm.pkl') def object_classifier_trainer_handler(req): cols = len(req) rows = 3 print cols #req = np.arange(9).reshape(3, 3) req = np.array(req) b = req.reshape(-1, 5) print b[0] print b[1] print b.shape[0] #req = np.array(req) #print req #fvect = object_classifier_construct_data(req, rows, cols); #lvect = convert_to_numpy_array(req.labels) if __name__ == "__main__": print 'In Main...' a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b = [10, 20, 4, 5, 6, 7, 10,60, 7, 122] object_classifier_trainer_handler(a) <file_sep>/openmp/for_loop.cpp #include <omp.h> #include <iostream> #define CHUNKSIZE 10 #define N 20 int main(int argc, char *argv[]) { int i, chunk; float a[N], b[N], c[N]; /* Some initializations */ for (i=0; i < N; i++) a[i] = b[i] = i * 1.0; chunk = CHUNKSIZE; #pragma omp parallel shared(a, b, c, chunk) private(i) { #pragma omp for schedule(dynamic, chunk) nowait for (i=0; i < N; i++) { std::cout << "\nIN FOR...." << i << std::endl; std::cout << " " << omp_get_thread_num() << std::endl; c[i] = a[i] + b[i]; } // if (omp_get_thread_num() == 0) { // std::cout /*<< "NUM THREADS: " << omp_get_num_threads()*/ // << " " << omp_get_thread_num() << std::endl; // } } for (int j = 0; j < N; j++) { // std::cout << a[j] << " " << b[j] << " " << c[j] // << std::endl; } } <file_sep>/rag/backup/main2.cpp #include <boost/graph/adjacency_list.hpp> #include <boost/tuple/tuple.hpp> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <boost/config.hpp> #include <iostream> #include <vector> #include <string> using namespace std; using namespace cv; typedef boost::property<boost::vertex_index_t, int> vertex_property; typedef boost::property<boost::edge_weight_t, float> edge_property; void boostSampleGraph() { enum family { Jeanie, Debbie, Rick, John, Amanda, Margaret, Benjamin, N }; const char *name[] = { "Jeanie", "Debbie", "Rick", "John", "Amanda", "Margaret", "Benjamin", "N" }; /* actual graph structure */ boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS, vertex_property, edge_property> graph; /* add vertices to the graph */ add_vertex(Jeanie, graph); add_vertex(Debbie, graph); add_vertex(Rick, graph); add_vertex(John, graph); add_vertex(Amanda, graph); add_vertex(Margaret, graph); add_vertex(Benjamin, graph); // add_vertex(N, graph); /* add edges to the vertices in the graph*/ add_edge(Jeanie, Debbie, edge_property(0.5f), graph); add_edge(Jeanie, Rick, edge_property(0.2f), graph); add_edge(Jeanie, John, edge_property(0.1f), graph); add_edge(Debbie, Amanda, edge_property(0.3f), graph); add_edge(Rick, Margaret, edge_property(0.4f), graph); add_edge(John, Benjamin, edge_property(0.6f), graph); // add_edge(Benjamin, Benjamin, edge_property(0.7f), graph); /* vertex iterator */ boost::graph_traits < boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS, vertex_property, edge_property> >::vertex_iterator i, end; typedef typename boost::graph_traits < boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS, vertex_property, edge_property> >::adjacency_iterator AdjacencyIterator; // AdjacencyIterator ai, a_end; /* gets the graph vertex index */ typedef typename boost::property_map < boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS, vertex_property, edge_property>, boost::vertex_index_t >::type IndexMap; IndexMap index_map = get(boost::vertex_index, graph); /* container to hold the edge descriptor info */ typedef typename boost::graph_traits< boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, vertex_property, edge_property> >::edge_descriptor EdgeDescriptor; EdgeDescriptor e_descriptor; typedef typename boost::property_map< boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, vertex_property, edge_property>, boost::edge_weight_t >::type EdgePropertyAccess; EdgePropertyAccess edge_weights = get(boost::edge_weight, graph); typedef typename boost::property_traits<boost::property_map< boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, vertex_property, edge_property>, boost::edge_weight_t>::const_type>::value_type EdgeValue; float edge_size = num_vertices(graph); std::cout << "# of Edges: " << edge_size << std::endl; /* iterator throught the graph */ for (tie(i, end) = vertices(graph); i != end; ++i) { std::cout << name[get(index_map, *i)]; AdjacencyIterator ai, a_end; tie(ai, a_end) = adjacent_vertices(*i, graph); // std::cout << "\n # Num: " << *ai << "\t" << *a_end << std::endl; if (ai == a_end) { std::cout << " has no children"; } else { std::cout << " is the parent of "; } for (; ai != a_end; ++ai) { AdjacencyIterator tmp; bool found; tie(e_descriptor, found) = edge(*i, *ai, graph); float weights_ = 0.0f; if (found) { EdgeValue edge_val = boost::get( boost::edge_weight, graph, e_descriptor); weights_ = edge_val; if (weights_ > 0.0f) { // - remove and merge AdjacencyIterator aI, aEnd; tie(aI, aEnd) = adjacent_vertices(*ai, graph); for (; aI != aEnd; aI++) { EdgeDescriptor ed; bool located; tie(ed, located) = edge(*aI, *ai, graph); if (located && *aI != *i) { add_edge( get(index_map, *i), get(index_map, *aI), graph); } std::cout << "\n DEBUG: " << *i << " " << *ai << " " << *aI << " "; } // std::cout << std::endl; // clear_vertex(*ai, graph); // remove_vertex(*ai, graph); // std::cout << "\nGraph Size: " << num_vertices(graph) << std::endl; } } // ai = tmp; std::cout << name[get(index_map, *ai)]; if (boost::next(ai) != a_end) { std::cout << ", "; } } std::cout << std::endl << std::endl; } std::cout << "\nGraph Size: " << num_vertices(graph) << std::endl; } /** * */ int main(int argc, const char *argv[]) { boostSampleGraph(); exit(-1); cv::Mat image = cv::Mat::zeros(480, 640, CV_8UC3); Rect rect = Rect(64, 96, 256, 96); rectangle(image, rect, Scalar(0, 255, 0), -1); int width = 64; int height = 48; vector<Mat> patches; int _num_element = (image.rows/height) * (image.cols/width); Mat centroid = Mat(_num_element, 2, CV_32F); int y = 0; for (int j = 0; j < image.rows; j += height) { for (int i = 0; i < image.cols; i += width) { Rect_<float> _rect = Rect_<float>(i, j, width, height); if (_rect.x + _rect.width <= image.cols && _rect.y + _rect.height <= image.rows) { Mat roi = image(_rect); patches.push_back(roi); Point2f _center = Point2f(_rect.x + _rect.width/2, _rect.y + _rect.height/2); // centroid.push_back(_center); centroid.at<float>(y, 0) = _center.x; centroid.at<float>(y++, 1) = _center.y; } } } cv::flann::KDTreeIndexParams indexParams(5); cv::flann::Index kdtree(centroid, indexParams); Mat index; Mat dist; kdtree.knnSearch(centroid, index, dist, 4, cv::flann::SearchParams(64)); imshow("image", image); waitKey(0); return EXIT_SUCCESS; } <file_sep>/pca_rot/contour_thinning.h #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> enum { EVEN, ODD }; inline void thinningIteration(cv::Mat& img, int iter) { cv::Mat marker = cv::Mat::zeros(img.size(), CV_32F); for (int i = 1; i < img.rows-1; i++) { for (int j = 1; j < img.cols-1; j++) { float *val = new float[9]; int icounter = 0; for (int y = -1; y <= 1; y++) { for (int x = -1; x <= 1; x++) { val[icounter] = img.at<float>(i + y, j + x); icounter++; } } int A = ((val[1] == 0 && val[2] == 1) ? ODD : EVEN) + ((val[2] == 0 && val[5] == 1) ? ODD : EVEN) + ((val[5] == 0 && val[8] == 1) ? ODD : EVEN) + ((val[8] == 0 && val[7] == 1) ? ODD : EVEN) + ((val[7] == 0 && val[6] == 1) ? ODD : EVEN) + ((val[6] == 0 && val[3] == 1) ? ODD : EVEN) + ((val[3] == 0 && val[0] == 1) ? ODD : EVEN) + ((val[0] == 0 && val[1] == 1) ? ODD : EVEN); int B = val[0] + val[1] + val[2] + val[3] + val[5] + val[6] + val[7] + val[8]; int m1 = iter == EVEN ? (val[1] * val[5] * val[7]) : (val[1] * val[3] * val[5]); int m2 = iter == EVEN ? (val[3] * val[5] * val[7]) : (val[1] * val[3] * val[7]); if (A == 1 && (B >= 2 && B <= 6) && !m1 && !m2) { marker.at<float>(i, j) = sizeof(char); } free(val); } } cv::bitwise_not(marker, marker); cv::bitwise_and(img, marker, img); } inline void thinning(cv::Mat& image) { if (image.type() == CV_8UC3) { cv::cvtColor(image, image, CV_BGR2GRAY); } cv::Mat img; image.convertTo(img, CV_32F, 1/255.0); cv::Mat prev = cv::Mat::zeros(img.size(), CV_32F); cv::Mat difference; do { thinningIteration(img, 0); thinningIteration(img, 1); cv::absdiff(img, prev, difference); img.copyTo(prev); } while (cv::countNonZero(difference) > 0); cv::imshow("thinning", img); cv::imshow("Original", image); cv::waitKey(0); } <file_sep>/optical_flow/fback.cpp #include "opencv2/video/tracking.hpp" #include "opencv2/imgproc/imgproc.hpp" //#include "opencv2/videoio/videoio.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> using namespace cv; using namespace std; static void drawOptFlowMap( const Mat& flow, Mat& cflowmap, int step, double, const Scalar& color) { for (int y = 0; y < cflowmap.rows; y += step) for (int x = 0; x < cflowmap.cols; x += step) { const Point2f& fxy = flow.at<Point2f>(y, x); Point pt = Point(x, y); Point npt = flow.at<Point2f>(y, x); npt.x += pt.x; npt.y += pt.y; double distance = cv::norm(cv::Mat(pt), cv::Mat(npt)); if (distance > 10) { line(cflowmap, Point(x, y), Point(cvRound(x+fxy.x), cvRound(y+fxy.y)), color); circle(cflowmap, Point(x, y), 2, color, -1); } } } int main(int, char**) { Mat prev = imread("frame0000.jpg"); Mat frame = imread("frame0001.jpg"); Mat flow, cflow; Mat gray, prevgray, uflow; namedWindow("flow", 1); cvtColor(prev, prevgray, COLOR_BGR2GRAY); cvtColor(frame, gray, COLOR_BGR2GRAY); if (!prevgray.empty()) { calcOpticalFlowFarneback( prevgray, gray, uflow, 0.5, 3, 15, 3, 5, 1.2, 1); cvtColor(prevgray, cflow, COLOR_GRAY2BGR); uflow.copyTo(flow); drawOptFlowMap(flow, cflow, 1, 1.5, Scalar(0, 255, 0)); imshow("flow", cflow); // std::cout << uflow << std::endl; } waitKey(0); std::swap(prevgray, gray); return 0; } <file_sep>/openmp/work_sharing_single.cpp #include <omp.h> #include <iostream> #define N 20 #define CHUNKSIZE 2 int main(int argc, char *argv[]) { int i, chunk; float a[N], b[N], c[N]; for (i=0; i < N; i++) { a[i] = b[i] = i * 1.0; } chunk = CHUNKSIZE; int val = 0; #pragma omp parallel \ for shared(a, b, c, chunk, val) private(i) \ schedule(static, chunk) num_threads(8) for (i=0; i < N; i++) { std::cout << "THREAD: " << omp_get_thread_num() << "\t" << omp_get_num_threads() << std::endl; c[i] = a[i] + b[i]; val++; } std::cout << "Val: " << val << std::endl; } <file_sep>/pca_rot/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project( pca_rot ) find_package( OpenCV REQUIRED ) set(HEADER_FILES main.cpp Object_Boundary.cpp RGBD_Image_Processing.cpp RGBD_Image_Processing.h Object_Boundary.h contour_thinning.h) add_executable( main ${HEADER_FILES} ) target_link_libraries( main ${OpenCV_LIBS} ) <file_sep>/gfpfh/main.cpp #include <pcl/io/pcd_io.h> #include <pcl/features/gfpfh.h> int main(int argc, char** argv) { // Cloud for storing the object. pcl::PointCloud<pcl::PointXYZRGB>::Ptr input( new pcl::PointCloud<pcl::PointXYZRGB>); // Object for storing the GFPFH descriptor. pcl::PointCloud<pcl::GFPFHSignature16>::Ptr descriptor( new pcl::PointCloud<pcl::GFPFHSignature16>); // Note: you should have performed preprocessing to cluster out the object // from the cloud, and save it to this individual file. // Read a PCD file from disk. if (pcl::io::loadPCDFile<pcl::PointXYZRGB>(argv[1], *input) != 0) { return -1; } pcl::PointCloud<pcl::PointXYZL>::Ptr object( new pcl::PointCloud<pcl::PointXYZL>); for (int i = 0; i < input->size(); i++) { pcl::PointXYZL pt; pt.x = input->points[i].x; pt.y = input->points[i].y; pt.z = input->points[i].z; pt.label = 1; object->push_back(pt); } std::cout << object->size() << "\t" << input->size() << std::endl; // Note: you should now perform classification on the cloud's // points. See the // original paper for more details. For this example, we will now consider 4 // different classes, and randomly label each point as one of them. // ESF estimation object. pcl::GFPFHEstimation< pcl::PointXYZL, pcl::PointXYZL, pcl::GFPFHSignature16> gfpfh; gfpfh.setInputCloud(object); // Set the object that contains the labels for each point. Thanks to the // PointXYZL type, we can use the same object we store the cloud in. gfpfh.setInputLabels(object); // Set the size of the octree leaves to 1cm (cubic). gfpfh.setOctreeLeafSize(0.01); // Set the number of classes the cloud has been labelled with // (default is 16). gfpfh.setNumberOfClasses(1); gfpfh.compute(*descriptor); std::cout << descriptor->size() << std::endl; std::cout << "Completed..." << std::endl; } <file_sep>/python_tutorial/class_tutorial.py #!/usr/bin/python import sys # An example of a class class Shape: def __init__(self, x, y): self.x = x self.y = y description = "This shape has not been declared" author = "Nobody is author" def area(self): return self.x * self.y def perimeter(self): return 2*self.x + 2*self.y def describe(self, text): self.description = text def authorName(self, text): self.author = text def scaleSize(self, scale): self.x *= scale self.y *= scale # class inheritance class Square(Shape): def __init__(self, x): self.x = x self.y = x class Triangle(Shape): def area(self): return 0.5 * self.x * self.y def main(option): print 'Executing main...' if option: rectangle = Shape(100, 45) print rectangle.area() else: triangle = Triangle(40, 20) print triangle.area() #square = Square(20) #print square.perimeter() if __name__ == '__main__': main(False) else: print 'Running Square....' square = Shape(20, 20) print square.perimeter() <file_sep>/macro/main.cpp #include <iostream> #define PRINT_RED(X) \ ((std::cout<< "\033[1m\033[35m" << X << " \033[0m" << std::endl), \ (void) 0)\ int main(int argc, char *argv[]) { PRINT_RED("Hello World"); PRINT_RED(2); return 0; } <file_sep>/pca_rot/build.old/main_5.cpp #include <iostream> #include <math.h> #include <fstream> #include <ctime> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include "Object_Boundary.h" #include "RGBD_Image_Processing.h" #include "contour_thinning.h" using namespace std; using namespace cv; const cv::Scalar colorRangeMIN = cv::Scalar(0, 56, 5); const cv::Scalar colorRangeMAX = cv::Scalar(64, 119, 103); double getOrientation(vector<Point> &, Mat &); bool getObjectROI(Mat &); void computeImageGradient(Mat &); void colorFilterTrackerBar(Mat &); void colorFilter(Mat &, cv::Scalar, cv::Scalar, bool = false); void getImageContours(Mat &, int = 30); void imageMorphologicalOp(Mat &, bool = true); RGBDImageProcessing * img_proc = new RGBDImageProcessing(); Mat original_img; /** * data-structure to hold the orientatio of each detected edges */ struct EdgeParam { cv::Point index; // save the cartesian coordinate of the edge float orientation; // value of edge orientatation bool flag; // true if junction and false if end-point }; /** * main program */ int main(int argc, char *argv[]) { Mat image; if(argc < 2) { image = imread("../pca_test1.jpg", 1); } else { image = imread(argv[1], 1); } if(image.empty()) { std::cout << "No Image Found...." << std::endl; return -1; } const int downsample_ = 1; cv::resize(image, image, cv::Size(image.cols/downsample_, image.rows/downsample_)); original_img = image.clone(); bool is_roi = getObjectROI(image); if(!is_roi) { std::cout << "Selected Object Size is too small to be processed...." << std::endl; exit(-1); } Mat img_bw; //cvtColor(image, img_bw, CV_BGR2GRAY); colorFilter(image, colorRangeMIN, colorRangeMAX, false); //colorFilterTrackerBar(image); cvtColor(image, img_bw, CV_BGR2GRAY); std::clock_t start; double duration; start = std::clock(); computeImageGradient(img_bw); duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC; std::cout<<"Total Processing Time: "<< duration <<'\n'; Mat c_out; Mat img_gray; //cv::threshold(img_bw, img_gray, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU); cvtColor(image, image, CV_BGR2GRAY); //img_proc->extractImageContour(image, c_out, true); vector<Vec4i> lines; cv::HoughLinesP(img_bw, lines, 1, CV_PI/180 , 20, 5, 5); imshow("input", image); waitKey(); //! Find all the contours in the thresholded image vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(img_bw, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_NONE); Mat img = image.clone(); for (size_t i = 0; i < contours.size(); ++i) { //! Calculate the area of each contour double area = contourArea(contours[i]); //! Ignore contours that are too small or too large if (area < 1e2 || 1e5 < area) { continue; } else { //! Draw each contour only for visualisation purposes drawContours(img, contours, i, CV_RGB(255, 0, 0), 2, 8, hierarchy, 0); //! Find the orientation of each shape getOrientation(contours[i], img); } } cv::imshow("img_bw", img_bw); cv::imshow("orig", img); cv::waitKey(0); return 0; } /** * Function to estimate the orientation of an object region using PCA * analysis on the object region */ double getOrientation(vector<Point> &pts, Mat &img) { //Construct a buffer used by the pca analysis Mat data_pts = Mat(pts.size(), 2, CV_64FC1); for (int i = 0; i < data_pts.rows; ++i) { data_pts.at<double>(i, 0) = pts[i].x; data_pts.at<double>(i, 1) = pts[i].y; } //Perform PCA analysis PCA pca_analysis(data_pts, Mat(), CV_PCA_DATA_AS_ROW); //Store the position of the object Point pos = Point(pca_analysis.mean.at<double>(0, 0), pca_analysis.mean.at<double>(0, 1)); //Store the eigenvalues and eigenvectors vector<Point2d> eigen_vecs(2); vector<double> eigen_val(2); for (int i = 0; i < 2; ++i) { eigen_vecs[i] = Point2d(pca_analysis.eigenvectors.at<double>(i, 0), pca_analysis.eigenvectors.at<double>(i, 1)); eigen_val[i] = pca_analysis.eigenvalues.at<double>(0, i); } // Draw the principal components circle(img, pos, 3, CV_RGB(255, 0, 255), 2); line(img, pos, pos + 0.02 * Point(eigen_vecs[0].x * eigen_val[0], eigen_vecs[0].y * eigen_val[0]) , CV_RGB(0, 255, 0)); line(img, pos, pos + 0.02 * Point(eigen_vecs[1].x * eigen_val[1], eigen_vecs[1].y * eigen_val[1]) , CV_RGB(0, 0, 255)); return atan2(eigen_vecs[0].y, eigen_vecs[0].x); } /** * Function to compute the raw image gradient using sobel operation in * x/y direction */ void computeImageGradient(Mat &image) { GaussianBlur(image, image, Size(5,5), 1); Mat src_gray = image.clone(); int scale = 1; int delta = 0; int ddepth = CV_16S; Mat grad_x, grad_y; Mat grad; Mat abs_grad_x, abs_grad_y; Sobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT ); convertScaleAbs( grad_x, abs_grad_x ); Sobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT ); convertScaleAbs( grad_y, abs_grad_y ); addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad ); grad = grad * 2; imageMorphologicalOp(grad); imshow( "gradient", grad ); waitKey(); } /** * User defined object region via bounding box plot */ bool getObjectROI(Mat &image) { ObjectBoundary *obj_roi = new ObjectBoundary(); Rect rect = obj_roi->cvGetobjectBoundary(image); if(rect.width < 10 && rect.height < 10) { return false; } else { Mat img = Mat::zeros(image.rows, image.cols, image.type()); for (int j = 0; j < image.rows; j++) { for (int i = 0; i < image.cols; i++) { if(i > (rect.x - 1) && i < (rect.x + rect.width + 1) && j > (rect.y - 1) && j < (rect.y + rect.height + 1)) { img.at<Vec3b>(j,i) = image.at<Vec3b>(j,i); } } } image = img.clone(); return true; } } /** * Function to filter the input image using the pre-set object color filter */ void colorFilter(Mat &image, Scalar colorMin, Scalar colorMax, bool isFind) { if(isFind) { colorFilterTrackerBar(image); } else { Mat dst; cv::inRange(image, colorMin, colorMax, dst); //cv::bitwise_and(img, dst, outimg); for (int j = 0; j < image.rows; j++) { for (int i = 0; i < image.cols; i++) { if((float)dst.at<uchar>(j,i) == 0) { image.at<Vec3b>(j,i)[0] = 0; image.at<Vec3b>(j,i)[1] = 0; image.at<Vec3b>(j,i)[2] = 0; } } } } } /** * Function to allow user to update the color thresholding */ int min_valR = 0; int max_valR = 255; int min_valG = 0; int max_valG = 255; int min_valB = 0; int max_valB = 255; Mat dst; Mat img; string window_name = "Result"; void threshCallBack(int, void*) { dst = img.clone(); Scalar lowerb = Scalar(min_valB, min_valG, min_valR); Scalar upperb = Scalar(max_valB, max_valG, max_valR); cv::inRange(img, lowerb, upperb, dst); Mat outimg = img.clone(); //cv::bitwise_and(img, dst, outimg); for (int j = 0; j < img.rows; j++) { for (int i = 0; i < img.cols; i++) { if((float)dst.at<uchar>(j,i) == 0) { outimg.at<Vec3b>(j,i)[0] = 0; outimg.at<Vec3b>(j,i)[1] = 0; outimg.at<Vec3b>(j,i)[2] = 0; } } } imshow( window_name, dst ); imshow("out", outimg); } void colorFilterTrackerBar(Mat &image) { img = image.clone(); namedWindow("Result", CV_WINDOW_AUTOSIZE); createTrackbar("Red Min", window_name, &min_valR, 256); createTrackbar("Red Max", window_name, &max_valR, 256); createTrackbar("Green Min", window_name, &min_valG, 256); createTrackbar("Green Max", window_name, &max_valG, 256); createTrackbar("Blue Min", window_name, &min_valB, 256); createTrackbar("Blue Max", window_name, &max_valB, 256); //cvtColor(image, img, CV_BGR2HSV); int c; while(true) { threshCallBack(0,0); c = waitKey( 20 ); if( (char)c == 27 ) { break; } } } /** * estimate the image contours */ void getImageContours(Mat &image, int contour_thresh) { if(image.empty() || image.type() != CV_8UC1) { std::cout << "Image is empty" << std::endl; return; } vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(image, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); Mat drawImg; cvtColor(image, drawImg, CV_GRAY2BGR); for (int i = 0; i < contours.size(); i++) { if(cv::contourArea(contours[i]) > contour_thresh) { drawContours(drawImg, contours, i, Scalar(255, 0, 255), 2, 8, hierarchy, 0, Point()); } } imshow("Image Contours", drawImg); } /** * Function to create a binary image for any pixel not equal to zero */ void cvCreateBinaryImage(Mat image, Mat &img_bw, int lowerb = 0) { img_bw = Mat::zeros(image.size(), CV_8UC1); for (size_t j = 0; j < image.rows; j++) { for (size_t i = 0; i < image.cols; i++) { if(static_cast<int>(image.at<uchar>(j,i)) > lowerb) { img_bw.at<uchar>(j,i) = 255; } } } } /** * compute the pixel edge directional orientation */ void computeEdgeCurvatureOrientation(std::vector<std::vector<cv::Point> > &contours_tangent, std::vector<std::vector<cv::Point> > &contours, std::vector<std::vector<float> > &orientation_, bool is_normalize = true) { for (int j = 0; j < contours_tangent.size(); j++) { std::vector<float> ang; for (int i = 0; i < contours_tangent[j].size(); i++) { float angle_ = 0.0f; if( contours_tangent[j][i].x == 0) { angle_ = 90.0f; } else { angle_ = atan2(contours_tangent[j][i].y, contours_tangent[j][i].x) * (180/CV_PI); } if(is_normalize) { angle_ /= static_cast<float>(360.0); } ang.push_back(static_cast<float>(angle_)); } orientation_.push_back(ang); ang.clear(); } } /** * Compute the image pixel curvature on the pixel edges. * "http://en.wikipedia.org/wiki/Finite_difference#Forward.2C_backward.2C_and_central_differences"" */ void computeEdgeCurvature(std::vector<std::vector<cv::Point> > &contours, std::vector<std::vector<cv::Point> > &tangents, std::vector<std::vector<float> > &orientation_, std::vector<EdgeParam> &hcurvature_pts) { for (int j = 0; j < contours.size(); j++) { std::vector<cv::Point> tangent; /* estimate the first tangent line*/ cv::Point2f edge_pt = contours[j].front(); cv::Point2f edge_tngt = contours[j].back() - contours[j].at(1); tangent.push_back(edge_tngt); const int neighbor_pts = 0; if(contours[j].size() > sizeof(short)) { for (int i = sizeof(char) + neighbor_pts; i < contours[j].size() - sizeof(char) - neighbor_pts; i++) { edge_pt = contours[j][i]; edge_tngt = contours[j][i-1-neighbor_pts] - contours[j][i+1+neighbor_pts]; tangent.push_back(edge_tngt); } } tangents.push_back(tangent); } /* compute the tangent orientation */ computeEdgeCurvatureOrientation(tangents, contours, orientation_); for (int j = 0; j < tangents.size(); j++) { if(tangents[j].size() < 2) { continue; } for (int i = sizeof(char); i < tangents[j].size() - sizeof(char); i++) { float y1 = tangents[j][i+1].y; float x1 = tangents[j][i+1].x; float y0 = tangents[j][i-1].y; float x0 = tangents[j][i-1].x; float tang1 = 0.0f; float tang0 = 0.0f; if(x1 != 0) { tang1 = y1/x1; } if(x0 != 0) { tang0 = y0/x0; } if((tang1 >= 0.0f && tang0 < 0.0f) || (tang1 < 0.0f && tang0 >= 0.0f)) { if((abs(tang0 - tang1) < 1.0f) || (abs(tang1 - tang0) < 1.0f)) { continue; } EdgeParam eP; eP.index = contours[j][i]; eP.orientation = orientation_[j][i]; hcurvature_pts.push_back(eP); //hcurvature_pts.push_back(contours[j][i1]); circle(original_img, contours[j][i], 1, Scalar(255, 0, 0), 1); circle(original_img, contours[j][i], 2, Scalar(0,255,0), 2); //circle(original_img, contours[j][i-1], 2, Scalar(255, 0, 0), 1); //circle(original_img, contours[j][i-1], 5, Scalar(0,255,0), 2); //circle(image, contours[j][i], 1, Scalar(0,0,255), 2); //circle(image, contours[j][i-1], 2, Scalar(0,0,255), 2); } } } cv::imshow("tangent", original_img); } /** * Function to filter multiple points on the same line direction by * box filter and comparision of the gradient orientation magnitude */ void filterJunctionPoints(cv::Mat &img_bw, std::vector<EdgeParam> &hcurvature_pts, std::vector<EdgeParam> &junction_pts, const int radius_ = 5, const float j_thresh = 0.450f) { Mat image; cvtColor(img_bw, image, CV_GRAY2BGR); junction_pts.clear(); for (int i = 0; i < hcurvature_pts.size(); i++) { if(!hcurvature_pts[i].flag) { continue; } cv::Point cur_pt = hcurvature_pts[i].index; float weight = 0.0f; int icounter = 0; for (int j = 0; j < hcurvature_pts.size(); j++) { if(i != j && hcurvature_pts[j].flag) { cv::Point nn_pt = hcurvature_pts[j].index; float r = cv::norm(nn_pt - cur_pt); if(r <= radius_) { weight += exp(- ((nn_pt.x/radius_ - cur_pt.x/radius_) * (nn_pt.x/radius_ - cur_pt.x/radius_)) + ((nn_pt.y/radius_ - cur_pt.y/radius_) * (nn_pt.y/radius_ - cur_pt.y/radius_))) * abs((hcurvature_pts[i].orientation - hcurvature_pts[j].orientation)); icounter++; } } else { continue; } } if(icounter > 0) { weight /= static_cast<float>(icounter); } if(weight > j_thresh) { junction_pts.push_back(hcurvature_pts[i]); circle(image, cur_pt, 3, Scalar(255,0,0), -1); } } imshow("search points", image); waitKey(0); } /** * function to filter points by within some set radius */ void filterJunctionPoints(cv::Mat &img_bw, std::vector<cv::Point> &hcurvature_pts, const int radius_ = 10) { // filter very close high curvature region for (int i = 0; i < hcurvature_pts.size(); i++) { cv::Point cur_pt = hcurvature_pts[i]; for (int j = 0; j < hcurvature_pts.size(); j++) { if(i != j) { cv::Point nn_pt = hcurvature_pts[j]; float r = cv::norm(nn_pt - cur_pt); if(r <= radius_) { hcurvature_pts.erase(hcurvature_pts.begin() + j); } } } } Mat image = img_bw.clone(); cvtColor(image, image, CV_GRAY2BGR); for (int i = 0; i < hcurvature_pts.size(); i++) { circle(image, hcurvature_pts[i], 1, Scalar(255,0,255), CV_FILLED); } imshow("hc", image); } /** * Function to move from junction points in direction of edge * orientation until next junction or end-point */ void traverseJunction2EndPoint(Mat &img_bw, std::vector<std::vector<cv::Point> > &contours_, std::vector<std::vector<cv::Point> > &tangents_, std::vector<std::vector<float> > &orientation_, std::vector<EdgeParam> &junction_points, std::vector<EdgeParam> &end_points) { Mat image = img_bw.clone(); cvtColor(image, image, CV_GRAY2BGR); cv::Mat img = cv::Mat::zeros(img_bw.rows, img_bw.cols, CV_8UC3); cv::Point junct_pt = junction_points[0].index; float junct_orient = junction_points[0].orientation; for (int i = 0; i < orientation_.size(); i++) { for (int j = 0; j < orientation_[i].size(); j++) { cv::Point pt = contours_[i][j]; cv::circle(img, pt, 1, Scalar(0,255,0), -1); float max_norm = std::max(abs(tangents_[i][j].x), abs(tangents_[i][j].y)); float tang_x = 0.0f; float tang_y = 0.0f; if(max_norm != 0) { tang_x = tangents_[i][j].x / static_cast<float>(max_norm); tang_y = tangents_[i][j].y / static_cast<float>(max_norm); } //float r = sqrt((tangents_[i][j].y * tangents_[i][j].y) + (tangents_[i][j].x * tangents_[i][j].x)); float r = sqrt((tang_y * tang_y) + (tang_x * tang_x)); float angle = orientation_[i][j] * 360.0f * (180.0f/CV_PI); cv::line(img, pt, Point(pt.x + r * cos(angle), pt.y + r * sin(angle)), Scalar(0,0,255), 1); } } cv::imshow("edge direction", img); cv::waitKey(0); } /** * Function to plot the edge orientation vector */ void plotGradientOrientation(Mat &img_bw, std::vector<std::vector<cv::Point> > &contours_, std::vector<std::vector<cv::Point> > &tangents_, std::vector<std::vector<float> > &orientation_) { if(img_bw.empty()) { std::cout << "The input image is empty...." << std::endl; return; } cv::Mat img = cv::Mat::zeros(img_bw.rows, img_bw.cols, CV_8UC3); for (int i = 0; i < orientation_.size(); i++) { for (int j = 0; j < orientation_[i].size(); j++) { cv::Point pt = contours_[i][j]; cv::circle(img, pt, 1, Scalar(0,255,0), -1); float r = sqrt((tangents_[i][j].y * tangents_[i][j].y) + (tangents_[i][j].x * tangents_[i][j].x)); float angle = orientation_[i][j] * 360.0f * (180.0f/CV_PI); cv::line(img, pt, Point(pt.x + r * cos(angle), pt.y + r * sin(angle)), Scalar(0,0,255), 1); } } cv::imshow("edge direction", img); } /** * Function to estimate the junction in the image silhouette when * passed with the normal vector and the high curvature data */ void cvJunctionEstimation(Mat &img_bw, std::vector<std::vector<cv::Point> > &contours_, std::vector<std::vector<cv::Point> > &tangents_, std::vector<std::vector<float> > &orientation_, std::vector<EdgeParam> &hcurvature_pts) { Mat image = img_bw.clone(); cvtColor(image, image, CV_GRAY2BGR); const int threshold_ = 2; const int search_radius = 10; std::vector<EdgeParam> end_points; std::vector<EdgeParam> junction_points; for(int i = 0; i < hcurvature_pts.size(); i++) { Mat testImg = Mat::zeros(img_bw.size(), img_bw.type()); circle(testImg, (cv::Point)hcurvature_pts[i].index, search_radius, Scalar(255), 1); Mat mask; cv::bitwise_and(img_bw, testImg, mask); int whitePix = cv::countNonZero(mask > 0); if(whitePix > threshold_ || whitePix == sizeof(char)) { EdgeParam ep_; ep_.index = hcurvature_pts[i].index; ep_.orientation = hcurvature_pts[i].orientation; if(whitePix == sizeof(char)) { end_points.push_back(hcurvature_pts[i]); ep_.flag = false; //circle(image, (cv::Point)hcurvature_pts[i].index, 2, Scalar(0,255,0),-1); } else { circle(image, (cv::Point)hcurvature_pts[i].index, 2, Scalar(255,0,255),-1); ep_.flag = true; } junction_points.push_back(ep_); } } std::vector<EdgeParam> junction_pts; filterJunctionPoints(img_bw, junction_points, junction_pts); //filterJunctionPoints(img_bw, junction_points, search_radius/2); traverseJunction2EndPoint(img_bw, contours_, tangents_, orientation_, junction_pts, end_points); imshow("junction", image); } /** * Function to perform contour estimation on the silhouette contour * and smooth the contour based on the pre-set threshold. */ void branchEstimation(Mat &img_bw) { /* get the image contour by fitering the small contour region */ imshow("input", img_bw); cv::Mat canny_out; int contour_area_thresh = 50; img_proc->extractImageContour(img_bw, canny_out, true, contour_area_thresh); std::vector<std::vector<cv::Point> > contours; img_proc->getContour(contours); // compute the edge orientation and high curvature points std::vector<std::vector<cv::Point> > tangents; std::vector<std::vector<float> > orientation_; std::vector<EdgeParam> hcurvature_pts; computeEdgeCurvature(contours, tangents, orientation_, hcurvature_pts); // plot the gradient orientation //plotGradientOrientation(img_bw, contours, tangents, orientation_); // junction estimation cvJunctionEstimation(img_bw, contours, tangents, orientation_, hcurvature_pts); cv::imshow("skeleton", img_bw); cv::waitKey(); } /** * Adequate image smoothing */ void imageMorphologicalOp(cv::Mat &src, bool is_errode) { cv::Mat erosion_dst; int erosion_size = 5; int erosion_const = 2; int erosion_type = MORPH_ELLIPSE; cv::Mat element = cv::getStructuringElement(erosion_type, cv::Size(erosion_const * erosion_size + 1, erosion_const * erosion_size + 1), cv::Point(erosion_size, erosion_size)); const int smooth_window = 7; const int smooth_sigma = 0; cv::GaussianBlur(src, src, cv::Size(smooth_window, smooth_window), smooth_sigma); cv::erode( src, erosion_dst, element ); //erosion_dst = erosion_dst * 4; /*convert the eroded image to binary*/ Mat img_bw; cvCreateBinaryImage(erosion_dst, img_bw); thinning(img_bw); /* estimate the branch */ branchEstimation(img_bw); imshow("image", src); imshow( "Erosion Demo", erosion_dst ); imshow("Binary", img_bw); waitKey(); } <file_sep>/region_adjacency_graph/backup/rag.cpp #include <boost/graph/adjacency_list.hpp> #include <boost/tuple/tuple.hpp> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <boost/config.hpp> #include <iostream> #include <vector> #include <string> using namespace std; using namespace cv; class RegionAdjacencyGraph { #define THRESHOLD (0.0) private: struct VertexProperty { int v_index; const char* v_name; VertexProperty( int i = -1, const char* name = "default") : v_index(i), v_name(name) {} }; typedef boost::property<boost::edge_weight_t, float> EdgeProperty; typedef typename boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, VertexProperty, EdgeProperty> Graph; typedef typename boost::graph_traits< Graph>::adjacency_iterator AdjacencyIterator; typedef typename boost::property_map< Graph, boost::vertex_index_t>::type IndexMap; typedef typename boost::graph_traits< Graph>::edge_descriptor EdgeDescriptor; typedef typename boost::property_map< Graph, boost::edge_weight_t>::type EdgePropertyAccess; typedef typename boost::property_traits<boost::property_map< Graph, boost::edge_weight_t>::const_type>::value_type EdgeValue; typedef typename boost::graph_traits< Graph>::vertex_iterator VertexIterator; typedef typename boost::graph_traits< Graph>::vertex_descriptor VertexDescriptor; Graph graph; public: RegionAdjacencyGraph(); const char *name[7]; void generateRAG(); void regionMergingGraph(); void printGraph(const Graph &); void updateRAG( Graph &, const std::vector<VertexDescriptor> &, bool = false); }; RegionAdjacencyGraph::RegionAdjacencyGraph() { name[0] = "Jeanie"; name[1] = "Debbie"; name[2] = "Rick"; name[3] = "John"; name[4] = "Amanda"; name[5] = "Margaret"; name[6] = "Benjamin"; } void RegionAdjacencyGraph::generateRAG() { VertexDescriptor Jeanie = add_vertex( VertexProperty(0, name[0]), this->graph); VertexDescriptor Debbie = add_vertex( VertexProperty(1, name[1]), this->graph); VertexDescriptor Rick = add_vertex( VertexProperty(2, name[2]), this->graph); VertexDescriptor John = add_vertex( VertexProperty(3, name[3]), this->graph); VertexDescriptor Amanda = add_vertex( VertexProperty(4, name[4]), this->graph); VertexDescriptor Margaret = add_vertex( VertexProperty(5, name[5]), this->graph); VertexDescriptor Benjamin = add_vertex( VertexProperty(6, name[6]), this->graph); add_edge(Jeanie, Debbie, EdgeProperty(0.5f), this->graph); add_edge(Jeanie, Rick, EdgeProperty(0.2f), this->graph); add_edge(Jeanie, John, EdgeProperty(0.1f), this->graph); add_edge(Debbie, Amanda, EdgeProperty(0.3f), this->graph); add_edge(Rick, Margaret, EdgeProperty(0.4f), this->graph); add_edge(John, Benjamin, EdgeProperty(-0.7f), this->graph); } /** * Create and process the graph */ void RegionAdjacencyGraph::regionMergingGraph() { IndexMap index_map = get(boost::vertex_index, graph); EdgePropertyAccess edge_weights = get(boost::edge_weight, graph); VertexIterator i, end; std::vector<VertexDescriptor> to_remove; for (tie(i, end) = vertices(graph); i != end; i++) { std::cout << name[get(index_map, *i)]; AdjacencyIterator ai, a_end; tie(ai, a_end) = adjacent_vertices(*i, graph); if (ai == a_end) { std::cout << " has no children\n\n"; } else { std::cout << " is the parent of "; } std::vector<VertexDescriptor> to_clear; for (; ai != a_end; ++ai) { bool found = false; EdgeDescriptor e_descriptor; tie(e_descriptor, found) = edge(*i, *ai, graph); if (found) { EdgeValue edge_val = boost::get( boost::edge_weight, graph, e_descriptor); float weights_ = edge_val; if (weights_ > THRESHOLD) { to_remove.push_back(*ai); to_clear.push_back(*ai); AdjacencyIterator aI, aEnd; tie(aI, aEnd) = adjacent_vertices(*ai, graph); for (; aI != aEnd; aI++) { EdgeDescriptor ed; bool located; tie(ed, located) = edge(*aI, *ai, graph); if (located && *aI != *i) { EdgeValue e_val = boost::get( boost::edge_weight, graph, ed); tie(ed, located) = add_edge( *i, *aI, EdgeProperty(static_cast<float>(e_val)), graph); std::cout << "Is Added: " << located << "\t" << ed << "\tEdge weight: " << e_val << std::endl; // std::cout << " DEBUG: " << *i << " " // << *ai << " " // << *aI << " \n" ; } std::cout << " -- OUT DEBUG: " << *i << " " << *ai << " " << *aI << " \n"; } } } } updateRAG(graph, to_clear); to_clear.clear(); } updateRAG(graph, to_remove, true); printGraph(graph); std::cout << "\nGraph Size: " << num_vertices(graph) << std::endl; } /** * Print the tree */ void RegionAdjacencyGraph::printGraph(const Graph &graph) { VertexIterator i, end; for (tie(i, end) = vertices(graph); i != end; ++i) { std::cout << "- Graph Property: " << graph[*i].v_index << "\t" << graph[*i].v_name << std::endl; } } /** * updating the graph */ void RegionAdjacencyGraph::updateRAG( Graph &graph, const std::vector<VertexDescriptor> &to_remove, bool is_rem) { for (int i = to_remove.size() - 1; i >= 0; i--) { VertexDescriptor it = to_remove.at(i); std::cout << graph[it].v_index << "\t" << graph[it].v_name << std::endl; clear_vertex(it, graph); if (is_rem) { remove_vertex(it, graph); } } } /** * */ int main(int argc, const char *argv[]) { RegionAdjacencyGraph rag; rag.generateRAG(); rag.regionMergingGraph(); exit(1); cv::Mat image = cv::Mat::zeros(480, 640, CV_8UC3); Rect rect = Rect(64, 96, 256, 96); rectangle(image, rect, Scalar(0, 255, 0), -1); int width = 64; int height = 48; vector<Mat> patches; int _num_element = (image.rows/height) * (image.cols/width); Mat centroid = Mat(_num_element, 2, CV_32F); int y = 0; for (int j = 0; j < image.rows; j += height) { for (int i = 0; i < image.cols; i += width) { Rect_<float> _rect = Rect_<float>(i, j, width, height); if (_rect.x + _rect.width <= image.cols && _rect.y + _rect.height <= image.rows) { Mat roi = image(_rect); patches.push_back(roi); Point2f _center = Point2f(_rect.x + _rect.width/2, _rect.y + _rect.height/2); // centroid.push_back(_center); centroid.at<float>(y, 0) = _center.x; centroid.at<float>(y++, 1) = _center.y; } } } cv::flann::KDTreeIndexParams indexParams(5); cv::flann::Index kdtree(centroid, indexParams); Mat index; Mat dist; kdtree.knnSearch(centroid, index, dist, 4, cv::flann::SearchParams(64)); imshow("image", image); waitKey(0); return EXIT_SUCCESS; } <file_sep>/region_adjacency_graph/main.cpp #include <boost/graph/adjacency_list.hpp> #include <boost/tuple/tuple.hpp> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <boost/config.hpp> #include <iostream> #include <vector> #include <string> using namespace std; using namespace cv; class RegionAdjacencyGraph { #define THRESHOLD (0.65) private: struct VertexProperty { int v_index; cv::Point2f v_center; int v_label; VertexProperty( int i = -1, cv::Point2f center = cv::Point2f(-1, -1), int label = -1) : v_index(i), v_center(center), v_label(label) {} }; typedef boost::property<boost::edge_weight_t, float> EdgeProperty; typedef typename boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, VertexProperty, EdgeProperty> Graph; typedef typename boost::graph_traits< Graph>::adjacency_iterator AdjacencyIterator; typedef typename boost::property_map< Graph, boost::vertex_index_t>::type IndexMap; typedef typename boost::graph_traits< Graph>::edge_descriptor EdgeDescriptor; typedef typename boost::property_map< Graph, boost::edge_weight_t>::type EdgePropertyAccess; typedef typename boost::property_traits<boost::property_map< Graph, boost::edge_weight_t>::const_type>::value_type EdgeValue; typedef typename boost::graph_traits< Graph>::vertex_iterator VertexIterator; typedef typename boost::graph_traits< Graph>::vertex_descriptor VertexDescriptor; Graph graph; public: RegionAdjacencyGraph(); void generateRAG( const vector<cv::Mat> &, const cv::Mat &, const cv::Mat &); void regionMergingGraph( const vector<cv::Mat> &, const cv::Mat &); void printGraph(const Graph &); void computeHistogram( const cv::Mat &, cv::Mat &, bool = true); void concatenateRegion( const cv::Mat &, const cv::Point2i &, cv::Mat &); void getImageGridLabels(std::vector<int> &); }; /** * constructor */ RegionAdjacencyGraph::RegionAdjacencyGraph() { } void RegionAdjacencyGraph::generateRAG( const vector<cv::Mat> &patches, const cv::Mat &neigbours, const cv::Mat &centroids) { if (neigbours.empty() || centroids.empty()) { std::cout << "Error" << std::endl; return; } if (neigbours.rows == centroids.rows) { std::vector<VertexDescriptor> vertex_descriptor; int icounter = 0; for (int j = 0; j < neigbours.rows; j++) { float c_x = static_cast<float>(centroids.at<float>(j, 0)); float c_y = static_cast<float>(centroids.at<float>(j, 1)); VertexDescriptor v_des = add_vertex( VertexProperty(j, cv::Point2f(c_x, c_y)), this->graph); vertex_descriptor.push_back(v_des); } for (int j = 0; j < neigbours.rows; j++) { VertexDescriptor r_vd = vertex_descriptor[j]; cv::Mat pHist; this->computeHistogram(patches[j], pHist); for (int i = 1; i < neigbours.cols; i++) { int n_index = neigbours.at<int>(j, i); VertexDescriptor vd = vertex_descriptor[n_index]; cv::Mat nHist; this->computeHistogram(patches[n_index], nHist); float distance = static_cast<float>( compareHist(pHist, nHist, CV_COMP_BHATTACHARYYA)); if (r_vd != vd) { bool found = false; EdgeDescriptor e_descriptor; tie(e_descriptor, found) = edge(r_vd, vd, graph); if (!found) { boost::add_edge( r_vd, vd, EdgeProperty(distance), this->graph); } } } } } } /** * Create and process the graph */ void RegionAdjacencyGraph::regionMergingGraph( const vector<cv::Mat> &patches, const Mat &centroids) { if (num_vertices(this->graph) == 0) { std::cout << "Empty Graph..." << std::endl; return; } IndexMap index_map = get(boost::vertex_index, this->graph); EdgePropertyAccess edge_weights = get(boost::edge_weight, this->graph); VertexIterator i, end; int label = -1; for (tie(i, end) = vertices(this->graph); i != end; i++) { if (this->graph[*i].v_label == -1) { graph[*i].v_label = ++label; } AdjacencyIterator ai, a_end; tie(ai, a_end) = adjacent_vertices(*i, this->graph); for (; ai != a_end; ++ai) { bool found = false; EdgeDescriptor e_descriptor; tie(e_descriptor, found) = edge(*i, *ai, this->graph); if (found) { EdgeValue edge_val = boost::get( boost::edge_weight, this->graph, e_descriptor); float weights_ = edge_val; if (weights_ > THRESHOLD) { remove_edge(e_descriptor, this->graph); } else { if (this->graph[*ai].v_label == -1) { this->graph[*ai].v_label = this->graph[*i].v_label; } } } } } this->printGraph(this->graph); std::cout << "\nPRINT INFO. \n --Graph Size: " << num_vertices(graph) << std::endl << "--Total Label: " << label << "\n\n"; } /** * Print the tree */ void RegionAdjacencyGraph::printGraph( const Graph &_graph) { VertexIterator i, end; int icount = 0; for (tie(i, end) = vertices(_graph); i != end; ++i) { std::cout << _graph[*i].v_label << " "; /* AdjacencyIterator ai, a_end; tie(ai, a_end) = adjacent_vertices(*i, _graph); icount++; for (; ai != a_end; ++ai) { bool found = false; EdgeDescriptor e_descriptor; tie(e_descriptor, found) = edge(*i, *ai, _graph); if (found) { VertexDescriptor s = boost::source(e_descriptor, graph); VertexDescriptor t = boost::target(e_descriptor, graph); std::cout << graph[s].v_label << "," << graph[t].v_label << "\t "; // std::cout << e_descriptor << " " // << s << " " // << t << "\t"; } }std::cout << "\n" << std::endl; */ // std::cout << *i << "\t" << _graph[*i].v_label << std::endl; } std::cout << "Final Count: " << icount << std::endl; } /** * function to merge the 2 given node and the corresponding regions */ void RegionAdjacencyGraph::concatenateRegion( const cv::Mat &n_region, const cv::Point2i &centroids, cv::Mat &out_img) { int x_off = centroids.x - n_region.cols/2; int y_off = centroids.y - n_region.rows/2; for (int j = 0; j < n_region.rows; j++) { for (int i = 0; i < n_region.cols; i++) { out_img.at<cv::Vec3b>(y_off + j, x_off + i) = n_region.at<cv::Vec3b>(j, i); } } } /** * compute the histogram */ void RegionAdjacencyGraph::computeHistogram( const cv::Mat &src, cv::Mat &hist, bool isNormalized) { cv::Mat hsv; cv::cvtColor(src, hsv, CV_BGR2HSV); int hBin = 10; int sBin = 10; int histSize[] = {hBin, sBin}; float h_ranges[] = {0, 180}; float s_ranges[] = {0, 256}; const float* ranges[] = {h_ranges, s_ranges}; int channels[] = {0, 1}; cv::calcHist( &hsv, 1, channels, Mat(), hist, 2, histSize, ranges, true, false); if (isNormalized) { cv::normalize(hist, hist, 0, 1, NORM_MINMAX, -1, Mat()); } } /** * */ void RegionAdjacencyGraph::getImageGridLabels(std::vector<int> &labelMD) { VertexIterator i, end; for (tie(i, end) = vertices(this->graph); i != end; ++i) { labelMD.push_back(static_cast<int>(this->graph[*i].v_label)); } } // ----------------------------- void makeLabelImage( const std::vector<int> &labelMD, std::vector<Rect_<float> > region, cv::Size _sz) { if (labelMD.size() != region.size()) { std::cout << "Error Not Same Size" << std::endl; return; } cv::RNG rng(12345); int gen_size = labelMD.size() + 1; cv::Scalar color[gen_size]; for (int i = 0; i < gen_size; i++) { color[i] = cv::Scalar( rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); } cv::Mat image = cv::Mat(_sz, CV_8UC3); for (int i = 0; i < labelMD.size(); i++) { int label = labelMD.at(i); cv::Rect_<float> rect = region.at(i); cv::rectangle(image, rect, color[label], -1); } imshow("image", image); } /** * */ int main(int argc, const char *argv[]) { srand(time(NULL)); cv::Mat image = cv::imread("room.jpg"); if (image.empty()) { std::cout << "NO IMAGE FOUND!!" << std::endl; return EXIT_FAILURE; } cv::resize(image, image, cv::Size(640, 480)); int width = 20; int height = 15; vector<Mat> patches; std::vector<cv::Rect_<float> > region; int _num_element = (image.rows/height) * (image.cols/width); Mat centroid = Mat(_num_element, 2, CV_32F); int y = 0; for (int j = 0; j < image.rows; j += height) { for (int i = 0; i < image.cols; i += width) { Rect_<float> _rect = Rect_<float>(i, j, width, height); if (_rect.x + _rect.width <= image.cols && _rect.y + _rect.height <= image.rows) { Mat roi = image(_rect); patches.push_back(roi); region.push_back(_rect); Point2f _center = Point2f(_rect.x + _rect.width/2, _rect.y + _rect.height/2); // centroid.push_back(_center); centroid.at<float>(y, 0) = _center.x; centroid.at<float>(y++, 1) = _center.y; } } } cv::flann::KDTreeIndexParams indexParams(2); cv::flann::Index kdtree(centroid, indexParams); Mat neigbour_index; Mat dist; kdtree.knnSearch( centroid, neigbour_index, dist, 8, cv::flann::SearchParams(64)); RegionAdjacencyGraph rag; rag.generateRAG(patches, neigbour_index, centroid); rag.regionMergingGraph(patches, centroid); std::vector<int> labelMD; rag.getImageGridLabels(labelMD); makeLabelImage(labelMD, region, image.size()); imshow("original", image); waitKey(0); return EXIT_SUCCESS; } <file_sep>/spatial_change/octree_change_detection.cpp #include <pcl/point_cloud.h> #include <pcl/octree/octree.h> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <iostream> #include <vector> #include <ctime> int main (int argc, char** argv) { srand ((unsigned int) time (NULL)); // Octree resolution - side length of octree voxels float resolution = 32.0f; // Instantiate octree-based point cloud change detection class pcl::octree::OctreePointCloudChangeDetector<pcl::PointXYZRGB> octree (resolution); pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloudA (new pcl::PointCloud<pcl::PointXYZRGB> ); if (pcl::io::loadPCDFile<pcl::PointXYZRGB> ("test_pcd.pcd", *cloudA) == -1) //* load the file { PCL_ERROR ("Couldn't read file test_pcd.pcd \n"); return (-1); } // Add points from cloudA to octree octree.setInputCloud (cloudA); octree.addPointsFromInputCloud (); // Switch octree buffers: This resets octree but keeps previous tree structure in memory. octree.switchBuffers (); pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloudB (new pcl::PointCloud<pcl::PointXYZRGB> ); if (pcl::io::loadPCDFile<pcl::PointXYZRGB> ("test1_pcd.pcd", *cloudB) == -1) //* load the file { PCL_ERROR ("Couldn't read file test1_pcd.pcd \n"); return (-1); } // Add points from cloudB to octree octree.setInputCloud (cloudB); octree.addPointsFromInputCloud (); std::vector<int> newPointIdxVector; // Get vector of point indices from octree voxels which did not exist in previous buffer octree.getPointIndicesFromNewVoxels (newPointIdxVector); // Output points std::cout << "Output from getPointIndicesFromNewVoxels:" << std::endl; for (size_t i = 0; i < newPointIdxVector.size (); ++i) std::cout << i << "# Index:" << newPointIdxVector[i] << " Point:" << cloudB->points[newPointIdxVector[i]].x << " " << cloudB->points[newPointIdxVector[i]].y << " " << cloudB->points[newPointIdxVector[i]].z << std::endl; } <file_sep>/connect_component/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project( connect_component ) find_package( OpenCV REQUIRED ) set(HEADER_FILES main.cpp connectedcomponents.cpp precomp.hpp) add_executable( main ${HEADER_FILES} ) target_link_libraries( main ${OpenCV_LIBS} ) <file_sep>/openmp/section.cpp #include <omp.h> #include <iostream> #define N 20 int main(int argc, char *argv[]) { int i; float a[N], b[N], c[N], d[N]; /* Some initializations */ for (i=0; i < N; i++) { a[i] = i * 1.5; b[i] = i + 22.35; } #pragma omp parallel shared(a, b, c, d) private(i) { #pragma omp sections nowait { #pragma omp section for (i=0; i < N; i++) { std::cout << "THREAD S1: " << omp_get_thread_num() << std::endl; c[i] = a[i] + b[i]; } #pragma omp section for (i=0; i < N; i++) { std::cout << "THREAD S2: " << omp_get_thread_num() << std::endl; d[i] = a[i] * b[i]; } } /* end of sections */ } /* end of parallel section */ }
3f70c0da51d20dd5237e08196509340fa1b70101
[ "CMake", "Python", "C", "C++", "Shell" ]
60
C++
iKrishneel/sample_programs
f00d710dcc22b86d9fc3889b0080e404e44c026d
c5b6937d3ec5136afa5e6f415f463c061668d059
refs/heads/master
<file_sep>Pod::Spec.new do |s| s.name = "Pod1" s.version = "1.0.1" s.summary = "Cocoa Pods test" s.description = <<-DESC Example of making CocoaPods of your own code DESC s.homepage = "https://github.com/xialiuliu/Pod1" s.license = "MIT" # s.license = { :type => "MIT", :file => "FILE_LICENSE" } s.author = { "lcy" => "<EMAIL>" } s.platform = :ios s.platform = :ios, "7.0" s.source = { :git => "https://github.com/xialiuliu/Pod1.git", :tag => "1.0.1" } s.source_files = "Pod1", "Pod/**/*.{h,m}" s.exclude_files = "Pod1/Pod" # s.public_header_files = "Classes/**/*.h" s.requires_arc = true # s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" } #s.dependency "JSONKit", "~> 1.4" end
03a9bf96b0135a15468ab3d17286d33e6c76a6b9
[ "Ruby" ]
1
Ruby
xialiuliu/Pod1
2c79cad722d6258acd87a1faff7f95d2bd040cdf
4d3eebb2220e6a67d43e7b5fa479ce0b37a63ce0
refs/heads/master
<repo_name>thu/Template<file_sep>/README.md # MyBatis Spring Template Project.<file_sep>/src/main/java/demo/service/impl/UserServiceImpl.java package demo.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import demo.dao.GenericDao; import demo.model.User; import demo.service.UserService; @Service public class UserServiceImpl extends GenericServiceImpl<User, Integer> implements UserService { @Autowired public UserServiceImpl(GenericDao<User, Integer> genericDao) { super(genericDao); } @Override public User login(User user) { return genericDao.query("user.login", user); } }<file_sep>/src/main/java/demo/controller/UserController.java package demo.controller; import demo.model.User; import demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("user") public class UserController extends BaseController { @Autowired private UserService userService; @RequestMapping("login") private String login(User user) { user = userService.login(user); if (user != null) { session.setAttribute("user", user); if (user.getRole().equals("admin")) { return "redirect:/admin.jsp"; } if (user.getRole().equals("user")) { return "redirect:/user.jsp"; } } request.setAttribute("message", "invalid username or password."); return "/index.jsp"; } }<file_sep>/sql/db.sql DROP DATABASE IF EXISTS db_test; CREATE DATABASE db_test; DROP TABLE IF EXISTS db_test.user; CREATE TABLE db_test.user ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT 'PK', username VARCHAR(255) NOT NULL COMMENT '', password VARCHAR(255) NOT NULL COMMENT '', role VARCHAR(255) NOT NULL COMMENT 'admin; user' ); INSERT INTO db_test.user VALUE (NULL, 'admin', '123', 'admin'); INSERT INTO db_test.user VALUE (NULL, 'user', '123', 'user'); SELECT * FROM db_test.user;
8e17a1830458d63516b353251f3b14ea753d5728
[ "Markdown", "Java", "SQL" ]
4
Markdown
thu/Template
cddf02506f88678d62a066490672198c6cec9b02
aeac188d0a108f3faaa9a0355123d3a9082fb44a
refs/heads/master
<file_sep>package com.jun.booktransaction.bean; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "tb_major") public class MajorBean implements Serializable { /** * 专业表 */ private static final long serialVersionUID = 5349026679182550972L; /** * 专业表对应的id,他是uuid生成策略 */ private String id; public static final String ATTR_ID = "id"; /** * 专业名字字段 */ private String majorName; public static final String ATTR_MAJOR_NAME = "major_name"; /** * 所属的表的ID */ private String belongDepartmentId; public static final String ATTR_BELONG_DEPARTMENT_ID = "belongDepartmentId"; @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid") @Column(name = "id") public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name = "major_name") public String getMajorName() { return majorName; } public void setMajorName(String majorName) { this.majorName = majorName; } @Column(name = "belongDepartmentId") public String getBelongDepartmentId() { return belongDepartmentId; } public void setBelongDepartmentId(String belongDepartmentId) { this.belongDepartmentId = belongDepartmentId; } } <file_sep>package com.jun.file.util; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.jun.file.constant.Constant; public class DoNoLogin { public static void print(HttpServletResponse resp) { PrintWriter printWriter; try { printWriter = resp.getWriter(); BaseEntity baseEntity = new BaseEntity(Constant.STATUS_NO_LOGIN, "您还没有登录", "fail"); Gson gson2 = new Gson(); String jsonString = gson2.toJson(baseEntity); printWriter.print(jsonString); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package com.jun.booktransaction.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "tb_order_item") public class OrderItemBean { private String id;// 唯一标识ID public static final String ATTR_ID = "id"; private String belongOrder;// 所属的订单ID public static final String ATTR_BELONG_ORDER = "belongOrder"; private String belongUserName;// 所属的用户ID public static final String ATTR_BELONG_USER_NAME = "belongUserName"; private String belongMajorId;// 所属的课程 public static final String ATTR_BELONG_MAJOR_ID = "belongMajorId"; private int belongJuniorClass;// 所属的年级 public static final String ATTR_BELONG_JUNIOR_CLASS = "belongJuniorClass"; private String bookName;// 书名 public static final String ATTR_BOOK_NAME = "bookName"; private int oldDegree;// 新旧程度 public static final String ATTR_OLD_DEGREE = "oldDegree"; private int haveExerciseBook;// 是否有练习册 public static final String ATTR_HAVE_EXERCISE_BOOK = "haveExerciseBook"; private double price;// 价格 public static final String ATTR_PRICE = "price"; private String describle;// 描述 public static final String ATTR_DESCRIBLE = "describle"; private String projectId; public static final String ATTR_PROJECT_ID = "projectId"; @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid") @Column(name = "id") public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name = "belongOrder") public String getBelongOrder() { return belongOrder; } public void setBelongOrder(String belongOrder) { this.belongOrder = belongOrder; } @Column(name = "belongUserName") public String getBelongUserName() { return belongUserName; } public void setBelongUserName(String belongUserName) { this.belongUserName = belongUserName; } @Column(name = "belongJuniorClass") public int getBelongJuniorClass() { return belongJuniorClass; } public void setBelongJuniorClass(int belongJuniorClass) { this.belongJuniorClass = belongJuniorClass; } @Column(name = "bookName") public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } @Column(name = "oldDegree") public int getOldDegree() { return oldDegree; } public void setOldDegree(int oldDegree) { this.oldDegree = oldDegree; } @Column(name = "haveExerciseBook") public int getHaveExerciseBook() { return haveExerciseBook; } public void setHaveExerciseBook(int haveExerciseBook) { this.haveExerciseBook = haveExerciseBook; } @Column(name = "price") public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Column(name = "belongMajorId") public String getBelongMajorId() { return belongMajorId; } public void setBelongMajorId(String belongMajorId) { this.belongMajorId = belongMajorId; } @Column(name = "projectId") public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } @Column(name = "describle") public String getDescrible() { return describle; } public void setDescrible(String describle) { this.describle = describle; } } <file_sep>package com.jun.booktransaction.bean; import java.util.List; public class DepartmentAndMajor { private List<DepartmentBean> departmentBeans; private List<MajorBean> majorBeans; public DepartmentAndMajor(){ } public DepartmentAndMajor(List<DepartmentBean> departmentBeans,List<MajorBean> majorBeans){ this.departmentBeans = departmentBeans; this.majorBeans = majorBeans; } public List<DepartmentBean> getDepartmentBeans() { return departmentBeans; } public void setDepartmentBeans(List<DepartmentBean> departmentBeans) { this.departmentBeans = departmentBeans; } public List<MajorBean> getMajorBeans() { return majorBeans; } public void setMajorBeans(List<MajorBean> majorBeans) { this.majorBeans = majorBeans; } } <file_sep>package com.jun.booktransaction.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "tb_project") public class ProjectBean { private String id; public static final String ATTR_ID = "id"; private String projectName; public static final String ATTR_PROJECT_NAME = "projectName"; private String belongMajorName; public static final String ATTR_BELONG_MAJOR_NAME = "belongMajorName"; private int belongJuniorClss; public static final String ATTR_BELONG_JUNIOR_CLSS = "belongJuniorClss"; private String belongMajorId; public static final String ATTR_BELONG_MAJOR_ID = "belongMajorId"; @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid") @Column(name = "id") public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name = "project_name") public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } @Column(name = "belongMajorName") public String getBelongMajorName() { return belongMajorName; } public void setBelongMajorName(String belongMajorName) { this.belongMajorName = belongMajorName; } @Column(name = "belongJuniorClss") public int getBelongJuniorClss() { return belongJuniorClss; } public void setBelongJuniorClss(int belongJuniorClss) { this.belongJuniorClss = belongJuniorClss; } @Column(name = "belongMajorId") public String getBelongMajorId() { return belongMajorId; } public void setBelongMajorId(String belongMajorId) { this.belongMajorId = belongMajorId; } } <file_sep>package com.jun.file.dao; import com.jun.booktransaction.bean.MajorBean; public class MajorDao extends BaseDao{ @Override public Class<MajorBean> getT() { return MajorBean.class; } } <file_sep>package com.jun.book.servlet; import java.util.Date; import java.util.HashMap; import java.util.List; import com.jun.booktransaction.bean.UserBean; import com.jun.file.dao.UserDao; import com.jun.file.util.BaseActionSupport; import com.jun.file.util.PrintObjectToJson; import com.jun.file.util.SessionUtils; public class UserAction extends BaseActionSupport { /** * 用户注册、登录、修改用户信息功能 */ private static final long serialVersionUID = 1558439185764539275L; private String userName;// 账号 private String psw;// 密码 private String remind = "";// 返回提示文字 private String verificationCode;// 验证码 private String majorId;// 专业ID private String nickName;// 昵称 private String grade; private String majorName;//专业名字 public String getRemind() { return remind; } public void setRemind(String remind) { this.remind = remind; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPsw() { return psw; } public void setPsw(String psw) { this.psw = psw; } public String getVerificationCode() { return verificationCode; } public void setVerificationCode(String verificationCode) { this.verificationCode = verificationCode; } public String getMajorId() { return majorId; } public void setMajorId(String majorId) { this.majorId = majorId; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } /** * 用户登录接口 * * @return * @throws Exception */ public void login() { System.out.println("userName=" + userName + " psw=" + psw); UserDao userDao = new UserDao(); HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put(UserBean.ATTR_USER_NAME, userName); List<UserBean> users = userDao.findList(hashMap); UserBean userBean = null; int status = 0; /** * Status状态码:1表示成功 2表示账号不存在 3表示密码错误 4表示账号被封 */ if (users == null || users.size() == 0) {// 账号不存在 status = 2; remind = "账号不存在"; } else { userBean = users.get(0); System.out.println("userName="+userBean.getUserName()+" psw="+userBean.getPsw()); if (userBean.getPsw().equals(psw)) {// 如果账号密码相同 if (userBean.getIsUseAble()) { status = 1;// 登录成功 SessionUtils.putSession(userBean); remind = "登录成功"; } else { status = 4;// 账号被封 remind = "账号被封"; } } else { status = 3;// 密码错误 remind = "密码错误"; } } PrintObjectToJson.print(response, status, remind, status==1?userBean:""); } /** * 用户注册,status 为判断码,1表示注册成功,2表示注册失败 */ public void register() throws Exception { HashMap<String, Object> where = new HashMap<String, Object>(); where.put(UserBean.ATTR_USER_NAME, userName); UserDao userDao = new UserDao(); List<UserBean> userBeans = userDao.findList(where); UserBean userBean = null; int status = 0; if (userBeans != null && userBeans.size() > 0) {// 这里表明,存在这个注册用户,不能注册 status = 2; remind = "已经存在这个用户"; } else {// 不存在这个用户,可以注册 status = 1; userBean = new UserBean(); userBean.setGrade(grade); userBean.setIsUseAble(true); userBean.setIsVip(0); userBean.setMajorId(majorId); userBean.setNickName(nickName); userBean.setPsw(psw); userBean.setRegisterDate(new Date().getTime()); userBean.setUserName(userName); userBean.setMajorName(majorName); userDao.save(userBean); remind = "注册成功"; SessionUtils.putSession(userBean); } PrintObjectToJson.print(response, status, remind, userBean == null ? "" : userBean); } /** * 退出登录 * * @throws Exception */ public void loginOut() throws Exception { SessionUtils.clearSession(request); remind = "退出登录成功"; PrintObjectToJson.print(response, 1, remind, ""); } /** * 修改用户信息,status为状态码,1表示修改成功,2表示登录过期或者未登录 */ public void updateUserMessage() throws Exception { int status = 0; UserBean sessionBean = SessionUtils.getSession(); UserBean updateUserBean = null; if (sessionBean == null || sessionBean.getUserName() == null) {// 这说明未登录,或者没有这个用户 status = 2; remind = "用户未登录,或者登录失效"; } else {// 已经登录 UserDao userDao = new UserDao(); HashMap<String, Object> where = new HashMap<String, Object>(); where.put(UserBean.ATTR_USER_NAME, sessionBean.getUserName()); List<UserBean> userBeans = userDao.findList(where); updateUserBean = userBeans.get(0); updateUserBean.setGrade(grade); updateUserBean.setNickName(nickName); updateUserBean.setPsw(psw); userDao.upsert(updateUserBean); remind = "修改成功"; } PrintObjectToJson.print(response, status, remind, updateUserBean == null ? "" : updateUserBean); } /** * 获取用户基本信息,status为1表示获取成功,2表示获取失败 */ public void getUserMessage(){ UserBean userBean = SessionUtils.getSession(); int status = 0; if (userBean == null) { status = 2; remind = "您还未登录"; }else { status = 1; remind = "登录成功"; } PrintObjectToJson.print(response, status, remind, userBean == null ?"":userBean); } public String getMajorName() { return majorName; } public void setMajorName(String majorName) { this.majorName = majorName; } } <file_sep>package com.jun.book.servlet; import java.util.HashMap; import java.util.List; import java.util.Random; import com.jun.booktransaction.bean.MajorBean; import com.jun.booktransaction.bean.ProjectBean; import com.jun.file.dao.MajorDao; import com.jun.file.dao.ProjectDao; import com.jun.file.util.BaseActionSupport; import com.jun.file.util.PrintObjectToJson; public class ProjectAction extends BaseActionSupport { /** * */ private static final long serialVersionUID = 2689166193391255151L; private String majorId; private int belongJuniorCalss; private String projectName; private String majorName; public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getMajorId() { return majorId; } public void setMajorId(String majorId) { this.majorId = majorId; } public void findAllProject() { PrintObjectToJson.print(response, 1, "返回所有课程成功", new ProjectDao().findList(new HashMap<String, Object>())); } public int getBelongJuniorCalss() { return belongJuniorCalss; } public void setBelongJuniorCalss(int belongJuniorCalss) { this.belongJuniorCalss = belongJuniorCalss; } public void findProjectByMajorId() { HashMap<String, Object> map = new HashMap<String, Object>(); map.put(ProjectBean.ATTR_BELONG_MAJOR_ID, majorId); if (belongJuniorCalss != -1) { map.put(ProjectBean.ATTR_BELONG_JUNIOR_CLSS, Integer.valueOf(belongJuniorCalss)); } PrintObjectToJson.print(response, 1, "返回查询的课程成功", new ProjectDao().findList(map)); } public void insertProject() { ProjectBean projectBean = new ProjectBean(); projectBean.setBelongJuniorClss(belongJuniorCalss); projectBean.setBelongMajorName(majorName); projectBean.setProjectName(projectName); projectBean.setBelongMajorId(majorId); new ProjectDao().save(projectBean); PrintObjectToJson.print(response, 1, "插入成功", projectBean); } public void createProject() { List<MajorBean> majorBeans = new MajorDao() .findList(new HashMap<String, Object>()); for (int i = 0; i < majorBeans.size(); i++) { for (int j = 0; j < 5; j++) { ProjectBean projectBean = new ProjectBean(); projectBean .setBelongMajorName(majorBeans.get(i).getMajorName()); projectBean.setProjectName(majorBeans.get(i).getMajorName() + "课程" + j); projectBean.setBelongMajorId(majorBeans.get(i).getId()); int[] juniorClass = { 1, 2, 3, 4 }; projectBean.setBelongJuniorClss(juniorClass[new Random() .nextInt(4)]); new ProjectDao().save(projectBean); } } } public String getMajorName() { return majorName; } public void setMajorName(String majorName) { this.majorName = majorName; } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jun</groupId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.10.Final</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>2.3.14</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.14</version> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.12.1.GA</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>2.3.10</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.3.7</version> </dependency> </dependencies> <build> <defaultGoal>compile</defaultGoal> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <compilerId>groovy-eclipse-compiler</compilerId> <encoding>utf-8</encoding> <source>1.7</source> <target>1.7</target> </configuration> <dependencies> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-eclipse-compiler</artifactId> <version>2.9.2-01</version> </dependency> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-eclipse-batch</artifactId> <version>2.4.3-01</version> </dependency> </dependencies> </plugin> </plugins> <finalName>${project.artifactId}</finalName> </build> <artifactId>BookTransaction</artifactId> </project><file_sep>package com.jun.file.util; public class BaseEntity { private int status;//请求返回的状态码 private String sessionId;//这个是sessionID,因为我们不做持久化登录,所以不需要这个了 private String response;//响应的提示文字 private Object value;//返回真正内容 public BaseEntity(int status, String response, Object object, String sessionId) { this.status = status; this.response = response; this.value = object; this.sessionId = sessionId; } public BaseEntity(int status, String response, Object object) { this.status = status; this.response = response; this.value = object; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getResponse() { return response; } public void setResponse(String response) { this.response = response; } } <file_sep>package com.jun.file.dao; import com.jun.booktransaction.bean.OrderBean; public class OrderDao extends BaseDao{ @Override public Class<OrderBean> getT() { return OrderBean.class; } } <file_sep>package com.jun.book.servlet; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import org.hibernate.Query; import org.hibernate.Session; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.jun.booktransaction.bean.OrderBean; import com.jun.booktransaction.bean.OrderItemBean; import com.jun.booktransaction.bean.UserBean; import com.jun.file.dao.OrderDao; import com.jun.file.dao.OrderItemDao; import com.jun.file.util.BaseActionSupport; import com.jun.file.util.HibernateUtil; import com.jun.file.util.PrintObjectToJson; import com.jun.file.util.SessionUtils; /** * 订单action */ public class OrderAction extends BaseActionSupport { private static final long serialVersionUID = 8031997397426997137L; /** * 所有订单的Json */ private String orderItemBeans; /** * 联系人的电话号码 */ private String orderContactPhone; /** * 联系的QQ */ private String orderContactQQ; /** * 订单描述 */ private String orderDescribe; /** * 搜索订单key */ private String searchKey; /** * 订单发布状态 */ private boolean publishStatus; private String searchJuniorClassValue;// 查询的年级ID private String searchDepartmentValue;// 查询系的ID private String searchMajorValue;// 查询专业的ID private String searchProjectValue;// 查询课程的ID private int limit; private int offset; private String remind = ""; public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public boolean isPublishStatus() { return publishStatus; } public void setPublishStatus(boolean publishStatus) { this.publishStatus = publishStatus; } public String getSearchJuniorClassValue() { return searchJuniorClassValue; } public void setSearchJuniorClassValue(String searchJuniorClassValue) { this.searchJuniorClassValue = searchJuniorClassValue; } public String getSearchDepartmentValue() { return searchDepartmentValue; } public void setSearchDepartmentValue(String searchDepartmentValue) { this.searchDepartmentValue = searchDepartmentValue; } public String getSearchMajorValue() { return searchMajorValue; } public void setSearchMajorValue(String searchMajorValue) { this.searchMajorValue = searchMajorValue; } public String getSearchProjectValue() { return searchProjectValue; } public void setSearchProjectValue(String searchProjectValue) { this.searchProjectValue = searchProjectValue; } public String getOrderContactPhone() { return orderContactPhone; } public void setOrderContactPhone(String orderContactPhone) { this.orderContactPhone = orderContactPhone; } public String getOrderContactQQ() { return orderContactQQ; } public void setOrderContactQQ(String orderContactQQ) { this.orderContactQQ = orderContactQQ; } public String getOrderDescribe() { return orderDescribe; } public void setOrderDescribe(String orderDescribe) { this.orderDescribe = orderDescribe; } public String getSearchKey() { return searchKey; } public void setSearchKey(String searchKey) { this.searchKey = searchKey; } /** * 发布订单,status为1表示发布成功,status为2表示发布失败 */ public void publishOrder() { int status = 0; UserBean userBean = SessionUtils.getSession(); if (userBean == null) {// 没有登录的情况下 status = 2; remind = "您未登录"; } else {// 登录了,先删除订单信息,再添加订单信息 status = 1; OrderDao orderDao = new OrderDao(); OrderItemDao orderItemDao = new OrderItemDao(); HashMap<String, Object> orderMap = new HashMap<String, Object>(); orderMap.put(OrderBean.ATTR_BELONG_USER_NAME, userBean.getUserName()); List<OrderBean> orderBeans = orderDao.findList(orderMap); if (orderBeans != null && orderBeans.size() != 0) {// 存在数据,就删除 for (OrderBean orderBean2 : orderBeans) { Set<OrderItemBean> set = orderBean2.getSet(); for (OrderItemBean orderItemBean : set) { orderItemDao.delete(orderItemBean.getId()); } orderDao.delete(orderBean2.getId()); } } List<OrderItemBean> jsonOrderItemBeans = new ArrayList<OrderItemBean>(); System.out.println(orderItemBeans); try { Gson gson = new Gson(); jsonOrderItemBeans = gson.fromJson(orderItemBeans, new TypeToken<List<OrderItemBean>>() { }.getType()); } catch (Exception e) { System.err.println(e.toString()); } if (jsonOrderItemBeans == null || jsonOrderItemBeans.size() == 0) {// 这里我们判断解析的图书条数是否为空或者为0,如果为空,我们就放弃保存。 PrintObjectToJson.print(response, status, remind, ""); return; } OrderBean orderBean = new OrderBean(); orderBean.setSet(new HashSet<OrderItemBean>(jsonOrderItemBeans)); orderBean.setBelongUserName(userBean.getUserName()); orderBean.setContactPhone(orderContactPhone); orderBean.setContactQQ(orderContactQQ); orderBean.setCreateDate(new Date().getTime()); orderBean.setOrderDescribe(orderDescribe); orderBean.setBelongUserMajorName(userBean.getMajorName()); orderBean.setBelongUserMajorId(userBean.getMajorId()); orderBean.setPublishStatus(true); orderBean.setBelongUserJunirClass(userBean.getGrade()); orderBean.setBelongUserNickName(userBean.getNickName()); String includeBookName = ""; String includeJuniorClass = ""; for (OrderItemBean orderItemBean : jsonOrderItemBeans) { includeBookName = includeBookName + orderItemBean.getBookName() + ","; includeJuniorClass = includeJuniorClass + orderItemBean.getBelongJuniorClass() + ","; } orderBean.setIncludeBookName(includeBookName); orderBean.setIncludeJuniorClass(includeJuniorClass); orderBean.setOrderItemSize(jsonOrderItemBeans == null ? 0 : jsonOrderItemBeans.size()); orderDao.save(orderBean);// 填充订单 } PrintObjectToJson.print(response, status, remind, ""); } // /** // * 生成测试订单 // */ // public void createOrder() { // int status = 0; // UserBean userBean = SessionUtils.getSession(); // List<OrderItemBean> orderItemBeans = new ArrayList<OrderItemBean>(); // OrderBean orderBean = new OrderBean(); // if (userBean == null || userBean.getUserName().equals("")) {// 没有登录的情况下 // status = 2; // remind = "您未登录"; // } else {// 登录了,先删除订单信息,再添加订单信息 // System.out.println(userBean.getUserName() + "\n"); // System.out.println(orderContactPhone + "\n"); // System.out.println(orderContactQQ + "\n"); // System.out.println(new Date().getTime() + "\n"); // System.out.println(orderDescribe + "\n"); // OrderDao orderDao = new OrderDao(); // OrderItemDao orderItemDao = new OrderItemDao(); // orderBean.setBelongUserName(userBean.getUserName()); // orderBean.setContactPhone(orderContactPhone); // orderBean.setContactQQ(orderContactQQ); // orderBean.setCreateDate(new Date().getTime()); // orderBean.setOrderDescribe(orderDescribe); // orderBean.setPublishStatus(true); // orderDao.save(orderBean);// 填充订单 // for (int i = 0; i < 10; i++) {// 填充书籍 // OrderItemBean orderItemBean = new OrderItemBean(); // orderItemBean.setBelongJuniorClass(1); // orderItemBean.setBelongMajorId(userBean.getMajor()); // orderItemBean.setBelongUserName(userBean.getUserName()); // orderItemBean.setBookName("书名" + i); // orderItemBean.setDescrible("这是描述" + i); // orderItemBean.setHaveExerciseBook(1); // orderItemBean.setOldDegree(90); // orderItemBean.setPrice(10.00); // orderItemDao.save(orderItemBean); // orderItemBeans.add(orderItemBean); // } // } // OrderAndOrderItemBean orderAndOrderItemBean = new // OrderAndOrderItemBean(); // orderAndOrderItemBean.setOrderBean(orderBean); // orderAndOrderItemBean.setOrderItemBeans(orderItemBeans); // PrintObjectToJson // .print(response, status, remind, orderAndOrderItemBean); // } /** * 获取我自己的订单,status=1表示获取成功,status=2表示未登录,或者登录失败 */ public void getMyOrder() { UserBean userBean = SessionUtils.getSession(); int status = 0; List<OrderBean> orderBeans = null; if (userBean == null) {// 没有登录 status = 2;// 未登录 remind = "未登录"; } else { System.out.println(userBean.getUserName()); status = 1; remind = "获取数据成功!"; OrderDao orderDao = new OrderDao(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put(OrderBean.ATTR_BELONG_USER_NAME, userBean.getUserName()); orderBeans = orderDao.findList(map); } if (orderBeans != null && orderBeans.size() > 0) { PrintObjectToJson .print(response, status, remind, orderBeans.get(0)); } else { PrintObjectToJson.print(response, status, remind, new OrderBean()); } } /** * 根据条件获取订单,如果需要这个条件的全部,那么就 不添加這個搜索條件 */ public void getAllOrderByCondition() { String hql = "select orders from OrderBean as orders where orders.publishStatus=true and orders.orderItemSize>0"; System.out.println("================" + searchMajorValue + "============="); if (searchMajorValue == null || searchMajorValue.equals("-1") || searchMajorValue.equals("")) {// 搜索的专业,如果为-1或者为空,就表示返回所有的值 } else {// 表示筛选年级和课程 hql = hql + " and orders.belongUserMajorName like '%" + searchMajorValue + "%'"; if (searchJuniorClassValue != null && !searchJuniorClassValue.equals("-1") && !searchJuniorClassValue.equals("")) {// 搜索的年级,-1表示搜索所有的值,不等于-1则表示需要添加限定条件 hql = hql + " and orders.includeJuniorClass like '%" + searchJuniorClassValue + "%'"; if (searchProjectValue != null && !searchProjectValue.equals("-1") && !searchProjectValue.equals("")) {// 搜索的课程,01表示搜索所有的值,不等于-1表示需要添加限定条件 hql = hql + " and orders.includeBookName like '%" + searchProjectValue + "%'"; } } } Session session = HibernateUtil.getSession(); Query query = session.createQuery(hql); query.setFirstResult(offset); query.setMaxResults(offset + limit); @SuppressWarnings("unchecked") List<OrderBean> orderBeans = query.list(); int status = 1; remind = "获取数据成功"; PrintObjectToJson.print(response, status, remind, orderBeans); System.out.println("----------------" + query.toString() + "--------------------"); System.out.println("----------------" + hql + "--------------------"); } /** * 搜索订单 */ public void searchOrder() { String sql = "select orders from OrderBean as orders where orders.publishStatus=true and orders.orderItemSize>0 and orders.includeBookName like ?"; Session session = HibernateUtil.getSession(); Query query = session.createQuery(sql); query.setString(0, "%" + searchKey + "%"); query.setFirstResult(offset); query.setMaxResults(limit + offset); @SuppressWarnings("unchecked") List<OrderBean> orderBeans = query.list(); PrintObjectToJson.print(response, 1, remind, orderBeans == null ? "" : orderBeans); System.out.println(query.toString()); } public void setPublishOrderStatus() { UserBean userBean = SessionUtils.getSession(); int status = 0; if (userBean == null) { status = 2; remind = "您还未登录"; } else { status = 1; System.out.println(userBean.getUserName()); System.out.println(publishStatus); HashMap<String, Object> where = new HashMap<String, Object>(); where.put(OrderBean.ATTR_PUBLISH_STATUS, false); where.put(OrderBean.ATTR_BELONG_USER_NAME, userBean.getUserName()); HashMap<String, Object> fiedls = new HashMap<String, Object>(); fiedls.put(OrderBean.ATTR_PUBLISH_STATUS, publishStatus); new OrderDao().update(where, fiedls); remind = "修改成功"; } PrintObjectToJson.print(response, status, remind, ""); } public String getOrderItemBeans() { return orderItemBeans; } public void setOrderItemBeans(String orderItemBeans) { this.orderItemBeans = orderItemBeans; } } <file_sep># BookTransaction 针对于我们学校的一个二手教材交易系统 系统架构为Struts+hibernate,前端采用ajax和后端交互。 欢迎Follow我们O(∩_∩)OO(∩_∩)O~ 网站地址为:www.shoumaiba.com email:<EMAIL> qq:2890974079(后端开发) <file_sep>// 添加一个验证器 (function ($) { jQuery.validator.addMethod("equalToPsw", function(value, element, old) { console.log(old); if( hex_md5( value ) === $(old).val() ) return this.optional(element); else return false; }, "和原来的密码不一样"); })(jQuery); // var URL = 'http://192.168.1.108:8080'; var URL = ''; // 日期格式化工具 Date.prototype.format = function (fmt) { //author: meizz var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } jQuery(document).ready(function($) { // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 页面初始化 // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 查看是否有cookie 如果有cookie则直接登录 if( $.cookie('user') ) { var user = $.parseJSON( $.cookie('user') ); $.ajax({ url:URL+"/BookTransaction_Service/loginAction" ,type : 'post' ,data:{ userName: user.userName ,psw : user.psw } ,dataType:'json' ,success:function (json) { if(json.status != 1) loginError.text( json.response ); else if( json.status == 1){ var user = json.value; // after login afterLogin(user); } } }); } var departmentOptions = []; var departmentButtons = []; var departmentObject = {}; // 初始化轮播图 $('.carousel').carousel(); // 获取所有的系和专业 $.ajax({ url: URL+'/BookTransaction_Service/getAllDepartmentAndMajor', async: false, dataType:'json' }) .done(function (depts) { depts = depts.value; departmentOptions.push('<option value=""></option>') $.each(depts.departmentBeans,function (i,item) { departmentOptions.push( '<option value="'+item.id+'"> '+item.departmentName+' </option>' ); departmentButtons.push( '<button type="button" class="list-group-item" data-value="'+item.id+'" >'+item.departmentName+'</button>') departmentObject[item.id] = []; }); $.each(depts.majorBeans,function (i,item) { departmentObject[item.belongDepartmentId].push(item); }); $('select[name="departmentId"]').html( departmentOptions.join(' ') ); $('#departmentFilter').append( departmentButtons.join(' ') ); }) .fail(function(a1,a2,a3){ console.log(a1); console.log(a2); console.log(a2); }); // 初始显示所有的订单 SearchURL = '/BookTransaction_Service/getAllOrderByCondition.action' $('#nextPage').data('SearchURL' , SearchURL); $('#nextPage').data('page', 1); getOrder(URL+ SearchURL +'?offset=0&limit=10'); // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 筛选 // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 筛选按钮 $('#filterBtn').click(function(e) { $('#filterForm').slideToggle(); $(this).find('span').toggleClass('glyphicon-triangle-bottom') .toggleClass('glyphicon-triangle-top'); }); // 四级筛选器 var $seniorFilter = $('#seniorFilter'), $departmentFilter = $('#departmentFilter'), $majorFilter = $('#majorFilter'), $courseFilter = $('#courseFilter'); // 激活当前按钮 $('#departmentFilter,#majorFilter,#seniorFilter,#courseFilter') .on('click', 'button', function(e) { $(this).addClass('active').siblings('button').removeClass('active'); }); // 系过滤 $departmentFilter.on('click', 'button', function(e) { var key = $(this).data('value') var major = departmentObject[key]; $courseFilter.html('') $.each(major , function (i , item) { // 订单筛选时候使用的是专业名称而不是专业id $majorFilter.append('<button type="button" class="list-group-item" data-value="'+item.id+'">'+item.majorName+'</button>'); }); }); // 专业过滤 $majorFilter.on('click', 'button', function(e) { // 根据专业和年级更新课程信息 $seniorFilter.slideDown('fast'); if($seniorFilter.find('button.active').size() != 0){ var majorId = $(this).data('value'); var grade = $seniorFilter.find('button.active').data('value'); filterCourse(majorId,grade); } }); // 年级过滤 $seniorFilter.on('click', 'button', function(e) { // 展开$courseFilter // $departmentFilter.slideDown('fast'); if($majorFilter.find('button.active').size() != 0){ var majorName = $majorFilter.find('button.active').html(); var majorId = $majorFilter.find('button.active').data('value'); var grade = $(this).data('value'); var SearchURL = ''; if( grade === -1 ){ SearchURL = '/BookTransaction_Service/getAllOrderByCondition.action?searchMajorValue=' +majorName+'&searchJuniorClassValue=-1'; $('#nextPage').data('SearchURL' , SearchURL); $('#nextPage').data('page', 1); getOrder(SearchURL + '&offset=0&limit=10'); $courseFilter.html(''); $('#filterForm').slideUp(); } else{ filterCourse(majorId,grade); } } }); // 课程过滤 $courseFilter.on('click', 'button', function(e) { // 请求订单数据更新订单列表 var majorName = $majorFilter.find('button.active').html(); var grade = $seniorFilter.find('button.active').data('value'); var courseId = $(this).data('value'); var SearchURL = ''; SearchURL = '/BookTransaction_Service/getAllOrderByCondition.action?searchMajorValue=' +majorName+'&searchProjectValue='+courseId+'&searchJuniorClassValue='+grade; $('#nextPage').data('SearchURL' , SearchURL); $('#nextPage').data('page', 1); getOrder(SearchURL+'&offset=0&limit=10'); $('#filterForm').slideUp(); }); /** * 根据专业和年级更新课程信息 * @param {string} majorId 专业id * @param {string} grade 年级 */ function filterCourse(majorId,grade){ $courseFilter.html('<div class="list-group-item list-group-item-info">课程</div>'); $.ajax({ url:URL+'/BookTransaction_Service/findProjectByMajorId', data:{"majorId":majorId,"belongJuniorCalss":grade}, dataType:'json', async:false }) .done(function (json) { course = json.value; $courseFilter.append('<button type="button" class="list-group-item" data-value="-1">全部</button>'); $.each(course,function (i ,item) { // 请求订单时候是课程名而不是id $courseFilter.append('<button type="button" class="list-group-item" data-value="'+item.projectName+'">'+item.projectName+'</button>'); }); }); } // 展开效果 var $ajaxContent = $('#ajax-content'); $ajaxContent.on('click', '.expand-btn', function(e) { $(this).prev('table').fadeToggle('fast'); // 切换小箭头 $(this).find('span').toggleClass('glyphicon-triangle-bottom') .toggleClass('glyphicon-triangle-top'); }); // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 搜索 // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// $('input[name="search"]').on('keydown',function (e) { if (e.which===13) { keyWord = $(this).val(); SearchURL = '/BookTransaction_Service/searchOrder.action?searchKey=' + keyWord; getOrder(URL + '/BookTransaction_Service/searchOrder.action?searchKey=' + keyWord + '&offset=0&limit=10'); $('#nextPage').data('SearchURL' , SearchURL); $('#nextPage').data('page', 1); } }); $('#searchBtn').on('click',function (e) { keyWord = $('input[name="search"]').val(); SearchURL = '/BookTransaction_Service/searchOrder.action?searchKey=' + keyWord; getOrder(URL + '/BookTransaction_Service/searchOrder.action?searchKey=' + keyWord + '&offset=0&limit=10'); $('#nextPage').data('SearchURL' , SearchURL); $('#nextPage').data('page', 1); }); // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 注册 // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 弹出框 $("#navLoginBtn").click(function(e) { $("#loginModal").modal('show'); }); $("#navRegistBtn").click(function(e) { $("#registModal").modal('show'); }); //注册表单验证 $('#registForm').validate({ rules: { userName: { required: true, digits:true, maxlength: 11, minlength:11 }, nickName: { required:true, maxlength:20 }, psw: { required: true, minlength: 6 }, grade: { required: true }, majorId: { required: true } }, errorPlacement: function(error, element) { error.addClass('text-danger').appendTo(element.parent()); }, submitHandler: function(form) { ajaxData = {}; $(form).find('[name]').each(function(i,item) { var key = $(this).attr('name'); var val = $(this).val(); if( key === 'psw' ) { ajaxData[key] = hex_md5(val); } else { ajaxData[key] = val; } }); ajaxData.majorName = $(form).find('[name="majorId"]').find('option:selected').text(); $.post(URL+'/BookTransaction_Service/registerAction',ajaxData,function (json) { json = $.parseJSON(json); var user = json.value; var registError = $(form).find('.registError'); if(json.status === 1){ // 注册成功 afterLogin(user); $('#registModal').modal('hide'); }else { registError.text(josn.response); } }); } }); $('#registBtn').click(function(e) { $('#registForm').submit(); }); // 选择了系之后更新专业列表 $('select[name="departmentId"]').on('change', function(e) { var key = $(this).val() var major = departmentObject[key]; var majorOptions = []; $.each(major,function (i,item) { majorOptions.push( '<option value="'+item.id+'">'+item.majorName+'</option>' ) }) $('select[name="majorId"]').html(majorOptions.join(' ')); }); // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 登录 // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 登录表单 $('#loginForm').validate({ rules:{ userName:{ required:true, digits:true, maxlength:11, minlength:11 }, passWord:{ required:true, minlength:6 } }, errorPlacement: function(error, element) { error.addClass('text-danger').appendTo(element.parent().next('.error')); }, submitHandler: function(form) { var userName = $(form).find('[name="userName"]').val(); var psw = hex_md5 ( $(form).find('[name="passWord"]').val() ); var loginError = $(form).find('.loginError'); $.ajax({ url:URL+"/BookTransaction_Service/loginAction" ,type : 'post' ,data:{ userName: userName ,psw : psw } ,dataType:'json' ,success:function (json) { if(json.status != 1) loginError.text( json.response ); else if( json.status == 1){ var user = json.value; // after login afterLogin(user); } } }); } }); $('#loginBtn').click(function(e) { $('#loginForm').submit(); }); // 登录之后的一系列操作 function afterLogin( user ){ // 添加cookie // 存储用户信息 cookie保存7天 $.cookie('user',JSON.stringify(user),{ expires: 7 }); // 隐藏登录框 $('#loginModal').modal('hide'); $('#orginPassword').val(<PASSWORD>.psw); // 显示用户名和默认图片 $('.userName').find('a').html( '<img class="img-circle userPhoto" src="img/userphoto/default.png" height="30" width="30" > ' + user.nickName); $('.userName').show(); // 显示发布图书和退出按钮 $('.releaseBook,.loginOut').show(); // 隐藏登录注册按钮 $('.login,.regist').hide(); } // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 退出登录 // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 退出登录按钮 var $loginOut = $('.loginOut').eq(0), $sureLogout = $('#sureLogout'), $logoutModal = $('#logoutModal'); $loginOut.on('click', function() { $logoutModal.modal('show'); }); $sureLogout.on('click', function(e){ $logoutModal.modal('hide'); afterLogout(); }); function afterLogout () { $('.login,.regist').show(); $('.userName,.releaseBook,.loginOut').hide(); $.cookie('user','',{expires:-1}); $.get(URL+'/BookTransaction_Service/loginOutAction'); location.href = 'index.html'; } // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 修改个人资料 // ////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////// // 弹出修改框 $("#navModifyBtn").click(function(e) { $("#modifyModal").modal('show'); var user = $.parseJSON( $.cookie('user') ); $('#modifyForm').find('[name]').each(function (i,item) { var key = $(item).attr('name'); $(item).val( user[key] ); }); }); // 提交按钮 $('#modifyBtn').click(function(e) { $('#modifyForm').submit(); }); // 表单验证 $('#modifyForm').validate({ rules:{ nickName:{ required:true, maxlength:20 }, oldPassWord:{ required:true, minlength:6, equalToPsw:"#orgin<PASSWORD>" }, psw:{ required:true, minlength:6 }, grade:{ required:true }, major:{ required:true } }, errorPlacement: function(error, element) { error.addClass('text-danger').appendTo(element.parent().next('.error')); }, submitHandler: function(form) { var ajaxData = {}; $(form).find('[name]').each(function (i,item) { var key = $(item).attr('name'); var val = $(item).val(); if(key === 'psw') ajaxData[key] = hex_md5(val); else ajaxData[key] = val; }); $.ajax({ url: URL+'/BookTransaction_Service/updateUserMessageAction', type: 'post', dataType: 'json', data: ajaxData, }) .done(function(json) { $('#modifyModal').modal('hide'); var msg = json.response; $('#messageModal').find('modal-body').text(msg); setTimeout(function(){ $('#messageModal').modal('show'); },1000); var user = JSON.stringify ( $.cookie('user') ); for(key in ajaxData){ user[key] = ajaxData[key]; } }); } });//end of //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // 分页 //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// $('#nextPage').on('click', function(e) { var reg = /\?/; var SearchURL = $(this).data('SearchURL'); // var page = $(this).data('page'); var page = $('#ajax-content').find('.col-xs-12').size(); // 没有更多的数据了 // $(this).data('page',page+1); if(page % 10 !== 0) { $(this).text('没有更多了'); $(this).attr('disabled','disabled'); return; } var from = parseInt( page / 10) * 10; if( reg.test(SearchURL) ) { getOrder(URL + SearchURL + '&offset='+from+'&limit=10',true); } else{ getOrder(URL + SearchURL + '?offset='+from+'&limit=10',true); } }); //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // 获取订单信息并解析放入容器中 //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// function getOrder(url,method){ var method = method || false; var userInfoHTML = ''; var tfootHTML = ''; var labelHTML = ''; var tbodyHTML = ''; var orderHTML = ''; var grade = { "1" : "大一上", "2" : "大一下", "3" : "大二上", "4" : "大二下", "5" : "大三上", "6" : "大三下", "7" : "大四上", "8" : "大四下" } var $ajaxContent = $('#ajax-content'); $.getJSON(url) .done(function (json) { var orderData = json.value; console.log(orderData) // 如果method为true则将结果继续往后面叠加,不清空原来的数据 if(!method) $ajaxContent.html(''); if(orderData.length === 0) { $ajaxContent.html('<span class="text-danger">没有搜索到相关书籍</span>'); return; } $.each(orderData, function(i,item) { var userInfoHTML = ''; var tfootHTML = ''; var labelHTML = ''; var tbodyHTML = ''; var orderHTML = ''; var order = item; userInfoHTML = [ '<div class="panel-heading">', ' <div class="row">', ' <div class="col-xs-2">ID:'+ order.belongUserNickName +'</div>', ' <div class="col-xs-2">年级:'+grade[ order.belongUserJunirClass ]+'</div>', ' <div class="col-xs-6">专业:'+order.belongUserMajorName+'</div>', ' <div class="col-xs-2 ">日期:'+new Date(order.createDate).format('yyyy-MM-dd')+'</div>', ' </div>', '</div>' ].join(''); tfootHTML = [ '<tfoot>', ' <tr class="info">', ' <th colspan="5">', ' <div class="row">', ' <div class="col-xs-3">', ' 他(她)的QQ: <span class="qq">'+ order.contactQQ +'</span>', ' </div>', ' <div class="col-xs-3">', ' 他(她)的电话: <span class="phone">'+ order.contactPhone +'</span><br>', ' </div>', ' <div class="col-xs-6">', ' 订单描述:<span class="desc">'+order.orderDescribe+'</span>', ' </div>', ' </div>', ' </th>', ' </tr>', '</tfoot>' ].join(''); tbodyHTML += '<tbody>'; labelHTML += '<div class="panel-body"><h4 class="text-info">标签</h4><div class="tags f20">' $.each(order.set ,function (i,book) { tbodyHTML += '<tr> ' tbodyHTML += '<td> ' + book.bookName + ' </td>'; tbodyHTML += '<td> ' + book.oldDegree + '% </td>'; tbodyHTML += '<td> ' + book.haveExerciseBook + ' </td>'; tbodyHTML += '<td> ' + book.price + ' </td>'; tbodyHTML += '<td> ' + book.describle + ' </td>'; tbodyHTML += '</tr> ' labelHTML+= '<span class="label label-info mr10" style="display:inline-block;"> <i class="glyphicon glyphicon-tag f12"></i> '+book.bookName+' </span> \n'; }); tbodyHTML += '</tbody>'; labelHTML += '</div></div>'; orderHTML = [ '<div class="col-xs-12">', ' <div class="panel panel-default">', userInfoHTML, labelHTML, ' <table class="table table-hover table-striped none">', ' <thead>', ' <tr>', ' <th>书名</th>', ' <th>新旧程度</th>', ' <th>是否有练习</th>', ' <th>价格</th>', ' <th>说明</th>', ' </tr>', ' </thead>', tbodyHTML, tfootHTML, ' ', ' </table>', ' <div class="panel-footer tc expand-btn">', ' <span class="glyphicon glyphicon-triangle-bottom"></span> 展开查看该用户寄售的所有书籍', ' </div>', ' </div>', '</div>' ].join(''); $ajaxContent.append(orderHTML); });// end of 一个用户的订单 }) } }); // end of ready
3d5d1c5f197154e3e7be004f1d5205faa835d9a0
[ "Markdown", "Java", "JavaScript", "Maven POM" ]
14
Java
GitHubOverlord/BookTransaction
c030abbff54ce83aed020d95a3bfb21ace3756cd
55f4c86141e1e1a00431f7457f935a8b20ea0b9a
refs/heads/main
<repo_name>Beka-Bat1/weather-app<file_sep>/README.md # weather-app React-Native weather app ![watherApp1](https://imgur.com/AD230O5.png) ![weatherApp2](https://imgur.com/abgdFYw.png) <file_sep>/App.js /* eslint-disable prettier/prettier */ /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */ /* eslint-disable prettier/prettier */ import React, { useState } from "react"; import { View, StyleSheet, Alert, TouchableWithoutFeedback, Keyboard, } from "react-native"; import { useDispatch, useSelector } from "react-redux"; import { getWeather } from "./store/actions/weatherActions"; import Form from "./components/Form"; import Weather from "./components/Weather"; import LongWeatherData from "./components/LongWeatherData" const App = () => { const [search, setSearch] = useState(""); const [loading, setLoading] = useState(false); const [longDataVisible, setLongDataVisible] = useState(false); const dispatch = useDispatch(); const { data, error } = useSelector((state) => state.weather); const searchSubmitHandler = () => { if (search === "") { return Alert.alert("Validation", "City name is required!", [ { text: "OK" }, ]); } setLoading(true); dispatch( getWeather( search, () => setLoading(false), () => setLoading(false) ) ); setSearch(""); Keyboard.dismiss(); }; const longWeatherDataSubmit = () => { setLongDataVisible(!longDataVisible); Keyboard.dismiss(); }; return ( <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}> <View style={styles.container}> <Form search={search} onSetSearch={setSearch} onSubmit={searchSubmitHandler} /> <Weather loading={loading} data={data} error={error} longDataVisible={longDataVisible} longWeatherDataSubmit={longWeatherDataSubmit} /> </View> </TouchableWithoutFeedback> ); }; const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center", }, }); export default App; <file_sep>/components/Weather.js /* eslint-disable prettier/prettier */ import React from "react"; import { View, Text, StyleSheet, ActivityIndicator, Button } from "react-native"; import WeatherData from "./WeatherData"; import LongWeatherData from "./LongWeatherData"; const Weather = ({ loading, data, error, longDataVisible, longWeatherDataSubmit, }) => { if (error) { return ( <View style={styles.container}> <Text style={styles.error}>{error}</Text> </View> ); } if (!loading && !data) { return null; } return ( <View style={styles.container}> {/* if is loading show loading, if long data asked show, else show normal data */} {loading ? ( <ActivityIndicator size="large" color="#00d1b2" /> ) : longDataVisible ? ( <LongWeatherData data={data} /> ) : ( <WeatherData data={data} /> )} <Button title= {longDataVisible ? "Current Forecast" : "7 Day Forecast" } style={styles.boxLabel} onPress={longWeatherDataSubmit} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, paddingVertical: 20, }, error: { color: "red", fontSize: 20, textAlign: "center", }, boxLabel: { textTransform: "uppercase", fontSize: 12, letterSpacing: 2, marginBottom: 5, }, }); export default Weather;
d9827a2de94766c38d6e5e2b40275829aa69f9c5
[ "Markdown", "JavaScript" ]
3
Markdown
Beka-Bat1/weather-app
acf30ed580934a1cefe4653d1a79e9b8bc6e7904
0708f7dc21d1da27e7c2d9eaf2bd06a30696c7f1
refs/heads/master
<repo_name>maxence-charriere/client<file_sep>/news.go package main import ( "net/http" "time" "encoding/json" "github.com/murlokswarm/app" ) type NewsInfo struct { Id int64 Title string Image string Url string Author string AuthorLink string Author2 string Author2Link string Updated time.Time } // Hello implements app.Componer interface. type NewsList struct { Contents []NewsInfo Error string } func (h *NewsList) LoadData() error { // FIXME: load data from network resp, err := http.Get("http://godaily.org/api/v1/news") if err != nil { return err } defer resp.Body.Close() err = json.NewDecoder(resp.Body).Decode(&h.Contents) if err != nil { return err } return nil } // Render returns the HTML markup that describes the appearance of the // component. // It supports standard HTML and extends it slightly to handle other component // declaration or Golang callbacks. // Can be templated following rules from https://golang.org/pkg/text/template. func (h *NewsList) Render() string { err := h.LoadData() if err != nil { h.Error = err.Error() } return ` <div class="WindowLayout"> <div><RefreshButton></RefreshButton></div> {{if .Contents}} <ul class="contents"> {{range .Contents}} <li> <a href="{{.Url}}">{{.Title}}</a> - {{time .Updated "2006-01-02"}} </li> {{end}} </ul> {{else if .Error}} <div>Load data error: {{.Error}}</div> {{else}} <div>No data</div> {{end}} </div> ` } func init() { // Registers the Hello component. // Allows the app to create a Hello component when it finds its declaration // into a HTML markup. app.RegisterComponent(&NewsList{}) } <file_sep>/refresh.go package main import "github.com/murlokswarm/app" type RefreshButton struct { BKColor string List *NewsList } func (r *RefreshButton) Render() string { return `<div style="cursor:pointer;background-color:{{.BKColor}}" onclick="OnClick" class="btn_refresh" onmouseover="OnMouseOver" onmouseout="OnMouseOut" onmouseup="OnMouseUp" onmousedown="OnMouseDown">Refresh</div>` } func (r *RefreshButton) OnMouseOver(args app.MouseArg) { r.BKColor = "red" app.Render(r) } func (r *RefreshButton) OnMouseDown(args app.MouseArg) { r.BKColor = "green" app.Render(r) } func (r *RefreshButton) OnMouseUp(args app.MouseArg) { r.BKColor = "black" app.Render(r) } func (r *RefreshButton) OnMouseOut(args app.MouseArg) { r.BKColor = "" app.Render(r) } func (r *RefreshButton) OnClick(args app.MouseArg) { app.Render(r.List) } func init() { // Registers the Hello component. // Allows the app to create a Hello component when it finds its declaration // into a HTML markup. app.RegisterComponent(&RefreshButton{}) } <file_sep>/README.md # Introduce This is an experiment repository to test github.com/murlokswarm/app. It will get data from godaily.org/api/v1/news and display in the UI.
9d4eaa0c99e84378457212008d1dfc9c4d85159e
[ "Markdown", "Go" ]
3
Go
maxence-charriere/client
fe4ef20961b02fb39e8398a80624e7e94fa3961d
6459d957192ecda67fbb5db06f35da205bbee4e1
refs/heads/master
<repo_name>RicePavel/dvd<file_sep>/src/java/startup/Startup.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package startup; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import service.FirstTimeMarkService; import service.UserService; /** * * @author <NAME> */ @Component public class Startup implements ApplicationListener<ContextRefreshedEvent> { @Autowired private FirstTimeMarkService firstTimeMarkService; @Autowired private UserService userService; @Override public void onApplicationEvent(final ContextRefreshedEvent event) { if (firstTimeMarkService.inFirstTime()) { addTestUsers(); } } private void addTestUsers() { String login = "user1"; String password = "<PASSWORD>"; String name = "Иван"; String surname = "Иванов"; List<String> errors = new ArrayList(); userService.registration(login, password, name, surname, errors); login = "user2"; password = "<PASSWORD>"; name = "Петр"; surname = "Петров"; userService.registration(login, password, name, surname, errors); } } <file_sep>/src/java/entity/Disk.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entity; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; /** * * @author <NAME> */ @Entity @Table(name = "disk") public class Disk { @Id @javax.persistence.GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "disk_id") private Long diskId; @NotEmpty(message = "Не передан обязательный параметр - название") @Column(name = "name") private String name; @Column(name = "description") private String description; @NotNull @ManyToOne @JoinColumn(name = "owner_id") private User owner; @OneToMany(mappedBy = "disk") private List<TakenItem> takenItemList; public Long getDiskId() { return diskId; } public void setDiskId(Long diskId) { this.diskId = diskId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } public List<TakenItem> getTakenItemList() { return takenItemList; } public void setTakenItemList(List<TakenItem> takenItemList) { this.takenItemList = takenItemList; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } <file_sep>/src/java/dao/DiskDao.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import entity.Disk; import entity.TakenItem; import entity.User; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Property; import org.hibernate.criterion.Restrictions; import org.hibernate.criterion.Subqueries; import org.springframework.stereotype.Repository; /** * * @author <NAME> */ @Repository public class DiskDao extends Dao<Disk> { @Override public Class getSupportedClass() { return Disk.class; } public List<Disk> getFreeDisks(Long currentUserId) { /* DetachedCriteria subCrit = DetachedCriteria.forClass(TakenItem.class, "takenItem"); subCrit.createAlias("takenItem.disk", "td"); //subCrit.add(Property.forName("td.diskId").eq("11111")); Criteria crit = getCurrentSession().createCriteria(Disk.class, "disk"); //crit.add(Subqueries.notExists(subCrit)); return crit.list(); */ String hql = "from Disk d where not exists ( from TakenItem ti where ti.disk.diskId = d.diskId) and d.owner.userId != :userId "; Query query = getCurrentSession().createQuery(hql); query.setParameter("userId", currentUserId); return query.list(); } public List<Object[]> getAllDiskList(User user) { /* Criteria crit = currentSession().createCriteria(Disk.class, "disk"); crit. crit.createAlias("disk.takenItemList", "takenItem", JoinType.LEFT_OUTER_JOIN); crit.add(Restrictions.eq("disk.user.userId", user.getUserId())); return crit.list(); */ String hql = "select d, ti from Disk as d left join d.takenItemList as ti where d.owner.userId = :userId "; Query query = currentSession().createQuery(hql); query.setParameter("userId", user.getUserId()); return query.list(); } /** * диски, которые пользователь взял * @param user * @return */ public List<Disk> getDisksUserTake(User user) { /* DetachedCriteria subCrit = DetachedCriteria.forClass(TakenItem.class, "takenItem"); subCrit.add(Property.forName("takenItem.disk.diskId").eqProperty("disk.diskId")); subCrit.add(Property.forName("takenItem.user.userId").eq(user.getUserId())); Criteria crit = getCurrentSession().createCriteria(Disk.class); crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); crit.add(Subqueries.exists(subCrit)); return crit.list(); */ String hql = "from Disk as disk where exists (from TakenItem as ti where ti.disk.diskId = disk.diskId and ti.user.userId = :userId) "; Query query = currentSession().createQuery(hql); query.setParameter("userId", user.getUserId()); return query.list(); } /** * диски, которыми пользователь владеет * @param user * @return */ public List<Disk> getDisksByOwner(User user) { Criteria crit = getCurrentSession().createCriteria(Disk.class); crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); crit.add(Restrictions.eq("user.userId", user.getUserId())); return crit.list(); } }
7b48e172b2e6ad255eb5ed9a222f6278012732c6
[ "Java" ]
3
Java
RicePavel/dvd
128b8e005fea232e4380c523aec74554b355137b
d44b1fee2c3c36368c5d5ef04703abdfccb32ece
refs/heads/main
<file_sep>## Miscellaneous samples This folder contains various scripts that we used for different purposes but that are probably a little bit more complicated or bound to our infrastructure to serve as good samples. It's more like an unstructured collection of scripts we had used previously. <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 // // 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. /** * @fileoverview Wraps some octokit GitHub API calls. */ import {Gaxios, GaxiosPromise, GaxiosOptions} from 'gaxios'; import {Config} from './config.js'; import {debuglog} from 'util'; const debug = debuglog('repo'); export function getClient(config: Config) { const client = new Gaxios({ baseURL: config.baseUrl || 'https://api.github.com', headers: {Authorization: `token ${config.githubToken}`}, }); // Report rate limit information if NODE_DEBUG=repo set. let counter = 0; const request = client.request.bind(client); client.request = async (opts: GaxiosOptions): GaxiosPromise => { const resp = await request(opts); const rateLimit = resp.headers['x-ratelimit-limit'] ? Number(resp.headers['x-ratelimit-limit']) : 0; const rateLimitRemaining = resp.headers['x-ratelimit-remaining'] ? Number(resp.headers['x-ratelimit-remaining']) : 0; const reset = resp.headers['x-ratelimit-reset']; if (counter++ % 10 === 0) { debug( `GitHub rate limit: limit = ${rateLimit} remaining = ${rateLimitRemaining} reset epoch = ${reset}` ); } return resp; }; return client; } interface SearchReposResponse { items: { full_name: string; default_branch: string; }[]; } /** * Wraps some octokit GitHub API calls. */ export class GitHub { protected config: Config; protected client: Gaxios; constructor(config: Config) { this.config = config; this.client = getClient(config); } async fetchRepositoriesFromGitHub(): Promise<GitHubRepository[]> { if (!this.config.repos) { return []; } const repos = new Array<GitHubRepository>(); const type = 'public'; const proms = this.config.repos.map(async repo => { const org = repo.org; if (repo.name) { const res = await this.client.request<Repository>({ url: `/repos/${org}/${repo.name}`, }); repos.push(new GitHubRepository(this.client, res.data, org)); } else if (repo.regex) { const repoNameRegex = new RegExp(repo.regex); for (let page = 1; ; ++page) { const result = await this.client.request<Repository[]>({ url: `/orgs/${org}/repos`, params: {type, page, per_page: 100}, }); for (const restRepo of result.data) { if (restRepo.name.match(repoNameRegex)) { repos.push(new GitHubRepository(this.client, restRepo, org)); } } if (result.data.length < 100) { break; } } } else { throw new Error( 'Each organization in the config must provide either a name or a regex.' ); } }); await Promise.all(proms); return repos.filter(repo => !repo.repository.archived); } async fetchRepositoriesFromJson(): Promise<GitHubRepository[]> { if (!this.config.repoSearch) { return []; } const repoList = []; for (let page = 1; ; ++page) { const res = await this.client.request<SearchReposResponse>({ url: '/search/repositories', params: { per_page: 100, page, q: this.config.repoSearch, }, }); repoList.push( ...res.data.items.map(r => { return {name: r.full_name, branch: r.default_branch}; }) ); if (res.data.items.length < 100) { break; } } const repos = new Array<GitHubRepository>(); for (const repo of repoList) { const [org, name] = repo.name.split('/'); if (!org || !name) { console.warn(`Warning: repository name ${repo} cannot be parsed.`); } const repository = { owner: {login: org}, name, ssh_url: `git<EMAIL>:${org}/${name}.git`, default_branch: repo.branch, }; repos.push(new GitHubRepository(this.client, repository, org)); } return repos; } /** * List all public repositories of the organization that match the regex * filter. Organization name and regex are taken from the configuration file. * @returns {GitHubRepository[]} Repositories matching the filter. */ async getRepositories(): Promise<GitHubRepository[]> { const repos = new Array<GitHubRepository>(); const githubRepos = await this.fetchRepositoriesFromGitHub(); if (githubRepos.length > 0) { console.log(`Loaded ${githubRepos.length} repositories from GitHub.`); } const jsonRepos = await this.fetchRepositoriesFromJson(); if (jsonRepos.length > 0) { console.log(`Loaded ${jsonRepos.length} repositories from JSON config.`); } const unique: {[key: string]: GitHubRepository} = {}; for (const repo of githubRepos.concat(jsonRepos)) { const name = `${repo.organization}/${repo.name}`; if (!(name in unique)) { repos.push(repo); unique[name] = repo; } } if (repos.length === 0) { throw new Error( 'No repositories configured. Use config.repos and/or config.repoSearch.' ); } console.log(`Total ${repos.length} unique repositories loaded.`); return repos; } } /** * Wraps some octokit GitHub API calls for the given repository. */ export class GitHubRepository { repository: Repository; organization: string; baseBranch: string; protected client: Gaxios; /** * Creates an object to work with the given GitHub repository. * @constructor * @param {Object} octokit OctoKit instance. * @param {Object} repository Repository object, as returned by GitHub API. * @param {string} organization Name of GitHub organization. */ constructor(client: Gaxios, repository: Repository, organization: string) { this.client = client; this.repository = repository; this.organization = organization; this.baseBranch = this.repository.default_branch; } /** * Returns the Repository object as returned by GitHub API. * @returns {Object} Repository object. */ getRepository() { return this.repository; } /** * Returns the name of repository. * @returns {string} Name of repository. */ get name() { return this.repository.name; } /** * Returns contents of the file in GitHub repository * @param {string} path Path to file in repository. * @returns {Object} File object, as returned by GitHub API. */ async getFile(path: string) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/contents/${path}`; const res = await this.client.request<File>({url}); return res.data; } /** * Returns contents of the file from the given branch in GitHub repository. * @param {string} branch Branch name. * @param {string} path Path to file in repository. * @returns {Object} File object, as returned by GitHub API. */ async getFileFromBranch(branch: string, path: string) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/contents/${path}`; const res = await this.client.request<File>({url, params: {ref: branch}}); return res.data; } /** * Lists open pull requests in the repository. * @param {string} state Pull request state (open, closed), defaults to open. * @returns {Object[]} Pull request objects, as returned by GitHub API. */ async listPullRequests(state: 'open' | 'closed' | 'all' = 'open') { const owner = this.repository.owner.login; const repo = this.repository.name; const prs: PullRequest[] = []; const url = `/repos/${owner}/${repo}/pulls`; for (let page = 1; ; ++page) { const result = await this.client.request<PullRequest[]>({ url, params: {state, page}, }); if (result.data.length === 0) { break; } prs.push(...result.data); } return prs; } /** * List issues on a repository. * @param {string} state Issue state (open, closed), defaults to open. * @returns {Object[]} Issue objects, as returned by GitHub API. */ async listIssues(state: 'open' | 'closed' | 'all' = 'open') { const owner = this.repository.owner.login; const repo = this.repository.name; const prs: Issue[] = []; const url = `/repos/${owner}/${repo}/issues`; for (let page = 1; ; ++page) { const result = await this.client.request<Issue[]>({ url, params: {state, page}, }); if (result.data.length === 0) { break; } prs.push(...result.data); } return prs; } /** * Returns latest commit to the default branch of the GitHub repository. * @param {string} [customBranch] Specify a branch to use other than the default base branch * @returns {Object} Commit object, as returned by GitHub API. */ async getLatestCommitToBaseBranch(customBranch?: string) { const owner = this.repository.owner.login; const repo = this.repository.name; const ref = `heads/${customBranch || this.baseBranch}`; const shaUrl = `/repos/${owner}/${repo}/commits/${ref}`; const {data: sha} = await this.client.request<string>({ url: shaUrl, headers: {accept: 'application/vnd.github.VERSION.sha'}, }); const url = `/repos/${owner}/${repo}/commits/${sha}`; const result = await this.client.request({url}); return result.data; } /** * Creates a new branch in the given GitHub repository. * @param {string} branch Name of the new branch. * @param {string} sha SHA of the main commit to base the branch on. * @returns {Object} Reference object, as returned by GitHub API. */ async createBranch(branch: string, sha: string) { const owner = this.repository.owner.login; const repo = this.repository.name; const ref = `refs/heads/${branch}`; const url = `/repos/${owner}/${repo}/git/refs`; const result = await this.client.request({ url, method: 'POST', data: {ref, sha}, }); return result.data; } /** * Deletes the given branch. * @param {string} branch Name of the branch. */ async deleteBranch(branch: string) { const owner = this.repository.owner.login; const repo = this.repository.name; const ref = `heads/${branch}`; const url = `/repos/${owner}/${repo}/git/refs/${ref}`; await this.client.request({ url, method: 'DELETE', }); } /** * Merges one branch into another. * @param {string} base Name of branch to merge info. * @param {string} head Name of branch to merge from. * @returns {Object} Commit object of the merge commit, as returned by GitHub * API. */ async updateBranch(base: string, head: string) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/merges`; const result = await this.client.request({ url, method: 'POST', data: {base, head}, }); return result.data; } /** * Creates a new file in the given branch and commits the change to * GitHub. * @param {string} branch Branch name to update. * @param {string} path Path to an existing file in that branch. * @param {string} message Commit message. * @param {string} content Base64-encoded content of the file. * @returns {Object} Commit object, as returned by GitHub API. */ async createFileInBranch( branch: string, path: string, message: string, content: string ) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/contents/${path}`; const result = await this.client.request({ url, method: 'PUT', data: { message, content, branch, }, }); return result.data; } /** * Updates an existing file in the given branch and commits the change to * GitHub. * @param {string} branch Branch name to update. * @param {string} path Path to an existing file in that branch. * @param {string} message Commit message. * @param {string} content Base64-encoded content of the file. * @param {string} sha SHA of the file to be updated. * @returns {Object} Commit object, as returned by GitHub API. */ async updateFileInBranch( branch: string, path: string, message: string, content: string, sha: string ) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/contents/${path}`; const result = await this.client.request({ url, method: 'PUT', data: {message, content, sha, branch}, }); return result.data; } /** * Creates a new pull request from the given branch to the base branch. * @param {string} branch Branch name to create a pull request from. * @param {string} title Pull request title. * @param {string} body Pull request body. * @returns {Object} Pull request object, as returned by GitHub API. */ async createPullRequest(branch: string, title: string, body: string) { const owner = this.repository.owner.login; const repo = this.repository.name; const head = branch; const base = this.baseBranch; const url = `/repos/${owner}/${repo}/pulls`; const result = await this.client.request({ url, method: 'POST', data: { head, base, title, body, }, }); return result.data; } /** * Request a review for the existing pull request. * @param {number} prNumber Pull request number (the one visible in its URL). * @param {string[]} reviewers Reviewers' GitHub logins for the pull request. * @returns Review object, as returned by GitHub API. */ async requestReview(prNumber: number, reviewers: string[]) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/pulls/${prNumber}/requested_reviewers`; const result = await this.client.request({ url, method: 'POST', data: { reviewers, }, }); return result.data; } /** * Approves the given pull request. * @param {Object} pr Pull request object, as returned by GitHib API. * @returns Review object, as returned by GitHub API. */ async approvePullRequest(pr: PullRequest) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/pulls/${pr.number}/reviews`; const result = await this.client.request({ url, method: 'POST', data: {event: 'APPROVE'}, }); return result.data; } /** * Renames the given pull request. * @param {Object} pr Pull request object, as returned by GitHib API. * @param {string} title New title to give the PR * @returns Review object, as returned by GitHub API. */ async renamePullRequest(pr: PullRequest, title: string) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/pulls/${pr.number}`; const result = await this.client.request({ url, method: 'PATCH', data: {title}, }); return result.data; } /** * Applies a set of labels to a given pull request. * @param {Object} pr Pull request object, as returned by GitHib API. * @param {Array<string>} labels Labels to apply to the PR * @returns A list of labels that was added to the issue.. */ async tagPullRequest(pr: PullRequest, labels: string[]) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/issues/${pr.number}/labels`; const result = await this.client.request({ url, method: 'POST', data: {labels}, }); return result.data; } /** * Removes label with a given name to a given pull request. * @param {Object} pr Pull request object, as returned by GitHib API. * @param {Array<string>} labels Labels to apply to the PR * @returns A list of labels that was added to the issue.. */ async unTagPullRequest(pr: PullRequest, name: string) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/issues/${pr.number}/labels/${name}`; const result = await this.client.request({ url, method: 'DELETE', data: {name}, }); return result.data; } /** * Closes the given pull request without merging it. * @param {Object} pr Pull request object, as returned by GitHub API. */ async closePullRequest(pr: PullRequest) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/pulls/${pr.number}`; const result = await this.client.request({ url, method: 'PATCH', data: {state: 'closed'}, }); return result.data; } /** * Merges the given pull request. * @param {Object} pr Pull request object, as returned by GitHib API. * @returns Merge object, as returned by GitHub API. */ async mergePullRequest(pr: PullRequest) { const owner = this.repository.owner.login; const repo = this.repository.name; const title = pr.title; const url = `/repos/${owner}/${repo}/pulls/${pr.number}/merge`; const result = await this.client.request({ url, method: 'PUT', data: { merge_method: 'squash', commit_title: title, }, }); return result.data; } /** * Returns branch settings for the given branch. * @param {string} branch Name of the branch. * @returns {Object} Branch object, as returned by GitHub API. */ async getBranch(branch: string) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/branches/${branch}`; const result = await this.client.request<Branch>({url}); return result.data; } /** * Returns branch protection settings for the base branch. * @returns {Object} Branch protection object, as returned by GitHub API. */ async getRequiredBaseBranchProtection() { const owner = this.repository.owner.login; const repo = this.repository.name; const branch = this.baseBranch; const url = `/repos/${owner}/${repo}/branches/${branch}/protection`; const result = await this.client.request({url}); return result.data; } /** * Returns branch protection status checks for the base branch. * @returns {Object} Status checks object, as returned by GitHub API. */ async getRequiredBaseBranchProtectionStatusChecks() { const owner = this.repository.owner.login; const repo = this.repository.name; const branch = this.baseBranch; const url = `/repos/${owner}/${repo}/branches/${branch}/protection/required_status_checks`; const result = await this.client.request<StatusCheck[]>({url}); return result.data; } /** * Updates branch protection status checks for the base branch. * @param {string[]} contexts Required status checks. * @returns {Object} Status checks object, as returned by GitHub API. */ async updateRequiredBaseBranchProtectionStatusChecks(contexts: string[]) { const owner = this.repository.owner.login; const repo = this.repository.name; const branch = this.baseBranch; const strict = true; const url = `/repos/${owner}/${repo}/branches/${branch}/protection/required_status_checks`; const result = await this.client.request({ url, method: 'PATCH', data: {strict, contexts}, }); return result.data; } /** * Updates admin enforcement for branch protection status checks for the base branch. * @param {boolean} enforce Whether to enforce branch protection for admins. * @returns {Object} HTTP response */ async updateEnforceAdmin(enforce: boolean) { const owner = this.repository.owner.login; const repo = this.repository.name; const branch = this.baseBranch; const url = `/repos/${owner}/${repo}/branches/${branch}/protection/enforce_admins`; const method = enforce ? 'POST' : 'DELETE'; const result = await this.client.request({ url, method, }); return result.data; } /** * Adds a collaborator to this repository. * @param {string} username Username of the new collaborator. * @param {string} permission Permission (pull, push, or admin, default: * push). * @returns {Object} As returned by GitHub API. */ async addCollaborator( username: string, permission: 'pull' | 'push' | 'admin' ) { const owner = this.repository.owner.login; const repo = this.repository.name; const url = `/repos/${owner}/${repo}/collaborators/${username}`; const result = await this.client.request({ url, method: 'PUT', data: {permission}, }); return result.data; } } export interface PullRequest extends Issue { patch_url: string; base: {sha: string}; head: {ref: string; label: string; repo: Repository}; labels: Array<{ name: string; }>; } export interface Issue { number: number; title: string; body: string; html_url: string; user: User; } export interface Repository { name: string; owner: User; default_branch: string; clone_url?: string; archived?: boolean; ssh_url?: string; } export interface User { login: string; } export interface Branches { [index: string]: { _latest: string; }; } export interface File { type: string; encoding: string; size: number; name: string; path: string; content: string; sha: string; url: string; git_url: string; html_url: string; download_url: string; _links: {git: string; self: string; html: string}; } export interface StatusCheck { url: string; strict: boolean; contexts: string[]; contexts_url: string; } export interface Branch { protected: boolean; } <file_sep>const consoleLog = console.log; const consoleWarn = console.warn; const consoleError = console.error; function noConsole() { // This check will be disabled in the new gts /* eslint-disable @typescript-eslint/no-empty-function */ console.log = () => {}; console.warn = () => {}; console.error = () => {}; } function restoreConsole() { console.error = consoleError; console.warn = consoleWarn; console.log = consoleLog; } export async function suppressConsole(func: Function) { noConsole(); await func().catch((err: Error) => { restoreConsole(); throw err; }); restoreConsole(); } <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 // // 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 chalk from 'chalk'; import * as fs from 'fs'; import {Writable} from 'stream'; let stream: Writable; const path = 'repo-debug.log'; export interface LogEntry { message: string; time: Date; level: LogLevel; } export enum LogLevel { 'INFO', 'WARN', 'ERROR', } export async function log(message: string) { console.log(message); push(LogLevel.INFO, message); } function push(level: LogLevel, message: string) { if (!stream) { stream = fs.createWriteStream(path); } stream.write(`${new Date()}\t${level}\t${message}`, err => { if (err) { console.error('Error writing to log.'); console.error(err); } }); } export function info(message: string) { console.error(chalk.cyan(message)); push(LogLevel.INFO, message); } export function warn(message: string) { console.error(chalk.yellow(message)); push(LogLevel.WARN, message); } export function error(message: string) { console.error(chalk.red(message)); push(LogLevel.ERROR, message); } <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 // // 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. /** * @fileoverview Runs the given command in each repository, and commits * files that were added or changed. */ import * as childProcess from 'child_process'; import commandLineUsage from 'command-line-usage'; import {updateRepo, UpdateRepoOptions} from './lib/update-repo.js'; import {question} from './lib/question.js'; import meow from 'meow'; // tslint:disable-next-line:no-any const exec = (command: string, options?: object): Promise<string> => new Promise<string>((resolve, reject) => { childProcess.exec(command, options, (err, stdout, stderr) => { if (err) { reject(stderr); } else { resolve(stdout.toString()); } }); }); const commandLineOptions = [ {name: 'help', alias: 'h', type: Boolean, description: 'Show help.'}, { name: 'branch', alias: 'b', type: String, description: 'Branch name to create.', }, { name: 'message', alias: 'm', type: String, description: 'Commit message and pull request title.', }, { name: 'comment', alias: 'c', type: String, description: 'Pull request comment.', }, { name: 'reviewers', alias: 'r', type: String, description: 'Comma-separated list of reviewers.', }, { name: 'silent', alias: 's', type: Boolean, description: 'No interactive questions - just make commits. Use carefully.', }, ]; const helpSections = [ { header: 'apply-change.js', content: [ 'Iterates over repositories defined in {bold config.yaml}, clones each repository ', 'into a temporary folder and executes the provided command in that folder. ', 'If the command exits with exit code 0, all created and edited files are ', 'checked in into a new branch, and a new pull request is created.', ], }, { header: 'Synopsis', content: [ '$ node apply-change.js {bold --branch} {underline branch} {bold --message} {underline message}', ' {bold --comment} {underline comment} [{bold --reviewers} {underline username}[,{underline username}...]]', ' [{bold --silent}] {underline command}', '$ node apply-change.js {bold --help}', ], raw: true, }, { header: 'Options', optionList: commandLineOptions, }, ]; /** * Runs `git status` and parses the output to get a list of added and * changed files to commit. * @returns {string[]} List of filenames. */ async function getFilesToCommit() { const gitStatus = await exec('git status --porcelain --untracked-files'); const lines = gitStatus.split('\n').filter((line: string) => line !== ''); const files: string[] = []; for (const line of lines) { const matchResult = line.match(/^(?: M|\?\?) (.*)$/); if (matchResult !== null) { files.push(matchResult[1]); } } return files; } /** * Checks if options are valid and it's OK to continue. * Prints a message to stderr if not, and returns false. * @param {Object} options Options object, as returned by meow. * @returns {Boolean} True if OK to continue, false otherwise. */ function checkOptions(cli: ReturnType<typeof meow>) { if (cli.flags.help) { console.log(commandLineUsage(helpSections)); return false; } let badOptions = false; if (cli.flags.branch === undefined) { badOptions = true; console.error('Error: --branch is required.'); } if (cli.flags.message === undefined) { badOptions = true; console.error('Error: --message is required.'); } if (cli.flags.comment === undefined) { badOptions = true; console.error('Error: --comment is required.'); } if (cli.input[1] === undefined) { badOptions = true; console.error('Error: command is required.'); } if (badOptions) { console.error( 'Please run the script with --help to get some help on the command line options.' ); return false; } return true; } /** * A function to be used in callback to `update-repo.js`. * Executes the given command in the repository cloned into the given * location, should return a promise resolving to a list of files to * commit. * @param {Object} options Command-line options, as returned by meow. * @param {String} repoPath Path to a folder where the current repository is * cloned. * @returns {Promise<string[]>} A promise resolving to a list of files to * commit. */ async function updateCallback(cli: ReturnType<typeof meow>, repoPath: string) { const cwd = process.cwd(); try { process.chdir(repoPath); const command = cli.input.slice(1).join(' '); console.log('Executing command:', command); await exec(command); // will throw an error if non-zero exit code const files = await getFilesToCommit(); if (files.length > 0 && !cli.flags.silent) { for (;;) { const response = await question( 'Going to commit the following files:\n' + files.map(line => ` ${line}\n`).join('') + 'Do it? [y/n]' ); if (response === 'y') { break; } else if (response === 'n') { throw new Error('Change rejected by user'); } else { continue; } } } process.chdir(cwd); return Promise.resolve(files); } catch (err) { process.chdir(cwd); return Promise.reject(err); } } /** * Main function. */ export async function main(cli: ReturnType<typeof meow>) { if (!checkOptions(cli)) { return; } const updateRepoOptions = { updateCallback: (path: string) => updateCallback(cli, path), branch: cli.flags.branch, message: cli.flags.message, comment: cli.flags.comment, } as UpdateRepoOptions; if (cli.flags.reviewers !== undefined) { updateRepoOptions.reviewers = (cli.flags.reviewers as string).split( /\s*,\s*/ ); } await updateRepo(updateRepoOptions); } <file_sep># Changelog [npm history][1] [1]: https://www.npmjs.com/package/@google/repo?activeTab=versions ## [7.0.0](https://github.com/googleapis/github-repo-automation/compare/v6.2.0...v7.0.0) (2023-08-10) ### ⚠ BREAKING CHANGES * upgrade to Node 14 ([#647](https://github.com/googleapis/github-repo-automation/issues/647)) ### Miscellaneous Chores * Upgrade to Node 14 ([#647](https://github.com/googleapis/github-repo-automation/issues/647)) ([119377f](https://github.com/googleapis/github-repo-automation/commit/119377fdb37549eaa8a53efada7dce0f54cfb32b)) ## [6.2.0](https://github.com/googleapis/github-repo-automation/compare/v6.1.3...v6.2.0) (2023-03-29) ### Features * Make possible to read custom baseUrl from config.yaml ([#631](https://github.com/googleapis/github-repo-automation/issues/631)) ([9862fe5](https://github.com/googleapis/github-repo-automation/commit/9862fe5e38645d930e68d469588d07b19d317f62)) ## [6.1.3](https://github.com/googleapis/github-repo-automation/compare/v6.1.2...v6.1.3) (2023-03-07) ### Bug Fixes * **deps:** Update dependency command-line-usage to v7 ([#627](https://github.com/googleapis/github-repo-automation/issues/627)) ([2dbf995](https://github.com/googleapis/github-repo-automation/commit/2dbf9950e7500cfa3333523ac2602c22eb32a3b0)) ## [6.1.2](https://github.com/googleapis/github-repo-automation/compare/v6.1.1...v6.1.2) (2022-12-08) ### Bug Fixes * **deps:** Update dependency meow to v11 ([#624](https://github.com/googleapis/github-repo-automation/issues/624)) ([f9ed780](https://github.com/googleapis/github-repo-automation/commit/f9ed7807a2429301bd4c6f9a8a552111050b56aa)) ## [6.1.1](https://github.com/googleapis/github-repo-automation/compare/v6.1.0...v6.1.1) (2022-09-14) ### Bug Fixes * **deps:** Update dependency async-mutex to ^0.4.0 ([#617](https://github.com/googleapis/github-repo-automation/issues/617)) ([fb7c7a8](https://github.com/googleapis/github-repo-automation/commit/fb7c7a8b772891c2b2d3e80157d54cbbbf72b8b5)) * Remove update-notifier ([#618](https://github.com/googleapis/github-repo-automation/issues/618)) ([ae9be5d](https://github.com/googleapis/github-repo-automation/commit/ae9be5d7cb03adbfbe1846c13725b2ab1ee0f7a6)) ## [6.1.0](https://github.com/googleapis/github-repo-automation/compare/v6.0.0...v6.1.0) (2022-08-29) ### Features * use cache when listing PRs and issues ([#616](https://github.com/googleapis/github-repo-automation/issues/616)) ([6572a87](https://github.com/googleapis/github-repo-automation/commit/6572a87c73be076d6b685a73a2e0a1b81fa5ae55)) ### Bug Fixes * remove pip install statements ([#1546](https://github.com/googleapis/github-repo-automation/issues/1546)) ([#613](https://github.com/googleapis/github-repo-automation/issues/613)) ([a046b29](https://github.com/googleapis/github-repo-automation/commit/a046b295487d5da45597d26110effad0c15982ad)) ## [6.0.0](https://github.com/googleapis/github-repo-automation/compare/v5.0.0...v6.0.0) (2022-07-27) ### ⚠ BREAKING CHANGES * ESM, drop API, drop Node 12 support (#611) ### Bug Fixes * ESM, drop API, drop Node 12 support ([#611](https://github.com/googleapis/github-repo-automation/issues/611)) ([47834fe](https://github.com/googleapis/github-repo-automation/commit/47834fee545f742e8fcb606e897f3a21575bfdc1)) ## [5.0.0](https://github.com/googleapis/github-repo-automation/compare/v4.8.1...v5.0.0) (2022-05-19) ### ⚠ BREAKING CHANGES * update library to use Node 12 (#595) ### Build System * update library to use Node 12 ([#595](https://github.com/googleapis/github-repo-automation/issues/595)) ([a10f39d](https://github.com/googleapis/github-repo-automation/commit/a10f39dcb2cfc3f7a39c0c22b76509dc55d7b3ee)) ### [4.8.1](https://github.com/googleapis/github-repo-automation/compare/v4.8.0...v4.8.1) (2022-04-12) ### Bug Fixes * approve command requires an --author ([#586](https://github.com/googleapis/github-repo-automation/issues/586)) ([1b1d1c5](https://github.com/googleapis/github-repo-automation/commit/1b1d1c5f530e066dc61227f0e8659beb13f6b5b3)) ## [4.8.0](https://github.com/googleapis/github-repo-automation/compare/v4.7.0...v4.8.0) (2022-01-17) ### Features * delay by default ([#568](https://github.com/googleapis/github-repo-automation/issues/568)) ([2e522e4](https://github.com/googleapis/github-repo-automation/commit/2e522e4ef4ff8b9aad6ce204b5736abe47bab0f2)) * detailed debugging now configured with NODE_DEBUG=repo ([#567](https://github.com/googleapis/github-repo-automation/issues/567)) ([5306b21](https://github.com/googleapis/github-repo-automation/commit/5306b2155387e5d99f199762390aff0baa12ffe8)) ## [4.7.0](https://github.com/googleapis/github-repo-automation/compare/v4.6.1...v4.7.0) (2022-01-14) ### Features * introduce retry and delay configuration ([#563](https://github.com/googleapis/github-repo-automation/issues/563)) ([f08bf08](https://github.com/googleapis/github-repo-automation/commit/f08bf08805a669f94c5d3d6f48de1f829452b877)) ### [4.6.1](https://www.github.com/googleapis/github-repo-automation/compare/v4.6.0...v4.6.1) (2021-09-02) ### Bug Fixes * **build:** switch primary branch to main ([#538](https://www.github.com/googleapis/github-repo-automation/issues/538)) ([45354f2](https://www.github.com/googleapis/github-repo-automation/commit/45354f22f791f24c475ed6ca9f03dd7ed4467b0e)) ## [4.6.0](https://www.github.com/googleapis/github-repo-automation/compare/v4.5.0...v4.6.0) (2021-09-02) ### Features * better logging for approve, extra flag for merge ([#532](https://www.github.com/googleapis/github-repo-automation/issues/532)) ([32260c1](https://www.github.com/googleapis/github-repo-automation/commit/32260c156770720367bd413024f21f466da8eb21)) ## [4.5.0](https://www.github.com/googleapis/github-repo-automation/compare/v4.4.1...v4.5.0) (2021-07-08) ### Features * **list:** allow PRs to be filtered by label ([#519](https://www.github.com/googleapis/github-repo-automation/issues/519)) ([5e4cd3a](https://www.github.com/googleapis/github-repo-automation/commit/5e4cd3ac2a02543345e768e7f491878fa5cc4f16)) ### [4.4.1](https://www.github.com/googleapis/github-repo-automation/compare/v4.4.0...v4.4.1) (2021-05-24) ### Bug Fixes * fetch all branches during sync ([#508](https://www.github.com/googleapis/github-repo-automation/issues/508)) ([5a43559](https://www.github.com/googleapis/github-repo-automation/commit/5a43559d5af32749c0ba295764b8c985583ae947)) ## [4.4.0](https://www.github.com/googleapis/github-repo-automation/compare/v4.3.1...v4.4.0) (2021-04-05) ### Features * add optional branch cleanup to reject command ([#421](https://www.github.com/googleapis/github-repo-automation/issues/421)) ([df75eb2](https://www.github.com/googleapis/github-repo-automation/commit/df75eb2f147ac0b75e9400c05bd3ef19cab80439)) ### [4.3.1](https://www.github.com/googleapis/github-repo-automation/compare/v4.3.0...v4.3.1) (2021-02-05) ### Bug Fixes * **deps:** upgrade to js-yaml 4.0 ([#486](https://www.github.com/googleapis/github-repo-automation/issues/486)) ([62757e8](https://www.github.com/googleapis/github-repo-automation/commit/62757e82fe1b5f8ea92ef4a76111d35b11784544)) ## [4.3.0](https://www.github.com/googleapis/github-repo-automation/compare/v4.2.3...v4.3.0) (2021-01-07) ### Features * add ability to toggle admin enforcement for branch protection ([#475](https://www.github.com/googleapis/github-repo-automation/issues/475)) ([b6cf2df](https://www.github.com/googleapis/github-repo-automation/commit/b6cf2df2c1ae87d4297822d7257bd65fda4ac65f)) ### Bug Fixes * **deps:** update dependency meow to v9 ([#481](https://www.github.com/googleapis/github-repo-automation/issues/481)) ([1ce401b](https://www.github.com/googleapis/github-repo-automation/commit/1ce401b731b630f14bcdfbe15c0fd92a3d6376f0)) ### [4.2.3](https://www.github.com/googleapis/github-repo-automation/compare/v4.2.2...v4.2.3) (2020-10-29) ### Bug Fixes * **deps:** update dependency meow to v8 ([#472](https://www.github.com/googleapis/github-repo-automation/issues/472)) ([7825499](https://www.github.com/googleapis/github-repo-automation/commit/7825499bb6c663609360b36cb26c9d8680cd2d03)) ### [4.2.2](https://www.github.com/googleapis/github-repo-automation/compare/v4.2.1...v4.2.2) (2020-10-27) ### Bug Fixes * **deps:** update dependency gaxios to v4 ([#466](https://www.github.com/googleapis/github-repo-automation/issues/466)) ([2e1d05a](https://www.github.com/googleapis/github-repo-automation/commit/2e1d05a289c3e6c5027bf9832800adabc5a2f03b)) ### [4.2.1](https://www.github.com/googleapis/github-repo-automation/compare/v4.2.0...v4.2.1) (2020-10-05) ### Bug Fixes * **deps:** update dependency update-notifier to v5 ([#458](https://www.github.com/googleapis/github-repo-automation/issues/458)) ([90c4e90](https://www.github.com/googleapis/github-repo-automation/commit/90c4e90796dfb95cfe2375d3fcf9e9d0957fc6d7)) ## [4.2.0](https://www.github.com/googleapis/github-repo-automation/compare/v4.1.0...v4.2.0) (2020-08-28) ### Features * add functionality to remove labels ([#454](https://www.github.com/googleapis/github-repo-automation/issues/454)) ([2cb06b7](https://www.github.com/googleapis/github-repo-automation/commit/2cb06b7174e89aea6d4bbecac7638990afd97c16)) ## [4.1.0](https://www.github.com/googleapis/github-repo-automation/compare/v4.0.2...v4.1.0) (2020-08-11) ### Features * add support for non-master default branches ([#443](https://www.github.com/googleapis/github-repo-automation/issues/443)) ([9785786](https://www.github.com/googleapis/github-repo-automation/commit/9785786db6a9d3d1b07d49b0d565dc3d5d4dd8ea)) ### Bug Fixes * **deps:** update dependency ora to v5 ([#444](https://www.github.com/googleapis/github-repo-automation/issues/444)) ([1a05cdd](https://www.github.com/googleapis/github-repo-automation/commit/1a05cdd4a1017b2ac2773be262279122873b0cb8)) ### [4.0.2](https://www.github.com/googleapis/github-repo-automation/compare/v4.0.1...v4.0.2) (2020-07-09) ### Bug Fixes * typeo in nodejs .gitattribute ([#428](https://www.github.com/googleapis/github-repo-automation/issues/428)) ([caaeb16](https://www.github.com/googleapis/github-repo-automation/commit/caaeb163fcbee6b0241a82a9bac8cf90f8718e2a)) ### [4.0.1](https://www.github.com/googleapis/github-repo-automation/compare/v4.0.0...v4.0.1) (2020-07-01) ### Bug Fixes * allow regex search for branch listing ([#425](https://www.github.com/googleapis/github-repo-automation/issues/425)) ([c706c78](https://www.github.com/googleapis/github-repo-automation/commit/c706c782dd4b3ceb5d1789ab7d1c3bd853685878)) ## [4.0.0](https://www.github.com/googleapis/github-repo-automation/compare/v3.0.1...v4.0.0) (2020-06-24) ### ⚠ BREAKING CHANGES * This PR removes support for using `repos.json` as a source of repositories, and adds support for using GitHub's [repository search API](https://help.github.com/en/github/searching-for-information-on-github/searching-for-repositories) instead. To upgrade to this version of the module, you need to modify your `.repo.yaml` file to use the new config language: ### Features * use GitHub repo search for identifying repositories ([#418](https://www.github.com/googleapis/github-repo-automation/issues/418)) ([320af6c](https://www.github.com/googleapis/github-repo-automation/commit/320af6cb029685ee2d5b9bdf011c08ef70935ead)) ### [3.0.1](https://www.github.com/googleapis/github-repo-automation/compare/v3.0.0...v3.0.1) (2020-06-08) ### Bug Fixes * push empty commit to trigger release PR ([#411](https://www.github.com/googleapis/github-repo-automation/issues/411)) ([a98d275](https://www.github.com/googleapis/github-repo-automation/commit/a98d275b0ddd470cb2e16daad6728721b4de7a9f)) ## [3.0.0](https://www.github.com/googleapis/github-repo-automation/compare/v2.5.0...v3.0.0) (2020-05-14) ### ⚠ BREAKING CHANGES * rename regex match as --title option (#388) ### Features * **deps:** update dependency & drop Node 8 ([#384](https://www.github.com/googleapis/github-repo-automation/issues/384)) ([3ecad5e](https://www.github.com/googleapis/github-repo-automation/commit/3ecad5ee821e2d4741d3752b4d9637dc7183ee2a)) * adds support for performing mass operations on issues ([#407](https://www.github.com/googleapis/github-repo-automation/issues/407)) ([0cc958c](https://www.github.com/googleapis/github-repo-automation/commit/0cc958c87af1e749c0c14198d03711f060952ade)) * rename regex match as --title option ([#388](https://www.github.com/googleapis/github-repo-automation/issues/388)) ([410f274](https://www.github.com/googleapis/github-repo-automation/commit/410f27435c43938bf6a7e5b54e7febca225400ad)) ### Bug Fixes * apache license URL ([#468](https://www.github.com/googleapis/github-repo-automation/issues/468)) ([#394](https://www.github.com/googleapis/github-repo-automation/issues/394)) ([5a1cb9c](https://www.github.com/googleapis/github-repo-automation/commit/5a1cb9c14fd7ab27e2142a779d2928d951e37e8a)) * **deps:** update dependency @types/tmp to ^0.2.0 ([#402](https://www.github.com/googleapis/github-repo-automation/issues/402)) ([ebdf1cf](https://www.github.com/googleapis/github-repo-automation/commit/ebdf1cfe6376f9b8706a664649561b5726708934)) * **deps:** update dependency chalk to v4 ([#391](https://www.github.com/googleapis/github-repo-automation/issues/391)) ([044c767](https://www.github.com/googleapis/github-repo-automation/commit/044c76728745cb02a2f6ab308b66af21d2a270c1)) * **deps:** update dependency meow to v7 ([#404](https://www.github.com/googleapis/github-repo-automation/issues/404)) ([897ff19](https://www.github.com/googleapis/github-repo-automation/commit/897ff196c8f2d272a2c83c988fb4a936b8852d73)) * **deps:** update dependency tmp-promise to v3 ([#406](https://www.github.com/googleapis/github-repo-automation/issues/406)) ([c4b4f40](https://www.github.com/googleapis/github-repo-automation/commit/c4b4f40a3bf7a9e66d552ac377798dfa6ad030ae)) * **deps:** update dependency tweetsodium to v0.0.5 ([#395](https://www.github.com/googleapis/github-repo-automation/issues/395)) ([ca44539](https://www.github.com/googleapis/github-repo-automation/commit/ca44539949a7c5994a222108b45da6bc626449f0)) ## [2.5.0](https://www.github.com/googleapis/github-repo-automation/compare/v2.4.0...v2.5.0) (2020-03-24) ### Features * **samples:** add sample demonstrating populating secrets for GitHub… ([#374](https://www.github.com/googleapis/github-repo-automation/issues/374)) ([a71bafd](https://www.github.com/googleapis/github-repo-automation/commit/a71bafd08b543077991265bd88c943bab4c3c1ba)) * add option for filtering by pr author ([#383](https://www.github.com/googleapis/github-repo-automation/issues/383)) ([484ab19](https://www.github.com/googleapis/github-repo-automation/commit/484ab19a07c6183a6fcb7a6e3583546e89cdf8b9)) ## [2.4.0](https://www.github.com/googleapis/github-repo-automation/compare/v2.3.0...v2.4.0) (2020-01-28) ### Features * implement --branch for repo commands ([#357](https://www.github.com/googleapis/github-repo-automation/issues/357)) ([e56839c](https://www.github.com/googleapis/github-repo-automation/commit/e56839c883511df0593dceb31d753e6e74a17ac1)) ## [2.3.0](https://www.github.com/googleapis/github-repo-automation/compare/v2.2.2...v2.3.0) (2020-01-06) ### Features * repo list, and pretty printing PRs ([#346](https://www.github.com/googleapis/github-repo-automation/issues/346)) ([44fd2d2](https://www.github.com/googleapis/github-repo-automation/commit/44fd2d20c32f8f9287328dbb9d70b1fb5b4f9b5d)) ### Bug Fixes * **deps:** update dependency chalk to v3 ([#332](https://www.github.com/googleapis/github-repo-automation/issues/332)) ([aa00d00](https://www.github.com/googleapis/github-repo-automation/commit/aa00d0040e62889fe6ff3cf7619210b6f6fcf414)) * **deps:** update dependency update-notifier to v4 ([#339](https://www.github.com/googleapis/github-repo-automation/issues/339)) ([ef45dc0](https://www.github.com/googleapis/github-repo-automation/commit/ef45dc0027873387693fd75aa09ef37e10184b3f)) * **deps:** use meow v6.0.0 with its own types ([#348](https://www.github.com/googleapis/github-repo-automation/issues/348)) ([573a985](https://www.github.com/googleapis/github-repo-automation/commit/573a98596b8eb82490e5b2b665ed5843b4a8dc0f)) ### [2.2.2](https://www.github.com/googleapis/github-repo-automation/compare/v2.2.1...v2.2.2) (2019-10-12) ### Bug Fixes * **deps:** update dependency ora to v4 ([#326](https://www.github.com/googleapis/github-repo-automation/issues/326)) ([88b2f1e](https://www.github.com/googleapis/github-repo-automation/commit/88b2f1e8e16ec6000e6b078d637f2d5424bce879)) ### [2.2.1](https://www.github.com/googleapis/github-repo-automation/compare/v2.2.0...v2.2.1) (2019-08-02) ### Bug Fixes * set commit title when merging PR ([#310](https://www.github.com/googleapis/github-repo-automation/issues/310)) ([a7b1bb0](https://www.github.com/googleapis/github-repo-automation/commit/a7b1bb0)) ## [2.2.0](https://www.github.com/googleapis/github-repo-automation/compare/v2.1.2...v2.2.0) (2019-07-31) ### Features * make samples/update-branch-protection.js is a flexible CLI ([#303](https://www.github.com/googleapis/github-repo-automation/issues/303)) ([b23c2b7](https://www.github.com/googleapis/github-repo-automation/commit/b23c2b7)) ### [2.1.2](https://www.github.com/googleapis/github-repo-automation/compare/v2.1.1...v2.1.2) (2019-07-29) ### Bug Fixes * **deps:** update dependency command-line-usage to v6 ([#299](https://www.github.com/googleapis/github-repo-automation/issues/299)) ([ab395a9](https://www.github.com/googleapis/github-repo-automation/commit/ab395a9)) ### [2.1.1](https://www.github.com/googleapis/github-repo-automation/compare/v2.1.0...v2.1.1) (2019-06-05) ### Bug Fixes * make other PR commands concurrent ([#289](https://www.github.com/googleapis/github-repo-automation/issues/289)) ([ec70b56](https://www.github.com/googleapis/github-repo-automation/commit/ec70b56)) * **deps:** update dependency axios to ^0.19.0 ([#291](https://www.github.com/googleapis/github-repo-automation/issues/291)) ([913c93c](https://www.github.com/googleapis/github-repo-automation/commit/913c93c)) ## [2.1.0](https://www.github.com/googleapis/github-repo-automation/compare/v2.0.1...v2.1.0) (2019-05-29) ### Features * add the `rename` command ([#284](https://www.github.com/googleapis/github-repo-automation/issues/284)) ([7991585](https://www.github.com/googleapis/github-repo-automation/commit/7991585)) ### [2.0.1](https://www.github.com/googleapis/github-repo-automation/compare/v2.0.0...v2.0.1) (2019-05-23) ### Bug Fixes * **deps:** update dependency tmp-promise to v2 ([#278](https://www.github.com/googleapis/github-repo-automation/issues/278)) ([a7a7b2d](https://www.github.com/googleapis/github-repo-automation/commit/a7a7b2d)) * **deps:** update dependency update-notifier to v3 ([#275](https://www.github.com/googleapis/github-repo-automation/issues/275)) ([d8e9529](https://www.github.com/googleapis/github-repo-automation/commit/d8e9529)) ## [2.0.0](https://www.github.com/googleapis/github-repo-automation/compare/v1.1.0...v2.0.0) (2019-05-03) ### Bug Fixes * stop supporting Node.js v6 ([#270](https://www.github.com/googleapis/github-repo-automation/issues/270)) ([02eb085](https://www.github.com/googleapis/github-repo-automation/commit/02eb085)) * **deps:** update dependency p-queue to v5 ([#261](https://www.github.com/googleapis/github-repo-automation/issues/261)) ([75e5bb6](https://www.github.com/googleapis/github-repo-automation/commit/75e5bb6)) ### BREAKING CHANGES * stop supporting Node.js v6 (#270) ## v1.1.0 04-18-2019 14:47 PDT ### New features - feat: let user specify concurrency ([#258](https://github.com/googleapis/github-repo-automation/pull/258)) - feat: add `tag` command to apply labels to PRs ([#237](https://github.com/googleapis/github-repo-automation/pull/237)) - feat: repo check Kokoro status enabled, samples code for enabling Kokoro checks ([#183](https://github.com/googleapis/github-repo-automation/pull/183)) ### Bug fixes - fix: log message ([#193](https://github.com/googleapis/github-repo-automation/pull/193)) - fix: repo apply fails when untracked dirs were added ([#188](https://github.com/googleapis/github-repo-automation/pull/188)) - fix(deps): update dependency p-queue to v4 ([#252](https://github.com/googleapis/github-repo-automation/pull/252)) - fix: remove unused packages ([#249](https://github.com/googleapis/github-repo-automation/pull/249)) - fix: update sample for updating status checks ([#202](https://github.com/googleapis/github-repo-automation/pull/202)) ### Docs - docs: update links in contrib guide ([#246](https://github.com/googleapis/github-repo-automation/pull/246)) - docs: update contributing guide ([#242](https://github.com/googleapis/github-repo-automation/pull/242)) - docs: add lint/fix example to contributing guide ([#239](https://github.com/googleapis/github-repo-automation/pull/239)) ### Internal changes - chore(deps): update dependency nyc to v14 ([#262](https://github.com/googleapis/github-repo-automation/pull/262)) - chore: publish to npm using wombat ([#255](https://github.com/googleapis/github-repo-automation/pull/255)) - build: use per-repo publish token ([#254](https://github.com/googleapis/github-repo-automation/pull/254)) - build: Add docuploader credentials to node publish jobs ([#251](https://github.com/googleapis/github-repo-automation/pull/251)) - build: use node10 to run samples-test, system-test etc ([#250](https://github.com/googleapis/github-repo-automation/pull/250)) - build: update release configuration ([#248](https://github.com/googleapis/github-repo-automation/pull/248)) - chore(deps): update dependency mocha to v6 ([#247](https://github.com/googleapis/github-repo-automation/pull/247)) - build: use linkinator for docs test ([#245](https://github.com/googleapis/github-repo-automation/pull/245)) - build: create docs test npm scripts ([#244](https://github.com/googleapis/github-repo-automation/pull/244)) - build: test using @grpc/grpc-js in CI ([#243](https://github.com/googleapis/github-repo-automation/pull/243)) - chore(deps): update dependency eslint-config-prettier to v4 ([#238](https://github.com/googleapis/github-repo-automation/pull/238)) - build: ignore googleapis.com in doc link check ([#236](https://github.com/googleapis/github-repo-automation/pull/236)) - build: check for 404s in the docs ([#235](https://github.com/googleapis/github-repo-automation/pull/235)) - chore(deps): update dependency @types/ora to v3 ([#233](https://github.com/googleapis/github-repo-automation/pull/233)) - chore(deps): update dependency @types/sinon to v7 ([#232](https://github.com/googleapis/github-repo-automation/pull/232)) - chore(build): inject yoshi automation key ([#231](https://github.com/googleapis/github-repo-automation/pull/231)) - chore: update nyc and eslint configs ([#230](https://github.com/googleapis/github-repo-automation/pull/230)) - chore: fix publish.sh permission +x ([#228](https://github.com/googleapis/github-repo-automation/pull/228)) - fix(build): fix Kokoro release script ([#227](https://github.com/googleapis/github-repo-automation/pull/227)) - build: add Kokoro configs for autorelease ([#226](https://github.com/googleapis/github-repo-automation/pull/226)) - chore: always nyc report before calling codecov ([#223](https://github.com/googleapis/github-repo-automation/pull/223)) - chore: nyc ignore build/test by default ([#222](https://github.com/googleapis/github-repo-automation/pull/222)) - chore(build): update prettier config ([#220](https://github.com/googleapis/github-repo-automation/pull/220)) - chore(deps): update dependency @types/sinon to v5.0.7 ([#213](https://github.com/googleapis/github-repo-automation/pull/213)) - chore(build): update CI config ([#217](https://github.com/googleapis/github-repo-automation/pull/217)) - fix(build): fix system key decryption ([#214](https://github.com/googleapis/github-repo-automation/pull/214)) - refactor: drop octokit, just use rest ([#216](https://github.com/googleapis/github-repo-automation/pull/216)) - fix(deps): update dependency @octokit/rest to v16 ([#207](https://github.com/googleapis/github-repo-automation/pull/207)) - chore(deps): update dependency @types/p-queue to v3 ([#209](https://github.com/googleapis/github-repo-automation/pull/209)) - fix: Pin @types/sinon to last compatible version ([#210](https://github.com/googleapis/github-repo-automation/pull/210)) - chore: add a synth.metadata - chore(deps): update dependency gts to ^0.9.0 ([#205](https://github.com/googleapis/github-repo-automation/pull/205)) - chore: update eslintignore config ([#204](https://github.com/googleapis/github-repo-automation/pull/204)) - chore: use latest npm on Windows ([#203](https://github.com/googleapis/github-repo-automation/pull/203)) - chore: update CircleCI config ([#201](https://github.com/googleapis/github-repo-automation/pull/201)) - chore: include build in eslintignore ([#198](https://github.com/googleapis/github-repo-automation/pull/198)) - chore(deps): update dependency eslint-plugin-node to v8 ([#194](https://github.com/googleapis/github-repo-automation/pull/194)) - chore: update issue templates ([#192](https://github.com/googleapis/github-repo-automation/pull/192)) - chore: remove old issue template ([#190](https://github.com/googleapis/github-repo-automation/pull/190)) - build: run tests on node11 ([#189](https://github.com/googleapis/github-repo-automation/pull/189)) - chores(build): run codecov on continuous builds ([#185](https://github.com/googleapis/github-repo-automation/pull/185)) - chores(build): do not collect sponge.xml from windows builds ([#186](https://github.com/googleapis/github-repo-automation/pull/186)) - chore: update new issue template ([#184](https://github.com/googleapis/github-repo-automation/pull/184)) ## v1.0.0 ### Fixes - fix: `repo apply` command ([#179](https://github.com/googleapis/github-repo-automation/pull/179)) - fix: repair repo sync ([#154](https://github.com/googleapis/github-repo-automation/pull/154)) ### New Features - feat: split the approve command ([#164](https://github.com/googleapis/github-repo-automation/pull/164)) ### Internal / Testing Changes - build: fix codecov uploading on Kokoro ([#178](https://github.com/googleapis/github-repo-automation/pull/178)) - chore(deps): update dependency sinon to v7 ([#177](https://github.com/googleapis/github-repo-automation/pull/177)) - chore(deps): update dependency @types/meow to v5 ([#165](https://github.com/googleapis/github-repo-automation/pull/165)) - Update kokoro config ([#163](https://github.com/googleapis/github-repo-automation/pull/163)) - chore(deps): update dependency eslint-plugin-prettier to v3 ([#162](https://github.com/googleapis/github-repo-automation/pull/162)) - Update CI config ([#160](https://github.com/googleapis/github-repo-automation/pull/160)) - Don't publish sourcemaps ([#158](https://github.com/googleapis/github-repo-automation/pull/158)) - Re-generate library using /synth.py ([#157](https://github.com/googleapis/github-repo-automation/pull/157)) - Update kokoro config ([#156](https://github.com/googleapis/github-repo-automation/pull/156)) - test: remove appveyor config ([#155](https://github.com/googleapis/github-repo-automation/pull/155)) - Update kokoro config ([#153](https://github.com/googleapis/github-repo-automation/pull/153)) - Enable prefer-const in the eslint config ([#152](https://github.com/googleapis/github-repo-automation/pull/152)) ## v0.3.0 ### Features - feat: print report after repo approve ([#148](https://github.com/googleapis/github-repo-automation/pull/148)) - feat: load repositories from sloth JSON config ([#143](https://github.com/googleapis/github-repo-automation/pull/143)) - feat: make repo exec async ([#111](https://github.com/googleapis/github-repo-automation/pull/111)) - feat: delete branch after approving and merging ([#116](https://github.com/googleapis/github-repo-automation/pull/116)) ### Bug Fixes - fix: make repo-check work ([#149](https://github.com/googleapis/github-repo-automation/pull/149)) - fix: actually delete branch ([#147](https://github.com/googleapis/github-repo-automation/pull/147)) - fix: proper ssh_url for github repos from json ([#145](https://github.com/googleapis/github-repo-automation/pull/145)) - fix: properly delete branch by git reference ([#139](https://github.com/googleapis/github-repo-automation/pull/139)) - fix: clone if dir does not exist ([#128](https://github.com/googleapis/github-repo-automation/pull/128)) - fix: update compilation errors due to new octokit ([#129](https://github.com/googleapis/github-repo-automation/pull/129)) - fix: speed up sync ([#121](https://github.com/googleapis/github-repo-automation/pull/121)) - fix: do not include archived repos ([#119](https://github.com/googleapis/github-repo-automation/pull/119)) - fix: repo apply CLI should not accept --execute/--command ([#115](https://github.com/googleapis/github-repo-automation/pull/115)) ## Keepin' the lights on - Enable no-var in eslint ([#146](https://github.com/googleapis/github-repo-automation/pull/146)) - chore(deps): update dependency nock to v10 ([#144](https://github.com/googleapis/github-repo-automation/pull/144)) - Update CI config ([#142](https://github.com/googleapis/github-repo-automation/pull/142)) - Fix sample tests ([#141](https://github.com/googleapis/github-repo-automation/pull/141)) - Retry npm install in CI ([#137](https://github.com/googleapis/github-repo-automation/pull/137)) - Update CI config ([#135](https://github.com/googleapis/github-repo-automation/pull/135)) - fix(deps): update dependency p-queue to v3 ([#134](https://github.com/googleapis/github-repo-automation/pull/134)) - chore(deps): update dependency nyc to v13 ([#133](https://github.com/googleapis/github-repo-automation/pull/133)) - add (dummy) system-test key ([#132](https://github.com/googleapis/github-repo-automation/pull/132)) - Add and run synth file ([#130](https://github.com/googleapis/github-repo-automation/pull/130)) - chore(deps): update dependency eslint-config-prettier to v3 ([#127](https://github.com/googleapis/github-repo-automation/pull/127)) - chore(deps): update dependency assert-rejects to v1 ([#125](https://github.com/googleapis/github-repo-automation/pull/125)) - chore: ignore package-lock.json ([#124](https://github.com/googleapis/github-repo-automation/pull/124)) - chore(deps): lock file maintenance ([#123](https://github.com/googleapis/github-repo-automation/pull/123)) - chore: use CircleCI for publish ([#109](https://github.com/googleapis/github-repo-automation/pull/109)) - chore: update renovate config ([#122](https://github.com/googleapis/github-repo-automation/pull/122)) - chore: throw on deprecation ([#120](https://github.com/googleapis/github-repo-automation/pull/120)) - chore(deps): lock file maintenance ([#118](https://github.com/googleapis/github-repo-automation/pull/118)) - chore(deps): update dependency typescript to v3 ([#117](https://github.com/googleapis/github-repo-automation/pull/117)) - chore: assert.deelEqual => assert.deepStrictEqual ([#114](https://github.com/googleapis/github-repo-automation/pull/114)) - chore: move mocha options to mocha.opts ([#110](https://github.com/googleapis/github-repo-automation/pull/110)) <file_sep>#!/bin/sh # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # @fileoverview Some of our repositories have both `package.json` and # `samples/package.json`. This script, being fed to `apply-change.js`, # will verify that versions in those two files match, and fix it if not. # Requires `jq` tool to be installed (https://stedolan.github.io/jq/). if ! test -f samples/package.json ; then echo "No samples, all good here." exit 0 fi main_name=`jq -r .name package.json` main_version=`jq -r .version package.json` samples_dependency=`jq -r ".dependencies.\"$main_name\"" samples/package.json` if [ "$main_version" == "$samples_dependency" ]; then echo "All good here." exit 0 fi echo "Making changes! Current version of $main_name is $main_version, samples depend on version $samples_dependency." jq -r ".dependencies.\"$main_name\"=\"$main_version\"" samples/package.json > samples/package.json.new mv samples/package.json.new samples/package.json npm install npm link cd samples npm link ../ npm install cd .. npm run lint echo "Git status:" git status echo "Done!" exit 0 <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 // // 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. /** * @fileoverview A quick'n'dirty console UI to approve a bunch of pull requests. * Usage: `node approve-prs.js [regex]` -- will go through open PRs with title * matching `regex`, one by one. Without a regex, will go through all open PRs. */ import * as meow from 'meow'; import {GitHubRepository, PullRequest} from './lib/github.js'; import {processPRs} from './lib/asyncItemIterator.js'; async function processMethod(repository: GitHubRepository, pr: PullRequest) { const htmlUrl = pr.html_url; const baseSha = pr.base.sha; const ref = pr.head.ref; let latestCommit: {[index: string]: string}; try { latestCommit = await repository.getLatestCommitToBaseBranch(); } catch (err) { console.warn( ' cannot get sha of latest commit to the base branch, skipping:', (err as Error).toString() ); return false; } const latestMasterSha = latestCommit['sha']; if (latestMasterSha !== baseSha) { try { await repository.updateBranch(ref, repository.baseBranch); console.log( 'You might not be able to merge immediately because CI tasks will take some time.' ); } catch (err) { console.warn( ` cannot update branch for PR ${htmlUrl}, skipping:`, (err as Error).toString() ); return false; } } try { await repository.mergePullRequest(pr); try { await repository.deleteBranch(ref); } catch (err) { console.warn(` error trying to delete branch ${ref}: ${err}`); return false; } } catch (err) { console.warn(`\t error trying to merge PR ${htmlUrl}: ${err}`); return false; } return true; } export async function merge(cli: meow.Result<meow.AnyFlags>) { if (!cli.flags.yespleasedoit) { console.error('repo merge might do bad things if you are an admin.'); console.error('It might ignore your CI and merge some bad code.'); console.error( 'It it safer to rely on automerge functionality if you have it set up' ); console.error('(for Googlers: `repo tag --title ... automerge`)'); console.error( 'Please add --yespleasedoit if you still want to proceed with the merge.' ); return; } return processPRs(cli, { processMethod, commandActive: 'merging', commandNamePastTense: 'merged', commandName: 'merge', commandDesc: 'Will show all open PRs with title matching regex and allow to merge them.', }); } <file_sep>#!/usr/bin/env node // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {main as apply} from './apply-change.js'; import {list} from './list-prs.js'; import {listIssues} from './list-issues.js'; import {approve} from './approve-prs.js'; import {rename} from './rename-prs.js'; import {reject} from './reject-prs.js'; import {update} from './update-prs.js'; import {merge} from './merge-prs.js'; import {main as check} from './repo-check.js'; import {sync, exec} from './sync.js'; import meow from 'meow'; import {tag} from './tag-prs.js'; import {untag} from './untag-prs.js'; const cli = meow( ` Usage $ repo <command> Examples $ repo list [--branch branch] [--author author] [--title title] [--label] $ repo list-issues [--branch branch] [--author author] [--title title] [--body body] $ repo approve [--branch branch] [--author author] [--title title] $ repo update [--branch branch] [--author author] [--title title] $ repo merge [--branch branch] [--author author] [--title title] [--yespleasedoit] $ repo reject [--branch branch] [--author author] [--title title] [--clean] $ repo rename [--branch branch] [--author author] [--title title] 'new PR title' $ repo tag [--branch branch] [--author author] [--title title] label1 label2 ... $ repo untag [--branch branch] [--author author] [--title title] label1 $ repo apply --branch branch --message message --comment comment [--reviewers username[,username...]] [--silent] command $ repo check $ repo sync $ repo exec -- git status $ repo exec --concurrency 10 -- git status `, { importMeta: import.meta, flags: { branch: { type: 'string', alias: 'b', }, message: { type: 'string', alias: 'm', }, comment: { type: 'string', alias: 'c', }, reviewers: { type: 'string', alias: 'r', }, silent: { type: 'boolean', alias: 'q', }, title: { type: 'string', alias: 't', }, delay: { type: 'number', }, retry: { type: 'boolean', }, auto: {type: 'boolean'}, concurrency: {type: 'string'}, author: {type: 'string'}, yespleasedoit: {type: 'boolean'}, nocache: {type: 'boolean'}, }, } ); if (cli.input.length < 1) { cli.showHelp(-1); } let p: Promise<void>; switch (cli.input[0]) { case 'list': p = list(cli); break; case 'list-issues': p = listIssues(cli); break; case 'approve': if (!cli.flags.author) { throw new Error('You must pass an --author for the approve command.'); } p = approve(cli); break; case 'rename': p = rename(cli); break; case 'reject': p = reject(cli); break; case 'update': p = update(cli); break; case 'merge': p = merge(cli); break; case 'apply': p = apply(cli); break; case 'untag': p = untag(cli); break; case 'tag': p = tag(cli); break; case 'check': p = check(); break; case 'sync': p = sync(cli); break; case 'exec': p = exec(cli); break; default: cli.showHelp(-1); break; } p!.catch(console.error); <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 // // 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. /** * @fileoverview Promisified version of readline.question. */ import * as readline from 'readline'; /** * Promisified version of readline question. Prints a prompt and waits for * response. * @param {string} prompt A prompt to print. * @returns {string} Response from stdin. */ export async function question(prompt: string) { return new Promise<string>(resolve => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question(prompt, response => { rl.close(); resolve(response); }); }); } <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 // // 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. /** * @fileoverview Fake GitHub and GitHubRepository implementations for tests. */ import * as crypto from 'crypto'; import {Config} from '../../src/lib/config.js'; import {Repository} from '../../src/lib/github.js'; function hash(input: string) { return crypto.createHash('md5').update(input).digest('hex'); } export class FakeGitHubRepository { /* eslint-disable @typescript-eslint/no-explicit-any */ branches: any; /* eslint-disable @typescript-eslint/no-explicit-any */ prs: any; /* eslint-disable @typescript-eslint/no-explicit-any */ baseBranch: any; _name?: string; constructor(name: string) { this.name = name; } reset() { this.branches = { main: { _latest: hash('latest-main-commit'), }, }; this.prs = { _count: 0, }; this.baseBranch = 'main'; } testSetFile(branch: string, path: string, content: string) { if (this.branches[branch] === undefined) { this.branches[branch] = {}; } const sha = hash(content); const type = 'file'; this.branches[branch][path] = {content, sha, type}; } testChangeBaseBranch(newBaseBranch: string) { this.baseBranch = newBaseBranch; this.branches[newBaseBranch] = {_latest: this.branches.main._latest}; delete this.branches.main._latest; } getRepository() { return {ssh_url: 'https://fake-clone-url/test.git'} as Repository; } async getFileFromBranch(branch: string, path: string) { if (this.branches[branch][path] === undefined) { return Promise.reject(`No file ${path} in branch ${branch}`); } return Promise.resolve(this.branches[branch][path]); } async getFile(path: string) { return this.getFileFromBranch(this.baseBranch, path); } async getLatestCommitToBaseBranch(customBranch?: string) { const sha = this.branches[customBranch || this.baseBranch]['_latest']; return Promise.resolve({sha}); } async createBranch(branch: string, latestSha: string) { if (this.branches[branch] !== undefined) { return Promise.reject(`Branch ${branch} already exists`); } if (this.branches[this.baseBranch]['_latest'] !== latestSha) { return Promise.reject( `SHA ${latestSha} is not found in branch ${branch}` ); } this.branches[branch] = Object.assign({}, this.branches[this.baseBranch]); return Promise.resolve({}); } async createFileInBranch( branch: string, path: string, message: string, content: string ) { if (this.branches[branch] === undefined) { return Promise.reject(`Branch ${branch} does not exist`); } if (this.branches[branch][path] !== undefined) { return Promise.reject(`File ${path} already exists in branch ${branch}`); } const sha = hash(content); const newFile = {content, sha, message}; this.branches[branch][path] = newFile; this.branches[branch]['_latest'] = sha; return Promise.resolve(newFile); } async updateFileInBranch( branch: string, path: string, message: string, content: string, oldFileSha: string ) { if (this.branches[branch] === undefined) { return Promise.reject(`Branch ${branch} does not exist`); } if (this.branches[branch][path] === undefined) { return Promise.reject(`File ${path} does not exist in branch ${branch}`); } const file = this.branches[branch][path]; if (file['sha'] !== oldFileSha) { return Promise.reject( `SHA of file ${path} in branch ${branch} is ${file['sha']} but not ${oldFileSha}` ); } const sha = hash(content); const newFile = {content, sha, message}; this.branches[branch][path] = newFile; this.branches[branch]['_latest'] = sha; return Promise.resolve(newFile); } async createPullRequest(branch: string, message: string, comment: string) { if (this.branches[branch] === undefined) { return Promise.reject(`Branch ${branch} does not exist`); } const prNumber = ++this.prs['_count']; const htmlUrl = `http://example.com/pulls/${prNumber}`; const pr = { number: prNumber, branch, message, comment, base: this.baseBranch, html_url: htmlUrl, }; this.prs[prNumber] = pr; return Promise.resolve(pr); } async requestReview(prNumber: number, reviewers: string[]) { if (this.prs[prNumber] === undefined) { return Promise.reject(`Pull request ${prNumber} does not exist`); } this.prs[prNumber]['reviewers'] = reviewers; return this.prs[prNumber]; } get name() { return this._name; } set name(n) { this._name = n; } } export const repository = new FakeGitHubRepository('test-repository'); export class FakeGitHub { protected config: Config; constructor(config: Config) { this.config = config; } async getRepositories() { return [repository]; } } <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 // // 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. /** * @fileoverview Unit tests for lib/config.js. */ import assert from 'assert'; import {describe, it} from 'mocha'; import * as fs from 'fs'; import * as yaml from 'js-yaml'; import * as os from 'os'; import * as path from 'path'; import {Config, GetConfig} from '../src/lib/config.js'; import * as tmp from 'tmp-promise'; const clonePath = path.join(os.homedir(), '.repo'); const configObject1: Config = { githubToken: 'test-github-token', clonePath, repos: [{org: 'test-organization', regex: 'test-repo-name-regex'}], }; const configObject2: Config = { githubToken: 'test-github-token-2', clonePath, repos: [{org: 'test-organization-2', regex: 'test-repo-name-regex-2'}], }; describe('Config', () => { const envCache = process.env.REPO_CONFIG_PATH; const cwd = process.cwd(); let tmpDir; // eslint-disable-next-line no-undef before(async () => { tmpDir = await tmp.dir({unsafeCleanup: true}); process.chdir(tmpDir.path); const configYaml1 = yaml.dump(configObject1); const configYaml2 = yaml.dump(configObject2); delete process.env['REPO_CONFIG_PATH']; fs.writeFileSync('./config.yaml', configYaml1); fs.writeFileSync('./config2.yaml', configYaml2); }); // eslint-disable-next-line no-undef after(() => { process.env.REPO_CONFIG_PATH = envCache; process.chdir(cwd); }); it('should read default configuration file', async () => { const config = await GetConfig.getConfig(); assert.deepStrictEqual(config, configObject1); }); it('should return individual values', async () => { const config = await GetConfig.getConfig(); assert.strictEqual(config.githubToken, configObject1.githubToken); assert.deepStrictEqual(config.repos, configObject1.repos); }); it('should accept configuration filename', async () => { const config = await GetConfig.getConfig('./config2.yaml'); assert.deepStrictEqual(config, configObject2); }); it('should read environment variable', async () => { process.env.REPO_CONFIG_PATH = './config2.yaml'; const config = await GetConfig.getConfig(); delete process.env.REPO_CONFIG_PATH; assert.deepStrictEqual(config, configObject2); }); it('should fail if configuration file does not exist', done => { // This check will be disabled in the new gts /* eslint-disable @typescript-eslint/no-empty-function */ console.error = () => {}; GetConfig.getConfig('./config3.yaml').catch(err => { assert(err instanceof Error); done(); }); }); }); <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 // // 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. /** * @fileoverview Configuration class. */ import * as fs from 'fs'; import {promisify} from 'util'; const readFile = promisify(fs.readFile); import * as yaml from 'js-yaml'; import * as path from 'path'; import * as os from 'os'; const cache = new Map<string, Config>(); export class GetConfig { static async getConfig(configFilename?: string) { let filename: string; if (configFilename) { filename = configFilename; } else if (process.env.REPO_CONFIG_PATH) { filename = process.env.REPO_CONFIG_PATH; } else { filename = './config.yaml'; } if (cache.has(filename)) { return cache.get(filename)!; } try { const yamlContent = await readFile(filename, {encoding: 'utf8'}); const config = yaml.load(yamlContent) as Config; cache.set(filename, config); config.clonePath = config.clonePath || path.join(os.homedir(), '.repo'); return config; } catch (err) { console.error( `Cannot read configuration file ${filename}. Have you created it? Use config.yaml.default as a sample.` ); throw new Error('Configuration file is not found'); } } } export interface Config { githubToken: string; clonePath: string; baseUrl?: string; repos?: [ { org: string; regex?: string; name?: string; }, ]; repoSearch?: string; retryStrategy?: Array<number>; } <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 // // 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. /** * @fileoverview Updates main branch protection to add/remove admin enforcement */ 'use strict'; const meow = require('meow'); const {getConfig} = require('../build/src/lib/config.js'); const {GitHub} = require('../build/src/lib/github'); async function main(input) { const config = await getConfig(); const github = new GitHub(config); const repos = await github.getRepositories(); const enforce = input[0] === 'add'; if (enforce) { console.log('adding admin enforcement on branch protection'); } else { console.log('removing admin enforcement on branch protection.'); } for (const repository of repos) { console.log(repository.getRepository()['name']); await repository.updateEnforceAdmin(enforce); } } const cli = meow( ` Usage $ node update-admin-branch-protection.js remove $ node update-admin-branch-protection.js add ` ); if (cli.input.length < 1) { cli.showHelp(-1); } else { main(cli.input).catch(err => { console.error(err.toString()); }); } <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 // // 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. /** * @fileoverview Performs a common tasks of applying the same change to * many GitHub repositories, and sends pull requests with the change. */ import * as child_process from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import {promisify} from 'util'; const exec = promisify(child_process.exec); const readFile = promisify(fs.readFile); import * as tmp from 'tmp-promise'; import {GitHub, GitHubRepository} from './github.js'; import {GetConfig} from './config.js'; /** * Updates files in the cloned repository and sends a pull request with * this change. * @param {GitHubRepository} repository Repository to work with. * @param {updateCallback} updateCallback Callback function that should * modify the files it wants to update, and return a promise resolving to the * list of updated files. * @param {string} branch Name for a new branch to use. * @param {string} message Commit message and pull request title. * @param {string} comment Pull request body. * @param {string[]} reviewers Reviewers' GitHub logins for the pull request. * @returns {undefined} No return value. Prints its progress to the console. */ async function processRepository( repository: GitHubRepository, updateCallback: Function, branch: string, message: string, comment: string, reviewers: string[] ) { const tmpDir = await tmp.dir({unsafeCleanup: true}); const cloneUrl = repository.getRepository().ssh_url; await exec(`git clone ${cloneUrl} ${tmpDir.path}`); let filesToUpdate; try { filesToUpdate = await updateCallback(tmpDir.path); } catch (err) { console.warn( ' callback function threw an exception, skipping this repository', err ? (err as Error).stack : '' ); return; } if (filesToUpdate === undefined) { console.warn( ' callback function returned undefined value, skipping this repository' ); return; } if (filesToUpdate.length === 0) { console.warn( ' callback function returned empty list, skipping this repository' ); return; } let latestCommit: {[index: string]: string}; try { latestCommit = await repository.getLatestCommitToBaseBranch(); } catch (err) { console.warn( ' cannot get sha of latest commit, skipping this repository:', (err as Error).toString() ); return; } const latestSha = latestCommit.sha; try { await repository.createBranch(branch, latestSha); } catch (err) { console.warn( ` cannot create branch ${branch}, skipping this repository:`, (err as Error).toString() ); return; } for (const filePath of filesToUpdate) { let file; try { file = await repository.getFile(filePath); } catch (err) { // ignore: will create new file } if (file !== undefined && file['type'] !== 'file') { console.warn(' requested path is not file, skipping this repository'); return; } const oldFileSha = file === undefined ? undefined : file['sha']; let patchedContent; try { patchedContent = await readFile(path.join(tmpDir.path, filePath)); } catch (err) { console.warn( ` cannot read file ${filePath}, skipping this repository:`, (err as Error).toString() ); return; } const encodedPatchedContent = Buffer.from(patchedContent).toString('base64'); try { if (oldFileSha === undefined) { await repository.createFileInBranch( branch, filePath, message, encodedPatchedContent ); } else { await repository.updateFileInBranch( branch, filePath, message, encodedPatchedContent, oldFileSha ); } } catch (err) { console.warn( ` cannot commit file ${filePath} to branch ${branch}, skipping this repository:`, (err as Error).toString() ); return; } } let pullRequest; try { pullRequest = await repository.createPullRequest(branch, message, comment); } catch (err) { console.warn( ` cannot create pull request for branch ${branch}! Branch is still there.`, (err as Error).toString() ); return; } const pullRequestNumber = pullRequest.number!; const pullRequestUrl = pullRequest.html_url; if (reviewers.length > 0) { try { await repository.requestReview(pullRequestNumber, reviewers); } catch (err) { console.warn( ` cannot request review for pull request #${pullRequestNumber}! Pull request is still there.`, (err as Error).toString() ); return; } } console.log(` success! ${pullRequestUrl}`); } export interface UpdateRepoOptions { config?: string; updateCallback: Function; branch: string; message: string; comment: string; reviewers?: string[]; } /** * Updates files in the cloned repository and sends a pull request with * this change. * @param {Object} options Options object, should contain the following fields: * @param {string} option.config Path to a configuration file. Will use default * `./config.yaml` if omitted. * @param {updateCallback} options.updateCallback Callback function that should * modify the files it wants to update, and return a promise resolving to the * list of updated files. * @param {string} options.branch Name for a new branch to use. * @param {string} options.message Commit message and pull request title. * @param {string} options.comment Pull request body. * @param {string[]} options.reviewers Reviewers' GitHub logins for the pull request. * @returns {undefined} No return value. Prints its progress to the console. */ export async function updateRepo(options: UpdateRepoOptions) { if (options.updateCallback === undefined) { throw new Error('updateRepo: updateCallback is required'); } if (options.branch === undefined) { throw new Error('updateRepo: branch is required'); } if (options.message === undefined) { throw new Error('updateRepo: message is required'); } const comment = options.comment || ''; const reviewers = options.reviewers || []; const config = await GetConfig.getConfig(); const github = new GitHub(config); const repos = await github.getRepositories(); for (const repository of repos) { console.log(repository.name); await processRepository( repository, options.updateCallback, options.branch, options.message, comment, reviewers ); } } /** * Callback async function that performs required change to the cloned * repository. * @callback updateCallback * @param {string} path Path to a temporary directory where the repository is * cloned. * @returns {Promise<string[]>} Promise resolving to a list of new or updated files * to include in commit. * Must resolve to `undefined` if the change was not applied for * any reason. In this case, no change will be committed. */ <file_sep><img src="https://avatars0.githubusercontent.com/u/1342004?v=3&s=96" alt="Google Inc. logo" title="Google" align="right" height="96" width="96"/> # GitHub Repo Automation > A set of tools to automate multiple GitHub repository management. **This is not an officially supported Google product.** As we publish Node.js client libraries to multiple repositories under [googleapis](https://github.com/googleapis/), we need a set of small tools to perform management of those repositories, such as updating continuous integration setup, updating dependencies, and so on. This repository contains some scripts that may be useful for this kind of tasks. ## Installation **Googlers**: You should install this tool on your laptop or workstation, as folks have run into timeout issues when using a Google Cloud Compute Engine instance. If you're not familiar with Node.js development you can still use the tools included as they don't require writing any Javascript code. Before running the scripts, make sure you have Node.js version 8+ installed (e.g. from [here](https://nodejs.org/en/)) and available in your `PATH`, and install the required dependencies: ```sh $ npm install -g @google/repo ``` You need to make your own [`config.yaml`](https://github.com/googleapis/github-repo-automation/blob/main/config.yaml.default) and put your GitHub token there. Example: ``` baseUrl: https://git.mycompany.com/api/v3 # optional, if you are using GitHub Enterprise githubToken: your-github-token clonePath: /User/my-user/.repo # optional repoSearch: org:googleapis language:typescript language:javascript is:public archived:false ``` The `repoSearch` field uses the [GitHub Repository Search syntax](https://help.github.com/en/github/searching-for-information-on-github/searching-for-repositories). You can set the path to the config file with the `REPO_CONFIG_PATH` environment variable: ```sh $ echo $REPO_CONFIG_PATH /User/beckwith/config.yaml ``` Now you are good to go! ## Usage ### PR based workflows The following commands operate over a collection of PRs. #### repo approve ```sh $ repo approve [--title title] ``` Iterates over all open pull requests matching `title` (this can be a regex, and all PRs will be processed if no regex for title is given) in all configured repositories. For each pull request, asks (in console) if it should be approved and merged. Useful for managing GreenKeeper's PRs: `$ repo approve 🚀` or all PRs with the word `test` in the title: `$ repo approve test` #### repo list ```sh $ repo list [--title title] ``` Iterates over all open pull requests matching `title` (this can be a regex, and all PRs will be processed if no regex for title is given) in all configured repositories, and prints them. `$ repo list --title 🚀` or all PRs with the word `test` in the title: `$ repo list --title test` #### repo reject ```sh $ repo reject [--title title] [--clean] ``` Iterates over all open pull requests matching `title` (this can be a regex, and all PRs will be processed if no regex for title is given) and closes them. For example, close all PRs with the word `test` in the title: `$ repo reject --title test` If `--clean` is specified, the branch associated with the PR will also be deleted. Branches on forked PRs will be ignored. #### repo rename ```sh $ repo rename --title title 'new title' ``` Iterates over all open pull requests matching `title` (this can be a regex, and all PRs will be processed if no regex for title is given), and renames them. #### repo apply ```sh $ repo apply --branch branch --message message --comment comment [--reviewers username[,username...]] [--silent] command ``` Iterates over all configured repositories, clones each of them into a temporary folder, and runs `command` to apply any changes you need. After `command` is run, `git status` is executed and all added and changed files are committed into a new branch `branch` with commit message `message`, and then a new pull request is created with comment `comment` and the given list of reviewers. Please note that because of GitHub API [does not support](https://github.com/isaacs/github/issues/199) inserting multiple files into one commit, each file will be committed separately. It can be fixed by changing this library to use the low-level [Git data API](https://developer.github.com/v3/git/), your contributions are welcome! #### repo check ```sh $ repo check ``` Iterates all configured repositories and checks that each repository is configured properly (branch protection, continuous integration, valid `README.md`, etc.). ### Repository based workflows In some cases, you may want to clone all of the repositories that match a given filter, and perform operations over them all locally. #### repo sync To clone or reset all repositories in a given filter set, run: ```sh $ repo sync ``` This will clone all repositories in the configured `clonePath`. From there, you can open the entire codebase in your favorite editor, and make changes. #### repo exec After cloning all repositories and making a set of batch changes, you will likely want to commit those changes, push upstream, and submit a pull request. For these, you can use `repo exec`. This command executes a given command over every cloned repository brought in via `repo sync`: ```sh $ repo exec -- git status ``` For example - to go through a typical PR workflow, you would run: ```sh $ repo exec -- git checkout -b my-branch-name $ repo exec -- git add -A $ repo exec -- git commit -m \"chore: do something fun\" $ repo exec -- git push origin my-branch-name $ repo exec --concurrency 1 -- gh pr create --fill ``` The `gh` tool referenced above uses https://cli.github.com/, and the `--concurrency` flag allows you to control how many pull requests are sent to the GitHub API at once. This is useful if you run into rate limiting or abuse errors. ## List of libraries The tools listed above use the following libraries available in `lib/` folder. Feel free to use them directly from your JavaScript code if you need more flexibility than provided by the tools. The files in `samples/` folder can serve as samples that show library usage. ### `lib/update-repo.js` Iterates over all configured repositories, clones each of them into a temporary folder, and calls the provided function to apply any changes you need. The function must return a promise resolving to the list of files to create or modify. These files are committed into a new branch with the given commit message, and then a new pull request is created with the given comment and the given list of reviewers. Please note that because of GitHub API [does not support](https://github.com/isaacs/github/issues/199) inserting multiple files into one commit, each file will be committed separately. It can be fixed by changing this library to use the low-level [Git data API](https://developer.github.com/v3/git/), your contributions are welcome! ```js const updateRepo = require('./lib/update-repo.js'); async function callbackFunction(repoPath) { // make any changes to the cloned repo in repoPath let files = ['path/to/updated/file', 'path/to/new/file']; return Promise.resolve(files); } async function example() { await updateRepo({ updateCallback: callbackFunction, branch: 'new-branch', message: 'commit message', comment: 'pull request comment', reviewers: ['github-username1', 'github-username2'], }); } ``` ### `lib/update-file.js` A function that applies the same fix to one file in all configured repositories, and sends pull requests (that can be approved and merged later by `approve-pr.js` or manually). Useful if you need to make the same boring change to all the repositories, such as change some configuration file in a certain way. ```js const updateFile = require('./lib/update-file.js'); function callbackFunction(content) { let newContent = content; // make any changes to file content return newContent; } async function example() { await updateFile({ path: 'path/to/file/in/repository', patchFunction: callbackFunction, branch: 'new-branch', message: 'commit message', comment: 'pull request comment', reviewers: ['github-username1', 'github-username2'], }); } ``` ### `lib/update-file-in-branch.js` A function that does pretty much the same, but to the file in the given branch in all configured repositories, and does not send any pull requests. Useful if you created a bunch of PRs using `update-file.js`, but then decided to apply a quick change in all created branches. ```js const updateFileInBranch = require('./lib/update-file-in-branch.js'); function callbackFunction(content) { let newContent = content; // make any changes to file content return newContent; } async function example() { await updateFileInBranch({ path: 'path/to/file/in/repository', patchFunction: callbackFunction, branch: 'existing-branch', message: 'commit message', }); } ``` ### Other files in `lib/` #### `lib/github.js` A simple wrapper to GitHub client API ([@octokit/rest](https://github.com/octokit/rest.js)) that at least lets you pass less parameters to each API call. #### `lib/question.js` A promisified version of `readline.question` to provide some primitive interaction. ## Handling large numbers of repositories If you are running GitHub Repo Automation against a large number of repositories, you may find that the default settings lead to quota issues. There are settings you can configure to make this less likely: 1. Set `--concurrency=N` to reduce the # of concurrent requests you are performing: ```bash repo approve --concurrency=4 --title='.*foo dep.*' ``` 2. Set `--retry` to automatically retry exceptions with an exponential backoff: ``` repo approve --retry --title='.*foo dep.*' ``` 3. Set `--delay=N` to introduce a delay between requests, allowing you to spread out operations over a longer timeframe: ``` repo approve --delay=2500 ``` When running against a large number of repos, try the following as a starting point: ```bash repo [command] --delay=1000 --concurrency=2 --retry --title='.*some title.*' ``` If you are continuing to run into problems, run with: ``` NODE_DEBUG=repo repo [command] --delay=1000 --concurrency=2 --retry --title='.*some title.*' ``` And share the debug output in an issue, along with the command you are running. <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 // // 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. /** * @fileoverview Runs the given command in each repository, and commits * files that were added or changed. */ import * as cp from 'child_process'; import * as fs from 'fs'; import * as meow from 'meow'; import ora from 'ora'; import Q from 'p-queue'; import * as path from 'path'; import {promisify} from 'util'; import {GetConfig} from './lib/config.js'; import {GitHub} from './lib/github.js'; import * as logger from './lib/logger.js'; const mkdir = promisify(fs.mkdir); const readdir = promisify(fs.readdir); const stat = promisify(fs.stat); const spawn = promisify(cp.exec); function print(res: {stdout: string; stderr: string}) { if (res.stdout) { console.log(res.stdout); } if (res.stderr) { console.log(res.stderr); } return res; } /** * Clone all repositories into ~/.repo. * If repo already exists, fetch and reset. */ export async function sync(cli: meow.Result<meow.AnyFlags>) { const repos = await getRepos(); const rootPath = await getRootPath(); const dirs = await readdir(rootPath); const orb = ora('Synchronizing repositories...').start(); let i = 0; const concurrency = cli.flags.concurrency ? Number(cli.flags.concurrency) : 50; const q = new Q({concurrency}); const proms = repos.map(repo => { const cloneUrl = repo.getRepository().ssh_url!; const cwd = path.join(rootPath, repo.name); return q.add(async () => { if (dirs.indexOf(repo.name) !== -1) { await spawn('git fetch --all', {cwd}); await spawn(`git reset --hard origin/${repo.baseBranch}`, {cwd}); await spawn(`git checkout ${repo.baseBranch}`, {cwd}); await spawn('git fetch origin', {cwd}); await spawn(`git reset --hard origin/${repo.baseBranch}`, {cwd}); orb.text = `[${i + 1}/${repos.length}] Synchronized ${repo.name}...`; } else { await spawn(`git clone ${cloneUrl}`, {cwd: rootPath}); orb.text = `[${i + 1}/${repos.length}] Cloned ${repo.name}...`; } i++; }); }); await Promise.all(proms); orb.succeed('Repo sync complete.'); } export async function exec(cli: meow.Result<meow.AnyFlags>) { const command = cli.input.slice(1); const rootPath = await getRootPath(); // get all of the subdirectories in ~/.repo. const files: string[] = await readdir(rootPath); const ps = await Promise.all( files.map(async file => { file = path.join(rootPath, file); const stats = await stat(file); return {file, isDirectory: stats.isDirectory()}; }) ); const dirs = ps.filter(x => x.isDirectory).map(x => x.file); if (dirs.length === 0) { // the user likely hasn't run sync yet. Lets be nice and do that for them. await sync(cli); } logger.info(`Executing '${command}' in ${dirs.length} directories.`); let i = 0; const concurrency = cli.flags.concurrency ? Number(cli.flags.concurrency) : 10; const q = new Q({concurrency}); const proms = dirs.map(dir => { return q.add(() => { return spawn(command.join(' '), {cwd: dir}) .then(r => { i++; logger.info(`[${i}/${dirs.length}] Executed cmd in ${dir}.`); print(r); }) .catch(e => { i++; logger.error(dir); logger.error(e); }); }); }); await Promise.all(proms); logger.info('Command execution successful.'); } async function getRepos() { const config = await GetConfig.getConfig(); const github = new GitHub(config); const repos = await github.getRepositories(); return repos.filter(x => !x.repository.archived); } async function getRootPath() { const config = await GetConfig.getConfig(); const repoPath = config.clonePath; if (!fs.existsSync(repoPath)) { await mkdir(repoPath); } return repoPath; } <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 // // 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 * as meow from 'meow'; import Q from 'p-queue'; import ora from 'ora'; import {debuglog} from 'util'; const debug = debuglog('repo'); import * as configLib from './config.js'; import {GitHub, GitHubRepository, PullRequest, Issue} from './github.js'; import {CacheType, readFromCache, saveToCache} from './cache.js'; /** * Retry the promise returned by a function if the promise throws * an exception. * @param {function} eventual method that returns a promise to retry. * @param {number[]} retryStrategy array of retry intervals. */ async function retryException<T>( eventual: () => Promise<T>, retryStrategy: Array<number> = [] ): Promise<T> { let result: T | undefined = undefined; for (let i = 0; i <= retryStrategy.length; i++) { try { result = await eventual(); return result; } catch (err) { if (i < retryStrategy.length) { debug(`operation failed: ${(err as Error).toString()}`); const delay = nextDelay(retryStrategy[i]); debug(`retrying in ${delay}ms`); await delayMs(delay); continue; } throw err; } } throw Error('unreachable'); } /** * Retry if the promise returned by the eventual function resolves * as false, indicating the operation failed. * @param {function} eventual method that returns a promise. * @param {number[]} retryStrategy array of retry intervals. */ async function retryBoolean( eventual: () => Promise<boolean>, retryStrategy: Array<number> = [] ): Promise<boolean> { for (let i = 0; i <= retryStrategy.length; i++) { const result = await eventual(); if (!result && i < retryStrategy.length) { const delay = nextDelay(retryStrategy[i]); debug(`retrying in ${delay}ms`); await delayMs(delay); continue; } else { return result; } } return true; } /* * Propose next delay, introducing some jitter. * @param {number} base delay. */ function nextDelay(base: number) { return base + (base / 4) * Math.random(); } /** * Promise that will resolve after ms provided. * @param {number} ms ms to delay. */ function delayMs(ms: number) { return new Promise(resolve => { setTimeout(() => { resolve(undefined); }, ms); }); } export interface PRIteratorOptions extends IteratorOptions { processMethod: ( repository: GitHubRepository, item: PullRequest, cli: meow.Result<meow.AnyFlags> ) => Promise<boolean>; } export interface IssueIteratorOptions extends IteratorOptions { processMethod: ( repository: GitHubRepository, item: Issue, cli: meow.Result<meow.AnyFlags> ) => Promise<boolean>; } export interface IteratorOptions { commandName: string; // approve commandNamePastTense: string; // approved commandActive: string; // approving commandDesc: string; additionalFlags?: string[]; } /** * Main function. Iterates pull requests or issues in the repositories of the * given organization matching given filters. Organization, filters, and GitHub * token should be given in the configuration file. * @param {string[]} args Command line arguments. */ async function process( cli: meow.Result<meow.AnyFlags>, options: PRIteratorOptions | IssueIteratorOptions, type: CacheType ) { if ( !cli.flags.title && !cli.flags.branch && !cli.flags.body && !cli.flags.label ) { console.log( `Usage: repo ${ options.commandName } [--branch branch] [--title title] [--body body] [--label label] ${options?.additionalFlags?.join( ' ' )}` ); console.log( 'Either branch name, body, label, or title regex must present.' ); console.log(options.commandDesc); return; } const concurrency = cli.flags.concurrency ? Number(cli.flags.concurrency) : 15; // Introduce a delay between requests, this may be necessary if // processing many repos in a row to avoid rate limits: const delay: number = cli.flags.delay ? Number(cli.flags.delay) : 500; const retry: boolean = cli.flags.retry ? Boolean(cli.flags.retry) : false; const config = await configLib.GetConfig.getConfig(); const retryStrategy = retry ? config.retryStrategy ?? [3000, 6000, 15000, 30000, 60000] : []; const github = new GitHub(config); const regex = new RegExp((cli.flags.title as string) || '.*'); const bodyRe = new RegExp((cli.flags.body as string) || '.*'); const repos = await retryException<GitHubRepository[]>(() => { return github.getRepositories(); }, retryStrategy); const successful: Issue[] = []; const failed: Issue[] = []; let error: string | undefined; let processed = 0; let scanned = 0; let items = new Array<{repo: GitHubRepository; item: PullRequest | Issue}>(); const orb1 = ora( `[${scanned}/${repos.length}] Scanning repos for ${ type === 'issues' ? 'issues' : 'PR' }s` ).start(); // Concurrently find all PRs or issues in all relevant repositories let cached = 0; const q = new Q({concurrency}); q.addAll( repos.map(repo => { return async () => { try { let localItems; if (!cli.flags.nocache) { const cachedData = await readFromCache(repo, type); if (cachedData !== null) { localItems = (type === 'issues' ? cachedData.issues : cachedData.prs) ?? []; ++cached; } } if (!localItems) { if (type === 'issues') { localItems = await retryException<Issue[]>(async () => { if (delay) await delayMs(nextDelay(delay)); return await repo.listIssues(); }, retryStrategy); await saveToCache(repo, type, {prs: [], issues: localItems}); } else { localItems = await retryException<PullRequest[]>(async () => { if (delay) await delayMs(nextDelay(delay)); return await repo.listPullRequests(); }, retryStrategy); await saveToCache(repo, type, {prs: localItems, issues: []}); } } items.push( ...localItems.map(item => { return {repo, item}; }) ); scanned++; orb1.text = `[${scanned}/${repos.length}] Scanning repos for ${ type === 'issues' ? 'issue' : 'PR' }`; } catch (err) { error = `cannot list open ${type === 'issues' ? 'issue' : 'PR'}s: ${( err as Error ).toString()}`; } }; }) ); await q.onIdle(); if (cached > 0) { console.log( `\nData for ${cached} repositories was taken from cache. Use --nocache to override.` ); } // Filter the list of PRs or Issues to ones who match the PR title and/or the branch name items = items.filter(itemSet => itemSet.item.title.match(regex)); if (cli.flags.branch) { console.log(`Branch scan: ${cli.flags.branch}`); items = items.filter(itemSet => { const pr = itemSet.item as PullRequest; return new RegExp(cli.flags.branch as string).test(pr.head.ref); }); } if (cli.flags.label) { console.log(`Label scan: ${cli.flags.label}`); items = items.filter(itemSet => { const pr = itemSet.item as PullRequest; return pr.labels.some(label => { return new RegExp(cli.flags.label as string).test(label.name); }); }); } if (cli.flags.body) { items = items.filter(itemSet => { if (!itemSet.item.body) return false; else return itemSet.item.body.match(bodyRe); }); } if (cli.flags.author) { items = items.filter( itemSet => itemSet.item.user.login === cli.flags.author ); } orb1.succeed( `[${scanned}/${repos.length}] repositories scanned, ${ items.length } matching ${type === 'issues' ? 'issue' : 'PR'}s found` ); // Concurrently process each relevant PR or Issue const orb2 = ora( `[${processed}/${items.length}] ${options.commandNamePastTense}` ).start(); q.addAll( items.map(itemSet => { return async () => { const title = itemSet.item.title!; if (title.match(regex)) { orb2.text = `[${processed}/${items.length}] ${ options.commandActive } ${type === 'issues' ? 'issue' : 'PR'}s`; let result; // By setting the process issues flag, the iterator can be made to // process a list of issues rather than PR: if (type === 'issues') { const opts = options as IssueIteratorOptions; result = await retryBoolean(async () => { if (delay) await delayMs(nextDelay(delay)); return await opts.processMethod( itemSet.repo, itemSet.item as Issue, cli ); }, retryStrategy); } else { const opts = options as PRIteratorOptions; result = await retryBoolean(async () => { if (delay) await delayMs(nextDelay(delay)); return await opts.processMethod( itemSet.repo, itemSet.item as PullRequest, cli ); }, retryStrategy); } if (result) { successful.push(itemSet.item); } else { failed.push(itemSet.item); } processed++; orb2.text = `[${processed}/${items.length}] ${ options.commandActive } ${type === 'issues' ? 'issue' : 'PR'}s`; } }; }) ); await q.onIdle(); orb2.succeed( `[${processed}/${items.length}] ${type === 'issues' ? 'issue' : 'PR'}s ${ options.commandNamePastTense }` ); // Pretty-print as a table const maxUrlLength = items .map(item => item.item) .reduce( (maxLength: number, item: Issue | PullRequest) => item.html_url.length > maxLength ? item.html_url.length : maxLength, 0 ); console.log( `Successfully processed: ${successful.length} ${ type === 'issues' ? 'issue' : 'PR' }s` ); for (const item of successful) { console.log(` ${item.html_url.padEnd(maxUrlLength, ' ')} ${item.title}`); } if (failed.length > 0) { console.log( `Unable to process: ${failed.length} ${ type === 'issues' ? 'issue' : 'PR' }(s)` ); for (const item of failed) { console.log(` ${item.html_url.padEnd(maxUrlLength, ' ')} ${item.title}`); } } if (error) { console.log( `Error when processing ${type === 'issues' ? 'issue' : 'PR'}s: ${error}` ); } } // Shorthand for processing list of PRs: export async function processPRs( cli: meow.Result<meow.AnyFlags>, options: PRIteratorOptions | IssueIteratorOptions ) { return process(cli, options, 'prs'); } // Shorthand for processing list of issues: export async function processIssues( cli: meow.Result<meow.AnyFlags>, options: PRIteratorOptions | IssueIteratorOptions ) { return process(cli, options, 'issues'); } <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 // // 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. /** * @fileoverview Unit tests for lib/github.js. */ import assert from 'assert'; import {describe, it} from 'mocha'; import nock from 'nock'; import {Config} from '../src/lib/config.js'; import { getClient, GitHub, GitHubRepository, Repository, } from '../src/lib/github.js'; nock.disableNetConnect(); const testConfig: Config = { githubToken: 'test-github-token', clonePath: '', repos: [{org: 'test-organization', regex: 'matches'}], }; const testRepo: Repository = { name: 'test-repo', owner: {login: 'test-organization'}, default_branch: 'main', }; const testConfigSearch: Config = { githubToken: 'test-github-token', clonePath: '', repoSearch: 'a-search', }; const url = 'https://api.github.com'; let repo: GitHubRepository; describe('GitHub', () => { it('should get the list of repositories', async () => { const github = new GitHub(testConfig); const path = '/orgs/test-organization/repos?type=public&page=1&per_page=100'; const name = 'matches'; const owner = {login: 'test-organization'}; const scope = nock(url).get(path).reply(200, [{name, owner}]); const repos = await github.getRepositories(); scope.done(); assert.strictEqual(repos.length, 1); repo = repos[0]; }); it('should search for repositories', async () => { const github = new GitHub(testConfigSearch); const path = '/search/repositories?per_page=100&page=1&q=a-search'; const full_name = 'test-organization/matches'; const default_branch = 'main'; const scope = nock(url) .get(path) .reply(200, { items: [ { full_name, default_branch, }, ], }); const repos = await github.getRepositories(); scope.done(); assert.strictEqual(repos.length, 1); assert.deepStrictEqual(repos[0].repository, { owner: {login: 'test-organization'}, name: 'matches', ssh_url: '<EMAIL>.com:test-organization/matches.git', default_branch: 'main', }); repo = repos[0]; }); it('should include auth headers', async () => { const response = {hello: 'world'}; const path = '/repos/test-organization/matches/contents/index.test'; const scope = nock(url) .get(path, undefined, { reqheaders: {authorization: 'token test-github-token'}, }) .reply(200, response); const file = await repo.getFile('index.test'); assert.deepStrictEqual(file, response); scope.done(); }); it('should get a list of repos when using the query syntax', async () => { const github = new GitHub({ githubToken: 'test-github-token', clonePath: '', repoSearch: 'org:testy language:python', }); const path = '/search/repositories?q=org%3Atesty+language%3Apython&per_page=100&page=1'; const name = 'matches'; const owner = {login: 'testy'}; const scope = nock(url) .get(path) .reply(200, { items: [{full_name: `${owner}/${name}`, default_branch: 'main'}], }); const repos = await github.getRepositories(); scope.done(); assert.strictEqual(repos.length, 1); }); }); describe('GitHubRepository', () => { it('should create a branch', async () => { const testingClient = getClient(testConfig); const repo = new GitHubRepository( testingClient, testRepo, 'test-organization' ); const path = '/repos/test-organization/test-repo/git/refs'; const ref = 'refs/heads/test-branch'; const sha = '97C0FFA2A1F8E1034924EB33567B5AF77DA18255'; const scope = nock(url).post(path, {ref, sha}).reply(201, {ref}); const branch = await repo.createBranch('test-branch', sha); scope.done(); assert.deepEqual(branch, {ref}); }); it('should delete a branch', async () => { const testingClient = getClient(testConfig); const repo = new GitHubRepository( testingClient, testRepo, 'test-organization' ); const path = '/repos/test-organization/test-repo/git/refs/heads/test-branch'; const scope = nock(url).delete(path).reply(204); await repo.deleteBranch('test-branch'); scope.done(); }); it('should merge two branches', async () => { const testingClient = getClient(testConfig); const repo = new GitHubRepository( testingClient, testRepo, 'test-organization' ); const path = '/repos/test-organization/test-repo/merges'; const base = 'test-branch-base'; const head = 'test-branch-head'; const ref = 'test-branch-base'; const scope = nock(url).post(path, {base, head}).reply(201, {ref}); const branch = await repo.updateBranch(base, head); scope.done(); assert.deepEqual(branch, {ref}); }); it('should get a branch', async () => { const testingClient = getClient(testConfig); const repo = new GitHubRepository( testingClient, testRepo, 'test-organization' ); const path = '/repos/test-organization/test-repo/branches/test-branch'; const ref = 'refs/heads/test-branch'; const scope = nock(url).get(path).reply(200, {ref}); const branch = await repo.getBranch('test-branch'); scope.done(); assert.deepEqual(branch, {ref}); }); }); <file_sep>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Adds a collaborator to all repositories. */ 'use strict'; const {getConfig} = require('../build/src/lib/config'); const {GitHub} = require('../build/src/lib/github.js'); const sodium = require('tweetsodium'); const meow = require('meow'); const {TextEncoder} = require('text-encoding-shim'); /** Main function. */ async function main() { const cli = meow( ` Usage $ node ./samples/create-secret.js key secret `, {} ); if (cli.input.length < 2) { return cli.showHelp(-1); } const [key, secret] = cli.input; const config = await getConfig(); const github = new GitHub(config); const repos = await github.getRepositories(); let index = 0; for (const repository of repos) { const publicKey = ( await github.client.get( `/repos/${repository.repository.owner.login}/${repository.repository.name}/actions/secrets/public-key` ) ).data; const encoder = new TextEncoder(); const messageBytes = encoder.encode(secret); const encoded = sodium.seal( messageBytes, Buffer.from(publicKey.key, 'base64') ); await github.client.put( `/repos/${repository.repository.owner.login}/${repository.repository.name}/actions/secrets/${key}`, { encrypted_value: Buffer.from(encoded).toString('base64'), key_id: publicKey.key_id, } ); console.log( `${repository.name}: [.] creating secret repository (${index} of ${repos.length} repositories completed)` ); ++index; } console.log(`${repos.length} repositories completed`); } main().catch(err => { console.error(err.toString()); }); <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 // // 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. /** * @fileoverview Verifies that the repository is compliant: CI running, * greenkeeper enabled, the base branch protected, README links valid, etc. */ import {request, GaxiosResponse} from 'gaxios'; import {GetConfig} from './lib/config.js'; import {GitHub, GitHubRepository} from './lib/github.js'; /** * Logs and counts errors and warnings to console with fancy coloring. */ class Logger { errorCount: number; warningCount: number; constructor() { this.errorCount = 0; this.warningCount = 0; } /** * Log error to console. * @param {text} Error message. */ error(text: string) { ++this.errorCount; console.log(text); } /** * Log warning to console. * @param {text} Warning message. */ warning(text: string) { ++this.warningCount; console.log(`\x1b[2m${text}\x1b[0m`); } /** * Log information to console. * @param {text} Message. */ info(text: string) { console.log(`\x1b[2m${text}\x1b[0m`); } } /** * Checks GitHub base branch protection settings. * Logs all errors and warnings. * @param {GitHubRepository} repository Repository object. * @param {Logger} logger Logger object. */ async function checkGithubBaseBranchProtection( logger: Logger, repository: GitHubRepository ) { let getBranchRes; try { getBranchRes = await repository.getBranch(repository.baseBranch); } catch (err) { logger.error( `${repository.name}: [!] cannot fetch branch information, no access?` ); return; } if (!getBranchRes.protected) { logger.error( `${repository.name}: [!] branch protection for ${repository.baseBranch} branch is disabled` ); return; } let response; try { response = await repository.getRequiredBaseBranchProtection(); } catch (err) { logger.error( `${repository.name}: [!] cannot fetch branch protection settings, no access?` ); return; } if (response['required_pull_request_reviews'] === undefined) { logger.error( `${repository.name}: [!] branch protection for ${repository.baseBranch} branch - pull request reviews are not required` ); } if (response['required_status_checks'] !== undefined) { const requiredStatusChecks = [ 'ci/kokoro: node6', 'ci/kokoro: node8', 'ci/kokoro: node10', 'ci/kokoro: lint', 'ci/kokoro: Samples test', 'ci/kokoro: System test', ]; for (const check of requiredStatusChecks) { let enabled = false; for (const enabledCheck of response['required_status_checks'][ 'contexts' ]) { if (enabledCheck === check) { enabled = true; } } if (!enabled) { logger.error( `${repository.name}: [!] branch protection for ${repository.baseBranch} branch - status check ${check} is not required` ); } } } else { logger.error( `${repository.name}: [!] branch protection for ${repository.baseBranch} branch - status checks are not enabled` ); } } /** * Checks if Renovate is enabled for GitHub repository. * Logs all errors and warnings. * @param {GitHubRepository} repository Repository object. * @param {Logger} logger Logger object. */ async function checkRenovate(logger: Logger, repository: GitHubRepository) { const response = await repository.listPullRequests('closed'); let renovateFound = false; for (const pullRequest of response) { if (pullRequest.user!.login === 'renovate[bot]') { renovateFound = true; break; } } if (!renovateFound) { logger.error(`${repository.name}: [!] GreenKeeper is probably not enabled`); } } /** * Checks that the version of the dependency in samples/package.json * matches the version of the package defined in package.json. * E.g. if the package is "@google-cloud/example" version "1.2.3", * samples must depend on exactly "@google-cloud/example": "1.2.3". * Logs all errors and warnings. * @param {GitHubRepository} repository Repository object. * @param {Logger} logger Logger object. */ async function checkSamplesPackageDependency( logger: Logger, repository: GitHubRepository ) { let response; try { response = await request({ url: `https://raw.githubusercontent.com/${repository.organization}/${repository.name}/${repository.baseBranch}/package.json`, }); } catch (err) { logger.error( `${repository.name}: [!] cannot download package.json: ${( err as Error ).toString()}` ); return; } // eslint-disable-next-line @typescript-eslint/no-explicit-any const packageJson: any = response.data; try { response = await request({ url: `https://raw.githubusercontent.com/${repository.organization}/${repository.name}/${repository.baseBranch}/samples/package.json`, }); } catch (err) { logger.warning(`${repository.name}: [!] no samples/package.json.`); return; } // eslint-disable-next-line @typescript-eslint/no-explicit-any const samplesPackageJson: any = response.data; try { const mainVersion = packageJson['version']; const mainName = packageJson['name']; const samplesDependency = samplesPackageJson['dependencies'][mainName]; const regex = '^[^]?' + mainVersion.replace(/\./g, '.') + '$'; // 1.12.3 ==> ^[^]?1\.12\.3$ if (!samplesDependency.match(regex)) { logger.error( `${repository.name}: [!] main package version ${mainVersion} does not match samples dependency ${samplesDependency}` ); } } catch (err) { logger.error( `${repository.name}: cannot check samples package dependencies: ${( err as Error ).toString()}` ); } } /** * Checks if README.md contains any broken links. * Logs all errors and warnings. * @param {Logger} logger Logger object. * @param {GitHubRepository} repository Repository object. */ async function checkReadmeLinks(logger: Logger, repository: GitHubRepository) { let response: GaxiosResponse<string>; try { response = await request<string>({ url: `https://raw.githubusercontent.com/${repository.organization}/${repository.name}/${repository.baseBranch}/README.md`, }); } catch (err) { logger.error( `${repository.name}: [!] cannot download README.md: ${( err as Error ).toString()}` ); return; } const readme = response.data; const links: string[] = []; const reflinksRegex = /\[[^[\]]*?\]: (http.*)/g; for (;;) { const reflinksMatch = reflinksRegex.exec(readme); if (reflinksMatch === null) { break; } links.push(reflinksMatch[1]); } const linksRegex = /\[[^[\]]*?\]\((http.*?)\)/g; for (;;) { const linksMatch = linksRegex.exec(readme); if (linksMatch === null) { break; } links.push(linksMatch[1]); } for (const link of links) { const regex = /^(https?):\/\/([^/]+)(\/.*?)?(?:#.*)?$/; const match = regex.exec(link); if (!match) { logger.error( `${repository.name}: [!] README.md has link ${link} which does not look valid` ); continue; } try { await request({url: link}); } catch (err) { logger.error( `${repository.name}: [!] README.md has link ${link} which does not work` ); } } } /** * Iterates over all repositories according to the configuration file and runs * all checks for each of them. Logs errors and warnings. * @param {Logger} logger Logger object. */ async function checkAllRepositories(logger: Logger) { const config = await GetConfig.getConfig(); const github = new GitHub(config); const repos = await github.getRepositories(); let index = 0; for (const repository of repos) { logger.info( `${repository.name}: [.] checking repository (${index} of ${repos.length} repositories completed)` ); const errorCounter = logger.errorCount; await checkGithubBaseBranchProtection(logger, repository); await checkRenovate(logger, repository); await checkSamplesPackageDependency(logger, repository); await checkReadmeLinks(logger, repository); const foundErrors = logger.errorCount - errorCounter; logger.info( `${repository.name}: [.] ${foundErrors === 0 ? 'no' : foundErrors} error${ foundErrors === 1 ? '' : 's' } found` ); ++index; } logger.info(`${repos.length} repositories completed`); } /** * Main function. */ export async function main() { const logger = new Logger(); await checkAllRepositories(logger); process.exitCode = logger.errorCount; logger.info(`Total errors: ${logger.errorCount}`); logger.info(`Total warnings: ${logger.warningCount}`); } <file_sep>// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {existsSync} from 'fs'; import {mkdir, readFile, stat, unlink, writeFile} from 'fs/promises'; import {tmpdir} from 'os'; import {join} from 'path'; import {Mutex} from 'async-mutex'; import {GitHubRepository, Issue, PullRequest} from './github'; const cacheDirectory = join(tmpdir(), 'google-repo-cache'); const cacheMaxAge = 60 * 60 * 1000; // 1 hour export type CachedData = {issues?: Issue[]; prs?: PullRequest[]}; export type CacheType = 'prs' | 'issues'; const mutex = new Mutex(); async function initCache() { if (!existsSync(cacheDirectory)) { await mkdir(cacheDirectory); } } function cacheFilename(repo: GitHubRepository, type: CacheType) { const owner = repo.repository.owner.login; const name = repo.repository.name; return join( cacheDirectory, `${owner}-${name}`.replace(/\W/g, '-') + `-${type}` ); } export async function readFromCache(repo: GitHubRepository, type: CacheType) { const release = await mutex.acquire(); try { await initCache(); const cacheFile = cacheFilename(repo, type); if (!existsSync(cacheFile)) { return null; } const cacheStat = await stat(cacheFile); const mtime = cacheStat.mtimeMs ?? cacheStat.ctimeMs; const now = Date.now(); if (now - mtime >= cacheMaxAge) { await unlink(cacheFile); return null; } const content = await readFile(cacheFile); const json = JSON.parse(content.toString()) as CachedData; return json; } finally { release(); } } export async function saveToCache( repo: GitHubRepository, type: CacheType, data: CachedData ) { const release = await mutex.acquire(); try { await initCache(); const cacheFile = cacheFilename(repo, type); if (!data.issues) { data.issues = []; } if (!data.prs) { data.prs = []; } const content = JSON.stringify(data, null, ' '); await writeFile(cacheFile, content); } finally { release(); } } export async function deleteCache(repo: GitHubRepository, type: CacheType) { const release = await mutex.acquire(); try { await initCache(); const cacheFile = cacheFilename(repo, type); if (existsSync(cacheFile)) { await unlink(cacheFile); } } finally { release(); } } <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 // // 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. /** * @fileoverview Updates main branch protection to remove node7 task from the * list of required CI tasks. */ 'use strict'; const meow = require('meow'); const {getConfig} = require('../build/src/lib/config.js'); const {GitHub} = require('../build/src/lib/github'); async function main(input) { const config = await getConfig(); const github = new GitHub(config); const repos = await github.getRepositories(); for (const repository of repos) { console.log(repository.getRepository()['name']); let statusChecks; try { statusChecks = await repository.getRequiredMasterBranchProtectionStatusChecks(); } catch (err) { console.warn(' error getting required status checks:', err.toString()); continue; } if (statusChecks === undefined) { console.warn(' no status checks set up for this repo, skipping'); continue; } const contexts = statusChecks['contexts']; if (input[0] === 'remove') { const index = contexts.indexOf(input[1]); contexts.splice(index, 1); } else if (input[0] === 'add') { contexts.push(input[1]); } else { throw Error(`unrecognized command ${input[0]}`); } try { await repository.updateRequiredBaseBranchProtectionStatusChecks(contexts); } catch (err) { console.warn(' error setting required status checks:', err.toString()); continue; } } } const cli = meow( ` Usage $ node update-branch-protection.js remove "ci/kokoro: node11" $ node update-branch-protection.js add "ci/kokoro: node12" ` ); if (cli.input.length < 2) { cli.showHelp(-1); } else { main(cli.input).catch(err => { console.error(err.toString()); }); } <file_sep>// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for lib/asyncItemIterator.js. */ import assert from 'assert'; import meow from 'meow'; import {describe, it} from 'mocha'; import nock from 'nock'; import * as sinon from 'sinon'; import {GitHubRepository, PullRequest} from '../src/lib/github.js'; import * as config from '../src/lib/config.js'; import {processPRs} from '../src/lib/asyncItemIterator.js'; import {deleteCache} from '../src/lib/cache.js'; nock.disableNetConnect(); describe('asyncItemIterator', () => { afterEach(() => { sinon.restore(); }); it('should retry list operation on failure', async () => { sinon.stub(config.GetConfig, 'getConfig').resolves({ githubToken: '<PASSWORD>', clonePath: '/foo/bar', retryStrategy: [5, 10, 20], repoSearch: 'org:googleapis language:typescript language:javascript is:public archived:false', }); const cli = { flags: { title: '.*', retry: true, nocache: true, }, } as unknown as ReturnType<typeof meow>; const githubRequests = nock('https://api.github.com') .get( '/search/repositories?per_page=100&page=1&q=org%3Agoogleapis%20language%3Atypescript%20language%3Ajavascript%20is%3Apublic%20archived%3Afalse' ) .reply(200, { items: [ { full_name: 'googleapis/foo', default_branch: 'main', }, ], }) .get('/repos/googleapis/foo/pulls?state=open&page=1') .reply(403) .get('/repos/googleapis/foo/pulls?state=open&page=1') .reply(403) .get('/repos/googleapis/foo/pulls?state=open&page=1') .reply(200); await processPRs(cli, { commandName: 'update', commandActive: 'updating', commandNamePastTense: 'updated', commandDesc: 'Iterates over all PRs matching the regex, and updates them, to the latest on the base branch.', processMethod: async () => { return true; }, }); githubRequests.done(); }); it('should use cache', async () => { await deleteCache( { repository: { owner: { login: 'googleapis', }, name: 'foo', }, } as GitHubRepository, 'prs' ); sinon.stub(config.GetConfig, 'getConfig').resolves({ githubToken: '<PASSWORD>', clonePath: '/foo/bar', repoSearch: 'org:googleapis language:typescript language:javascript is:public archived:false', }); const cli = { flags: { title: '.*', retry: true, nocache: false, }, } as unknown as ReturnType<typeof meow>; const githubRequests = nock('https://api.github.com') // for the first invocation .get( '/search/repositories?per_page=100&page=1&q=org%3Agoogleapis%20language%3Atypescript%20language%3Ajavascript%20is%3Apublic%20archived%3Afalse' ) .reply(200, { items: [ { full_name: 'googleapis/foo', default_branch: 'main', }, ], }) .get('/repos/googleapis/foo/pulls?state=open&page=1') .reply(200, [ { title: 'feat: foo pull request', html_url: 'http://example.com/pr/2', }, ]) .get('/repos/googleapis/foo/pulls?state=open&page=2') .reply(200) // just the repositories for the second invocation .get( '/search/repositories?per_page=100&page=1&q=org%3Agoogleapis%20language%3Atypescript%20language%3Ajavascript%20is%3Apublic%20archived%3Afalse' ) .reply(200, { items: [ { full_name: 'googleapis/foo', default_branch: 'main', }, ], }); // First invocation: fill the cache await processPRs(cli, { commandName: 'update', commandActive: 'updating', commandNamePastTense: 'updated', commandDesc: 'Iterates over all PRs matching the regex, and updates them, to the latest on the base branch.', processMethod: async () => { return true; }, }); // Second invocation: must use the cache const titles: string[] = []; await processPRs(cli, { commandName: 'update', commandActive: 'updating', commandNamePastTense: 'updated', commandDesc: 'Iterates over all PRs matching the regex, and updates them, to the latest on the base branch.', processMethod: async (_repo: unknown, pr: {title: string}) => { titles.push(pr.title); return true; }, }); githubRequests.done(); assert.strictEqual(titles.length, 1); assert.strictEqual(titles[0], 'feat: foo pull request'); }); it('should retry process method if it returns false', async () => { sinon.stub(config.GetConfig, 'getConfig').resolves({ githubToken: 'abc123', clonePath: '/foo/bar', retryStrategy: [5, 10, 20], repoSearch: 'org:googleapis language:typescript language:javascript is:public archived:false', }); const cli = { flags: { title: '.*', retry: true, nocache: true, }, } as unknown as ReturnType<typeof meow>; const githubRequests = nock('https://api.github.com') .get( '/search/repositories?per_page=100&page=1&q=org%3Agoogleapis%20language%3Atypescript%20language%3Ajavascript%20is%3Apublic%20archived%3Afalse' ) .reply(200, { items: [ { full_name: 'googleapis/foo', default_branch: 'main', }, ], }) .get('/repos/googleapis/foo/pulls?state=open&page=1') .reply(200, [ { title: 'feat: foo pull request', html_url: 'http://example.com/pr/2', }, ]) .get('/repos/googleapis/foo/pulls?state=open&page=2') .reply(200); let retryCount = 0; await processPRs(cli, { commandName: 'update', commandActive: 'updating', commandNamePastTense: 'updated', commandDesc: 'Iterates over all PRs matching the regex, and updates them, to the latest on the base branch.', processMethod: async (repository: GitHubRepository, pr: PullRequest) => { assert.strictEqual(repository.name, 'foo'); assert.strictEqual(pr.html_url, 'http://example.com/pr/2'); retryCount++; if (retryCount > 2) return true; else return false; }, }); assert.strictEqual(retryCount, 3); githubRequests.done(); }); }); <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 // // 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. /** * @fileoverview Adds a collaborator to all repositories. */ 'use strict'; const GitHub = require('../build/src/lib/github.js'); const question = require('../build/src/lib/question.js'); /** Main function. */ async function main() { const username = await question('Enter username to add as collaborator:'); if (username === undefined || username.match(/^\s*$/)) { console.log('Canceling.'); return; } let permission = await question( 'Enter permission level: push, pull, or admin [push]:' ); if (permission === undefined || permission.match(/^\s*$/)) { permission = 'push'; } if (!['push', 'pull', 'admin'].includes(permission)) { console.log('Incorrect permission entered.'); return; } const github = new GitHub(); await github.init(); const repos = await github.getRepositories(); let index = 0; for (const repository of repos) { console.log( `${repository.name}: [.] processing repository (${index} of ${repos.length} repositories completed)` ); await repository.addCollaborator(username, permission); ++index; } console.log(`${repos.length} repositories completed`); } main().catch(err => { console.error(err.toString()); }); <file_sep>#!/bin/sh # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # @fileoverview Update package-lock.json in both the main package and # the samples package. Also, verify that samples depend on the correct # version of the main package. # Requires `jq` tool to be installed (https://stedolan.github.io/jq/). # Pass this script as a parameter to `apply-change.js`. rm -f package-lock.json if test -f samples/package.json ; then main_name=`jq -r .name package.json` main_version=`jq -r .version package.json` samples_dependency=`jq -r ".dependencies.\"$main_name\"" samples/package.json` if [ "$main_version" == "$samples_dependency" ]; then echo "Samples version is good." else echo "Making changes! Current version of $main_name is $main_version, samples depend on version $samples_dependency." jq -r ".dependencies.\"$main_name\"=\"$main_version\"" samples/package.json > samples/package.json.new mv samples/package.json.new samples/package.json fi rm -f samples/package-lock.json fi npm install npm link if test -f samples/package.json ; then cd samples npm link ../ npm install cd .. fi echo "Git status:" git status echo "Done!" exit 0
9ed1532994a7e21fb8cbc454a54229ca5ce9b7d6
[ "Markdown", "TypeScript", "JavaScript", "Shell" ]
26
Markdown
googleapis/github-repo-automation
98a62c01242d1034da2373d0b6ad752af5c8711d
f313d40d6cea895aaae881561ea140d35ff2abb0
refs/heads/master
<file_sep>__author__ = 'Jason' # DONE from addVHS import * from createVHSdatabase import * from deleteVHS import * from displayVHScollection import * from displayVHS import * from updateVHS import * # Import functions def main(): while True: print(" ------------------------------ _________________________________________\n" "|/////// VHS Database /////////| | ___________________^___________________ |\n" "|/////// Manager /////////| |/ \|\n" "|------------------------------| | ______ _________________ ______ |\n" "| 1 - Create VHS Database | | / ####| || ------------- || |## \ |\n" "| 2 - Add a VHS to Database | | | ####/| || ------------- || |\## | |\n" "| 3 - Update a VHS | | | ####| | || ----V/H/S---- || | |## | |\n" "| 4 - Delete a VHS | | | ####| | || ------------- || | |## | |\n" "| 5 - Display VHS collection | | | ####\| || ------------- || |/## | |\n" "| 6 - Display a VHS | | \__####| ||_______________|| |##____/ |\n" "| 7 - Quit | | |\n" " ------------------------------ |_________________________________________|") # Display menu while True: try: menu_choice = int(input("Which function would you like to use? (1-7): ")) # Get user input for menu choice except ValueError: print("\n//ERROR//:Please choose a valid number (1-7)//") else: if menu_choice < 1 or menu_choice > 7: print("\n//ERROR//:Please choose a valid number (1-7)//") else: break # Check for valid menu choice option if menu_choice == 1: create_vhs_database() # Menu option 1 - create database elif menu_choice == 2: add_vhs() # Menu option 2 - add VHS to database elif menu_choice == 3: update_vhs() # Menu option 3 - update VHS in database elif menu_choice == 4: delete_vhs() # Menu option 4 - delete VHS from database elif menu_choice == 5: display_vhs_collection() # Menu option 5 - display all VHS in database elif menu_choice == 6: display_vhs() # Menu option 6 - display single VHS from database elif menu_choice == 7: break # Menu option 7 - Quit program main() <file_sep>__author__ = "Jason" # DONE import sqlite3 # Import sqlite3 for database def display_vhs_collection(): while True: try: vhs_database = "VHSDatabase.db" # Get VHS database current_conn = sqlite3.connect(vhs_database) cur_cur = current_conn.cursor() print("\n//VHS Database connected//\n") # Connect to VHS database cur_cur.execute("SELECT * FROM VHS_TAPES") # Query to display VHS database except sqlite3.OperationalError: print("\n//ERROR//:VHS Database needs to be created//") break # Check for valid database else: for row in cur_cur: print("\nUPC = ", row[0]) print("TITLE = ", row[1]) print("GENRE = ", row[2]) print("PRICE_PAID = ", row[3]) print("PRICE_WORTH = ", row[4]) print("NOTES = ", row[5]) print("RENTALS = ", row[6], "\n") # Display each VHS_TITLE in VHS database current_conn.commit() current_conn.close() break # Commit changes to VHS database and close <file_sep>__author__ = 'Jason' # DONE import sqlite3 # Import sqlite3 for database def create_vhs_database(): cur_con = sqlite3.connect('VHSDatabase.db') print("\n//VHS Database connected//\n") # Open/create VHS database while True: try: cur_con.execute("CREATE TABLE VHS_TAPES \ (UPC INTEGER PRIMARY KEY NOT NULL, \ TITLE TEXT NOT NULL, \ GENRE TEXT, \ PRICE_PAID INT, \ PRICE_WORTH REAL NOT NULL, \ NOTES CHAR(50), \ RENTALS INT);") # Create VHS_TAPES table except sqlite3.OperationalError: print("\n//ERROR//:VHS Table already exists//") # Check for preexisting VHS_TAPES table else: cur_con.close() print("//VHS Table created//\n") # Close VHS database break <file_sep>__author__ = "Jason" # DONE import sqlite3 # Import sqlite3 for database def display_vhs(): while True: try: vhs_database = "VHSDatabase.db" # Create variable for VHS database while True: try: vhs_upc = int(input("\nEnter the UPC of the VHS to view: ")) # Get user input for VHS UPC number except ValueError: print("\n//ERROR//:VHS UPC must be a valid integer//") # Check for valid UPC number else: break cur_con = sqlite3.connect(vhs_database) cur_cur = cur_con.cursor() print("\n//VHS Database connected//\n") # Create connection to VHS database do_what = "SELECT * FROM PRODUCTS WHERE UPC = ?" do_how = (vhs_upc,) # Variables for VHS database entries cur_cur.execute(do_what, do_how) # Query to display VHS except sqlite3.OperationalError: print("\n//ERROR//:VHS table does not exist, please create//") break # Check for VHS_TAPES table else: for row in cur_cur: print("\nUPC = ", row[0]) print("TITLE = ", row[1]) print("GENRE = ", row[2]) print("PRICE_PAID = ", row[3]) print("PRICE_WORTH = ", row[4]) print("NOTES = ", row[5]) print("RENTALS = ", row[6], "\n") # Display all rows for current VHS cur_con.commit() cur_con.close() break # Commit changes to VHS database and close <file_sep>__author__ = "Jason" # DONE import sqlite3 # Import sqlite3 for database def delete_vhs(): vhs_database = "VHSDatabase.db" # Get VHS database while True: try: while True: try: vhs_upc = int(input("\nEnter UPC of the VHS to delete: ")) # Get user input for VHS UPC number except ValueError: print("\n//ERROR//:VHS UPC must be a valid integer//") # Check for valid UPC number else: cur_con = sqlite3.connect(vhs_database) cur_cur = cur_con.cursor() print("\n//VHS Database connected//\n") # Connect to VHS database do_what = "DELETE FROM PRODUCTS WHERE UPC = ?" do_how = (vhs_upc,) # Variables for VHS database entries cur_cur.execute(do_what, do_how) break # Enter variables into VHS database except sqlite3.OperationalError: print("\n//ERROR//:VHS table does not exist, please create//") break # Check for VHS_TAPES table else: cur_con.commit() cur_con.close() print("//VHS UPC:" + vhs_upc + " deleted//\n") break # Commit changes to VHS database and close <file_sep>__author__ = "Jason" # DONE import sqlite3 # Import sqlite3 for database def update_vhs(): vhs_database = "VHSDatabase.db" # Create variable for VHS database cur_con = sqlite3.connect(vhs_database) cur_cur = cur_con.cursor() print("\n//VHS Database connected//\n") # Create connection to VHS database vhs_queries = {"vhs_title_q": "UPDATE VHS_TAPES SET TITLE = ? WHERE UPC = ?", "vhs_genre_q": "UPDATE VHS_TAPES SET GENRE = ? WHERE UPC = ?", "vhs_p_p_q": "UPDATE VHS_TAPES SET PRICE_PAID = ? WHERE UPC = ?", "vhs_p_w_q": "UPDATE VHS_TAPES SET PRICE_WORTH = ? WHERE UPC = ?", "vhs_notes_q": "UPDATE VHS_TAPES SET NOTES = ? WHERE UPC = ?", "vhs_rentals_q": "UPDATE VHS_TAPES SET RENTALS = ? WHERE UPC = ?"} # Create variables for queries while True: try: while True: try: vhs_id = int(input("\nEnter UPC of the VHS to update: ")) # Get user input for VHS UPC number except ValueError: print("\n//ERROR//:VHS UPC must be a valid integer//") # Check for valid UPC number else: break while True: try: print(" ------------------------ \n" "|//// UPDATE OPTIONS ////|\n" "|------------------------|\n" "| 1 - Rename VHS |\n" "| 2 - Change VHS Genre |\n" "| 3 - Update Price Paid |\n" "| 4 - Update Price Worth |\n" "| 5 - Edit VHS Notes |\n" "| 6 - Update VHS Rentals |\n" " ------------------------ ") # Display menu menu_choice = int(input("\nWhich function would you like to use? (1-6): ")) # Get user input for menu choice except ValueError: print("\n//ERROR//:Please choose a valid number (1-6)//") else: if menu_choice < 1 or menu_choice > 6: print("\n//ERROR//:Please choose a valid number (1-6)//") # Check for valid menu choice option else: if menu_choice == 1: do_what = vhs_queries["vhs_title_q"] # Menu option 1 - VHS title edit while True: vhs_update = str(input("\nEnter new VHS Title: ")) # Get user input for new title if vhs_update == "": print("\n//ERROR//:VHS Title cannot be blank//") # Check for blank VHS title else: break elif menu_choice == 2: do_what = vhs_queries["vhs_genre_q"] # Menu option 2 - VHS genre edit vhs_update = str(input("\nEnter new VHS Genre: ")) break # Get user input for VHS genre elif menu_choice == 3: do_what = vhs_queries["vhs_p_p_q"] # Menu option 3 = update VHS price paid while True: try: vhs_update = float(input("\nUpdate the price paid: $")) # Get user input for price paid except ValueError: print("\n//ERROR//:Price paid must be dollar value or zero//") # Check for valid price paid else: vhs_update = (round(vhs_update, 2)) break # Round Price to 2 decimal places elif menu_choice == 4: do_what = vhs_queries["vhs_p_w_q"] # Menu option 4 - update VHS price worth while True: try: vhs_update = float(input("\nUpdate the price worth: $")) # Get user input for price worth except ValueError: print("\n//ERROR//:Price worth must be dollar value or zero//") # Check for valid price worth else: vhs_update = (round(vhs_update, 2)) break # Round price to 2 decimal places elif menu_choice == 5: do_what = vhs_queries["vhs_notes_q"] # Menu option 5 - notes vhs_update = str(input("\nEnter any notes or leave blank: ")) break # Get user input for notes elif menu_choice == 6: do_what = vhs_queries["vhs_rentals_q"] # Menu option 6 - update VHS rentals while True: try: vhs_update = int(input("\nEnter number of rentals: ")) except ValueError: print("\n//ERROR//:Rentals must be an integer or zero)//") # Check for valid rental number else: break break do_how = (vhs_update, vhs_id) # Variables for updated database entries cur_cur.execute(do_what,do_how) # Enter updated variables into database except sqlite3.OperationalError: print("\n//ERROR//:VHS table does not exist, please create//") break # Check for VHS_TAPES table else: cur_con.commit() cur_con.close() print("\n//Updates added to database//\n") break # Commit changes to VHS database and close <file_sep>__author__ = "Jason" # DONE import sqlite3 # Import sqlite3 for database def add_vhs(): vhs_database = "VHSDatabase.db" # Create variable for VHS database cur_con = sqlite3.connect(vhs_database) cur_cur = cur_con.cursor() print("\n//VHS Database connected//\n") # Create connection to VHS database while True: try: while True: vhs_title = str(input("\nEnter VHS Title: ")) # Get user input for title of VHS if vhs_title == "": print("\n//ERROR//:VHS Title cannot be blank//") # Check for blank VHS title else: break vhs_genre = str(input("\nEnter the VHS Genre for " + vhs_title + ": ")) # Get user input for VHS genre while True: try: price_paid = float(input("\nEnter the Price Paid for " + vhs_title + ": $")) # Get user input for price paid except ValueError: print("\n//ERROR//:Price Paid must be dollar value or zero//") # Check for valid Price Paid else: price_paid = (round(price_paid, 2)) break # Round Price Paid to 2 decimal places while True: try: price_worth = float(input("\nEnter the Price Worth for " + vhs_title + ": $")) # Get user input for price worth except ValueError: print("\n//ERROR//:Price Worth must be dollar value or zero//") # Check for valid Price Worth else: price_worth = (round(price_worth, 2)) break # Round Price Worth to 2 decimal places notes = str(input("\nEnter any notes for " + vhs_title + " (or leave blank): ")) # Get user input for notes while True: try: rentals = int(input("\nEnter the amount of " + vhs_title + " rentals: ")) # Get user input for number of rentals except ValueError: print("\n//ERROR//:Rentals must be an integer or zero)//") # Check for valid rental number else: break do_what = "INSERT INTO VHS_TAPES (TITLE, GENRE, PRICE_PAID, PRICE_WORTH, NOTES, RENTALS) \ VALUES (?, ?, ?, ?, ?, ?)" do_how = (vhs_title, vhs_genre, price_paid, price_worth, notes, rentals) # Variables for VHS database entries cur_cur.execute(do_what, do_how) # Enter variables into VHS database except sqlite3.OperationalError: print("\n//ERROR//:VHS table does not exist, please create//") break # Check for VHS_TAPES table else: cur_con.commit() cur_con.close() print("\n//" + vhs_title + " added to database//\n") break # Commit changes to VHS database and close
2c7574f444ee89c879874ba626e0760c89ef3417
[ "Python" ]
7
Python
jasClem/VHSDatabaseManager
6a33adbdfbf3ee85b07c4f1318566313e84967f7
1b331274d17e272d62e98e2dd97b6fabee422424
refs/heads/main
<repo_name>phucledien/major.farm<file_sep>/components/Strategies/StrategyYVaultV2.js /****************************************************************************** ** @Author: <NAME> <Tbouder> ** @Email: <EMAIL> ** @Date: Friday April 23rd 2021 ** @Filename: StrategyYVBoost.js ******************************************************************************/ import React, {useState, useEffect, useCallback} from 'react'; import useCurrencies from 'contexts/useCurrencies'; import useStrategies from 'contexts/useStrategies'; import {toAddress, bigNumber} from 'utils'; import {ethers} from 'ethers'; import SectionRemove from 'components/StrategyCard/SectionRemove' import SectionHead from 'components/StrategyCard/SectionHead' import SectionFoot from 'components/StrategyCard/SectionFoot' import Group, {GroupElement} from 'components/StrategyCard/Group' import * as api from 'utils/API'; import methods from 'utils/methodsSignatures'; import {getProvider, getSymbol} from 'utils/chains'; async function DetectStrategyYVaultV2(parameters, address, network, normalTx = undefined) { if (!normalTx) normalTx = await api.retreiveTxFrom(network, address); async function detectTx() { const hasSomeTx = ( normalTx .some(tx => ( ( toAddress(tx.from) === toAddress(address) && toAddress(tx.to) === toAddress(parameters.contractAddress) && ( tx.input.startsWith(methods.YV_DEPOSIT) || tx.input.startsWith(methods.YV_DEPOSIT_VOWID) ) ) || ( toAddress(tx.from) === toAddress(address) && toAddress(tx.to) === toAddress(parameters.contractAddress) && tx.input.startsWith(methods.YV_WITHDRAW) ) )) ); return (hasSomeTx); } const hasSomeTx = await detectTx(); return hasSomeTx; } async function PrepareStrategyYVaultV2(parameters, address, network, normalTx = undefined, erc20Tx = undefined) { let timestamp = undefined; if (!normalTx) normalTx = await api.retreiveTxFrom(network, address); if (!erc20Tx) erc20Tx = await api.retreiveErc20TxFrom(network, address); async function computeFees() { const cumulativeFees = ( normalTx .filter(tx => ( ( toAddress(tx.from) === toAddress(address) && toAddress(tx.to) === toAddress(parameters.contractAddress) && ( tx.input.startsWith(methods.YV_DEPOSIT) || tx.input.startsWith(methods.YV_DEPOSIT_VOWID) ) ) || ( toAddress(tx.from) === toAddress(address) && toAddress(tx.to) === toAddress(parameters.contractAddress) && tx.input.startsWith(methods.YV_WITHDRAW) ) || ( toAddress(tx.from) === toAddress(address) && toAddress(tx.to) === toAddress(parameters.contractAddress) && tx.input.startsWith(methods.YV_TRANSFER) ) || ( tx.input.startsWith(methods.STANDARD_APPROVE) && (tx.input.toLowerCase()).includes((parameters.contractAddress.slice(2)).toLowerCase()) ) )).reduce((accumulator, tx) => { const gasUsed = bigNumber.from(tx.gasUsed); const gasPrice = bigNumber.from(tx.gasPrice); const gasUsedPrice = gasUsed.mul(gasPrice); return bigNumber.from(accumulator).add(gasUsedPrice); }, bigNumber.from(0)) ); return (Number(ethers.utils.formatUnits(cumulativeFees, 18))); } async function computeSeeds() { const cumulativeSeeds = ( erc20Tx .filter(tx => ( ( (toAddress(tx.to) === toAddress(parameters.contractAddress)) && (tx.tokenSymbol === parameters.underlyingTokenSymbol) ) ) ).reduce((accumulator, tx) => { if (timestamp === undefined || timestamp > tx.timeStamp) { timestamp = tx.timeStamp; } return bigNumber.from(accumulator).add(tx.value); }, bigNumber.from(0)) ); return Number(ethers.utils.formatUnits(cumulativeSeeds, parameters.underlyingTokenDecimal || 18)); } async function computeCrops() { const provider = getProvider(network); const ABI = ['function balanceOf(address) external view returns (uint256)'] const smartContract = new ethers.Contract(parameters.contractAddress, ABI, provider) const balanceOf = await smartContract.balanceOf(address); return (Number(ethers.utils.formatUnits(balanceOf, parameters.underlyingTokenDecimal || 18))); } //SHOULD HANDLE TX OUT OF TOKEN async function computeHarvest() { const cumulativeHarvest = ( erc20Tx .filter(tx => ( (toAddress(tx.from) === toAddress(parameters.contractAddress)) && (toAddress(tx.to) === toAddress(address)) && (tx.tokenSymbol === parameters.underlyingTokenSymbol) )).reduce((accumulator, tx) => { return bigNumber.from(accumulator).add(tx.value); }, bigNumber.from(0)) ); return Number(ethers.utils.formatUnits(cumulativeHarvest, parameters.underlyingTokenDecimal || 18)); } const fees = await computeFees(); const initialCrops = await computeCrops(); const initialSeeds = await computeSeeds(); const harvest = await computeHarvest(); return { status: initialCrops === 0 ? 'KO' : 'OK', fees, initialSeeds, initialCrops, harvest, timestamp, } } function StrategyYVaultV2({parameters, network, address, uuid, fees, initialSeeds, initialCrops, harvest, date}) { const {strategies} = useStrategies(); const {tokenPrices, currencyNonce} = useCurrencies(); const [isHarvested, set_isHarvested] = useState(false); const [APY, set_APY] = useState(0); const [result, set_result] = useState(0); const [totalFees] = useState(fees); const [cropsYielded, set_cropsYielded] = useState(1); const [symbolToBaseCurrency, set_symbolToBaseCurrency] = useState(tokenPrices[getSymbol(network)]?.price || 0); const [underlyingToBaseCurrency, set_underlyingToBaseCurrency] = useState(tokenPrices[parameters.underlyingTokenCgID]?.price || 0); //Number of share in the vault const [shares, set_shares] = useState(initialCrops); //Values of the shares in the vault (shareValue - shares) const [underlyingEarned, set_underlyingEarned] = useState(0); const prepareData = useCallback(async () => { /********************************************************************** ** Retrieving the base prices **********************************************************************/ const _symbolToBaseCurrency = tokenPrices[getSymbol(network)]?.price || 0; const _underlyingToBaseCurrency = tokenPrices[parameters.underlyingTokenCgID]?.price || 0; set_symbolToBaseCurrency(_symbolToBaseCurrency); set_underlyingToBaseCurrency(_underlyingToBaseCurrency); /********************************************************************** ** Querying the smartContract to know if the strategy is still in use **********************************************************************/ const provider = getProvider(network); const ABI = [ 'function pricePerShare() external view returns (uint256)', 'function balanceOf(address) external view returns (uint256)' ] const vault = new ethers.Contract(parameters.contractAddress, ABI, provider) const balanceOf = await vault.balanceOf(address); if (balanceOf.isZero()) { set_isHarvested(true); set_shares(0); strategies.set(uuid, 'isHarvested', true, true); return; } /********************************************************************** ** Retrieving the shares & sharevalues **********************************************************************/ const pricePerShare = await vault.pricePerShare(); const _pricePerShare = Number(ethers.utils.formatUnits(pricePerShare, parameters.underlyingTokenDecimal || 18)); const _shares = Number(ethers.utils.formatUnits(balanceOf, parameters.underlyingTokenDecimal || 18)); const _underlyingEarned = _shares * _pricePerShare; const _cropsYielded = _shares - (initialSeeds / _pricePerShare); set_shares(_shares); set_underlyingEarned(_underlyingEarned); set_cropsYielded(_cropsYielded); /********************************************************************** ** Computing the result **********************************************************************/ const _initialSeedValue = initialSeeds * _underlyingToBaseCurrency; const _harvestValue = harvest * _underlyingToBaseCurrency; const _gasValue = totalFees * _symbolToBaseCurrency; const _yieldValue = _cropsYielded * _underlyingToBaseCurrency; const _result = (_harvestValue + _yieldValue) - (_gasValue); set_result(_result); set_APY((_harvestValue + _yieldValue) / _initialSeedValue * 100); strategies.set(uuid, 'lastShares', _shares, true); strategies.set(uuid, 'lastSharesValue', _underlyingEarned * _underlyingToBaseCurrency, true); strategies.set(uuid, 'lastResult', _result, true); strategies.set(uuid, 'lastGasValue', _gasValue, true); strategies.set(uuid, 'lastHarvestValue', _harvestValue, true); }, [tokenPrices, network, parameters.underlyingTokenCgID, parameters.contractAddress, parameters.underlyingTokenDecimal, address, strategies, uuid, initialSeeds, harvest, totalFees]); useEffect(() => { prepareData() }, [currencyNonce, prepareData]) return ( <div className={'flex flex-col col-span-1 rounded-lg shadow bg-dark-600 p-6 relative overflow-hidden'}> <SectionRemove uuid={uuid} /> <SectionHead network={network} parameters={parameters} address={address} date={date} APY={APY} /> <div className={'space-y-8'}> <Group title={'Seeds'}> <GroupElement network={network} image={parameters.underlyingTokenIcon} label={parameters.underlyingTokenSymbol} address={parameters.underlyingTokenAddress} amount={parseFloat(initialSeeds).toFixed(10)} value={(initialSeeds * underlyingToBaseCurrency).toFixed(2)} /> </Group> <Group title={'Crops'}> <GroupElement network={network} image={parameters.tokenIcon || '/tokens/yGeneric.svg'} label={`yv${parameters.underlyingTokenSymbol}`} address={parameters.contractAddress} amount={parseFloat(shares.toFixed(10))} value={(underlyingEarned * underlyingToBaseCurrency).toFixed(2)} /> </Group> {isHarvested ? <> <Group title={'Harvest'}> <GroupElement network={network} image={parameters.underlyingTokenIcon} label={parameters.underlyingTokenSymbol} address={parameters.underlyingTokenAddress} amount={parseFloat(harvest.toFixed(10))} value={(harvest * underlyingToBaseCurrency).toFixed(2)} /> <GroupElement network={network} image={'⛽️'} label={'Fees'} amount={parseFloat(totalFees.toFixed(10))} value={-(totalFees * symbolToBaseCurrency).toFixed(2)} /> </Group> </> : <Group title={'Yield'}> <GroupElement network={network} image={parameters.tokenIcon || '/tokens/yGeneric.svg'} label={`yv${parameters.underlyingTokenSymbol}`} address={parameters.contractAddress} amount={cropsYielded.toFixed(10)} value={cropsYielded * underlyingToBaseCurrency.toFixed(2)} /> {harvest.toFixed(10) > 0 ? <GroupElement network={network} image={parameters.underlyingTokenIcon} label={`Harvested ${parameters.underlyingTokenSymbol}`} address={parameters.underlyingTokenAddress} amount={parseFloat(harvest.toFixed(10))} value={(harvest * underlyingToBaseCurrency).toFixed(2)} /> : null} <GroupElement network={network} image={'⛽️'} label={'Fees'} amount={parseFloat(totalFees.toFixed(10))} value={-(totalFees * symbolToBaseCurrency).toFixed(2)} /> </Group> } </div> <SectionFoot result={result} /> </div> ) } export {PrepareStrategyYVaultV2, DetectStrategyYVaultV2}; export default StrategyYVaultV2;
9b83680b50339e69fe94f652d63a7bf0e4b8bc56
[ "JavaScript" ]
1
JavaScript
phucledien/major.farm
a3ddfdd6e04f8bf2c717cb6e13c6359f08f8089c
e582da4b72d47f0cb23eb514944ea97776311660
refs/heads/master
<file_sep>#ifndef AIRPORT_H #define AIRPORT_H #include <string> #include <fstream> #include "flights.h" using std::string; using std::ifstream; using std::ofstream; using std::ostream; using std::istream; class airport { private: int max_num_flights; // максимальное кол-во полётов int max_num_failflights; int num_flights; // текущее число полётов int num_failflights; flight *flights; // массив объектов класса flight failflight *failflights; public: airport(unsigned int max_n, unsigned int max_ff); // конструктор класса ~airport(); //деструктор void operator += (flight &aflight); //добавления элемента void operator += (failflight &afailflight); void read_from_file(string filename); // ввести данные из файла void failread_from_file(string filename); void read_from_keyboard(); // ввести данные c клавиатуры void failread_from_keyboard(); friend istream& operator >> (istream& kin, airport& airport); //keyboard in friend ostream& operator << (ostream& ccout, airport& airport); //monitor out friend ifstream& operator >> (ifstream& fin, airport& airport); //file in friend ofstream& operator << (ofstream& fout, airport& airport); //file out void speed(); // вывести наибольшую среднюю скорость полёта void MSK(); // вывести протяженность рейсов из Москвы void checker(); }; #endif <file_sep>#ifndef FLIGHTS_H #define FLIGHTS_H #include <string> #include <fstream> using std::string; using std::ifstream; using std::ofstream; using std::ostream; using std::istream; class flight { protected: int number; // номер рейса string airline; //название авиакомпании string from; //откуда string to; //куда float distance; //дистанция перелёта float duration; //продолжительность перелёта string aircraft; // тип самолета int pessengers; //кол-во посадочных мест float ms;// средняя скорость public: flight() : number(0), airline(""), from(""), to(""), distance(0), duration(0), aircraft(""), pessengers(0), ms(0) {}; flight(int, string, string, string, float, float, string, int, float); bool operator==(flight another); friend istream& operator >> (istream& kin, flight& aflight); //keyboard in friend ifstream& operator >> (ifstream& fin, flight& aflight); //file in/reader friend ostream& operator << (ostream& mout, const flight& aflight); //monitor out friend ofstream& operator << (ofstream& fout, const flight& aflight); //file out float mss(); //скорость string maxaircraft(); //название самого быстрого int sum(); //протяженность авиаперелётов из Москвы }; class failflight : public flight // отложенные рейсы { private: float time; //рейс отложен на time часов public: failflight() : flight(), time(0) {}; failflight(int, string, string, string, float, float, string, int, float, int); friend bool operator==(failflight failflight1, failflight failflight2); friend istream& operator >> (istream& kin, failflight& afailflight); //keyboard in friend ifstream& operator >> (ifstream& fin, failflight& afailflight); //file in/reader friend ostream& operator << (ostream& mout,const failflight& afailflight); //monitor out friend ofstream& operator << (ofstream& fout,const failflight& afailflight); //file out }; #endif <file_sep>#include <iostream> #include "airport.h" #include <Windows.h> using namespace std; flight new_flight; failflight new_failflight; airport::airport(unsigned int max_n, unsigned int max_ff) { system("color f0"); max_num_flights = max_n; max_num_failflights = max_ff; flights = new flight[max_num_flights]; failflights = new failflight[max_num_failflights]; num_flights = 0; num_failflights = 0; cout << " Hello, it is Airport database! " << endl << " To work press any button" << endl << " Class airport is ready." << "\n Created flights - " << max_num_flights << "..." << endl << " Created failflights - " << max_num_failflights << "..." ; getchar(); system("cls"); } airport::~airport() { max_num_flights = 0; max_num_failflights = 0; delete[] flights; delete[] failflights; num_flights = 0; num_failflights = 0; cout << "\n Class 'Airport' was destroyed.\n Memory is clean."; } void airport::operator+=(flight &aflight) { if (num_flights < max_num_flights) // можем добавить еще один полёт? { flight new_flight; flights[num_flights] = aflight; // заносим полёт в массив num_flights++; // увеличиваем счетчик полётов } else cout << "Overflight" << endl; } void airport::operator+=(failflight &afailflight) { if (num_failflights < max_num_failflights) // можем добавить еще один полёт? { failflight new_failflight; failflights[num_failflights] = afailflight; // заносим полёт в массив num_failflights++; // увеличиваем счетчик полётов } else cout << "Overfailflight" << endl; } void airport::read_from_file(string filename) { ifstream fin; fin.open(filename); if (!fin.is_open()) { cout << "\n\nFile wasn`t found!" << endl; system("pause"); exit(1); } int N; fin >> N; fin.get(); flight new_flight; for (int i = 0; i < N; i++) { fin >> new_flight; this -> operator+=(new_flight); } fin.close(); cout << "\n Data was loaded" << endl <<" from: " << filename << ", flights : " << num_flights; getchar(); } void airport::failread_from_file(string filename) { ifstream fin; fin.open(filename); if (!fin.is_open()) { cout << "\n\nFile wasn`t found!" << endl; system("pause"); exit(1); } int N; fin >> N; fin.get(); failflight new_failflight; for (int i = 0; i < N; i++) { fin >> new_failflight; this -> operator+=(new_failflight); } fin.close(); cout << "\n Data was loaded" << endl << " from: " << filename << ", failflights : " << num_failflights; getchar(); } istream& operator >> (istream& kin, airport& airport) //keyboard in { airport.read_from_keyboard(); airport.failread_from_keyboard(); return kin; } ifstream& operator >> (ifstream& fin, airport& airport) //file in { airport.read_from_file("flights.txt"); airport.failread_from_file("FailFlights.txt"); return fin; } void airport::read_from_keyboard() { int N; system("cls"); cout << " Write amount flights : "; cin >> N; cout << endl; for (int i = 0; i < N; i++) { cout <<" Flight #"<< i+1 << endl; flight new_flight; cin >> new_flight; this -> operator+=(new_flight); } getchar(); } void airport::failread_from_keyboard() { int N; system("cls"); cout << " Write amount failflights : "; cin >> N; cout << endl; for (int i = 0; i < N; i++) { cout << " FailFlight #" << i + 1 << endl; failflight new_failflight; cin >> new_failflight; this -> operator+=(new_failflight); } getchar(); } ofstream& operator << (ofstream& fout, airport& airport) //file out { ofstream fout2; fout2.open("output.txt"); fout2 << " " << airport.num_flights << endl; for (int i = 0; i < airport.num_flights; i++) { fout2 << " Flight #" << i + 1 << endl; fout2 << airport.flights[i]; } fout2.close(); ofstream fout3; fout3.open("outputfail.txt"); fout3 << " " << airport.num_failflights << endl; for (int i = 0; i < airport.num_failflights; i++) { fout3 << " FailFlight #" << i + 1 << endl; fout3 << airport.failflights[i]; } fout3.close(); cout << endl << " " << airport.num_flights << " flights wrote in file " << "output.txt" << endl; cout << endl << " " << airport.num_failflights << " failflights wrote in file " << "outputfail.txt" << endl; return fout; } ostream& operator << (ostream& ccout, airport& airport) //monitor out { system("cls"); cout << " Reading from file.." << endl << endl; for (int i = 0; i < airport.num_flights; i++) { cout << " Flight #" << i + 1 << endl; cout << airport.flights[i] << endl; } cout << endl << endl; for (int i = 0; i < airport.num_failflights; i++) { cout << " FailFlight #" << i + 1 << endl; cout << airport.failflights[i]; } return ccout; } void airport::speed() { cout << "\n\n Maximum mid speed = " << new_flight.mss() << " km/hour " << " have " << new_flight.maxaircraft() << endl; } void airport::MSK() { cout << "\n\n Duration all flights from Moscow = " << new_flight.sum() << " km " << endl; } <file_sep>#include "airport.h" #include <iostream> #include <iomanip> using namespace std; void menu() { cout << "\n\n 1)Reading data from file - press <1>" << endl; //для чтения из файла - нажмите 1 cout << " 2)Reading data from keyboard - press <2>" << endl; //для чтения с клавиатуры - нажмите 2 cout << " 3)Output data on display - press <3>" << endl; //для вывода на экран нажмите - 3 cout << " 4)Quickest aircraft - press <4>" << endl; //вывести самый быстрый самолёт - нажмите 4 cout << " 5)All flights from Moscow - press <5>" << endl; //вывести все рейсы из Москвы - нажмите 5 cout << " 6)Write data in txt-file - press <6>" << endl; //запись в файл - нажмите 6 cout << " 7)Compare two flights - press <7>" << endl; //сравнить два рейса - нажмите 7 cout << " 8)Close data - press <8>" << endl; //запустить деструктор - нажмите 8 } airport vlg(25,25); int m=0; void airport::checker() { int c1 = 0; int c2 = 0; cout << " Write number of comparing flights. " << endl; cout << " Number #1: "; cin >> c1; cout << " Number #2: "; cin >> c2; if (vlg.flights[c1 - 1] == vlg.flights[c2 - 1]) cout << " Flight #1 == Flight #2"; else cout << " This is different flights!"; getchar(); } int main() { system("color f0"); if (m == 0) { menu(); m = 1; } int choose = 0; cout << "\n\n\n\n Input : "; cin >> choose; ifstream fin; fin.open("flights.txt"); ofstream fout; fout.open("output.txt"); switch (choose) { case 1: { fin >> vlg; getchar(); fin.close(); main(); break; } case 2: { cin >> vlg; system("cls"); menu(); cout << "\n\n DATA WAS CHANGED BY USER... " << endl; main(); break; } case 3: { cout << vlg; getchar(); menu(); main(); } case 4: { vlg.speed(); getchar(); main(); break; } case 5: { vlg.MSK(); getchar(); main(); break; } case 6: { fout << vlg; getchar(); main(); break; } case 7: { vlg.checker(); getchar(); main(); break; } case 8: { vlg.~airport(); getchar(); break; } default: { cout << "Failed!"; getchar(); main(); } } fin.close(); fout.close(); } <file_sep>#include "flights.h" #include <iostream> #include "Windows.h" using namespace std; float maxms = 0; string maxmsaicrft; float summa = 0; int sdvig = 0; int sdvig2 = 0; flight::flight(int nmbr, string arln, string frm, string toto, float dstnc, float drthn, string arcrft, int pssngrs, float mss) { number = nmbr; airline = arln; from = frm; to = toto; distance = dstnc; duration = drthn; aircraft = arcrft; pessengers = pssngrs; ms = mss; } ifstream& operator >> (ifstream& fin, flight& aflight) { fin >> aflight.number; fin >> aflight.airline; fin >> aflight.from; fin >> aflight.to; fin >> aflight.aircraft; fin >> aflight.distance; fin >> aflight.duration; fin >> aflight.pessengers; aflight.ms = aflight.distance / aflight.duration; if (aflight.ms > maxms) { maxms = aflight.ms; maxmsaicrft = aflight.aircraft; } if (aflight.from == "Moscow") summa = summa + aflight.distance; return fin; } int flight::sum() { return summa; } float flight::mss() { return maxms; } string flight::maxaircraft() { return maxmsaicrft; } istream& operator>>(istream& kin, flight& aflight) { cout << " Name : "; kin >> aflight.airline; cout << " From : "; cin >> aflight.from; cout << " To : "; cin >> aflight.to; cout << " Model/type : "; cin >> aflight.aircraft;; cout << " Distance(km) : "; cin >> aflight.distance; cout << " Duration(hour) : "; cin >> aflight.duration; cout << " Pessengers : "; cin >> aflight.pessengers; cout << endl; aflight.ms = aflight.distance / aflight.duration; if (aflight.ms > maxms) { maxms = aflight.ms; maxmsaicrft = aflight.aircraft; } return kin; } bool flight::operator==(flight another) { if (airline != another.airline) return false; if (from != another.from) return false; if (to != another.to) return false; if (distance != another.distance) return false; if (duration != another.duration) return false; if (aircraft != another.aircraft) return false; if (pessengers != another.pessengers) return false; } ostream& operator<<(ostream& mout, const flight& aflight) //monitor out { mout << " Airline : " << aflight.airline << endl; mout << " From: " << aflight.from << endl; mout << " Type aircraft : " << aflight.aircraft << endl; mout << " To : " << aflight.to << endl; mout << " Distance : " << aflight.distance << endl; mout << " Duration : " << aflight.duration << endl; mout << " Pessengers : " << aflight.pessengers << endl; return mout; } ofstream& operator<<(ofstream& fout, const flight& aflight) //file out { fout << " Airline : " << aflight.airline << endl; fout << " From: " << aflight.from << endl; fout << " Type aircraft : " << aflight.aircraft << endl; fout << " To : " << aflight.to << endl; fout << " Distance : " << aflight.distance << endl; fout << " Duration : " << aflight.duration << endl; fout << " Pessengers : " << aflight.pessengers << endl; return fout; } /// failflight go go go failflight::failflight(int nmbr, string arln, string frm, string toto, float dstnc, float drthn, string arcrft, int pssngrs, float mss, int tme) : flight(nmbr, arln, frm, toto, dstnc, drthn, arcrft, pssngrs, mss), time(0) { cout << " CLASS CONSTRUCTOR ACTIVATED"; } bool operator==(failflight failflight1, failflight failflight2) { bool are_equal_flights = static_cast<flight>(failflight1) == static_cast<flight>(failflight2); bool are_equal_time = failflight1.time == failflight2.time; if (are_equal_flights && are_equal_time) return true; return false; } istream& operator >> (istream& kin, failflight& afailflight) //keyboard in { cout << " Name : "; kin >> afailflight.airline; cout << " From : "; cin >> afailflight.from; cout << " To : "; cin >> afailflight.to; cout << " Model/type : "; cin >> afailflight.aircraft;; cout << " Distance(km) : "; cin >> afailflight.distance; cout << " Duration(hour) : "; cin >> afailflight.duration; cout << " Pessengers : "; cin >> afailflight.pessengers; afailflight.ms = afailflight.distance / afailflight.duration; if (afailflight.ms > maxms) { maxms = afailflight.ms; maxmsaicrft = afailflight.aircraft; } cout << " Time : "; kin >> afailflight.time; return kin; } ifstream& operator >> (ifstream& fin, failflight& afailflight)//file in/reader { fin >> afailflight.number; fin >> afailflight.airline; fin >> afailflight.from; fin >> afailflight.to; fin >> afailflight.aircraft; fin >> afailflight.distance; fin >> afailflight.duration; fin >> afailflight.pessengers; afailflight.ms = afailflight.distance / afailflight.duration; if (afailflight.ms > maxms) { maxms = afailflight.ms; maxmsaicrft = afailflight.aircraft; } if (afailflight.from == "Moscow") summa = summa + afailflight.distance; fin >> afailflight.time; return fin; } ostream& operator << (ostream& mout,const failflight& afailflight) //monitor out { mout << " Airline : " << afailflight.airline << endl; mout << " From: " << afailflight.from << endl; mout << " Type aircraft : " << afailflight.aircraft << endl; mout << " To : " << afailflight.to << endl; mout << " Distance : " << afailflight.distance << endl; mout << " Duration : " << afailflight.duration << endl; mout << " Pessengers : " << afailflight.pessengers << endl; mout << " Time : " << afailflight.time << endl << endl; return mout; } ofstream& operator << (ofstream& fout,const failflight& afailflight) //file out { fout << " Airline : " << afailflight.airline << endl; fout << " From: " << afailflight.from << endl; fout << " Type aircraft : " << afailflight.aircraft << endl; fout << " To : " << afailflight.to << endl; fout << " Distance : " << afailflight.distance << endl; fout << " Duration : " << afailflight.duration << endl; fout << " Pessengers : " << afailflight.pessengers << endl; fout << " Time : " << afailflight.time << endl << endl; return fout; }
d0af6145c5c4974be9085e0f75098f0c567c8eb1
[ "C++" ]
5
C++
TheEluzive/airport_database-c-structers.-etc-
bed0c08dd26f0e61f7be75a5229cec3bca9ec055
63d95c97e55b5ea00d4da3b2b8c445a619037673
refs/heads/master
<repo_name>yana22rus/bufer<file_sep>/bufer.py import pyperclip pyperclip.copy(pyperclip.waitForPaste().replace(".ru",".ru/app_dev.php"))
e3fe108c3e2cc129f666aea2f144860f5ab0e062
[ "Python" ]
1
Python
yana22rus/bufer
37da568cd6c3488c8f2668afd5e76b32f6fec37b
57f8c43e9501d509b23cfd865714f8078c0bf792
refs/heads/master
<repo_name>lpinilla/my_configs<file_sep>/i3/power_down.sh #!/bin/sh choices="shutdown\nreboot\nsuspend\nlog_off" chosen=$(echo "$choices" | dmenu -i) case "$chosen" in shutdown) sudo shutdown now ;; reboot) sudo reboot ;; suspend) sudo sysctemctl suspend ;; log_off) pkill -u lautaro ;; *) ;; esac
775ba73b7395157eb2a967e67e584aaf8db9f07f
[ "Shell" ]
1
Shell
lpinilla/my_configs
623e841e2576d0e6dc2ecd77cfb9de5cd4ef2c56
c931cb87a790017fa66275675c456542c2ebd59d
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php</title> </head> <body> <?php $maVariable = 'femme'; if ($maVariable != 'homme') { echo 'C\'est une développeuse !!!'; } elseif ($maVariable == 'homme') { echo 'C\'est un développeur !!!'; } ?> </body> </html>
4b2f1c1be8eef438b3c633fa18697d380849b5e3
[ "PHP" ]
1
PHP
Marie-Axelle/php2ex5
96e084286ee4797f4f6c7458b9d98e8055b6de8e
d73120be86e0a77dd191d36b7c219f276ace5794
refs/heads/master
<repo_name>asimonia/musichistory_api<file_sep>/musichistory/musichistory_api/admin.py from django.contrib import admin from musichistory_api.models import Album, Artist, Genre, Song admin.site.register(Album) admin.site.register(Artist) admin.site.register(Genre) admin.site.register(Song)<file_sep>/musichistory/musichistory_api/migrations/0003_auto_20170203_1804.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-03 18:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('musichistory_api', '0002_auto_20170203_1728'), ] operations = [ migrations.RemoveField( model_name='song', name='genres', ), migrations.AddField( model_name='album', name='genres', field=models.ManyToManyField(to='musichistory_api.Genre'), ), migrations.AddField( model_name='song', name='plays', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='album', name='album_length', field=models.DurationField(verbose_name='album length'), ), migrations.AlterField( model_name='album', name='release_date', field=models.DateField(verbose_name='release date'), ), migrations.AlterField( model_name='genre', name='label', field=models.CharField(max_length=20, unique=True), ), migrations.AlterField( model_name='song', name='release_date', field=models.DateField(verbose_name='release date'), ), migrations.AlterField( model_name='song', name='song_length', field=models.DurationField(verbose_name='track length'), ), ] <file_sep>/musichistory/musichistory_api/migrations/0002_auto_20170203_1728.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-03 17:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('musichistory_api', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='genre', name='description', ), migrations.AlterField( model_name='album', name='album_length', field=models.DurationField(), ), migrations.AlterField( model_name='song', name='song_length', field=models.DurationField(), ), ] <file_sep>/musichistory/musichistory_api/models.py from django.contrib.auth.models import User from django.db import models class Genre(models.Model): """ The genres table contains the various genres related to the songs. Songs can fit into more than one genre, or none at all. """ label = models.CharField(max_length=20, unique=True) class Meta: verbose_name_plural = 'Genres' def __str__(self): return '{}'.format(self.label) class Artist(models.Model): """ This table contains the name of the artist and the year the artist was established. """ name = models.CharField(max_length=40) year_established = models.IntegerField() class Meta: verbose_name_plural = 'Artists' def __str__(self): return '{}'.format(self.name) class Album(models.Model): """ This table contains the albums and the related information. """ title = models.CharField(max_length=40) release_date = models.DateField('release date') album_length = models.DurationField('album length') num_stars = models.IntegerField() label = models.CharField(max_length=40) artist = models.ForeignKey(Artist, on_delete=models.CASCADE) genres = models.ManyToManyField(Genre) class Meta: verbose_name_plural = 'Albums' def __str__(self): return '{}'.format(self.title) class Song(models.Model): """ This table contains a list of songs and the related information. """ title = models.CharField(max_length=40) song_length = models.DurationField('track length') release_date = models.DateField('release date') plays = models.IntegerField(default=0) artist = models.ForeignKey(Artist, on_delete=models.CASCADE) album = models.ForeignKey(Album, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Songs' def __str__(self): return '{}'.format(self.title) <file_sep>/musichistory/musichistory_api/views.py from django.contrib.auth.models import User from musichistory_api import serializers, models from rest_framework import viewsets class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = serializers.UserSerializer class GenreViewSet(viewsets.ModelViewSet): queryset = models.Genre.objects.all() serializer_class = serializers.GenreSerializer class ArtistViewSet(viewsets.ModelViewSet): queryset = models.Artist.objects.all().order_by('-name') serializer_class = serializers.ArtistSerializer class AlbumViewSet(viewsets.ModelViewSet): queryset = models.Album.objects.all().order_by('-artist') serializer_class = serializers.AlbumSerializer class SongViewSet(viewsets.ModelViewSet): queryset = models.Song.objects.all().order_by('-album') serializer_class = serializers.SongSerializer<file_sep>/musichistory/musichistory_api/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-03 16:45 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Album', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=40)), ('release_date', models.DateField()), ('album_length', models.TimeField()), ('num_stars', models.IntegerField()), ('label', models.CharField(max_length=40)), ], options={ 'verbose_name_plural': 'Albums', }, ), migrations.CreateModel( name='Artist', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ('year_established', models.IntegerField()), ], options={ 'verbose_name_plural': 'Artists', }, ), migrations.CreateModel( name='Genre', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('label', models.CharField(choices=[('', ''), ('Pop', 'Pop'), ('Rock', 'Rock'), ('Metal', 'Metal'), ('Jazz', 'Jazz'), ('Country', 'Country'), ('Gospel', 'Gospel')], default='', max_length=20)), ('description', models.TextField(max_length=4000)), ], options={ 'verbose_name_plural': 'Genres', }, ), migrations.CreateModel( name='Song', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=40)), ('song_length', models.TimeField()), ('release_date', models.DateField()), ('album', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='musichistory_api.Album')), ('artist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='musichistory_api.Artist')), ('genres', models.ManyToManyField(to='musichistory_api.Genre')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Songs', }, ), migrations.AddField( model_name='album', name='artist', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='musichistory_api.Artist'), ), ] <file_sep>/musichistory/musichistory_api/serializers.py from django.contrib.auth.models import User from rest_framework import serializers from musichistory_api import models class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'first_name', 'last_name', 'username', 'email', 'password', 'groups', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined',) class GenreSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Genre fields = ('url', 'label',) class ArtistSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Artist fields = ('url', 'name', 'year_established',) class AlbumSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Album fields = ('url', 'title', 'release_date', 'album_length', 'num_stars', 'label', 'artist', 'genres',) class SongSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Song fields = ('url', 'title', 'song_length', 'release_date', 'plays', 'artist', 'album', 'user',)
4e4de77faa0a47b7d7dcd8ae369f54ce188719db
[ "Python" ]
7
Python
asimonia/musichistory_api
f73f1f57ac19436b502534f7fa2841b6e5caa977
c8b481cd2ceea2d6b9a3525121bdcd32e6ca6dca
refs/heads/master
<repo_name>jwhite96/SOFT252-Practicals<file_sep>/Week06/PubSimulation/src/Templates/Spirits.java package Templates; //An abstract Template class for a spirits public abstract class Spirits { public final void prepareDrinks() { addIce(); addSpirit(); addMixer(); addGarnish(); } //Functions that are used by multiple different drinks (NOT ABSTRACT) protected void addIce() { System.out.println("Adding Ice"); } protected void addMixer() { System.out.println("Adding Mixer"); } //Functions for Long Drink protected abstract void addSpirit(); protected abstract void addGarnish(); } <file_sep>/Week01/Example1/nbproject/private/private.properties compile.on.save=true user.properties.file=C:\\Users\\jwhite12\\AppData\\Roaming\\NetBeans\\11.1\\build.properties <file_sep>/Week03/StockTracker/src/utilities/ISubject.java package utilities; /** * An interface to make a class a "subject which can be observed" * @author jwhite12 */ public interface ISubject { Boolean registerObserver(IObserver o); Boolean removeObserver(IObserver o); void notifyObservers(); }<file_sep>/README.md ## Practical work for SOFT252 ### Object Orientated Software Engineering & Design Patterns Practical work programmed with Java using various different design patterns <file_sep>/Week06/PubSimulation/src/Strategies/IDrinks.java package Strategies; /** * * @author jwhite12 */ public interface IDrinks { String serveDrink(); } <file_sep>/Week04/UniDemo/src/unidemo/Student.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package unidemo; public class Student extends UniPeople { //Constructor public Student (String name, int ID) { this.name = name; this.ID = ID; } //attend class function public void attendClass() { System.out.println(this.name + "is attending" + this.course.getCourseCode() + "in room" + this.course.getRoom()); } //do coursework function public void doCoursework() { if(this.course.getCourseWork() != null){ System.out.println(this.name + "is doing coursework" + this.course.getCourseWork()); } else { System.out.println("No coursework set"); } } } <file_sep>/Week03/StockTracker/src/stocktracker/stockdatamodel/StockItem.java package stocktracker.stockdatamodel; import java.util.ArrayList; import utilities.IObserver; import utilities.ISubject; /** * Super class from which specialised stock item classes will inherit * @author jwhite12 */ public abstract class StockItem implements ISubject { protected String name = "UNKNOWN"; protected Integer quantityInStock = 0; protected Double sellingPrice = 1000000.00; protected Double costPrice = 1000000.00; private ArrayList<IObserver> observers = null; public String getName() { return name; } public void setName(String name) { if(name != null && !name.isEmpty()){ this.name = name; notifyObservers(); } } public Integer getQuantityInStock() { return quantityInStock; } public void setQuantityInStock(Integer quantityInStock) { if(quantityInStock != null && quantityInStock >= 0){ this.quantityInStock = quantityInStock; notifyObservers(); } } public Double getSellingPrice() { return sellingPrice; } public void setSellingPrice(Double sellingPrice) { if(sellingPrice != null && sellingPrice >= this.costPrice && sellingPrice >= 0){ this.sellingPrice = sellingPrice; notifyObservers(); } } public Double getCostPrice() { return costPrice; } public void setCostPrice(Double costPrice) { if(costPrice != null && costPrice >= 0){ this.costPrice = costPrice; notifyObservers(); } } public Boolean isInStock(){ Boolean inStock = false; if(this.quantityInStock > 0){ inStock = true; } return inStock; } public StockItem(){ } public StockItem(String name){ this.name = name; } public StockItem(String name, Integer qty){ this.name = name; this.quantityInStock = qty; } public abstract StockType getItemType(); @Override public Boolean registerObserver(IObserver o){ Boolean blnAdded = false; //Assume the method will fail //Validate that observer exists if(o != null){ if(this.observers == null){ this.observers = new ArrayList<>(); } //Add the observer to the list of registered observers blnAdded = this.observers.add(o); } //Return result return blnAdded; } @Override public Boolean removeObserver(IObserver o){ Boolean blnRemove = false; //Assume the method will fail //Validate that observer exists if(o != null){ if(this.observers == null){ this.observers = new ArrayList<>(); } //Add the observer to the list of registered observers blnRemove = this.observers.remove(o); } //Return result return blnRemove; } @Override public void notifyObservers(){ //Ensure we have a valid list of observers if(this.observers != null && this.observers.size() > 0){ //Start foreach loop for(IObserver currentObserver : this.observers){ //Call update on this observer currentObserver.update(); } } } } <file_sep>/Week03/StockTracker/src/stocktracker/StockTracker.java package stocktracker; import stocktracker.stockdatamodel.*; //include all classes from this package public class StockTracker { public static void main(String[] args) { StockItem objTestItem1 = new PhysicalStockItem("Starcraft Manual"); StockItem objTestItem2 = new PhysicalStockItem("HALO 3", 100); StockItem objTestItem3 = new ServiceStockItem("Delivery"); //Lets ask each of the three items too print their type to the console //Item 1 if(objTestItem1.getItemType() == StockType.PHYSICALITEM){ System.out.println("Item 1 is a PHYSICAL stock item"); } else { System.out.println("Item 1 is a SERVICE stock item"); } //Item 2 if(objTestItem2.getItemType() == StockType.PHYSICALITEM){ System.out.println("Item 2 is a PHYSICAL stock item"); } else { System.out.println("Item 2 is a SERVICE stock item"); } //Item 3 if(objTestItem3.getItemType() == StockType.PHYSICALITEM){ System.out.println("Item 3 is a PHYSICAL stock item"); } else { System.out.println("Item 3 is a SERVICE stock item"); } } } <file_sep>/Week06/PubSimulation/src/Templates/HotDrinks.java package Templates; //An abstract template class for Hot drinks public abstract class HotDrinks { public final void prepareDrinks() { boilWater(); pourDrink(); addIngredients(); } //Functions that are used by multiple different drinks (NOT ABSTRACT) protected void boilWater(){ System.out.println("Boiling Water"); } protected void pourDrink(){ System.out.println("Pouring Drink"); } //Functions for adding ingredients protected abstract void addIngredients(); protected abstract void mixIngredients(); } <file_sep>/Week04/UniDemo/src/unidemo/Course.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package unidemo; /* * * Concrete class for course aspects */ public class Course { //Variable Declaration private String courseCode; private Lecturer teacher; private String courseWork; private String room; //Constructor public Course(String room, String code) { this.room = room; this.courseCode = code; } //Getters & Setters public String getCourseCode() { return courseCode; } public void setCourseCode(String courseCode) { this.courseCode = courseCode; } public Lecturer getTeacher() { return teacher; } public void setTeacher(Lecturer teacher) { this.teacher = teacher; } public String getCourseWork() { return courseWork; } public void setCourseWork(String courseWork) { this.courseWork = courseWork; } public String getRoom() { return room; } public void setRoom(String room) { this.room = room; } } <file_sep>/Week04/UniDemo/src/unidemo/UniDemo.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package unidemo; public class UniDemo { /** * @param args the command line arguments */ public static void main(String[] args) { Lecturer Mark = new Lecturer(1234, "<NAME> "); Student James = new Student(" <NAME> ", 10590453); Course Security = new Course(" SMB101 ", " SOFT252 "); //Print student details Admin.getDetails(James); //Assign course to lecturer Admin.assignCourse(Mark, Security); //Assign course to student Admin.assignCourse(James, Security); //Student attends James.attendClass(); //Lecturer teaches Mark.teach(); //Student coursework attempt James.doCoursework(); //Lecturer sets coursework Mark.setCoursework(" CW1: Java Programming "); //Student coursework reattempt James.doCoursework(); //Print lecturer details Admin.getDetails(Mark); } }
39463292d600b0014cf4468d6ed13a67b27c70af
[ "Markdown", "Java", "INI" ]
11
Java
jwhite96/SOFT252-Practicals
aca35fd1842886b913ea630c8a0d54b869fbe3a7
b2bf255002e93fee48fcf9ba87aa93b6aa5f333b
refs/heads/main
<file_sep>package ru.geekbrains.lesson.seven; public class Main { public static void main(String[] args) { Cat[] cats = { new Cat("Пушок", 15), new Cat("Барсик", 10), new Cat("Рыжик", 20), new Cat("Мурзик", 10) }; Plate plate = new Plate(40); plate.info(); for (int i = 0; i < cats.length; i++) { cats[i].eat(plate); cats[i].info(); plate.info(); } plate.addFood(); } }<file_sep>package ru.geekbrains.lesson.seven; import java.util.Scanner; public class Plate { private int food; private static final int MAX_FOOD = 100; public Plate(int food) { this.food = food; } public int addFood (){ System.out.println("Хотите наполнить тарелку? Да - 1, Нет - 0"); Scanner addfood = new Scanner(System.in); int i = addfood.nextInt(); if (i == 1) { food = MAX_FOOD; info(); return food; } System.out.println("Больше некого кормить"); return food; } public boolean reduceFood(int hunger) { if (hunger >= food) { return false; } else { food -= hunger; return true; } } public void info() { System.out.println("На тарелке: " + food); } }
30c94b51abe2c166b61316ba0ea86d72b6183476
[ "Java" ]
2
Java
TexMerphy/LessonSeven
5d80ebe4111eddd1d716668e5170d9aaf1eb4dee
68986a67532856ae6864d8a9092c95d61e1492ba
refs/heads/master
<repo_name>WhiteRaidho/ArduinoNightLamp<file_sep>/README.md # ArduinoNightLamp Kod do wielofunkcyjnej lampki nocnej. <file_sep>/ArduinoNightLamp/ArduinioNightLamp.ino #include <CapacitiveSensor.h> #define redPin 5 #define greenPin 9 #define bluePin 6 #define photoPin A3 #define potPin A0 #define touchRec 2 #define touchSen 4 #define modes 4 #define optionModes 2 #define potProbes 10 int startIlumination = 400; int red, green, blue; int col = 0; int mode = 0; int potPrev[potProbes] = {0}; int potCur = 0; int photoRes = 0; float maxPower = 255; CapacitiveSensor capSensor = CapacitiveSensor(touchRec, touchSen); int touchThreshold = 1000; float touchStart; bool wasTouched = false; int timer = 0; int lastPotRead = 0; bool optionMenu = false; int optionMode = 0; bool isLightOn = true; int redG = 0; int blueG = 255; int greenG = 0; int allColors = 0; void setup() { Serial.begin(9600); pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); pinMode(photoPin, INPUT); pinMode(potPin, INPUT); } void loop() { checkTouchSensor(); calcPot(); calcPhoto(); if (startIlumination > photoRes) { isLightOn = true; } else if (startIlumination < photoRes - 50) { isLightOn = false; } if (optionMenu) { optionsMenu(); } else { normalMode(); } delay(5); } void checkTouchSensor() { long sensorValue = capSensor.capacitiveSensor(30); if (sensorValue < 0) return; if (sensorValue > touchThreshold && !wasTouched) { touchStart = millis(); wasTouched = true; Serial.println("Nacisnieto"); } else if (sensorValue <= touchThreshold && wasTouched) { touchAction(millis() - touchStart); wasTouched = false; Serial.println("Puszczono"); } } void blinkRGB() { isLightOn = true; switch (optionMenu ? optionMode : mode) { case 0: blinkColor(120, 0, 0); break; case 1: blinkColor(0, 120, 0); break; case 2: blinkColor(0, 0, 120); break; } } void blinkColor(int r, int g, int b) { setColor(r, g, b); delay(150); setColor(0, 0, 0); delay(150); setColor(r, g, b); delay(150); setColor(0, 0, 0); delay(150); setColor(r, g, b); delay(150); setColor(0, 0, 0); delay(150); } void touchAction(float t) { if (t > 1000) { optionMenu = !optionMenu; optionMode = 0; Serial.print(optionMenu); } else if (t > 10) { if (!optionMenu) { mode = (mode + 1) % modes; } else { optionMode = (optionMode + 1) % optionModes; } } blinkRGB(); } void calcPot() { int cur = analogRead(potPin); int prev; for (int i = 0; i < potProbes - 1; i++) { potPrev[i] = potPrev[i + 1]; } potPrev[potProbes - 1] = cur; int avr = 0; for (int i = 0; i < potProbes; i++) { avr += potPrev[i]; } avr /= potProbes; potCur = avr; } void calcPhoto() { photoRes = analogRead(photoPin); } void setColor(int r, int g, int b) { if (isLightOn) { analogWrite(redPin, r * (maxPower / 255.f)); analogWrite(greenPin, g * (maxPower / 255.f)); analogWrite(bluePin, b * (maxPower / 255.f)); } else { analogWrite(redPin, 0); analogWrite(greenPin, 0); analogWrite(bluePin, 0); } } void calculateRGB(int c) { if (c < 120) { redG = map(c, 0, 119, 255, 0); greenG = map(c, 0, 119, 0, 255); blueG = 0; } else if (c < 240) { redG = 0; greenG = map(c, 120, 239, 255, 0); blueG = map(c, 120, 239, 0, 255); } else { redG = map(c, 240, 359, 0, 255); greenG = 0; blueG = map(c, 240, 359, 255, 0); } } void optionsMenu() { switch (optionMode) { case 0: isLightOn = true; maxPower = map(potCur, 0, 1023, 0, 255); setColor(maxPower, 0, 0); break; case 1: startIlumination = potCur; setColor(120, 120, 120); break; } } void normalMode() { switch (mode) { case 0: isLightOn = false; break; case 1: oneColorMode(); break; case 2: whiteMode(); break; case 3: allColorMode(); break; } } void oneColorMode() { int col = map(potCur, 0, 1023, 0, 359); calculateRGB(col); setColor(redG, blueG, greenG); } void whiteMode() { setColor(255, 255, 100); } void allColorMode(){ allColors = (++allColors)%7200; int c = allColors/20; calculateTGB(c); setColor(redG, blueG, greenG); }
f3c838fb626968781ce94784d53287438956dc95
[ "Markdown", "C++" ]
2
Markdown
WhiteRaidho/ArduinoNightLamp
382edbda37161c1b8b3e8da6580b74f443abe5a7
ec84e4ae7f96c261c380e83365613c8058e8568f
refs/heads/master
<repo_name>relayr/go-sdk<file_sep>/relayr/structs.go package relayr type Reading struct { Meaning string `json:"meaning"` Value string `json:"value"` } type Command struct { Path string `json:"path"` Name string `json:"name"` Value int `json:"value"` } type Commands struct { Commands string `json:"commands"` } type MQTTCred struct { User string Password string ClientId string Topic string Broker string Payload string } type User struct { Id string Email string Name string FirstName string LastName string CompanyName string Token string Host string UserAgent string Headers []byte } type Config struct { RelayrAPI string Token string RelayrHistoryAPI string ClientName string UserAgentString string DEBUG string LOG string RELAYR_MQTT_HOST string RELAYR_MQTT_PORT string } <file_sep>/examples/user.go package main import ( "fmt" "github.com/relayr/go-sdk/relayr" ) func main() { a := relayr.NewUser("<bearer token>") // Print the user authentication information directly from an HTTP request. fmt.Println(a.GetUserInfo()) // Fill user credentials struct. a.GetUserInfo() // Get information on the user's devices. fmt.Println(a.GetUserDevices(a.Id)) } <file_sep>/examples/HTTPreadings.go package main import ( "fmt" "github.com/relayr/go-sdk//relayr" ) func main() { // Create a new user and manually enter the Bearer token and target Device ID. a := relayr.NewUser("<bearer token>") a.GetUserInfo() deviceId := "<deviceid>" // Post a reading of humidity with an HTTP POST. var r relayr.Reading r.Meaning = "humidity" r.Value = "11" a.PostDeviceData(deviceId, r) // Command the device's control led with an HTTP POST. var c relayr.Command c.Path = "led" c.Name = "control_led" c.Value = 1 a.PostDeviceCommand(deviceId, c) // Print the device's current state. fmt.Println(a.GetDeviceState(deviceId)) } <file_sep>/relayr/HTTP.go package relayr import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" ) func ReadConfig() Config { file, _ := os.Open("relayr/config.json") decoder := json.NewDecoder(file) configuration := Config{} err := decoder.Decode(&configuration) if err != nil { log.Fatal(err) } return configuration } func NewUser(token string) User { // Parse inforamtion in config.json file and set user information from // HTTP GET request to credentials. Set the user header. var a User a.Token = token config := ReadConfig() a.Host = config.RelayrAPI a.UserAgent = config.UserAgentString userinfo := a.GetUserInfo() err := json.Unmarshal([]byte(userinfo), &a) if err != nil { log.Fatal(err) } h := fmt.Sprintf(`{"User-Agent": %s ,'Content-Type': 'application/json' }`, a.UserAgent) a.Headers = []byte(h) return a } func (a User) PerformRequest(method string, url string, jsonStr []byte) []byte { if method == "POST" { req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) req.Header.Set("Authorization", a.Token) req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println("response Body:", string(body)) return nil } else if method == "GET" { req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonStr)) req.Header.Set("Authorization", a.Token) req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() bodyText, err := ioutil.ReadAll(resp.Body) s := bodyText return s } else { return nil } } func (a User) PostDeviceData(deviceID string, r Reading) { url := a.Host + "/devices/" + deviceID + "/data" fmt.Printf("Posting data to device with id %s \n", deviceID) //Marshall the Reading r struct to JSON []byte format. d, err := json.Marshal(r) if err != nil { log.Fatal(err) } a.PerformRequest("POST", url, d) } func (a User) PostDeviceCommand(deviceID string, c Command) { url := a.Host + "/devices/" + deviceID + "/commands" fmt.Printf("Posting command to device with id %s \n", deviceID) //Marshall the Reading r struct to JSON []byte format. d, err := json.Marshal(c) if err != nil { log.Fatal(err) } a.PerformRequest("POST", url, d) } func (a User) GetDeviceState(deviceID string) string { fmt.Printf("Getting device state for device with ID %s \n", deviceID) url := a.Host + "/devices/" + deviceID + "/state" response := a.PerformRequest("GET", url, nil) return string(response) } func (a User) GetUserInfo() string { fmt.Println("Getting user information.") url := fmt.Sprintf("%s/oauth2/user-info", a.Host) response := a.PerformRequest("GET", url, nil) return string(response) } func (a User) GetUserDevices(userid string) string { // Get all devices registered for a user with a specific UUID. fmt.Println("List of all user's devices:") url := fmt.Sprintf("%s/users/%s/devices", a.Host, userid) response := a.PerformRequest("GET", url, nil) return string(response) } <file_sep>/relayr/MQTT.go package relayr import ( "encoding/json" "fmt" MQTT "github.com/eclipse/paho.mqtt.golang" "log" "os" ) func InitMQTTCred(mqttcred string) MQTTCred { // Unmarshal the user credentials and add broker field. var m MQTTCred err := json.Unmarshal([]byte(mqttcred), &m) fmt.Println(err) m.Broker = "tcp://mqtt.relayr.io:1883" return m } func (a User) GetMQTTCredentials(deviceID string) string { // Get all devices registered for a user with a specific UUID. fmt.Println("Get the device's MQTT credentials.") url := fmt.Sprintf("%s/devices/%s/credentials", a.Host, deviceID) response := a.PerformRequest("GET", url, nil) return string(response) } func (m MQTTCred) MQTTPublish(r Reading) { // Configuration of a new client. opts := MQTT.NewClientOptions() opts.AddBroker(m.Broker) opts.SetClientID(m.ClientId) opts.SetUsername(m.User) opts.SetPassword(<PASSWORD>) opts.SetCleanSession(false) client := MQTT.NewClient(opts) // Try to connect to the client. if token := client.Connect(); token.Wait() && token.Error() != nil { panic(token.Error()) } //Marshall the Reading r struct to JSON []byte format. d, err := json.Marshal(r) if err != nil { log.Fatal(err) } // Publish the Reading r to the Client. fmt.Println("Sample Publisher Started") token := client.Publish(m.Topic+"data", byte(0), false, d) token.Wait() client.Disconnect(250) fmt.Println("Sample Publisher Disconnected") } func (m MQTTCred) MQTTSubscribe() Command { // Configuration of a new client. opts := MQTT.NewClientOptions() opts.AddBroker(m.Broker) opts.SetClientID(m.ClientId) opts.SetUsername(m.User) opts.SetPassword(m.<PASSWORD>) opts.SetCleanSession(false) choke := make(chan [2]string) m.Topic = m.Topic + "cmd" opts.SetDefaultPublishHandler(func(client MQTT.Client, msg MQTT.Message) { choke <- [2]string{msg.Topic(), string(msg.Payload())} }) client := MQTT.NewClient(opts) // Try and connect to the client. if token := client.Connect(); token.Wait() && token.Error() != nil { panic(token.Error()) } // Subsccribe to the chosen Topic. if token := client.Subscribe(m.Topic, byte(0), nil); token.Wait() && token.Error() != nil { fmt.Println(token.Error()) os.Exit(1) } incoming := <-choke client.Disconnect(250) fmt.Println("Sample Subscriber Disconnected") // Unmarshall the JSON data to a Command struct and return this variable. var c Command err := json.Unmarshal([]byte(incoming[1]), &c) if err != nil { log.Fatal(err) } return c } <file_sep>/README.md #The relayr Go SDK ##Introduction The relayr Go SDK provides you with access points to the relayr API. It allows you to use the relayr Cloud Platform to interact with your cloud-connected devices. [Click here for the Go-SDK repository on GitHub] (https://github.com/relayr/go-sdk) This guide will explain how to get up and running with the Go SDK. ##Implementing the SDK Install the package using ```go get```: ```shell go get github.com/relayr/go-sdk ``` Then import the package in your file with ```shell import ( "github.com/relayr/go-sdk/relayr" ) ``` ##Authorization You must authorize as a user in the relayr cloud in order to access the full features of the SDK. This can be obtained by getting a token from the relayr dashboard. 1. Go to the relayr [developer dashboard] (https://developer.relayr.io/) 2. Navigate to Account, header Settings 2. Copy the presented token In creating a new instance of the User struct, you provide this authorization with the following code: ```go a := relayr.NewUser("<user_token>") ``` By calling this function, the instance 'a' is automatically populated by the user's Name, Email, Company, etc. These fields can be viewed independently by calling, for example, ```a.Id```. ##User Information ###Getting your user information By creating a new instance of a User and specifying your user token, you can also access a string of your user information with the following code: ```go a.GetUserInfo() ``` ###Listing your devices Listing a user's available devices can be done by the following code: ```go a.GetUserDevices(a.Id) ``` ##Device Information ###HTTP Requests ####Sending a reading to a device Publishing data to a device requires sending JSON data with an HTTP POST request. It involves sending data to the url ```<a.Host>/device/<deviceID>/data```. For example, to change the temperature of a device of id <deviceID> to 14 involves the following procedure, using the Reading struct: ```go deviceId := "4ead2f53-3dc1-4c8f-87b3-8b067c3b5ae4" var r relayr.Reading r.Meaning = "humidity" r.Value = "11" a.PostDeviceData(deviceId, r) ``` ####Sending a command to a device Sending data to a device is similar. It also requires sending JSON data with an HTTP POST request. However, it involves sending data to the url ```<a.Host>/devices/<deviceID>/commands``` instead of ```.../data```. For example, to control the LED of a device involves sending a command setting the "control_led" to 1. ```go var c relayr.Command c.Path = "led" c.Name = "control_led" c.Value = 1 a.PostDeviceCommand(deviceId, c) ``` ####Reading the state of a device Reading the state of a device involves a HTTP GET request. However, it involves a post to the url ```<a.Host>/devices/<deviceID>/state``` instead of ```.../data```. Reading the state of a device doesn't involve sending any reading or command to the device. For example, to see all the readings and commands on a specific device, all that is required is calling: ```go deviceId := "<deviceID>" fmt.Println(a.GetDeviceState(deviceId)) ``` This call prints directly the type [] byte data returned by the device. ###MQTT Requests The MQTT protocol allows publishing and subscribing to a device. Setting up MQTT credentials involves setting up the user's name, password, clientID, target topic, and target broker. To set these up involves putting the correct fields into the following code: ```go m := relayr.MQTTCred{} m.User = "<user_name>" m.Password = "<<PASSWORD>>" m.ClientId = "<client_id>" m.Topic = "<topic>" m.Broker = "tcp://mqtt.relayr.io:1883" ``` All information can be found on the relayr dashboard under Devices > "targeted device" > Device Settings. **This information can also be found by making a HTTP GET Request with the method ````GetMQTTCredentials(<device_id>)````.** ####Publishing to the device Publishing to a cloud-connected device involves sending a publish to the device with a reading. The following changes the temperature of the chosen device to 14. ```go var r relayr.Reading r.Meaning = "temperature" r.Value = "14" m.MQTTPublish(r) ``` ####Subscribing to the device Publishing to a cloud-connected device involves sending a subscribe request to the device. It does not require a payload because it is only reading from the device. The following subscribes to the chosen device and prints the returned string with its fields parsed into a struct. ```go c := m.MQTTSubscribe() fmt.Printf("Path is: %s. Name is: %s. Value is: %d. \n", c.Path, c.Name, c.Value) ``` ##Example The below example creates a new user, prints its cloud-connected devics, takes the targetted device ID and populated its MQTT credentials from a HTTP Get request, changes its humidity reading to 12 with a MQTT publication and then waits for a command from the device, outputting the data. ```go package main import ( "fmt" "github.com/relayr/go-sdk/relayr" ) func main() { // Create an API instance with the Token from the relayr Dashboard. a := relayr.NewUser("<bearer token>") a.GetUserInfo() // Print all the user's devices. fmt.Println(a.GetUserDevices(a.Id)) // Copy the target device Id and set its MQTT credentials using a HTTP GET request. deviceID := "<device id>" mqttcred := a.GetMQTTCredentials(deviceID) m := relayr.InitMQTTCred(mqttcred) // Publish, with the MQTT protocol, a value of 12 to the device's temperature reading. var r relayr.Reading r.Meaning = "humidity" r.Value = "12" m.MQTTPublish(r) // Subscribe to the device and print the first command before disconnecting. c := m.MQTTSubscribe() fmt.Printf("Path is: %s. Name is: %s. Value is: %d. \n", c.Path, c.Name, c.Value) } ```<file_sep>/examples/MQTTreadings.go package main import ( "fmt" "github.com/relayr/go-sdk/relayr" ) func main() { // Create an API instance with the Token from the relayr Dashboard. a := relayr.NewUser("<bearer token>") a.GetUserInfo() // Print all the user's devices. fmt.Println(a.GetUserDevices(a.Id)) // Copy the target device Id and set its MQTT credentials using a HTTP GET request. deviceID := "<device id>" mqttcred := a.GetMQTTCredentials(deviceID) m := relayr.InitMQTTCred(mqttcred) // Publish, with the MQTT protocol, a value of 12 to the device's temperature reading. var r relayr.Reading r.Meaning = "humidity" r.Value = "12" m.MQTTPublish(r) // Subscribe to the device and print the first command before disconnecting. c := m.MQTTSubscribe() fmt.Printf("Path is: %s. Name is: %s. Value is: %d. \n", c.Path, c.Name, c.Value) }
bd31b86e57b2edeb95eca6d6bf66339f47cb68be
[ "Markdown", "Go" ]
7
Go
relayr/go-sdk
b3e0e6cfed645c806b33c6f2557584d14661959f
ab4fe5d1ab256a1a45357b8ec3340191822faaa2
refs/heads/master
<file_sep>#!/usr/bin/env python """ Python source code - replace this with a description of the code and write the code below this text. """ # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import unittest class BaseTestCase(unittest.TestCase): @classmethod def setUpClass(cls): raise NotImplementedError() @classmethod def tearDownClass(cls): raise NotImplementedError() def setUp(self): raise NotImplementedError() def tearDown(self): raise NotImplementedError()
8a851c0d03acd87b256f66f3b28b1dd119abcdcf
[ "Python" ]
1
Python
rich-hart/Testing_Scripts
8949725ff9d5445461db43c6ea012bd331cc5ab9
0a73c49ad13df3d6de9025f3a72a00e7b91fdca4
refs/heads/master
<file_sep>Generator ========= The package ships with two generators, which are configurable through an associative array as constructor parameter. Alternatively if you have a project that uses the same configuration over and over again, extend the respective config object and pass it instead of the configuration array. :: <?php use gossi\codegen\generator\CodeGenerator; // a) new code generator with options passed as array $generator = new CodeGenerator([ 'generateDocblock' => false, ... ]); // b) new code generator with options passed as object $generator = new CodeGenerator(new MyCodeGenerationConfig()); CodeGenerator ------------- Generates code for a given model. Additionally (and by default), it will generate docblocks for all contained classes, methods, interfaces, etc. you have prior to generating the code. * Class: ``gossi\codegen\generator\CodeGenerator`` * Config: ``gossi\codegen\config\CodeGeneratorConfig`` * Options: +-------------------------+-----------------------------------+---------------+-------------------------------------------------------------------------+ | Key | Type | Default Value | Description | +=========================+===================================+===============+=========================================================================+ | generateDocblock | boolean | true | enables docblock generation prior to code generation | +-------------------------+-----------------------------------+---------------+-------------------------------------------------------------------------+ | generateEmptyDocblock | boolean | true | allows generation of empty docblocks | +-------------------------+-----------------------------------+---------------+-------------------------------------------------------------------------+ | generateScalarTypeHints | boolean | false | generates scalar type hints, e.g. in method/function parameters (PHP 7) | +-------------------------+-----------------------------------+---------------+-------------------------------------------------------------------------+ | generateReturnTypeHints | boolean | false | generates scalar type hints for return values (PHP 7) | +-------------------------+-----------------------------------+---------------+-------------------------------------------------------------------------+ | enableSorting | boolean | true | Enables sorting | +-------------------------+-----------------------------------+---------------+-------------------------------------------------------------------------+ | useStatementSorting | boolean|string|Closure|Comparator | default | Sorting mechanism for use statements | +-------------------------+-----------------------------------+---------------+-------------------------------------------------------------------------+ | constantSorting | boolean|string|Closure|Comparator | default | Sorting mechanism for constants | +-------------------------+-----------------------------------+---------------+-------------------------------------------------------------------------+ | propertySorting | boolean|string|Closure|Comparator | default | Sorting mechanism for properties | +-------------------------+-----------------------------------+---------------+-------------------------------------------------------------------------+ | methodSorting | boolean|string|Closure|Comparator | default | Sorting mechanism for methods | +-------------------------+-----------------------------------+---------------+-------------------------------------------------------------------------+ **Note**: when ``generateDocblock`` is set to ``false`` then ``generateEmptyDocblock`` is ``false`` as well. **Note 2**: For sorting ... * ... a string will used to find a comparator with that name (at the moment there is only default). * ... with a boolean you can disable sorting for a particular member * ... you can pass in your own ``\Closure`` for comparison * ... you can pass in a Comparator_ for comparison .. _Comparator: https://phootwork.github.io/lang/comparison/ * Example: :: <?php use gossi\codegen\generator\CodeGenerator; // will set every option to true, because of the defaults $generator = new CodeGenerator([ 'generateScalarTypeHints' => true, 'generateReturnTypeHints' => true ]); $code = $generator->generate($myClass); CodeFileGenerator ----------------- Generates a complete php file with the given model inside. Especially useful when creating PSR-4 compliant code, which you are about to dump into a file. It extends the ``CodeGenerator`` and as such inherits all its benefits. * Class: ``gossi\codegen\generator\CodeFileGenerator`` * Config: ``gossi\codegen\config\CodeFileGeneratorConfig`` * Options: Same options as ``CodeGenerator`` plus: +--------------------+----------------------+---------------+----------------------------------------------------------------------------------------+ | Key | Type | Default Value | Description | +====================+======================+===============+========================================================================================+ | headerComment | null|string|Docblock | null | A comment, that will be put after the ``<?php`` statement | +--------------------+----------------------+---------------+----------------------------------------------------------------------------------------+ | headerDocblock | null|string|Docblock | null | A docblock that will be positioned after the possible header comment | +--------------------+----------------------+---------------+----------------------------------------------------------------------------------------+ | blankLineAtEnd | boolean | true | Places an empty line at the end of the generated file | +--------------------+----------------------+---------------+----------------------------------------------------------------------------------------+ | declareStrictTypes | boolean | false | Whether or not a ``declare(strict_types=1);`` is placed at the top of the file (PHP 7) | +--------------------+----------------------+---------------+----------------------------------------------------------------------------------------+ **Note**: ``declareStrictTypes`` sets ``generateScalarTypeHints`` and ``generateReturnTypeHints`` to ``true``. * Example: :: <?php use gossi\codegen\generator\CodeFileGenerator; $generator = new CodeGenerator([ 'headerComment' => 'This will be placed at the top, woo', 'headerDocblock' => 'Full documentation mode confirmed!', 'declareStrictTypes' => true ]); $code = $generator->generate($myClass); <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator; use gossi\codegen\config\CodeFileGeneratorConfig; use gossi\codegen\model\GenerateableInterface; use phootwork\lang\Text; /** * Code file generator. * * Generates code for a model and puts it into a file with `<?php` statements. Can also * generate header comments. * * @author <NAME> */ class CodeFileGenerator extends CodeGenerator { /** * Creates a new CodeFileGenerator * * @see https://php-code-generator.readthedocs.org/en/latest/generator.html * @param CodeFileGeneratorConfig|array $config */ public function __construct($config = null) { parent::__construct($config); } protected function configure($config = null) { if (is_array($config)) { $this->config = new CodeFileGeneratorConfig($config); } else if ($config instanceof CodeFileGeneratorConfig) { $this->config = $config; } else { $this->config = new CodeFileGeneratorConfig(); } } /** * {@inheritDoc} * * @return CodeFileGeneratorConfig */ public function getConfig() { return $this->config; } /** * {@inheritDoc} */ public function generate(GenerateableInterface $model): string { $content = "<?php\n"; $comment = $this->config->getHeaderComment(); if ($comment !== null && !$comment->isEmpty()) { $content .= str_replace('/**', '/*', $comment->toString()) . "\n"; } $docblock = $this->config->getHeaderDocblock(); if ($docblock !== null && !$docblock->isEmpty()) { $content .= $docblock->toString() . "\n"; } if ($this->config->getDeclareStrictTypes()) { $content .= "declare(strict_types=1);\n\n"; } $content .= parent::generate($model); if ($this->config->getBlankLineAtEnd() && !Text::create($content)->endsWith("\n")) { $content .= "\n"; } return $content; } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\builder; use gossi\codegen\generator\builder\parts\RoutineBuilderPart; use gossi\codegen\model\AbstractModel; class FunctionBuilder extends AbstractBuilder { use RoutineBuilderPart; public function build(AbstractModel $model): void { $this->buildDocblock($model); $this->writeFunctionStatement($model); $this->writeBody($model); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\parser\visitor; use gossi\codegen\model\AbstractPhpStruct; use PhpParser\Comment\Doc; use PhpParser\Node\Const_; use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\ClassConst; use PhpParser\Node\Stmt\ClassLike; use PhpParser\Node\Stmt\ClassMethod; use PhpParser\Node\Stmt\Interface_; use PhpParser\Node\Stmt\Namespace_; use PhpParser\Node\Stmt\Property; use PhpParser\Node\Stmt\Trait_; use PhpParser\Node\Stmt\TraitUse; use PhpParser\Node\Stmt\UseUse; class StructParserVisitor implements ParserVisitorInterface { protected $struct; /** * @return AbstractPhpStruct */ protected function getStruct(): AbstractPhpStruct { return $this->struct; } public function __construct(AbstractPhpStruct $struct) { $this->struct = $struct; } public function visitStruct(ClassLike $node) {} public function visitClass(Class_ $node) {} public function visitInterface(Interface_ $node) {} public function visitTrait(Trait_ $node) {} public function visitTraitUse(TraitUse $node) {} public function visitConstants(ClassConst $node) {} public function visitConstant(Const_ $node, Doc $doc = null) {} public function visitProperty(Property $node) {} public function visitNamespace(Namespace_ $node) {} public function visitUseStatement(UseUse $node) {} public function visitMethod(ClassMethod $node) {} } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\utils; use gossi\codegen\model\AbstractPhpStruct; class TypeUtils { public static $phpTypes = [ 'string', 'int', 'integer', 'bool', 'boolean', 'float', 'double', 'object', 'mixed', 'resource', 'iterable', 'array', 'callable', ]; public static function expressionToTypes(?string $typeExpression): array { if (!$typeExpression) { return []; } return explode('|', $typeExpression); } public static function guessQualifiedName(AbstractPhpStruct $stuct, string $type): string { if (in_array($type, self::$phpTypes, true)) { return $type; } $suffix = ''; if (strpos($type, '[]') !== false) { $type = str_replace('[]', '', $type); $suffix = '[]'; } $uses = $stuct->getUseStatements(); foreach ($uses as $use) { $regexp = '/\\\\' . preg_quote($type, '/') . '$/'; if (preg_match($regexp, $use)) { return $use . $suffix; } } $sameNamespace = $stuct->getNamespace() . '\\' . $type; if (class_exists($sameNamespace)) { return $sameNamespace . $suffix; } return $type . $suffix; } public static function isGlobalQualifiedName(string $name): bool { return $name[0] === '\\' && substr_count($name, '\\') === 1; } public static function isNativeType(string $type): bool { return in_array($type, self::$phpTypes, true); } public static function typesToExpression(iterable $types): ?string { $typeExpr = ''; foreach ($types as $type) { $typeExpr .= '|' . $type; } if (!$typeExpr) { return null; } return trim($typeExpr, '|'); } } <file_sep><?php interface MyCollectionInterface extends phootwork\collection\Collection { } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\parser\visitor; use PhpParser\Comment\Doc; use PhpParser\Node\Const_; use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\ClassConst; use PhpParser\Node\Stmt\ClassLike; use PhpParser\Node\Stmt\ClassMethod; use PhpParser\Node\Stmt\Interface_; use PhpParser\Node\Stmt\Namespace_; use PhpParser\Node\Stmt\Property; use PhpParser\Node\Stmt\Trait_; use PhpParser\Node\Stmt\TraitUse; use PhpParser\Node\Stmt\UseUse; interface ParserVisitorInterface { /** * Visit a struct * * @param ClassLike $node * @return void */ public function visitStruct(ClassLike $node); /** * Visit a class * * @param Class_ $node * @return void */ public function visitClass(Class_ $node); /** * Visit an interface * * @param Interface_ $node * @return void */ public function visitInterface(Interface_ $node); /** * Visit a trait * * @param Trait_ $node * @return void */ public function visitTrait(Trait_ $node); /** * Visit a use statement inside a struct * * @param TraitUse $node * @return void */ public function visitTraitUse(TraitUse $node); /** * Visit class constants * * @param ClassConst $node * @return void */ public function visitConstants(ClassConst $node); /** * Visit a constant * * @param Const_ $node * @param Doc $doc * @return void */ public function visitConstant(Const_ $node, Doc $doc = null); /** * Visit a property * * @param Property $node * @return void */ public function visitProperty(Property $node); /** * Visit a namespace statement * * @param Namespace_ $node * @return void */ public function visitNamespace(Namespace_ $node); /** * Visit a use statement * * @param UseUse $node * @return void */ public function visitUseStatement(UseUse $node); /** * Visit a method * * @param ClassMethod $node * @return void */ public function visitMethod(ClassMethod $node); } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model; use gossi\codegen\model\parts\AbstractPart; use gossi\codegen\model\parts\ConstantsPart; use gossi\codegen\model\parts\FinalPart; use gossi\codegen\model\parts\InterfacesPart; use gossi\codegen\model\parts\PropertiesPart; use gossi\codegen\model\parts\TraitsPart; use gossi\codegen\parser\FileParser; use gossi\codegen\parser\visitor\ClassParserVisitor; use gossi\codegen\parser\visitor\ConstantParserVisitor; use gossi\codegen\parser\visitor\MethodParserVisitor; use gossi\codegen\parser\visitor\PropertyParserVisitor; /** * Represents a PHP class. * * @author <NAME> */ class PhpClass extends AbstractPhpStruct implements GenerateableInterface, TraitsInterface, ConstantsInterface, PropertiesInterface, PhpTypeInterface { use AbstractPart; use ConstantsPart; use FinalPart; use InterfacesPart; use PropertiesPart; use TraitsPart; /** @var string */ private $parentClassName; /** * Creates a PHP class from file * * @param string $filename * @return PhpClass */ public static function fromFile(string $filename): self { $class = new self(); $parser = new FileParser($filename); $parser->addVisitor(new ClassParserVisitor($class)); $parser->addVisitor(new MethodParserVisitor($class)); $parser->addVisitor(new ConstantParserVisitor($class)); $parser->addVisitor(new PropertyParserVisitor($class)); $parser->parse(); return $class; } /** * Creates a new PHP class * * @param string $name the qualified name */ public function __construct($name = null) { parent::__construct($name); $this->initProperties(); $this->initConstants(); $this->initInterfaces(); } /** * Returns the parent class name * * @return string */ public function getParentClassName(): ?string { return $this->parentClassName; } public function getParentClass(): PhpClass { return class_exists($this->parentClassName) ? self::fromName($this->parentClassName) : PhpClass::create($this->parentClassName); } /** * Sets the parent class name * * @param PhpClass|string|null $name the new parent * @return $this */ public function setParentClassName($parent) { if ($parent instanceof PhpClass) { $this->addUseStatement($parent->getQualifiedName()); $parent = $parent->getName(); } $this->parentClassName = $parent; return $this; } public function generateDocblock(): void { parent::generateDocblock(); foreach ($this->constants as $constant) { $constant->generateDocblock(); } foreach ($this->properties as $prop) { $prop->generateDocblock(); } } } <file_sep><?php namespace gossi\codegen\tests\parser; use gossi\codegen\model\PhpClass; use gossi\codegen\parser\FileParser; use gossi\codegen\parser\visitor\ClassParserVisitor; use PHPUnit\Framework\TestCase; /** * @group parser */ class FileParserTest extends TestCase { public function testVisitors() { $struct = new PhpClass(); $visitor = new ClassParserVisitor($struct); $parser = new FileParser('dummy-file'); $parser->addVisitor($visitor); $this->assertTrue($parser->hasVisitor($visitor)); $parser->removeVisitor($visitor); $this->assertFalse($parser->hasVisitor($visitor)); } /** * @expectedException phootwork\file\exception\FileNotFoundException */ public function testGetConstantThrowsExceptionWhenConstantDoesNotExist() { $parser = new FileParser('file-not-found'); $parser->parse(); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\comparator; use gossi\codegen\model\PhpMethod; use phootwork\lang\Comparator; /** * Default property comparator * * Orders them by static first, then visibility and last by property name */ class DefaultMethodComparator implements Comparator { /** * @param PhpMethod $a * @param PhpMethod $b */ public function compare($a, $b) { if ($a->isStatic() !== $isStatic = $b->isStatic()) { return $isStatic ? 1 : -1; } if (($aV = $a->getVisibility()) !== $bV = $b->getVisibility()) { $aV = 'public' === $aV ? 3 : ('protected' === $aV ? 2 : 1); $bV = 'public' === $bV ? 3 : ('protected' === $bV ? 2 : 1); return $aV > $bV ? -1 : 1; } return strcasecmp($a->getName(), $b->getName()); } } <file_sep><?php namespace gossi\codegen\tests\fixtures\sub; class SubClass { } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\parser\visitor; use gossi\codegen\parser\visitor\parts\StructParserPart; class TraitParserVisitor extends StructParserVisitor { use StructParserPart; } <file_sep><?php namespace Foo; use Bam\Baz as BamBaz; class Bar { } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator; use gossi\codegen\config\CodeGeneratorConfig; use gossi\codegen\generator\utils\Writer; use gossi\codegen\model\AbstractModel; use gossi\formatter\Formatter; /** * Model Generator * * @author <NAME> */ class ModelGenerator { /** @var Writer */ private $writer; /** @var BuilderFactory */ private $factory; /** @var CodeGeneratorConfig */ private $config; /** @var Formatter */ private $formatter; /** * * @param CodeGeneratorConfig|array $config */ public function __construct($config = null) { if (is_array($config)) { $this->config = new CodeGeneratorConfig($config); } else if ($config instanceof CodeGeneratorConfig) { $this->config = $config; } else { $this->config = new CodeGeneratorConfig(['generateDocblock' => false]); } $profile = $this->config->getProfile(); $this->writer = new Writer([ 'indentation_character' => $profile->getIndentation('character') == 'tab' ? "\t" : ' ', 'indentation_size' => $profile->getIndentation('size') ]); $this->formatter = new Formatter($profile); $this->factory = new BuilderFactory($this); } /** */ public function getConfig(): CodeGeneratorConfig { return $this->config; } /** * */ public function getWriter(): Writer { return $this->writer; } /** * */ public function getFactory(): BuilderFactory { return $this->factory; } /** * @param AbstractModel $model */ public function generate(AbstractModel $model): string { $this->writer->reset(); $builder = $this->factory->getBuilder($model); $builder->build($model); $code = $this->writer->getContent(); if ($this->config->isFormattingEnabled()) { $code = $this->formatter->format($code); } return $code; } } <file_sep><?php namespace gossi\codegen\tests\generator; use gossi\codegen\generator\ModelGenerator; use gossi\codegen\model\PhpConstant; use gossi\codegen\model\PhpParameter; use PHPUnit\Framework\TestCase; /** * @group generator */ class ParameterGeneratorTest extends TestCase { public function testPassedByReference() { $expected = '&$foo'; $param = PhpParameter::create('foo')->setPassedByReference(true); $generator = new ModelGenerator(); $code = $generator->generate($param); $this->assertEquals($expected, $code); } public function testTypeHints() { $generator = new ModelGenerator(); $param = PhpParameter::create('foo')->addType('Request'); $this->assertEquals('Request $foo', $generator->generate($param)); } public function testPhp5TypeHints() { $generator = new ModelGenerator(['generateScalarTypeHints' => false]); $param = PhpParameter::create('foo')->addType('string'); $this->assertEquals('$foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('int'); $this->assertEquals('$foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('integer'); $this->assertEquals('$foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('float'); $this->assertEquals('$foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('double'); $this->assertEquals('$foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('bool'); $this->assertEquals('$foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('boolean'); $this->assertEquals('$foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('mixed'); $this->assertEquals('$foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('object'); $this->assertEquals('$foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('resource'); $this->assertEquals('$foo', $generator->generate($param)); } public function testPhp7TypeHints() { $generator = new ModelGenerator(['generateScalarTypeHints' => true]); $param = PhpParameter::create('foo')->addType('string'); $this->assertEquals('string $foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('int'); $this->assertEquals('int $foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('integer'); $this->assertEquals('int $foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('float'); $this->assertEquals('float $foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('double'); $this->assertEquals('float $foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('bool'); $this->assertEquals('bool $foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('boolean'); $this->assertEquals('bool $foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('mixed'); $this->assertEquals('$foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('object'); $this->assertEquals('$foo', $generator->generate($param)); $param = PhpParameter::create('foo')->addType('resource'); $this->assertEquals('$foo', $generator->generate($param)); } public function testPhp73Nullable() { $generator = new ModelGenerator(['generateScalarTypeHints' => true, 'generateNullableTypes' => true]); $param = PhpParameter::create('foo')->addType('float')->setNullable(true); $this->assertEquals('?float $foo', $generator->generate($param)); } public function testValues() { $generator = new ModelGenerator(); $prop = PhpParameter::create('foo')->setValue('string'); $this->assertEquals('$foo = \'string\'', $generator->generate($prop)); $prop = PhpParameter::create('foo')->setValue(300); $this->assertEquals('$foo = 300', $generator->generate($prop)); $prop = PhpParameter::create('foo')->setValue(162.5); $this->assertEquals('$foo = 162.5', $generator->generate($prop)); $prop = PhpParameter::create('foo')->setValue(true); $this->assertEquals('$foo = true', $generator->generate($prop)); $prop = PhpParameter::create('foo')->setValue(false); $this->assertEquals('$foo = false', $generator->generate($prop)); $prop = PhpParameter::create('foo')->setValue(null); $this->assertEquals('$foo = null', $generator->generate($prop)); $prop = PhpParameter::create('foo')->setValue(PhpConstant::create('BAR')); $this->assertEquals('$foo = BAR', $generator->generate($prop)); $prop = PhpParameter::create('foo')->setExpression("['bar' => 'baz']"); $this->assertEquals('$foo = [\'bar\' => \'baz\']', $generator->generate($prop)); } } <file_sep><?php namespace gossi\codegen\model; use gossi\codegen\model\parts\QualifiedNamePart; class PhpType implements PhpTypeInterface { use QualifiedNamePart; public function __construct($qualifiedName) { $this->setQualifiedName($qualifiedName); } } <file_sep><?php namespace gossi\codegen\tests\fixtures; /** * A class with comments * * Here is a super dooper long-description * * @author gossi * @since 0.2 */ class ClassWithComments { /** * Best const ever * * Aaaand we go along long * * @var string baz */ const FOO = 'bar'; /** * Best prop ever * * Aaaand we go along long long * * @var string Wer macht sauber? */ private $propper = 'Meister'; /** * Short desc * * Looong desc * * @param bool $moo makes a cow * @param string $foo makes a fow * @return bool true on success and false if it fails */ public function setup($moo, $foo = 'test123') { } } <file_sep><?php namespace gossi\codegen\tests\model; use gossi\codegen\model\PhpProperty; use gossi\codegen\tests\parts\ValueTests; use PHPUnit\Framework\TestCase; /** * @group model */ class PropertyTest extends TestCase { use ValueTests; public function testSetGetValue() { $prop = new PhpProperty('needsName'); $this->assertNull($prop->getValue()); $this->assertFalse($prop->hasValue()); $this->assertSame($prop, $prop->setValue('foo')); $this->assertEquals('foo', $prop->getValue()); $this->assertTrue($prop->hasValue()); $this->assertSame($prop, $prop->unsetValue()); $this->assertNull($prop->getValue()); $this->assertFalse($prop->hasValue()); } public function testSetGetExpression() { $prop = new PhpProperty('needsName'); $this->assertNull($prop->getExpression()); $this->assertFalse($prop->isExpression()); $this->assertSame($prop, $prop->setExpression('null')); $this->assertEquals('null', $prop->getExpression()); $this->assertTrue($prop->isExpression()); $this->assertSame($prop, $prop->unsetExpression()); $this->assertNull($prop->getExpression()); $this->assertFalse($prop->isExpression()); } public function testValueAndExpression() { $prop = new PhpProperty('needsName'); $prop->setValue('abc'); $prop->setExpression('null'); $this->assertTrue($prop->hasValue()); $this->assertTrue($prop->isExpression()); } public function testValues() { $this->isValueString(PhpProperty::create('x')->setValue('hello')); $this->isValueInteger(PhpProperty::create('x')->setValue(2)); $this->isValueFloat(PhpProperty::create('x')->setValue(0.2)); $this->isValueBool(PhpProperty::create('x')->setValue(false)); $this->isValueNull(PhpProperty::create('x')->setValue(null)); } /** * @expectedException \InvalidArgumentException */ public function testInvalidValue() { PhpProperty::create('x')->setValue(new \stdClass()); } } <file_sep><?php namespace gossi\codegen\tests\fixtures; /** * Dummy docblock */ trait DummyTrait { use VeryDummyTrait; private $iAmHidden; public function foo() { } } <file_sep>Model ===== A model is a representation of your code, that you either read or create. Model Overview -------------- There are different types of models available which are explained in this section. Structured Models ^^^^^^^^^^^^^^^^^ Structured models are composites and can contain other models, these are: * ``PhpClass`` * ``PhpTrait`` * ``PhpInterface`` Generateable Models ^^^^^^^^^^^^^^^^^^^ There is only a couple of models available which can be passed to a generator. These are the mentioned structured models + ``PhpFunction``. Part Models ^^^^^^^^^^^ Structured models can be composed of various members. And functions and methods can itself contain zero to many parameters. All parts are: * ``PhpConstant`` * ``PhpProperty`` * ``PhpMethod`` * ``PhpParameter`` Name vs. Namespace vs. Qualified Name ? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ There can be a little struggle about the different names, which are `name`, `namespace` and `qualified name`. Every model has a name and generateable models additionally have a namespace and qualified name. The qualified name is a combination of namespace + name. Here is an overview: +--------------------+----------------+ | **Name** | Tool | +--------------------+----------------+ | **Namespace** | my\\cool | +--------------------+----------------+ | **Qualified Name** | my\\cool\\Tool | +--------------------+----------------+ Create Models programmatically ------------------------------ You can create models with the provided fluent API. The functionality is demonstrated for a ``PhpClass`` but also works accordingly for all the other generateable models. Create your first Class ^^^^^^^^^^^^^^^^^^^^^^^ Let's start with a simple example:: <?php use gossi\codegen\model\PhpClass; $class = new PhpClass(); $class->setQualifiedName('my\\cool\\Tool'); which will generate an empty:: <?php namespace my\cool; class Tool { } Adding a Constructor ^^^^^^^^^^^^^^^^^^^^ It's better to have a constructor, so we add one:: <?php use gossi\codegen\model\PhpClass; use gossi\codegen\model\PhpMethod; use gossi\codegen\model\PhpParameter; $class = new PhpClass('my\\cool\\Tool'); $class ->setMethod(PhpMethod::create('__construct') ->addParameter(PhpParameter::create('target') ->setType('string') ->setDescription('Creates my Tool') ) ) ; you can see the fluent API in action and the snippet above will generate:: <?php namespace my\cool; class Tool { /** * * @param $target string Creates my Tool */ public function __construct($target) { } } Adding members ^^^^^^^^^^^^^^ We've just learned how to pass a blank method, the constructor to the class. We can also add `properties`, `constants` and of course `methods`. Let's do so:: <?php use gossi\codegen\model\PhpClass; use gossi\codegen\model\PhpMethod; use gossi\codegen\model\PhpParameter; use gossi\codegen\model\PhpProperty; use gossi\codegen\model\PhpConstant; $class = PhpClass::create('my\\cool\\Tool') ->setMethod(PhpMethod::create('setDriver') ->addParameter(PhpParameter::create('driver') ->setType('string') ) ->setBody('$this->driver = $driver'); ) ->addProperty(PhpProperty::create('driver') ->setVisibility('private') ->setType('string') ) ->setConstant(new PhpConstant('FOO', 'bar')) ; will generate:: <?php namespace my\cool; class Tool { /** */ const FOO = 'bar'; /** * @var string */ private $driver; /** * * @param $driver string */ public function setDriver($driver) { $this->driver = $driver; } } Declare use statements ^^^^^^^^^^^^^^^^^^^^^^ When you put code inside a method there can be a reference to a class or interface, where you normally put the qualified name into a use statement. So here is how you do it:: <?php use gossi\codegen\model\PhpClass; use gossi\codegen\model\PhpMethod; $class = new PhpClass(); $class ->setName('Tool') ->setNamespace('my\\cool') ->setMethod(PhpMethod::create('__construct') ->setBody('$request = Request::createFromGlobals();') ) ->declareUse('Symfony\\Component\\HttpFoundation\\Request') ; which will create:: <?php namespace my\cool; use Symfony\Component\HttpFoundation\Request; class Tool { /** */ public function __construct() { $request = Request::createFromGlobals(); } } Much, much more ^^^^^^^^^^^^^^^ The API has a lot more to offer and has almost full support for what you would expect to manipulate on each model, of course everything is fluent API. Create from existing Models --------------------------- You can also read a model from existing code. Reading from a file is probably the best option here. It will parse the file and fill up the model. Alternatively if you do have the class already loaded you can use reflection to load the model. From File ^^^^^^^^^ Reading from a file is the simplest way to read existing code, just like this:: <?php use gossi\codegen\model\PhpClass; $class = PhpClass::fromFile('path/to/MyClass.php'); Through Reflection ^^^^^^^^^^^^^^^^^^ If you already have your class loaded, then you can use reflection to load your code:: <?php use gossi\codegen\model\PhpClass; $reflection = new \ReflectionClass('MyClass'); $class = PhpClass::fromReflection($reflection->getFileName()); Also reflection is nice, there is a catch to it. You must make sure ``MyClass`` is loaded. Also all the requirements (use statements, etc.) are loaded as well, anyway you will get an error when initializing the the reflection object. Understanding Values -------------------- The models ``PhpConstant``, ``PhpParameter`` and ``PhpProperty`` support values; all of them implement the ``ValueInterface``. Though, there is a difference between values and expressions. Values refer to language primitives (``string``, ``int``, ``float``, ``bool`` and ``null``). Additionally you can set a ``PhpConstant`` as value (the lib understands this as a library primitive ;-). If you want more complex control over the output, you can set an expression instead, which will be generated as is. Some Examples:: <?php PhpProperty::create('foo')->setValue('hello world.'); // $foo = 'hello world.'; PhpProperty::create('foo')->setValue(300); // $foo = 300; PhpProperty::create('foo')->setValue(3.14); // $foo = 3.14; PhpProperty::create('foo')->setValue(false); // $foo = false; PhpProperty::create('foo')->setValue(null); // $foo = null; PhpProperty::create('foo')->setValue(PhpConstant::create('BAR')); // $foo = BAR; PhpProperty::create('foo')->setExpression('self::MY_CONST'); // $foo = self::MY_CONST; PhpProperty::create('foo')->setExpression("['my' => 'array']"); // $foo = ['my' => 'array']; For retrieving values there is a ``hasValue()`` method which returns ``true`` whether there is a value or an expression present. To be sure what is present there is also an ``isExpression()`` method which you can use as a second check:: <?php if ($prop->hasValue()) { if ($prop->isExpression()) { // do something with an expression } else { // do something with a value } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model; use gossi\codegen\model\parts\PropertiesPart; use gossi\codegen\model\parts\TraitsPart; use gossi\codegen\parser\FileParser; use gossi\codegen\parser\visitor\ConstantParserVisitor; use gossi\codegen\parser\visitor\MethodParserVisitor; use gossi\codegen\parser\visitor\PropertyParserVisitor; use gossi\codegen\parser\visitor\TraitParserVisitor; /** * Represents a PHP trait. * * @author <NAME> */ class PhpTrait extends AbstractPhpStruct implements GenerateableInterface, TraitsInterface, PropertiesInterface { use PropertiesPart; use TraitsPart; /** * Creates a PHP trait from a file * * @param string $filename * @return PhpTrait */ public static function fromFile(string $filename): self { $trait = new self(); $parser = new FileParser($filename); $parser->addVisitor(new TraitParserVisitor($trait)); $parser->addVisitor(new MethodParserVisitor($trait)); $parser->addVisitor(new ConstantParserVisitor($trait)); $parser->addVisitor(new PropertyParserVisitor($trait)); $parser->parse(); return $trait; } /** * Creates a new PHP trait * * @param string $name qualified name */ public function __construct($name = null) { parent::__construct($name); $this->initProperties(); } /** * @inheritDoc */ public function generateDocblock(): void { parent::generateDocblock(); foreach ($this->properties as $prop) { $prop->generateDocblock(); } } } <file_sep><?php namespace gossi\codegen\tests\parser; use gossi\codegen\model\PhpInterface; use gossi\codegen\tests\Fixtures; use PHPUnit\Framework\TestCase; /** * @group parser */ class InterfaceParserTest extends TestCase { public function setUp() { // they are not explicitely instantiated through new WhatEver(); and such not // required through composer's autoload require_once __DIR__ . '/../fixtures/DummyInterface.php'; } public function testDummyInterface() { $expected = Fixtures::createDummyInterface(); $actual = PhpInterface::fromFile(__DIR__ . '/../fixtures/DummyInterface.php'); $this->assertEquals($expected, $actual); } public function testMyCollectionInterface() { $interface = PhpInterface::fromFile(__DIR__ . '/../fixtures/MyCollectionInterface.php'); $this->assertTrue($interface->hasInterface('phootwork\collection\Collection')); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model\parts; use gossi\codegen\model\PhpConstant; /** * Value part * * For all models that have a value (or expression) * * @author <NAME> */ trait ValuePart { /** @var mixed */ private $value; /** @var bool */ private $hasValue = false; /** @var string */ private $expression; /** @var bool */ private $hasExpression = false; /** * @deprecated use `setValue()` instead * @param mixed $value * @return $this */ public function setDefaultValue($value) { return $this->setValue($value); } /** * @deprecated use `unsetValue()` instead * @return $this */ public function unsetDefaultValue() { return $this->unsetValue(); } /** * @deprecated use `getValue()` instead * @return mixed */ public function getDefaultValue() { return $this->getValue(); } /** * @deprecated use `hasValue()` instead * @return bool */ public function hasDefaultValue(): bool { return $this->hasValue(); } /** * Returns whether the given value is a primitive * * @param mixed $value * @return bool */ private function isPrimitive($value): bool { return (is_string($value) || is_int($value) || is_float($value) || is_bool($value) || is_null($value) || ($value instanceof PhpConstant)); } /** * Sets the value * * @param string|int|float|bool|null|PhpConstant $value * @throws \InvalidArgumentException if the value is not an accepted primitve * @return $this */ public function setValue($value) { if (!$this->isPrimitive($value)) { throw new \InvalidArgumentException('Use setValue() only for primitives and PhpConstant, anyway use setExpression() instead.'); } $this->value = $value; $this->hasValue = true; return $this; } /** * Unsets the value * * @return $this */ public function unsetValue() { $this->value = null; $this->hasValue = false; return $this; } /** * Returns the value * * @return string|int|float|bool|null|PhpConstant */ public function getValue() { return $this->value; } /** * Checks whether a value or expression is set * * @return bool */ public function hasValue(): bool { return $this->hasValue || $this->hasExpression; } /** * Returns whether an expression is set * * @return bool */ public function isExpression(): bool { return $this->hasExpression; } /** * Sets an expression * * @param string $expr * @return $this */ public function setExpression(string $expr) { $this->expression = $expr; $this->hasExpression = true; return $this; } /** * Returns the expression * * @return string */ public function getExpression(): ?string { return $this->expression; } /** * Unsets the expression * * @return $this */ public function unsetExpression() { $this->expression = null; $this->hasExpression = false; return $this; } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model\parts; use gossi\codegen\model\PhpConstant; use phootwork\collection\Map; use phootwork\collection\Set; /** * Constants part * * For all models that can contain constants * * @author <NAME> */ trait ConstantsPart { /** @var Map|PhpConstant[] */ private $constants; private function initConstants() { $this->constants = new Map(); } /** * Sets a collection of constants * * @param array|PhpConstant[] $constants * @return $this */ public function setConstants(array $constants) { $normalizedConstants = []; foreach ($constants as $name => $value) { if ($value instanceof PhpConstant) { $name = $value->getName(); } else { $constValue = $value; $value = new PhpConstant($name); $value->setValue($constValue); } $normalizedConstants[$name] = $value; } $this->constants->setAll($normalizedConstants); return $this; } /** * Adds a constant * * @param string|PhpConstant $nameOrConstant constant name or instance * @param string $value * @param bool $isExpression whether the value is an expression or not * @return $this */ public function setConstant($nameOrConstant, string $value = null, bool $isExpression = false) { if ($nameOrConstant instanceof PhpConstant) { $name = $nameOrConstant->getName(); $constant = $nameOrConstant; } else { $name = $nameOrConstant; $constant = new PhpConstant($nameOrConstant, $value, $isExpression); } $this->constants->set($name, $constant); return $this; } /** * Removes a constant * * @param string|PhpConstant $nameOrConstant constant name * @throws \InvalidArgumentException If the constant cannot be found * @return $this */ public function removeConstant($nameOrConstant) { if ($nameOrConstant instanceof PhpConstant) { $nameOrConstant = $nameOrConstant->getName(); } if (!$this->constants->has($nameOrConstant)) { throw new \InvalidArgumentException(sprintf('The constant "%s" does not exist.', $nameOrConstant)); } $this->constants->remove($nameOrConstant); return $this; } /** * Checks whether a constant exists * * @param string|PhpConstant $nameOrConstant * @return bool */ public function hasConstant($nameOrConstant): bool { if ($nameOrConstant instanceof PhpConstant) { $nameOrConstant = $nameOrConstant->getName(); } return $this->constants->has($nameOrConstant); } /** * Returns a constant. * * @param string|PhpConstant $nameOrConstant * @throws \InvalidArgumentException If the constant cannot be found * @return PhpConstant */ public function getConstant($nameOrConstant): PhpConstant { if ($nameOrConstant instanceof PhpConstant) { $nameOrConstant = $nameOrConstant->getName(); } if (!$this->constants->has($nameOrConstant)) { throw new \InvalidArgumentException(sprintf('The constant "%s" does not exist.', $nameOrConstant)); } return $this->constants->get($nameOrConstant); } /** * Returns all constants * * @return Map|PhpConstant[] */ public function getConstants(): Map { return $this->constants; } /** * Returns all constant names * * @return Set */ public function getConstantNames(): Set { return $this->constants->keys(); } /** * Clears all constants * * @return $this */ public function clearConstants() { $this->constants->clear(); return $this; } } <file_sep>Welcome to PHP Code Generator's documentation! ============================================== .. |license| image:: https://poser.pugx.org/gossi/php-code-generator/license :target: https://packagist.org/packages/gossi/php-code-generator :alt: License .. |version| image:: https://poser.pugx.org/gossi/php-code-generator/v/stable :target: https://packagist.org/packages/gossi/php-code-generator :alt: Latest Stable Version .. |downloads| image:: https://poser.pugx.org/gossi/php-code-generator/downloads :target: https://packagist.org/packages/gossi/php-code-generator :alt: Total Downloads .. |hhvm| image:: http://hhvm.h4cc.de/badge/gossi/php-code-generator.svg?style=flat :target: http://hhvm.h4cc.de/package/gossi/php-code-generator :alt: HHVM Status .. |build| image:: https://travis-ci.org/gossi/php-code-generator.svg?branch=master :target: https://travis-ci.org/gossi/php-code-generator :alt: Build Status .. |quality| image:: https://scrutinizer-ci.com/g/gossi/php-code-generator/badges/quality-score.png?b=master :target: https://scrutinizer-ci.com/g/gossi/php-code-generator/?branch=master :alt: Scrutinizer Code Quality .. |coverage| image:: https://scrutinizer-ci.com/g/gossi/php-code-generator/badges/coverage.png?b=master :target: https://scrutinizer-ci.com/g/gossi/php-code-generator/?branch=master :alt: Code Coverage .. |br| raw:: html <br> |license| |version| |downloads| |br| |hhvm| |build| |quality| |coverage| This is a code generator for php code. Quickstart ---------- 1. Install: ``composer require gossi/php-code-generator`` 2. You need a :doc:`model` 3. You need a :doc:`generator` 4. Generate the code contained in the model Contents: .. toctree:: :maxdepth: 2 installation getting-started model generator best-practices api <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model\parts; use gossi\codegen\model\PhpType; use gossi\codegen\model\PhpTypeInterface; use gossi\codegen\utils\TypeUtils; use phootwork\collection\Map; /** * Type part * * For all models that have a type * * @author <NAME> */ trait TypePart { /** @var null|Map|string[]|PhpTypeInterface[] */ private $types; /** @var null|string */ private $typeDescription; /** @var bool */ private $typeNullable = false; public function initTypes(): void { $this->types = new Map(); } /** * Sets the type * * @param null|Map|string[]|PhpTypeInterface[] $types * @param string $description * * @return $this */ public function setTypes(?iterable $types) { if (!$types) { return $this; } $this->types->clear(); foreach ($types as $type) { $this->addType($type); } return $this; } /** * adds a type * * @param string|PhpTypeInterface $type * @param string $description * @return $this */ public function addType($type) { if ($type === 'null') { $this->setNullable(true); return $this; } if ($type) { if (!$type instanceof PhpTypeInterface) { if (substr($type, -2, 2) === '[]') { $this->addType('iterable'); } $type = new PhpType($type); } $this->types->set($type->getQualifiedName(), $type); } return $this; } /** * Sets the description for the type * * @param string $description * @return $this */ public function setTypeDescription(string $description) { if (!$description) { return $this; } $this->typeDescription = $description; return $this; } /** * Returns the type * * @return PhpTypeInterface[]|Map */ public function getTypes(): ?iterable { return $this->types; } public function getTypeExpression(): ?string { return TypeUtils::typesToExpression($this->types); } /** * Returns the type description * * @return string */ public function getTypeDescription(): ?string { return $this->typeDescription; } /** * Returns whether the type is nullable * * @return bool */ public function getNullable(): bool { return $this->typeNullable; } /** * Sets the type nullable * * @param bool $nullable * @return $this */ public function setNullable(bool $nullable) { $this->typeNullable = $nullable; return $this; } } <file_sep><?php namespace gossi\codegen\tests\fixtures; use gossi\codegen\tests\fixtures\DummyTrait as DT; class ClassWithTraits { use DT; } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\builder; use gossi\codegen\generator\builder\parts\StructBuilderPart; use gossi\codegen\model\AbstractModel; use gossi\codegen\model\PhpClass; class ClassBuilder extends AbstractBuilder { use StructBuilderPart; /** * {@inheritDoc} * @param PhpClass $model */ public function build(AbstractModel $model): void { $this->sort($model); $this->buildHeader($model); // signature $this->buildSignature($model); // body $this->writer->writeln(" {\n")->indent(); $this->buildTraits($model); $this->buildConstants($model); $this->buildProperties($model); $this->buildMethods($model); $this->writer->outdent()->rtrim()->write('}'); } private function buildSignature(PhpClass $model) { if ($model->isAbstract()) { $this->writer->write('abstract '); } if ($model->isFinal()) { $this->writer->write('final '); } $this->writer->write('class '); $this->writer->write($model->getName()); if ($parentClassName = $model->getParentClassName()) { $this->writer->write(' extends ' . $parentClassName); } if ($model->hasInterfaces()) { $this->writer->write(' implements '); $this->writer->write(implode(', ', $model->getInterfaces()->toArray())); } } private function sort(PhpClass $model) { $this->sortUseStatements($model); $this->sortConstants($model); $this->sortProperties($model); $this->sortMethods($model); } } <file_sep><?php class TypeClass { public function doSomething(Symfony\Component\OptionsResolver\OptionsResolver $options) { } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\parser\visitor; use gossi\codegen\model\PhpProperty; use gossi\codegen\parser\visitor\parts\MemberParserPart; use gossi\codegen\parser\visitor\parts\ValueParserPart; use PhpParser\Node\Stmt\Property; class PropertyParserVisitor extends StructParserVisitor { use ValueParserPart; use MemberParserPart; public function visitProperty(Property $node) { $prop = $node->props[0]; $p = new PhpProperty($prop->name->name); $p->setStatic($node->isStatic()); $p->setVisibility($this->getVisibility($node)); $this->parseValue($p, $prop); $this->parseMemberDocblock($p, $node->getDocComment()); $this->struct->addProperty($p); } } <file_sep><?php /* * Copyright 2011 <NAME> <<EMAIL>> * * 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. */ declare(strict_types=1); namespace gossi\codegen\model; use gossi\codegen\model\parts\BodyPart; use gossi\codegen\model\parts\DocblockPart; use gossi\codegen\model\parts\LongDescriptionPart; use gossi\codegen\model\parts\ParametersPart; use gossi\codegen\model\parts\QualifiedNamePart; use gossi\codegen\model\parts\ReferenceReturnPart; use gossi\codegen\model\parts\TypeDocblockGeneratorPart; use gossi\codegen\model\parts\TypePart; use gossi\docblock\Docblock; use gossi\docblock\tags\ReturnTag; /** * Represents a PHP function. * * @author <NAME> <<EMAIL>> * @author <NAME> * @deprecated Not a structural model. Please refer to https://github.com/gossi/php-code-generator/issues/35 and join the discussion if you really need this */ class PhpFunction extends AbstractModel implements GenerateableInterface, NamespaceInterface, DocblockInterface, RoutineInterface { use BodyPart; use DocblockPart; use LongDescriptionPart; use ParametersPart; use QualifiedNamePart; use ReferenceReturnPart; use TypeDocblockGeneratorPart; use TypePart; // /** // * Creates a PHP function from reflection // * // * @deprecated will be removed in version 0.5 // * @param \ReflectionFunction $ref // * @return PhpFunction // */ // public static function fromReflection(\ReflectionFunction $ref) { // $function = self::create($ref->name) // ->setReferenceReturned($ref->returnsReference()) // ->setBody(ReflectionUtils::getFunctionBody($ref)); // $docblock = new Docblock($ref); // $function->setDocblock($docblock); // $function->setDescription($docblock->getShortDescription()); // $function->setLongDescription($docblock->getLongDescription()); // foreach ($ref->getParameters() as $refParam) { // assert($refParam instanceof \ReflectionParameter); // hmm - assert here? // $param = PhpParameter::fromReflection($refParam); // $function->addParameter($param); // } // return $function; // } /** * Creates a new PHP function * * @param string $name qualified name * @return static */ public static function create($name = null) { return new static($name); } /** * Creates a new PHP function * * @param string $name qualified name */ public function __construct($name = null) { $this->setQualifiedName($name); $this->docblock = new Docblock(); $this->initParameters(); $this->initTypes(); } /** * @inheritDoc */ public function generateDocblock(): void { $docblock = $this->getDocblock(); $docblock->setShortDescription($this->getDescription()); $docblock->setLongDescription($this->getLongDescription()); // return tag $this->generateTypeTag(new ReturnTag()); // param tags $this->generateParamDocblock(); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\builder\parts; use gossi\codegen\model\AbstractModel; use gossi\codegen\model\parts\TypePart; use phootwork\collection\Map; trait TypeBuilderPart { protected static $noTypeHints = [ 'string', 'int', 'integer', 'bool', 'boolean', 'float', 'double', 'object', 'mixed', 'resource' ]; protected static $php7typeHints = [ 'string', 'int', 'integer', 'bool', 'boolean', 'float', 'double' ]; protected static $typeHintMap = [ 'string' => 'string', 'int' => 'int', 'integer' => 'int', 'bool' => 'bool', 'boolean' => 'bool', 'float' => 'float', 'double' => 'float' ]; /** * * @param AbstractModel|TypePart $model * @param bool $allowed * * @return string|null */ private function getType(AbstractModel $model, bool $allowed, bool $nullable): ?string { $types = $model->getTypes(); if ($types->get('iterable')) { $types = new Map(['iterable' => 'iterable']); } if (!$types || $types->size() !== 1) { return null; } $type = (string)$types->values()->toArray()[0]; if (!in_array($type, self::$noTypeHints, true) || ($allowed && in_array($type, self::$php7typeHints, true))) { $type = self::$typeHintMap[$type] ?? $type; if ($nullable && $model->getNullable()) { $type = '?' . $type; } return $type; } return null; } } <file_sep><?php namespace gossi\codegen\tests\parts; trait TestUtils { private function getGeneratedContent($file) { return file_get_contents(__DIR__ . '/../generator/generated/' . $file); } private function getFixtureContent($file) { return file_get_contents(__DIR__ . '/../fixtures/' . $file); } } <file_sep><?php namespace gossi\codegen\parser\visitor\parts; use gossi\codegen\model\ValueInterface; use gossi\codegen\parser\PrettyPrinter; use PhpParser\Node; use PhpParser\Node\Const_; use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\ClassConstFetch; use PhpParser\Node\Expr\ConstFetch; use PhpParser\Node\Scalar\DNumber; use PhpParser\Node\Scalar\LNumber; use PhpParser\Node\Scalar\MagicConst; use PhpParser\Node\Scalar\String_; trait ValueParserPart { private $constMap = [ 'false' => false, 'true' => true ]; /** * Parses the value of a node into the model * * @param ValueInterface $obj * @param Node $node * @return void */ private function parseValue(ValueInterface $obj, Node $node) { $value = $node instanceof Const_ ? $node->value : $node->default; if ($value !== null) { if ($this->isPrimitive($value)) { $obj->setValue($this->getPrimitiveValue($value)); } $expr = $this->getExpression($value); if ($expr) { $obj->setExpression($expr); } } } /** * Returns whether this node is a primitive value * * @param Node $node * @return bool */ private function isPrimitive(Node $node) { return $node instanceof String_ || $node instanceof LNumber || $node instanceof DNumber || $this->isBool($node) || $this->isNull($node); } /** * Returns the primitive value * * @param Node $node * @return mixed */ private function getPrimitiveValue(Node $node) { if ($this->isBool($node)) { return (bool) $this->getExpression($node); } if ($this->isNull($node)) { return null; } return $node->value; } /** * Returns whether this node is a boolean value * * @param Node $node * @return bool */ private function isBool(Node $node) { if ($node instanceof ConstFetch) { $const = $node->name->parts[0]; if (isset($this->constMap[$const])) { return is_bool($this->constMap[$const]); } return is_bool($const); } } /** * Returns whether this node is a null value * * @param Node $node * @return bool */ private function isNull(Node $node) { if ($node instanceof ConstFetch) { $const = $node->name->parts[0]; return $const === 'null'; } } /** * Returns the value from a node * * @param Node $node * @return mixed */ private function getExpression(Node $node) { if ($node instanceof ConstFetch) { $const = $node->name->parts[0]; if (isset($this->constMap[$const])) { return $this->constMap[$const]; } return $const; } if ($node instanceof ClassConstFetch) { return $node->class->parts[0] . '::' . $node->name; } if ($node instanceof MagicConst) { return $node->getName(); } if ($node instanceof Array_) { $prettyPrinter = new PrettyPrinter(); return $prettyPrinter->prettyPrintExpr($node); } } } <file_sep><?php class MyCollection2 extends \phootwork\collection\AbstractCollection implements \phootwork\collection\Collection { } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\builder\parts; use gossi\codegen\model\PhpConstant; use gossi\codegen\model\ValueInterface; trait ValueBuilderPart { private function writeValue(ValueInterface $model): void { if ($model->isExpression()) { $this->writer->write($model->getExpression()); } else { $value = $model->getValue(); if ($value instanceof PhpConstant) { $this->writer->write($value->getName()); } else { $this->writer->write($this->exportVar($value)); } } } private function exportVar($value) { // Simply to be sure a null value is displayed in lowercase. if (is_null($value)) { return 'null'; } return var_export($value, true); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\comparator; use gossi\codegen\model\PhpProperty; use phootwork\lang\Comparator; /** * Default property comparator * * Orders them by visibility first then by method name */ class DefaultPropertyComparator implements Comparator { /** * @param PhpProperty $a * @param PhpProperty $b */ public function compare($a, $b) { if (($aV = $a->getVisibility()) !== $bV = $b->getVisibility()) { $aV = 'public' === $aV ? 3 : ('protected' === $aV ? 2 : 1); $bV = 'public' === $bV ? 3 : ('protected' === $bV ? 2 : 1); return $aV > $bV ? -1 : 1; } return strcasecmp($a->getName(), $b->getName()); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model; use gossi\codegen\model\parts\ConstantsPart; use gossi\codegen\model\parts\InterfacesPart; use gossi\codegen\parser\FileParser; use gossi\codegen\parser\visitor\ConstantParserVisitor; use gossi\codegen\parser\visitor\InterfaceParserVisitor; use gossi\codegen\parser\visitor\MethodParserVisitor; /** * Represents a PHP interface. * * @author <NAME> */ class PhpInterface extends AbstractPhpStruct implements GenerateableInterface, ConstantsInterface, PhpTypeInterface { use ConstantsPart; use InterfacesPart; /** * Creates a PHP interface from file * * @param string $filename * @return PhpInterface */ public static function fromFile(string $filename): self { $interface = new self(); $parser = new FileParser($filename); $parser->addVisitor(new InterfaceParserVisitor($interface)); $parser->addVisitor(new MethodParserVisitor($interface)); $parser->addVisitor(new ConstantParserVisitor($interface)); $parser->parse(); return $interface; } /** * Create a new PHP interface * * @param string $name qualified name */ public function __construct($name = null) { parent::__construct($name); $this->initConstants(); $this->initInterfaces(); } /** * @inheritDoc */ public function generateDocblock(): void { parent::generateDocblock(); foreach ($this->constants as $constant) { $constant->generateDocblock(); } } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator; use gossi\codegen\generator\comparator\DefaultConstantComparator; use gossi\codegen\generator\comparator\DefaultMethodComparator; use gossi\codegen\generator\comparator\DefaultPropertyComparator; use gossi\codegen\generator\comparator\DefaultUseStatementComparator; use phootwork\lang\Comparator; class ComparatorFactory { /** * Creates a comparator for use statements * * @param string $type * @return Comparator */ public static function createUseStatementComparator(string $type): Comparator { // switch ($type) { // case CodeGenerator::SORT_USESTATEMENTS_DEFAULT: // default: // return new DefaultUseStatementComparator(); // } return new DefaultUseStatementComparator(); } /** * Creates a comparator for constants * * @param string $type * @return Comparator */ public static function createConstantComparator(string $type): Comparator { // switch ($type) { // case CodeGenerator::SORT_CONSTANTS_DEFAULT: // default: // return new DefaultConstantComparator(); // } return new DefaultConstantComparator(); } /** * Creates a comparator for properties * * @param string $type * @return Comparator */ public static function createPropertyComparator(string $type): Comparator { // switch ($type) { // case CodeGenerator::SORT_PROPERTIES_DEFAULT: // default: // return new DefaultPropertyComparator(); // } return new DefaultPropertyComparator(); } /** * Creates a comparator for methods * * @param string $type * @return Comparator */ public static function createMethodComparator(string $type): Comparator { // switch ($type) { // case CodeGenerator::SORT_METHODS_DEFAULT: // default: // return new DefaultMethodComparator(); // } return new DefaultMethodComparator(); } } <file_sep><?php namespace Foo; use Bam\Baz; class Bar { } <file_sep>Getting Started =============== There are two things you need to generate code. 1. A :doc:`model` that contains the code structure * PhpClass * PhpInterface * PhpTrait * PhpFunction 2. A :doc:`generator` * CodeGenerator * CodeFileGenerator You can create these models and push all the data using a fluent API or read from existing code through reflection. Here are two examples for each of those. Generate Code ------------- a) Simple: :: <?php use gossi\codegen\generator\CodeGenerator; use gossi\codegen\model\PhpClass; use gossi\codegen\model\PhpMethod; use gossi\codegen\model\PhpParameter; $class = new PhpClass(); $class ->setQualifiedName('my\\cool\\Tool') ->setMethod(PhpMethod::create('__construct') ->addParameter(PhpParameter::create('target') ->setType('string') ->setDescription('Creates my Tool') ) ) ; $generator = new CodeGenerator(); $code = $generator->generate($class); will generate: :: <?php namespace my\cool; class Tool { /** * * @param $target string Creates my Tool */ public function __construct($target) { } } b) From File: :: <?php use gossi\codegen\generator\CodeGenerator; use gossi\codegen\model\PhpClass; $class = PhpClass::fromFile('path/to/class.php'); $generator = new CodeGenerator(); $code = $generator->generate($class); c) From Reflection: :: <?php use gossi\codegen\generator\CodeGenerator; use gossi\codegen\model\PhpClass; $reflection = new \ReflectionClass('MyClass'); $class = PhpClass::fromReflection($reflection->getFileName()); $generator = new CodeGenerator(); $code = $generator->generate($class); <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model\parts; use gossi\codegen\model\PhpTrait; /** * Traits part * * For all models that can have traits * * @author <NAME> */ trait TraitsPart { /** @var string[] */ private $traits = []; /** * Adds a use statement with an optional alias * * @param string $qualifiedName * @param null|string $alias * @return $this */ abstract public function addUseStatement($qualifiedName, string $alias = null); /** * Removes a use statement * * @param string $qualifiedName * @return $this */ abstract public function removeUseStatement(string $qualifiedName); /** * Returns the namespace * * @return string */ abstract public function getNamespace(): ?string; /** * Adds a trait. * * If the trait is passed as PhpTrait object, * the trait is also added as use statement. * * @param PhpTrait|string $trait trait or qualified name * @return $this */ public function addTrait($trait) { if ($trait instanceof PhpTrait) { $name = $trait->getName(); $qname = $trait->getQualifiedName(); $this->addUseStatement($qname); } else { $name = $trait; } if (!in_array($name, $this->traits, true)) { $this->traits[] = $name; } return $this; } /** * Returns a collection of traits * * @return string[] */ public function getTraits(): array { return $this->traits; } /** * @return iterable|PhpTrait[] */ public function getPhpTraits(): iterable { $traits = []; foreach ($this->traits as $trait) { $traits[] = trait_exists($trait) ? PhpTrait::fromName($trait) : PhpTrait::create($trait); } return $traits; } /** * Checks whether a trait exists * * @param PhpTrait|string $trait * @return bool `true` if it exists and `false` if not */ public function hasTrait($trait): bool { if (!$trait instanceof PhpTrait) { $trait = new PhpTrait($trait); } $name = $trait->getName(); return in_array($name, $this->traits); } /** * Removes a trait. * * If the trait is passed as PhpTrait object, * the trait is also removed from use statements. * * @param PhpTrait|string $trait trait or qualified name * @return $this */ public function removeTrait($trait) { if ($trait instanceof PhpTrait) { $name = $trait->getName(); } else { $name = $trait; } $index = array_search($name, $this->traits); if ($index !== false) { unset($this->traits[$index]); if ($trait instanceof PhpTrait) { $qname = $trait->getQualifiedName(); $this->removeUseStatement($qname); } } return $this; } /** * Sets a collection of traits * * @param PhpTrait[] $traits * @return $this */ public function setTraits(array $traits) { foreach ($traits as $trait) { $this->addTrait($trait); } return $this; } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model; use gossi\codegen\model\parts\DocblockPart; use gossi\codegen\model\parts\LongDescriptionPart; use gossi\codegen\model\parts\NamePart; use gossi\codegen\model\parts\TypeDocblockGeneratorPart; use gossi\codegen\model\parts\TypePart; use gossi\codegen\model\parts\ValuePart; use gossi\docblock\Docblock; use gossi\docblock\tags\VarTag; /** * Represents a PHP constant. * * @author <NAME> */ class PhpConstant extends AbstractModel implements GenerateableInterface, DocblockInterface, ValueInterface { use DocblockPart; use LongDescriptionPart; use NamePart; use TypeDocblockGeneratorPart; use TypePart; use ValuePart; /** * Creates a new PHP constant * * @param string $name * @param mixed $value * @param bool $isExpression * @return static */ public static function create($name = null, $value = null, $isExpression = false) { return new static($name, $value, $isExpression); } /** * Creates a new PHP constant * * @param string $name * @param mixed $value * @param bool $isExpression */ public function __construct($name = null, $value = null, $isExpression = false) { $this->setName($name); if ($isExpression) { $this->setExpression($value); } else { $this->setValue($value); } $this->docblock = new Docblock(); $this->initTypes(); } /** * @inheritDoc */ public function generateDocblock(): void { $docblock = $this->getDocblock(); $docblock->setShortDescription($this->getDescription()); $docblock->setLongDescription($this->getLongDescription()); // var tag $this->generateTypeTag(new VarTag()); } } <file_sep>Installation ============ Install via Composer: .. code-block:: json { "require": { "gossi/php-code-generator": "~0" } } or via CLI: :: composer require 'gossi/php-code-generator' <file_sep><?php namespace gossi\codegen\tests\utils; use gossi\codegen\generator\utils\Writer; use gossi\codegen\utils\ReflectionUtils; use PHPUnit\Framework\TestCase; class ReflectionUtilsTest extends TestCase { public function setUp() { // they are not explicitely instantiated through new WhatEver(); and such not // required through composer's autoload require_once __DIR__ . '/../fixtures/functions.php'; require_once __DIR__ . '/../fixtures/OverridableReflectionTest.php'; } public function testFunctionBody() { $actual = ReflectionUtils::getFunctionBody(new \ReflectionFunction('wurst')); $expected = 'return \'wurst\';'; $this->assertEquals($expected, $actual); $actual = ReflectionUtils::getFunctionBody(new \ReflectionFunction('inline')); $expected = 'return \'x\';'; $this->assertEquals($expected, $actual); } public function testGetOverridableMethods() { $ref = new \ReflectionClass('gossi\codegen\tests\fixtures\OverridableReflectionTest'); $methods = ReflectionUtils::getOverrideableMethods($ref); $this->assertEquals(4, count($methods)); $methods = array_map(function ($v) { return $v->name; }, $methods); sort($methods); $this->assertEquals([ 'a', 'd', 'e', 'h' ], $methods); } public function testGetUnindentedDocComment() { $writer = new Writer(); $comment = $writer->writeln('/**')->indent()->writeln(' * Foo.')->write(' */')->getContent(); $this->assertEquals("/**\n * Foo.\n */", ReflectionUtils::getUnindentedDocComment($comment)); } } <file_sep><?php namespace gossi\codegen\tests\fixtures; class ValueClass { const CONST_STRING = 'foo'; const CONST_INTEGER = 10; const CONST_FLOAT = 7.5; const CONST_BOOL = true; const CONST_NULL = null; const CONST_CONST = self::CONST_STRING; private $propString = 'foo'; private $propInteger = 10; private $propFloat = 7.5; private $propBool = true; private $propNull = null; private $propConst = self::CONST_STRING; private $propExpr = ['foo' => ['bar' => 'baz']]; public function values($none, $paramString = 'foo', $paramInteger = 10, $paramFloat = 7.5, $paramBool = true, $paramNull = null, $paramConst = self::CONST_STRING, $paramExpr = ['foo' => ['bar' => 'baz']]) { } } <file_sep><?php namespace gossi\codegen\tests\fixtures; /** * Dummy docblock */ interface DummyInterface { /** */ public function foo(); } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model\parts; use gossi\codegen\model\PhpParameter; use gossi\codegen\model\PhpTypeInterface; use gossi\docblock\Docblock; use gossi\docblock\tags\ParamTag; use phootwork\collection\Map; /** * Parameters Part * * For all models that can have parameters * * @author <NAME> */ trait ParametersPart { /** @var PhpParameter[] */ private $parameters = []; private function initParameters() { // $this->parameters = new ArrayList(); } /** * Sets a collection of parameters * * Note: clears all parameters before setting the new ones * * @param PhpParameter[] $parameters * @return $this */ public function setParameters(array $parameters) { $this->parameters = []; foreach ($parameters as $parameter) { $this->addParameter($parameter); } return $this; } /** * Adds a parameter * * @param PhpParameter $parameter * @return $this */ public function addParameter(PhpParameter $parameter) { $this->parameters[] = $parameter; return $this; } /** * Checks whether a parameter exists * * @param string $name parameter name * @return bool `true` if a parameter exists and `false` if not */ public function hasParameter(string $name): bool { foreach ($this->parameters as $param) { if ($param->getName() == $name) { return true; } } return false; } /** * A quick way to add a parameter which is created from the given parameters * * @param string $name * @param null|Map|string[]|PhpTypeInterface[] $types * @param mixed $defaultValue omit the argument to define no default value * * @return $this */ public function addSimpleParameter(string $name, $types = null, $defaultValue = null) { $parameter = new PhpParameter($name); $parameter->setTypes($types); if (2 < func_num_args()) { $parameter->setValue($defaultValue); } $this->addParameter($parameter); return $this; } /** * A quick way to add a parameter with description which is created from the given parameters * * @param string $name * @param string[]|PhpTypeInterface[] $types * @param null|string $typeDescription * @param mixed $defaultValue omit the argument to define no default value * * @return $this */ public function addSimpleDescParameter(string $name, $types = null, string $typeDescription = null, $defaultValue = null) { $types = (array)$types; $parameter = new PhpParameter($name); $parameter->setTypes($types); $parameter->setTypeDescription($typeDescription); if (3 < func_num_args() == 3) { $parameter->setValue($defaultValue); } $this->addParameter($parameter); return $this; } /** * Returns a parameter by index or name * * @param string|int $nameOrIndex * @throws \InvalidArgumentException * @return PhpParameter */ public function getParameter($nameOrIndex): PhpParameter { if (is_int($nameOrIndex)) { $this->checkPosition($nameOrIndex); return $this->parameters[$nameOrIndex]; } foreach ($this->parameters as $param) { if ($param->getName() === $nameOrIndex) { return $param; } } throw new \InvalidArgumentException(sprintf('There is no parameter named "%s".', $nameOrIndex)); } /** * Replaces a parameter at a given position * * @param int $position * @param PhpParameter $parameter * @throws \InvalidArgumentException * @return $this */ public function replaceParameter(int $position, PhpParameter $parameter) { $this->checkPosition($position); $this->parameters[$position] = $parameter; return $this; } /** * Remove a parameter at a given position * * @param int|string|PhpParameter $param * @return $this */ public function removeParameter($param) { if (is_int($param)) { $this->removeParameterByPosition($param); } else if (is_string($param)) { $this->removeParameterByName($param); } else if ($param instanceof PhpParameter) { $this->removeParameterByName($param->getName()); } return $this; } private function removeParameterByPosition($position) { $this->checkPosition($position); unset($this->parameters[$position]); $this->parameters = array_values($this->parameters); } private function removeParameterByName($name) { $position = null; foreach ($this->parameters as $index => $param) { if ($param->getName() == $name) { $position = $index; } } if ($position !== null) { $this->removeParameterByPosition($position); } } private function checkPosition($position) { if ($position < 0 || $position > count($this->parameters)) { throw new \InvalidArgumentException(sprintf('The position must be in the range [0, %d].', count($this->parameters))); } } /** * Returns a collection of parameters * * @return PhpParameter[] */ public function getParameters() { return $this->parameters; } /** * Returns the docblock * * @return Docblock */ abstract protected function getDocblock(): Docblock; /** * Generates docblock for params */ protected function generateParamDocblock(array $noTypeHint = []) { $docblock = $this->getDocblock(); $tags = $docblock->getTags('param'); foreach ($this->parameters as $param) { if (!empty($noTypeHint[$param->getName()])) { continue; } $ptag = $param->getDocblockTag(); $tag = $tags->find($ptag, function (ParamTag $tag, ParamTag $ptag) { return $tag->getVariable() == $ptag->getVariable(); }); // try to update existing docblock first if ($tag !== null) { $tag->setDescription($ptag->getDescription()); $tag->setType($ptag->getType()); } // ... append if it doesn't exist else { $docblock->appendTag($ptag); } } } } <file_sep><?php namespace gossi\codegen\tests\fixtures; use gossi\codegen\tests\fixtures\sub\SubClass; class ClassWithTypes { /** * @param ClassWithConstants[]|SubClass|null|string|\StdClass $toto */ public function test(?iterable $toto) { } public function test2(?string $toto2) { } public function test3(?int $toto3 = null) { } } <file_sep><?php namespace gossi\codegen\tests\generator; use gossi\codegen\generator\ModelGenerator; use gossi\codegen\model\PhpFunction; use gossi\codegen\model\PhpParameter; use PHPUnit\Framework\TestCase; /** * @group generator */ class FunctionGeneratorTest extends TestCase { public function testReferenceReturned() { $expected = "function & foo() {\n}\n"; $method = PhpFunction::create('foo')->setReferenceReturned(true); $generator = new ModelGenerator(); $code = $generator->generate($method); $this->assertEquals($expected, $code); } public function testParameters() { $generator = new ModelGenerator(); $method = PhpFunction::create('foo')->addParameter(PhpParameter::create('bar')); $this->assertEquals("function foo(\$bar) {\n}\n", $generator->generate($method)); $method = PhpFunction::create('foo') ->addParameter(PhpParameter::create('bar')) ->addParameter(PhpParameter::create('baz')); $this->assertEquals("function foo(\$bar, \$baz) {\n}\n", $generator->generate($method)); } public function testReturnType() { $expected = "function foo(): int {\n}\n"; $generator = new ModelGenerator(['generateReturnTypeHints' => true, 'generateDocblock' => false]); $method = PhpFunction::create('foo')->addType('int'); $this->assertEquals($expected, $generator->generate($method)); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\builder; use gossi\codegen\generator\builder\parts\ValueBuilderPart; use gossi\codegen\model\AbstractModel; class ConstantBuilder extends AbstractBuilder { use ValueBuilderPart; public function build(AbstractModel $model): void { $this->buildDocblock($model); $this->writer->write('const ' . $model->getName() . ' = '); $this->writeValue($model); $this->writer->writeln(';'); } } <file_sep><?php namespace gossi\codegen\parser\visitor\parts; use gossi\codegen\model\AbstractPhpMember; use gossi\codegen\model\PhpConstant; use gossi\codegen\utils\TypeUtils; use PhpParser\Comment\Doc; use PhpParser\Node; trait MemberParserPart { /** * * @param AbstractPhpMember|PhpConstant $member * @param Doc $doc */ private function parseMemberDocblock(&$member, Doc $doc = null) { if ($doc !== null) { $member->setDocblock($doc->getReformattedText()); $docblock = $member->getDocblock(); $member->setDescription($docblock->getShortDescription()); $member->setLongDescription($docblock->getLongDescription()); $vars = $docblock->getTags('var'); if ($vars->size() > 0) { $var = $vars->get(0); $types = TypeUtils::expressionToTypes($var->getType()); foreach($types as $type) { $type = TypeUtils::guessQualifiedName($this->struct, $type); $member->addType($type); } $member->setTypeDescription($var->getDescription()); } } } /** * Returns the visibility from a node * * @param Node $node * @return string */ private function getVisibility(Node $node) { if ($node->isPrivate()) { return AbstractPhpMember::VISIBILITY_PRIVATE; } if ($node->isProtected()) { return AbstractPhpMember::VISIBILITY_PROTECTED; } return AbstractPhpMember::VISIBILITY_PUBLIC; } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\builder; use gossi\codegen\generator\builder\parts\StructBuilderPart; use gossi\codegen\model\AbstractModel; use gossi\codegen\model\PhpTrait; class TraitBuilder extends AbstractBuilder { use StructBuilderPart; public function build(AbstractModel $model): void { $this->sort($model); $this->buildHeader($model); // signature $this->buildSignature($model); // body $this->writer->writeln(" {\n")->indent(); $this->buildTraits($model); $this->buildProperties($model); $this->buildMethods($model); $this->writer->outdent()->rtrim()->write('}'); } private function buildSignature(PhpTrait $model) { $this->writer->write('trait '); $this->writer->write($model->getName()); } private function sort(PhpTrait $model) { $this->sortUseStatements($model); $this->sortProperties($model); $this->sortMethods($model); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\builder; use gossi\codegen\generator\builder\parts\ValueBuilderPart; use gossi\codegen\model\AbstractModel; class PropertyBuilder extends AbstractBuilder { use ValueBuilderPart; public function build(AbstractModel $model): void { $this->buildDocblock($model); $this->writer->write($model->getVisibility() . ' '); $this->writer->write($model->isStatic() ? 'static ' : ''); $this->writer->write('$' . $model->getName()); if ($model->hasValue()) { $this->writer->write(' = '); $this->writeValue($model); } $this->writer->writeln(';'); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator; use gossi\codegen\generator\builder\AbstractBuilder; use gossi\codegen\generator\builder\ClassBuilder; use gossi\codegen\generator\builder\ConstantBuilder; use gossi\codegen\generator\builder\FunctionBuilder; use gossi\codegen\generator\builder\InterfaceBuilder; use gossi\codegen\generator\builder\MethodBuilder; use gossi\codegen\generator\builder\ParameterBuilder; use gossi\codegen\generator\builder\PropertyBuilder; use gossi\codegen\generator\builder\TraitBuilder; use gossi\codegen\model\AbstractModel; use gossi\codegen\model\PhpClass; use gossi\codegen\model\PhpConstant; use gossi\codegen\model\PhpFunction; use gossi\codegen\model\PhpInterface; use gossi\codegen\model\PhpMethod; use gossi\codegen\model\PhpParameter; use gossi\codegen\model\PhpProperty; use gossi\codegen\model\PhpTrait; class BuilderFactory { /** @var ModelGenerator */ private $generator; private $classBuilder; private $constantBuilder; private $functionBuilder; private $interfaceBuilder; private $methodBuilder; private $parameterBuilder; private $propertyBuilder; private $traitBuilder; public function __construct(ModelGenerator $generator) { $this->generator = $generator; $this->classBuilder = new ClassBuilder($generator); $this->constantBuilder = new ConstantBuilder($generator); $this->functionBuilder = new FunctionBuilder($generator); $this->interfaceBuilder = new InterfaceBuilder($generator); $this->methodBuilder = new MethodBuilder($generator); $this->parameterBuilder = new ParameterBuilder($generator); $this->propertyBuilder = new PropertyBuilder($generator); $this->traitBuilder = new TraitBuilder($generator); } /** * Returns the related builder for the given model * * @param AbstractModel $model * @return AbstractBuilder */ public function getBuilder(AbstractModel $model): ?AbstractBuilder { if ($model instanceof PhpClass) { return $this->classBuilder; } if ($model instanceof PhpConstant) { return $this->constantBuilder; } if ($model instanceof PhpFunction) { return $this->functionBuilder; } if ($model instanceof PhpInterface) { return $this->interfaceBuilder; } if ($model instanceof PhpMethod) { return $this->methodBuilder; } if ($model instanceof PhpParameter) { return $this->parameterBuilder; } if ($model instanceof PhpProperty) { return $this->propertyBuilder; } if ($model instanceof PhpTrait) { return $this->traitBuilder; } return null; } } <file_sep># PHP Code Generator [![License](https://img.shields.io/github/license/gossi/php-code-generator.svg?style=flat-square)](https://packagist.org/packages/gossi/php-code-generator) [![Latest Stable Version](https://img.shields.io/packagist/v/gossi/php-code-generator.svg?style=flat-square)](https://packagist.org/packages/gossi/php-code-generator) [![Total Downloads](https://img.shields.io/packagist/dt/gossi/php-code-generator.svg?style=flat-square&colorB=007ec6)](https://packagist.org/packages/gossi/php-code-generator)<br> [![Build Status](https://img.shields.io/scrutinizer/build/g/gossi/php-code-generator.svg?style=flat-square)](https://travis-ci.org/gossi/php-code-generator) [![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/gossi/php-code-generator.svg?style=flat-square)](https://scrutinizer-ci.com/g/gossi/php-code-generator) [![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/gossi/php-code-generator.svg?style=flat-square)](https://scrutinizer-ci.com/g/gossi/php-code-generator) This library provides some tools that you commonly need for generating PHP code. ## Installation Install via Composer: ``` composer require gossi/php-code-generator ``` ## Documentation Documentation is available at [https://php-code-generator.readthedocs.org](https://php-code-generator.readthedocs.org) ## Contributing Feel free to fork and submit a pull request (don't forget the tests) and I am happy to merge. ## References - This project is a spin-off of the older [schmittjoh/cg-library](https://github.com/schmittjoh/cg-library) library. <file_sep><?php /** * Makes foo with bar * * @param string $baz * @return string */ function wurst($baz = null) { return 'wurst'; } function inline() { return 'x'; } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\parser\visitor; use gossi\codegen\parser\visitor\parts\StructParserPart; use PhpParser\Node\Stmt\Class_; class ClassParserVisitor extends StructParserVisitor { use StructParserPart; public function visitClass(Class_ $node) { $struct = $this->getStruct(); if ($node->extends !== null) { if ($node->extends->getType() === 'Name_FullyQualified') { $struct->setParentClassName('\\' . implode('\\', $node->extends->parts)); } else { $struct->setParentClassName(implode('\\', $node->extends->parts)); } } foreach ($node->implements as $interface) { if ($interface->getType() === 'Name_FullyQualified') { $struct->addInterface('\\' . implode('\\', $interface->parts)); } else { $struct->addInterface(implode('\\', $interface->parts)); } } $struct->setAbstract($node->isAbstract()); $struct->setFinal($node->isFinal()); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model; /** * Parent of all models * * @author <NAME> */ abstract class AbstractModel { /** @var string */ protected $description; /** * Returns this description * * @return string */ public function getDescription(): ?string { return $this->description; } /** * Sets the description, which will also be used when generating a docblock * * @param string|array $description * @return $this */ public function setDescription($description) { if (is_array($description)) { $description = implode("\n", $description); } if ($description) { $this->description = $description; } return $this; } } <file_sep><?php namespace gossi\codegen\model; interface PhpTypeInterface extends NamespaceInterface { public function getName(): ?string; public function getQualifiedName(): ?string; public function setName(?string $name); public function setQualifiedName(?string $qualifiedName); public function __toString(): string; } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model\parts; use gossi\codegen\model\PhpProperty; use phootwork\collection\Map; use phootwork\collection\Set; /** * Properties part * * For all models that can have properties * * @author <NAME> */ trait PropertiesPart { /** @var Map|PhpProperty[] */ private $properties; private function initProperties() { $this->properties = new Map(); } /** * Sets a collection of properties * * @param PhpProperty[] $properties * @return $this */ public function setProperties(array $properties) { foreach ($this->properties as $prop) { $prop->setParent(null); } $this->properties->clear(); foreach ($properties as $prop) { $this->addProperty($prop); } return $this; } /** * Adds a property * * @param PhpProperty $property * @return $this */ public function addProperty(PhpProperty $property) { $property->setParent($this); $types = $property->getTypes(); if ($types) { foreach ($types as $type) { $this->addUseStatement($type); $property->addType($type); } } $this->properties->set($property->getName(), $property); return $this; } /** * Removes a property * * @param PhpProperty|string $nameOrProperty property name or instance * @throws \InvalidArgumentException If the property cannot be found * @return $this */ public function removeProperty($nameOrProperty) { if ($nameOrProperty instanceof PhpProperty) { $nameOrProperty = $nameOrProperty->getName(); } if (!$this->properties->has($nameOrProperty)) { throw new \InvalidArgumentException(sprintf('The property "%s" does not exist.', $nameOrProperty)); } $p = $this->properties->get($nameOrProperty); $p->setParent(null); $this->properties->remove($nameOrProperty); return $this; } /** * Checks whether a property exists * * @param PhpProperty|string $nameOrProperty property name or instance * @return bool `true` if a property exists and `false` if not */ public function hasProperty($nameOrProperty): bool { if ($nameOrProperty instanceof PhpProperty) { $nameOrProperty = $nameOrProperty->getName(); } return $this->properties->has($nameOrProperty); } /** * Returns a property * * @param string $nameOrProperty property name * @throws \InvalidArgumentException If the property cannot be found * @return PhpProperty */ public function getProperty($nameOrProperty): PhpProperty { if ($nameOrProperty instanceof PhpProperty) { $nameOrProperty = $nameOrProperty->getName(); } if (!$this->properties->has($nameOrProperty)) { throw new \InvalidArgumentException(sprintf('The property "%s" does not exist.', $nameOrProperty)); } return $this->properties->get($nameOrProperty); } /** * Returns a collection of properties * * @return Map|PhpProperty[] */ public function getProperties(): Map { return $this->properties; } /** * Returns all property names * * @return Set */ public function getPropertyNames(): Set { return $this->properties->keys(); } /** * Clears all properties * * @return $this */ public function clearProperties() { foreach ($this->properties as $property) { $property->setParent(null); } $this->properties->clear(); return $this; } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\parser\visitor; use gossi\codegen\model\PhpMethod; use gossi\codegen\model\PhpParameter; use gossi\codegen\parser\PrettyPrinter; use gossi\codegen\parser\visitor\parts\MemberParserPart; use gossi\codegen\parser\visitor\parts\ValueParserPart; use gossi\codegen\utils\TypeUtils; use gossi\docblock\tags\ParamTag; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\NullableType; use PhpParser\Node\Stmt\ClassMethod; class MethodParserVisitor extends StructParserVisitor { use MemberParserPart; use ValueParserPart; public function visitMethod(ClassMethod $node) { $m = new PhpMethod($node->name->name); $m->setAbstract($node->isAbstract()); $m->setFinal($node->isFinal()); $m->setVisibility($this->getVisibility($node)); $m->setStatic($node->isStatic()); $m->setReferenceReturned($node->returnsByRef()); $this->parseMemberDocblock($m, $node->getDocComment()); $this->parseParams($m, $node); $this->parseType($m, $node); $this->parseBody($m, $node); $this->struct->addMethod($m); } private function parseParams(PhpMethod $m, ClassMethod $node) { $params = $m->getDocblock()->getTags('param'); foreach ($node->params as $param) { $name = $param->var ? $param->var->name : $param->name; $p = new PhpParameter(); $p->setName($name); $p->setPassedByReference($param->byRef); $type = null; if ($param->type instanceof NullableType) { $param->type = $param->type->type; $p->setNullable(true); } if ($param->type instanceof Identifier) { $param->type = $param->type->name; } if (is_string($param->type)) { $type = $param->type; } if ($param->type instanceof Name) { $type = implode('\\', $param->type->parts); $qualifiedType = TypeUtils::guessQualifiedName($this->struct, $type); if ($type !== $qualifiedType) { $type = $qualifiedType; } else { $type = '\\'.$type; } } if ($type) { $p->addType($type); } $this->parseValue($p, $param); if ($p->getExpression() === 'null') { $p->setNullable(true); } $tag = $params->find($p, static function (ParamTag $t, $p) { return $t->getVariable() === '$' . $p->getName(); }); if ($tag !== null) { $types = TypeUtils::expressionToTypes($tag->getType()); foreach ($types as $type) { $p->addType(TypeUtils::guessQualifiedName($this->struct, $type)); } $p->setTypeDescription($tag->getDescription()); } $m->addParameter($p); } } private function parseType(PhpMethod &$m, ClassMethod $node) { $returns = $m->getDocblock()->getTags('return'); if ($returns->size() > 0) { $return = $returns->get(0); $m->addType($return->getType())->setTypeDescription($return->getDescription()); } } private function parseBody(PhpMethod &$m, ClassMethod $node) { $stmts = $node->getStmts(); if (is_array($stmts) && count($stmts)) { $prettyPrinter = new PrettyPrinter(); $m->setBody($prettyPrinter->prettyPrint($stmts)); } } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model\parts; use gossi\codegen\utils\TypeUtils; /** * Qualified name part * * For all models that have a name and namespace * * @author <NAME> */ trait QualifiedNamePart { use NamePart; /** @var string */ private $namespace; /** * Sets the namespace * * @param string $namespace * @return $this */ public function setNamespace(?string $namespace) { $this->namespace = $namespace; return $this; } /** * In contrast to setName(), this method accepts the fully qualified name * including the namespace. * * @param string $name * @return $this */ public function setQualifiedName(?string $name) { if ($name === null) { return $this; } if (!TypeUtils::isGlobalQualifiedName($name) && false !== $pos = strrpos($name, '\\')) { $this->namespace = substr($name, 0, $pos); $this->name = substr($name, $pos + 1); return $this; } $this->namespace = null; $this->name = $name; return $this; } /** * Returns the namespace * * @return string */ public function getNamespace(): ?string { return $this->namespace; } /** * Returns the qualified name * * @return string */ public function getQualifiedName(): string { if ($this->namespace) { return $this->namespace . '\\' . $this->name; } return $this->name; } public function __toString(): string { return (string) $this->getName(); } } <file_sep><?php namespace gossi\codegen\tests\generator; use gossi\codegen\generator\ModelGenerator; use gossi\codegen\model\PhpInterface; use PHPUnit\Framework\TestCase; /** * @group generator */ class InterfaceGeneratorTest extends TestCase { public function testSignature() { $expected = 'interface MyInterface {' . "\n" . '}'; $interface = PhpInterface::create('MyInterface'); $generator = new ModelGenerator(); $code = $generator->generate($interface); $this->assertEquals($expected, $code); } public function testExtends() { $generator = new ModelGenerator(); $expected = 'interface MyInterface extends \Iterator {' . "\n" . '}'; $interface = PhpInterface::create('MyInterface')->addInterface('\Iterator'); $this->assertEquals($expected, $generator->generate($interface)); $expected = 'interface MyInterface extends \Iterator, \ArrayAccess {' . "\n" . '}'; $interface = PhpInterface::create('MyInterface')->addInterface('\Iterator')->addInterface('\ArrayAccess'); $this->assertEquals($expected, $generator->generate($interface)); } } <file_sep><?php namespace gossi\codegen\tests\model; use gossi\codegen\model\PhpMethod; use gossi\codegen\model\PhpParameter; use PHPUnit\Framework\TestCase; /** * @group model */ class MethodTest extends TestCase { public function testParameters() { $method = new PhpMethod('needsName'); $this->assertEquals([], $method->getParameters()); $this->assertSame($method, $method->setParameters($params = [ new PhpParameter('a') ])); $this->assertSame($params, $method->getParameters()); $this->assertSame($method, $method->addParameter($param = new PhpParameter('b'))); $this->assertSame($param, $method->getParameter('b')); $this->assertSame($param, $method->getParameter(1)); $params[] = $param; $this->assertSame($params, $method->getParameters()); $this->assertSame($method, $method->removeParameter(0)); $this->assertEquals('b', $method->getParameter(0)->getName()); unset($params[0]); $this->assertEquals([ $param ], $method->getParameters()); $this->assertSame($method, $method->addParameter($param = new PhpParameter('c'))); $params[] = $param; $params = array_values($params); $this->assertSame($params, $method->getParameters()); $this->assertSame($method, $method->replaceParameter(0, $param = new PhpParameter('a'))); $params[0] = $param; $this->assertSame($params, $method->getParameters()); $method->removeParameter($param); $method->removeParameter('c'); $this->assertEquals([], $method->getParameters()); } /** * @expectedException \InvalidArgumentException */ public function testGetNonExistentParameterByName() { $method = new PhpMethod('doink'); $method->getParameter('x'); } /** * @expectedException \InvalidArgumentException */ public function testGetNonExistentParameterByIndex() { $method = new PhpMethod('doink'); $method->getParameter(5); } /** * @expectedException \InvalidArgumentException */ public function testReplaceNonExistentParameterByIndex() { $method = new PhpMethod('doink'); $method->replaceParameter(5, new PhpParameter()); } /** * @expectedException \InvalidArgumentException */ public function testRemoveNonExistentParameterByIndex() { $method = new PhpMethod('doink'); $method->removeParameter(5); } public function testBody() { $method = new PhpMethod('needsName'); $this->assertSame('', $method->getBody()); $this->assertSame($method, $method->setBody('foo')); $this->assertEquals('foo', $method->getBody()); } public function testReferenceReturned() { $method = new PhpMethod('needsName'); $this->assertFalse($method->isReferenceReturned()); $this->assertSame($method, $method->setReferenceReturned(true)); $this->assertTrue($method->isReferenceReturned()); $this->assertSame($method, $method->setReferenceReturned(false)); $this->assertFalse($method->isReferenceReturned()); } } <file_sep><?php namespace gossi\codegen\parser; use PhpParser\Node; use PhpParser\Node\Expr; use PhpParser\Node\Expr\Array_; use PhpParser\Node\Stmt; use PhpParser\PrettyPrinter\Standard; class PrettyPrinter extends Standard { /** * Pretty prints an array of nodes (statements) and indents them optionally. * * @param Node[] $nodes Array of nodes * @param bool $indent Whether to indent the printed nodes * * @return string Pretty printed statements */ protected function pStmts(array $nodes, bool $indent = true): string { $result = ''; $prevNode = null; foreach ($nodes as $node) { $comments = $node->getAttribute('comments', []); if ($comments) { $result .= "\n" . $this->pComments($comments); if ($node instanceof Stmt\Nop) { continue; } } if ($prevNode && $prevNode->getLine() && $node->getLine()) { $diff = $node->getLine()- $prevNode->getLine(); if ($diff > 0) { $result .= str_repeat("\n", $diff - 1); } } $result .= "\n" . $this->p($node) . ($node instanceof Expr ? ';' : ''); $prevNode = $node; } if ($indent) { return preg_replace('~\n(?!$)~', "\n ", $result); } else { return $result; } } public function pExpr_Array(Array_ $node) { return '[' . $this->pCommaSeparated($node->items) . ']'; } } <file_sep><?php namespace gossi\codegen\tests\parser; use gossi\codegen\model\PhpClass; use gossi\codegen\tests\Fixtures; use gossi\codegen\tests\fixtures\ClassWithConstants; use gossi\codegen\tests\fixtures\sub\SubClass; use gossi\codegen\tests\parts\ModelAssertions; use gossi\codegen\tests\parts\ValueTests; use PHPUnit\Framework\TestCase; /** * @group parser */ class ClassParserTest extends TestCase { use ModelAssertions; use ValueTests; public function setUp() { // they are not explicitely instantiated through new WhatEver(); and such not // required through composer's autoload require_once __DIR__ . '/../fixtures/Entity.php'; require_once __DIR__ . '/../fixtures/ClassWithTraits.php'; require_once __DIR__ . '/../fixtures/ClassWithConstants.php'; require_once __DIR__ . '/../fixtures/ClassWithComments.php'; require_once __DIR__ . '/../fixtures/ClassWithValues.php'; } public function testEntity() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/Entity.php'); $this->assertEquals(Fixtures::createEntity(), $class); } public function testMethodBody() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/HelloWorld.php'); $this->assertTrue($class->hasMethod('sayHello')); $sayHello = $class->getMethod('sayHello'); $this->assertEquals('return \'Hello World!\';', $sayHello->getBody()); } public function testClassWithConstants() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/ClassWithConstants.php'); $this->assertTrue($class->hasConstant('FOO')); $this->assertEquals('bar', $class->getConstant('FOO')->getValue()); $this->assertTrue($class->hasConstant('NMBR')); $this->assertEquals(300, $class->getConstant('NMBR')->getValue()); $this->assertTrue($class->hasConstant('BAR')); $this->assertEquals('self::FOO', $class->getConstant('BAR')->getExpression()); } public function testClassWithTraits() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/ClassWithTraits.php'); $this->assertTrue($class->hasTrait('DT')); } public function testClassWithComments() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/ClassWithComments.php'); $this->assertClassWithComments($class); } public function testClassWithValues() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/ClassWithValues.php'); $this->assertClassWithValues($class); } public function testTypeClass() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/TypeClass.php'); $doSomething = $class->getMethod('doSomething'); $options = $doSomething->getParameter('options'); $this->assertEquals('OptionsResolver', $options->getTypeExpression()); $this->assertEquals( '\Symfony\Component\OptionsResolver\OptionsResolver', $class->getUseStatements()->get('OptionsResolver')); } public function testMyCollection() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/MyCollection.php'); $this->assertEquals('phootwork\collection\AbstractCollection', $class->getParentClassName()); $this->assertTrue($class->hasInterface('phootwork\collection\Collection')); } public function testMyCollection2() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/MyCollection2.php'); $this->assertEquals('\phootwork\collection\AbstractCollection', $class->getParentClassName()); $this->assertTrue($class->hasInterface('\phootwork\collection\Collection')); } public function testClassWithTypes() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/ClassWithTypes.php'); $param = $class->getMethod('test')->getParameter('toto'); $this->assertEquals( [ 'iterable', ClassWithConstants::class . '[]', SubClass::class, 'string', '\StdClass', ], array_keys($param->getTypes()->toArray()) ); $this->assertTrue($param->getNullable()); $param = $class->getMethod('test2')->getParameter('toto2'); $this->assertEquals( [ 'string', ], array_keys($param->getTypes()->toArray()) ); $this->assertTrue($param->getNullable()); $param = $class->getMethod('test3')->getParameter('toto3'); $this->assertEquals( [ 'int', ], array_keys($param->getTypes()->toArray()) ); $this->assertTrue($param->getNullable()); } } <file_sep><?php namespace gossi\codegen\tests\generator; use gossi\codegen\generator\ModelGenerator; use gossi\codegen\model\PhpConstant; use PHPUnit\Framework\TestCase; /** * @group generator */ class ConstantGeneratorTest extends TestCase { public function testValues() { $generator = new ModelGenerator(); $prop = PhpConstant::create('FOO')->setValue('string'); $this->assertEquals('const FOO = \'string\';' . "\n", $generator->generate($prop)); $prop = PhpConstant::create('FOO')->setValue(300); $this->assertEquals('const FOO = 300;' . "\n", $generator->generate($prop)); $prop = PhpConstant::create('FOO')->setValue(162.5); $this->assertEquals('const FOO = 162.5;' . "\n", $generator->generate($prop)); $prop = PhpConstant::create('FOO')->setValue(true); $this->assertEquals('const FOO = true;' . "\n", $generator->generate($prop)); $prop = PhpConstant::create('FOO')->setValue(false); $this->assertEquals('const FOO = false;' . "\n", $generator->generate($prop)); $prop = PhpConstant::create('FOO')->setValue(null); $this->assertEquals('const FOO = null;' . "\n", $generator->generate($prop)); $prop = PhpConstant::create('FOO')->setValue(PhpConstant::create('BAR')); $this->assertEquals('const FOO = BAR;' . "\n", $generator->generate($prop)); $prop = PhpConstant::create('FOO')->setExpression("['bar' => 'baz']"); $this->assertEquals('const FOO = [\'bar\' => \'baz\'];' . "\n", $generator->generate($prop)); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\builder\parts; use gossi\codegen\generator\ComparatorFactory; use gossi\codegen\model\AbstractModel; use gossi\codegen\model\AbstractPhpStruct; use gossi\codegen\model\ConstantsInterface; use gossi\codegen\model\DocblockInterface; use gossi\codegen\model\NamespaceInterface; use gossi\codegen\model\PropertiesInterface; use gossi\codegen\model\TraitsInterface; trait StructBuilderPart { /** * @return void */ abstract protected function ensureBlankLine(): void; /** * @param AbstractModel $model * @return void */ abstract protected function generate(AbstractModel $model): void; /** * @param DocblockInterface $model * @return void */ abstract protected function buildDocblock(DocblockInterface $model): void; protected function buildHeader(AbstractPhpStruct $model): void { $this->buildNamespace($model); $this->buildRequiredFiles($model); $this->buildUseStatements($model); $this->buildDocblock($model); } protected function buildNamespace(NamespaceInterface $model): void { if ($namespace = $model->getNamespace()) { $this->writer->writeln('namespace ' . $namespace . ';'); } } protected function buildRequiredFiles(AbstractPhpStruct $model): void { if ($files = $model->getRequiredFiles()) { $this->ensureBlankLine(); foreach ($files as $file) { $this->writer->writeln('require_once ' . var_export($file, true) . ';'); } } } protected function buildUseStatements(AbstractPhpStruct $model): void { if ($useStatements = $model->getUseStatements()) { $this->ensureBlankLine(); foreach ($useStatements as $alias => $namespace) { if (false === strpos($namespace, '\\')) { $commonName = $namespace; } else { $commonName = substr($namespace, strrpos($namespace, '\\') + 1); } if (false === strpos($namespace, '\\') && !$model->getNamespace()) { //avoid fatal 'The use statement with non-compound name '$commonName' has no effect' continue; } $this->writer->write('use ' . $namespace); if ($commonName !== $alias) { $this->writer->write(' as ' . $alias); } $this->writer->writeln(';'); } $this->ensureBlankLine(); } } protected function buildTraits(TraitsInterface $model): void { foreach ($model->getTraits() as $trait) { $this->writer->write('use '); $this->writer->writeln($trait . ';'); } } protected function buildConstants(ConstantsInterface $model): void { foreach ($model->getConstants() as $constant) { $this->generate($constant); } } protected function buildProperties(PropertiesInterface $model): void { foreach ($model->getProperties() as $property) { $this->generate($property); } } protected function buildMethods(AbstractPhpStruct $model): void { foreach ($model->getMethods() as $method) { $this->generate($method); } } private function sortUseStatements(AbstractPhpStruct $model): void { if ($this->config->isSortingEnabled() && ($useStatementSorting = $this->config->getUseStatementSorting()) !== false) { if (is_string($useStatementSorting)) { $useStatementSorting = ComparatorFactory::createUseStatementComparator($useStatementSorting); } $model->getUseStatements()->sort($useStatementSorting); } } private function sortConstants(ConstantsInterface $model): void { if ($this->config->isSortingEnabled() && ($constantSorting = $this->config->getConstantSorting()) !== false) { if (is_string($constantSorting)) { $constantSorting = ComparatorFactory::createConstantComparator($constantSorting); } $model->getConstants()->sort($constantSorting); } } private function sortProperties(PropertiesInterface $model): void { if ($this->config->isSortingEnabled() && ($propertySorting = $this->config->getPropertySorting()) !== false) { if (is_string($propertySorting)) { $propertySorting = ComparatorFactory::createPropertyComparator($propertySorting); } $model->getProperties()->sort($propertySorting); } } private function sortMethods(AbstractPhpStruct $model): void { if ($this->config->isSortingEnabled() && ($methodSorting = $this->config->getMethodSorting()) !== false) { if (is_string($methodSorting)) { $methodSorting = ComparatorFactory::createMethodComparator($methodSorting); } $model->getMethods()->sort($methodSorting); } } } <file_sep>API === API is available at `https://gossi.github.io/php-code-generator/api/master`_ .. _https://gossi.github.io/php-code-generator/api/master: https://gossi.github.io/php-code-generator/api/master <file_sep><?php /** * baz * @var string */ const FOO = 'bar'; <file_sep><?php require_once __DIR__ . '/vendor/autoload.php'; use Sami\Sami; use Sami\Version\GitVersionCollection; use Symfony\Component\Finder\Finder; use Sami\Parser\Filter\PublicFilter; $dir = __DIR__ . '/src'; $iterator = Finder::create() ->files() ->name('*.php') ->in($dir) ; $versions = GitVersionCollection::create($dir) ->addFromTags('v0.*') ->add('master', 'master branch') ; $sami = new Sami($iterator, [ 'title' => 'PHP Code Generator API', 'theme' => 'default', 'versions' => $versions, 'build_dir' => __DIR__ . '/api/%version%', 'cache_dir' => __DIR__ . '/cache/%version%', 'default_opened_level' => 2, 'sort_class_properties' => true, 'sort_class_methods' => true, 'sort_class_constants' => true, 'sort_class_traits' => true, 'sort_class_interfaces' => true ]); $sami['filter'] = function () { return new PublicFilter(); }; return $sami;<file_sep><?php namespace gossi\codegen\tests\generator; use gossi\codegen\config\CodeGeneratorConfig; use gossi\codegen\generator\CodeGenerator; use PHPUnit\Framework\TestCase; /** * @group generator */ class CodeGeneratorTest extends TestCase { public function testConfig() { $generator = new CodeGenerator(null); $this->assertTrue($generator->getConfig() instanceof CodeGeneratorConfig); $config = new CodeGeneratorConfig(); $generator = new CodeGenerator($config); $this->assertSame($config, $generator->getConfig()); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model; /** * Interface to all php structs that can have constants * * Implementation is realized in the `ConstantsPart` * * @author <NAME> */ interface ConstantsInterface { /** * Sets a collection of constants * * @param array|PhpConstant[] $constants * @return $this */ public function setConstants(array $constants); /** * Adds a constant * * @param string|PhpConstant $nameOrConstant constant or name * @param string $value * @return $this */ public function setConstant($nameOrConstant, string $value = null, bool $isExpression = false); /** * Removes a constant * * @param string|PhpConstant $nameOrConstant $nameOrConstant constant or name * @throws \InvalidArgumentException If the constant cannot be found * @return $this */ public function removeConstant($nameOrConstant); /** * Checks whether a constant exists * * @param string|PhpConstant $nameOrConstant * @return bool */ public function hasConstant($nameOrConstant); /** * Returns a constant * * @param string|PhpConstant $nameOrConstant constant or name * @throws \InvalidArgumentException If the constant cannot be found * @return PhpConstant */ public function getConstant($nameOrConstant); /** * Returns constants * * @return PhpConstant[] */ public function getConstants(); /** * Returns all constant names * * @return string[] */ public function getConstantNames(); /** * Clears all constants * * @return $this */ public function clearConstants(); } <file_sep><?php namespace gossi\codegen\tests; use gossi\codegen\model\PhpClass; use gossi\codegen\model\PhpConstant; use gossi\codegen\model\PhpInterface; use gossi\codegen\model\PhpMethod; use gossi\codegen\model\PhpParameter; use gossi\codegen\model\PhpProperty; use gossi\codegen\model\PhpTrait; use gossi\docblock\Docblock; use gossi\docblock\tags\AuthorTag; use gossi\docblock\tags\SinceTag; class Fixtures { /** * Creates the Fixture Class * * @return PhpClass */ public static function createEntity() { $classDoc = new Docblock('/** * Doc Comment. * * @author <NAME> <<EMAIL>> */'); $propDoc = new Docblock('/** * @var int */'); $class = new PhpClass(); $class->setQualifiedName('gossi\codegen\tests\fixtures\Entity') ->setAbstract(true) ->setDocblock($classDoc) ->setDescription($classDoc->getShortDescription()) ->setLongDescription($classDoc->getLongDescription()) ->addProperty(PhpProperty::create('id') ->setVisibility('private') ->setDocblock($propDoc) ->addType('int') ->setDescription($propDoc->getShortDescription())) ->addProperty(PhpProperty::create('enabled') ->setVisibility('private') ->setValue(false)); $methodDoc = new Docblock('/** * Another doc comment. * * @param $a * @param array $b * @param \stdClass $c * @param string $d * @param callable $e */'); $method = PhpMethod::create('__construct') ->setFinal(true) ->addParameter(PhpParameter::create('a')) ->addParameter(PhpParameter::create() ->setName('b') ->addType('array') ->setPassedByReference(true)) ->addParameter(PhpParameter::create() ->setName('c') ->addType('\\stdClass')) ->addParameter(PhpParameter::create() ->setName('d') ->addType('string') ->setValue('foo')) ->addParameter(PhpParameter::create() ->setName('e') ->addType('callable')) ->setDocblock($methodDoc) ->setDescription($methodDoc->getShortDescription()) ->setLongDescription($methodDoc->getLongDescription()); $class->addMethod($method); $class->addMethod(PhpMethod::create('foo')->setAbstract(true)->setVisibility('protected')); $class->addMethod(PhpMethod::create('bar')->setStatic(true)->setVisibility('private')); return $class; } /** * Create ClassWithConstants * * @return PhpClass */ public static function createClassWithConstants() { return PhpClass::create('gossi\\codegen\\tests\\fixtures\\ClassWithConstants') ->setConstant(PhpConstant::create('BAR')->setExpression('self::FOO')) ->setConstant(PhpConstant::create('FOO', 'bar')) ->setConstant(PhpConstant::create('NMBR', 300)); } /** * Creates ClassWithTraits * * @return PhpClass */ public static function createClassWithTraits() { return PhpClass::create('gossi\\codegen\\tests\\fixtures\\ClassWithTraits') ->addUseStatement('gossi\\codegen\\tests\\fixtures\\DummyTrait', 'DT') ->addTrait('DT'); } /** * * @return PhpClass */ public static function createABClass() { return PhpClass::create() ->setName('ABClass') ->addMethod(PhpMethod::create('a')) ->addMethod(PhpMethod::create('b')) ->addProperty(PhpProperty::create('a')) ->addProperty(PhpProperty::create('b')) ->setConstant('a', 'foo') ->setConstant('b', 'bar'); } /** * Creates ClassWithComments * * @return PhpClass */ public static function createClassWithComments() { $class = PhpClass::create('gossi\\codegen\\tests\\fixtures\\ClassWithComments'); $class->setDescription('A class with comments'); $class->setLongDescription('Here is a super dooper long-description'); $docblock = $class->getDocblock(); $docblock->appendTag(AuthorTag::create('gossi')); $docblock->appendTag(SinceTag::create('0.2')); $class->setConstant(PhpConstant::create('FOO', 'bar') ->setDescription('Best const ever') ->setLongDescription('Aaaand we go along long') ->addType('string') ->addTypeDescription('baz') ); $class->addProperty(PhpProperty::create('propper') ->setDescription('best prop ever') ->setLongDescription('Aaaand we go along long long') ->addType('string') ->addTypeDescription('Wer macht sauber?') ); $class->addMethod(PhpMethod::create('setup') ->setDescription('Short desc') ->setLongDescription('Looong desc') ->addParameter(PhpParameter::create('moo') ->addType('boolean') ->addTypeDescription('makes a cow')) ->addParameter(PhpParameter::create('foo') ->addType('foo', 'makes a fow')) ->addType('boolean', 'true on success and false if it fails') ); return $class; } /** * Creates DummyInterface * * @return PhpInterface */ public static function createDummyInterface() { $interface = PhpInterface::create('DummyInterface') ->setNamespace('gossi\codegen\tests\fixtures') ->setDescription('Dummy docblock') ->addMethod(PhpMethod::create('foo')); $interface->generateDocblock(); return $interface; } /** * Creates DummyTrait * * @return PhpTrait */ public static function createDummyTrait() { $trait = PhpTrait::create('DummyTrait') ->setNamespace('gossi\\codegen\\tests\\fixtures') ->setDescription('Dummy docblock') ->addMethod(PhpMethod::create('foo')->setVisibility('public')) ->addProperty(PhpProperty::create('iAmHidden')->setVisibility('private')) ->addTrait('VeryDummyTrait'); $trait->generateDocblock(); return $trait; } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\config; use gossi\code\profiles\Profile; use gossi\codegen\generator\CodeGenerator; use phootwork\lang\Comparator; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; /** * Configuration for code generation * * @author <NAME> */ class CodeGeneratorConfig { protected $options; /** @var Profile */ protected $profile; /** * Creates a new configuration for code generator * * @see https://php-code-generator.readthedocs.org/en/latest/generator.html * @param array $options */ public function __construct(array $options = []) { $resolver = new OptionsResolver(); $this->configureOptions($resolver); $this->options = $resolver->resolve($options); $this->profile = is_string($this->options['profile']) ? new Profile($this->options['profile']) : $this->options['profile']; } protected function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'profile' => 'default', 'generateDocblock' => true, 'generateEmptyDocblock' => function (Options $options) { return $options['generateDocblock']; }, 'generateScalarTypeHints' => false, 'generateReturnTypeHints' => false, 'generateNullableTypes' => false, 'enableFormatting' => false, 'enableSorting' => true, 'useStatementSorting' => CodeGenerator::SORT_USESTATEMENTS_DEFAULT, 'constantSorting' => CodeGenerator::SORT_CONSTANTS_DEFAULT, 'propertySorting' => CodeGenerator::SORT_PROPERTIES_DEFAULT, 'methodSorting' => CodeGenerator::SORT_METHODS_DEFAULT ]); $resolver->setAllowedTypes('profile', ['string', 'gossi\code\profiles\Profile']); $resolver->setAllowedTypes('generateDocblock', 'bool'); $resolver->setAllowedTypes('generateEmptyDocblock', 'bool'); $resolver->setAllowedTypes('generateScalarTypeHints', 'bool'); $resolver->setAllowedTypes('generateReturnTypeHints', 'bool'); $resolver->setAllowedTypes('generateNullableTypes', 'bool'); $resolver->setAllowedTypes('enableFormatting', 'bool'); $resolver->setAllowedTypes('enableSorting', 'bool'); $resolver->setAllowedTypes('useStatementSorting', ['bool', 'string', '\Closure', 'phootwork\lang\Comparator']); $resolver->setAllowedTypes('constantSorting', ['bool', 'string', '\Closure', 'phootwork\lang\Comparator']); $resolver->setAllowedTypes('propertySorting', ['bool', 'string', '\Closure', 'phootwork\lang\Comparator']); $resolver->setAllowedTypes('methodSorting', ['bool', 'string', '\Closure', 'phootwork\lang\Comparator']); } /** * Returns the code style profile * * @return Profile */ public function getProfile(): Profile { return $this->profile; } /** * Sets the code style profile * * @param Profile|string $profile * @return $this */ public function setProfile($profile) { if (is_string($profile)) { $profile = new Profile($profile); } $this->profile = $profile; return $this; } /** * Returns whether docblocks should be generated * * @return bool `true` if they will be generated and `false` if not */ public function getGenerateDocblock(): bool { return $this->options['generateDocblock']; } /** * Sets whether docblocks should be generated * * @param bool $generate `true` if they will be generated and `false` if not * @return $this */ public function setGenerateDocblock(bool $generate) { $this->options['generateDocblock'] = $generate; if (!$generate) { $this->options['generateEmptyDocblock'] = $generate; } return $this; } /** * Returns whether empty docblocks are generated * * @return bool `true` if they will be generated and `false` if not */ public function getGenerateEmptyDocblock(): bool { return $this->options['generateEmptyDocblock']; } /** * Sets whether empty docblocks are generated * * @param bool $generate `true` if they will be generated and `false` if not * @return $this */ public function setGenerateEmptyDocblock(bool $generate) { $this->options['generateEmptyDocblock'] = $generate; if ($generate) { $this->options['generateDocblock'] = $generate; } return $this; } /** * Returns whether scalar type hints will be generated for method parameters (PHP 7) * * @return bool `true` if they will be generated and `false` if not */ public function getGenerateScalarTypeHints(): bool { return $this->options['generateScalarTypeHints']; } /** * Returns whether sorting is enabled * * @return bool `true` if it is enabled and `false` if not */ public function isSortingEnabled(): bool { return $this->options['enableSorting']; } /** * Returns whether formatting is enalbed * * @return bool `true` if it is enabled and `false` if not */ public function isFormattingEnabled(): bool { return $this->options['enableFormatting']; } /** * Returns the use statement sorting * * @return string|bool|Comparator|\Closure */ public function getUseStatementSorting() { return $this->options['useStatementSorting']; } /** * Returns the constant sorting * * @return string|bool|Comparator|\Closure */ public function getConstantSorting() { return $this->options['constantSorting']; } /** * Returns the property sorting * * @return string|bool|Comparator|\Closure */ public function getPropertySorting() { return $this->options['propertySorting']; } /** * Returns the method sorting * * @return string|bool|Comparator|\Closure */ public function getMethodSorting() { return $this->options['methodSorting']; } /** * Sets whether scalar type hints will be generated for method parameters (PHP 7) * * @param bool $generate `true` if they will be generated and `false` if not * @return $this */ public function setGenerateScalarTypeHints(bool $generate) { $this->options['generateScalarTypeHints'] = $generate; return $this; } /** * Returns whether return type hints will be generated for method parameters (PHP 7) * * @return bool `true` if they will be generated and `false` if not */ public function getGenerateReturnTypeHints(): bool { return $this->options['generateReturnTypeHints']; } /** * Sets whether return type hints will be generated for method parameters (PHP 7) * * @param bool $generate `true` if they will be generated and `false` if not * @return $this */ public function setGenerateReturnTypeHints(bool $generate) { $this->options['generateReturnTypeHints'] = $generate; return $this; } /** * Returns whether return nullable type hints will be generated (PHP 7.3) * * @return bool `true` if they will be generated and `false` if not */ public function getGenerateNullableTypes(): bool { return $this->options['generateNullableTypes']; } /** * Sets whether return nullable type hints will be generated (PHP 7.3) * * @param bool $generate `true` if they will be generated and `false` if not * @return $this */ public function setGenerateNullableTypes(bool $generate) { $this->options['generateNullableTypes'] = $generate; return $this; } /** * Sets whether sorting is enabled * * @param $enabled bool `true` if it is enabled and `false` if not * @return $this */ public function setSortingEnabled(bool $enabled) { $this->options['enableSorting'] = $enabled; return $this; } /** * Sets whether formatting is enabled * * @param $enabled bool `true` if it is enabled and `false` if not * @return $this */ public function setFormattingEnabled(bool $enabled) { $this->options['enableFormatting'] = $enabled; return $this; } /** * Returns the use statement sorting * * @param $sorting string|bool|Comparator|\Closure * @return $this */ public function setUseStatementSorting($sorting) { $this->options['useStatementSorting'] = $sorting; return $this; } /** * Returns the constant sorting * * @param $sorting string|bool|Comparator|\Closure * @return $this */ public function setConstantSorting($sorting) { $this->options['constantSorting'] = $sorting; return $this; } /** * Returns the property sorting * * @param $sorting string|bool|Comparator|\Closure * @return $this */ public function setPropertySorting($sorting) { $this->options['propertySorting'] = $sorting; return $this; } /** * Returns the method sorting * * @param $sorting string|bool|Comparator|\Closure * @return $this */ public function setMethodSorting($sorting) { $this->options['methodSorting'] = $sorting; return $this; } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model\parts; use gossi\codegen\model\PhpTypeInterface; use gossi\codegen\utils\TypeUtils; use gossi\docblock\Docblock; use gossi\docblock\tags\AbstractTag; use phootwork\collection\Set; /** * Type docblock generator part * * For all models that have a type and need docblock tag generated from it * * @author <NAME> */ trait TypeDocblockGeneratorPart { /** * Returns the docblock * * @return Docblock */ abstract protected function getDocblock(): Docblock; /** * Returns the type * * @return string[]|PhpTypeInterface[]|Set */ abstract public function getTypes(): ?iterable; /** * Returns the type description * * @return string */ abstract public function getTypeDescription(): ?string; /** * Generates a type tag (return or var) but checks if one exists and updates this one * * @param AbstractTag $tag */ protected function generateTypeTag(AbstractTag $tag) { $docblock = $this->getDocblock(); $types = $this->getTypes(); if ($types->size() > 0) { // try to find tag at first and update $tags = $docblock->getTags($tag->getTagName()); $type = TypeUtils::typesToExpression($this->getTypes()); if ($tags->size() > 0) { $ttag = $tags->get(0); $ttag->setType($type); $ttag->setDescription($this->getTypeDescription()); } // ... anyway create and append else { $docblock->appendTag($tag ->setType($type) ->setDescription($this->getTypeDescription()) ); } } } } <file_sep><?php class ClassWithExpression { const FOO = 'BAR'; public $bembel = ['ebbelwoi' => 'is eh besser', 'als wie' => 'bier']; public function getValue($arr = [self::FOO => 'baz']) { } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\parser\visitor; use gossi\codegen\parser\visitor\parts\StructParserPart; use PhpParser\Node\Stmt\Interface_; class InterfaceParserVisitor extends StructParserVisitor { use StructParserPart; public function visitInterface(Interface_ $node) { foreach ($node->extends as $name) { $this->struct->addInterface(implode('\\', $name->parts)); } } } <file_sep>Best Practices ============== The code generator was written with some thoughts in mind. See for yourself, if they are useful for you, too. Template system for Code Bodies ------------------------------- It is useful to use some kind of template system to load the contents for your bodies. The template system can also be used to replace variables in the templates. Hack in Traits -------------- Let's assume you generate a php class. This class will be used in your desired framework as it serves a specific purpose in there. It possible needs to fulfill an interface or some abstract methods and your generated code will also take care of this - wonderful. Now imagine the programmer wants to change the code your code generation tools created. Once you run the code generation tools again his changes probably got overwritten, which would be bad. Here is the trick: First we declare the generated class as "host" class: .. image:: images/hack-in-trait.png :width: 50% :align: center Your generated code will target the trait, where you can savely overwrite code. However, you must make sure the trait will be used from the host class and also generate the host class, if it doesn't exist. So here are the steps following this paradigm: 1. Create the trait 2. Check if the host class exists a. if it exists, load it b. if not, create it 3. Add the trait to the host class 4. Generate the host class code That way, the host class will be user-land code and the developer can write his own code there. The code generation tools will keep that code intact, so it won't be destroyed when code generation tools run again. If you want to give the programmer more freedom offer him hook methods in the host class, that - if he wants to - can overwrite with his own logic. Format in Post-Processing ------------------------- After generating code is finished, it can happen that (especially) bodies are formatted ugly. Thus just run the suggested code formatter after generating the code. Can be found on github `gossi/php-code-formatter`_. .. _gossi/php-code-formatter: https://github.com/gossi/php-code-formatter <file_sep><?php declare(strict_types=1); namespace gossi\codegen\parser\visitor; use gossi\codegen\model\PhpConstant; use gossi\codegen\parser\visitor\parts\MemberParserPart; use gossi\codegen\parser\visitor\parts\ValueParserPart; use PhpParser\Comment\Doc; use PhpParser\Node\Const_; use PhpParser\Node\Stmt\ClassConst; class ConstantParserVisitor extends StructParserVisitor { use MemberParserPart; use ValueParserPart; public function visitConstants(ClassConst $node) { $doc = $node->getDocComment(); foreach ($node->consts as $const) { $this->visitConstant($const, $doc); } } public function visitConstant(Const_ $node, Doc $doc = null) { $const = new PhpConstant($node->name->name); $this->parseValue($const, $node); $this->parseMemberDocblock($const, $doc); $this->struct->setConstant($const); } } <file_sep><?php namespace gossi\codegen\parser\visitor\parts; use gossi\codegen\model\AbstractPhpStruct; use PhpParser\Node\Stmt\ClassLike; use PhpParser\Node\Stmt\Namespace_; use PhpParser\Node\Stmt\TraitUse; use PhpParser\Node\Stmt\UseUse; trait StructParserPart { /** * @return AbstractPhpStruct */ abstract protected function getStruct(): AbstractPhpStruct; public function visitStruct(ClassLike $node) { $struct = $this->getStruct(); $struct->setName($node->name->name); if (($doc = $node->getDocComment()) !== null) { $struct->setDocblock($doc->getReformattedText()); $docblock = $struct->getDocblock(); $struct->setDescription($docblock->getShortDescription()); $struct->setLongDescription($docblock->getLongDescription()); } } public function visitTraitUse(TraitUse $node) { $struct = $this->getStruct(); foreach ($node->traits as $trait) { $struct->addTrait(implode('\\', $trait->parts)); } } public function visitNamespace(Namespace_ $node) { if ($node->name !== null) { $this->getStruct()->setNamespace(implode('\\', $node->name->parts)); } } public function visitUseStatement(UseUse $node) { $name = implode('\\', $node->name->parts); $alias = !empty($node->alias) ? $node->alias : null; $this->getStruct()->addUseStatement($name, $alias); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\config; use gossi\docblock\Docblock; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; /** * Configuration for code file generation * * @author <NAME> */ class CodeFileGeneratorConfig extends CodeGeneratorConfig { protected function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); $resolver->setDefaults([ 'headerComment' => null, 'headerDocblock' => null, 'blankLineAtEnd' => true, 'declareStrictTypes' => false, 'generateScalarTypeHints' => function (Options $options) { return $options['declareStrictTypes']; }, 'generateReturnTypeHints' => function (Options $options) { return $options['declareStrictTypes']; }, ]); $resolver->setAllowedTypes('headerComment', ['null', 'string', 'gossi\\docblock\\Docblock']); $resolver->setAllowedTypes('headerDocblock', ['null', 'string', 'gossi\\docblock\\Docblock']); $resolver->setAllowedTypes('blankLineAtEnd', 'bool'); $resolver->setAllowedTypes('declareStrictTypes', 'bool'); $resolver->setNormalizer('headerComment', function (Options $options, $value) { return $this->toDocblock($value); }); $resolver->setNormalizer('headerDocblock', function (Options $options, $value) { return $this->toDocblock($value); }); } /** * * @param mixed $value * @return Docblock|null */ private function toDocblock($value): ?Docblock { if (is_string($value)) { $value = Docblock::create()->setLongDescription($value); } return $value; } /** * Returns the file header comment * * @return Docblock the header comment */ public function getHeaderComment(): ?Docblock { return $this->options['headerComment']; } /** * Sets the file header comment * * @param Docblock $comment the header comment * @return $this */ public function setHeaderComment(Docblock $comment) { $this->options['headerComment'] = $comment; return $this; } /** * Returns the file header docblock * * @return Docblock the docblock */ public function getHeaderDocblock(): ?Docblock { return $this->options['headerDocblock']; } /** * Sets the file header docblock * * @param Docblock $docblock the docblock * @return $this */ public function setHeaderDocblock(Docblock $docblock) { $this->options['headerDocblock'] = $docblock; return $this; } /** * Returns whether a blank line should be generated at the end of the file * * @return bool `true` if it will be generated and `false` if not */ public function getBlankLineAtEnd(): bool { return $this->options['blankLineAtEnd']; } /** * Sets whether a blank line should be generated at the end of the file * * @param bool $show `true` if it will be generated and `false` if not * @return $this */ public function setBlankLineAtEnd(bool $show) { $this->options['blankLineAtEnd'] = $show; return $this; } /** * Returns whether a `declare(strict_types=1);` statement should be printed * below the header comments (PHP 7) * * @return bool `true` if it will be printed and `false` if not */ public function getDeclareStrictTypes(): bool { return $this->options['declareStrictTypes']; } /** * Sets whether a `declare(strict_types=1);` statement should be printed * below the header comments (PHP 7) * * @param bool $strict `true` if it will be printed and `false` if not * @return $this */ public function setDeclareStrictTypes(bool $strict) { $this->options['declareStrictTypes'] = $strict; return $this; } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\builder\parts; use gossi\codegen\model\AbstractModel; use gossi\codegen\model\RoutineInterface; trait RoutineBuilderPart { use TypeBuilderPart; /** * @param AbstractModel $model * @return void */ abstract protected function generate(AbstractModel $model): void; protected function writeFunctionStatement(RoutineInterface $model): void { $this->writer->write('function '); if ($model->isReferenceReturned()) { $this->writer->write('& '); } $this->writer->write($model->getName() . '('); $this->writeParameters($model); $this->writer->write(')'); $this->writeFunctionReturnType($model); } protected function writeParameters(RoutineInterface $model): void { $first = true; foreach ($model->getParameters() as $parameter) { if (!$first) { $this->writer->write(', '); } $first = false; $this->generate($parameter); } } protected function writeFunctionReturnType(RoutineInterface $model): void { $type = $this->getType($model, $this->config->getGenerateReturnTypeHints(), $this->config->getGenerateNullableTypes()); if ($type !== null && $this->config->getGenerateReturnTypeHints()) { $this->writer->write(': ')->write($type); } } protected function writeBody(RoutineInterface $model): void { $this->writer->writeln(' {')->indent(); $this->writer->writeln(trim($model->getBody())); $this->writer->outdent()->rtrim()->writeln('}'); } } <file_sep><?php namespace gossi\codegen\tests\fixtures; abstract class OverridableReflectionTest { public function a() { } final public function b() { } public static function c() { } abstract public function d(); protected function e() { } final protected function f() { } protected static function g() { } abstract protected function h(); private function i() { } } <file_sep>#!/bin/bash #set -o errexit -o nounset rev=$(git rev-parse --short HEAD) php vendor/bin/sami.php update sami.php mkdir _site cp -R api _site/ cd _site git init git config user.name "gossi" git config user.email "<EMAIL>" git remote add upstream "https://$GH_TOKEN@github.com/gossi/php-code-generator.git" git fetch upstream git reset upstream/gh-pages touch . git add -A . git commit -m "rebuild API at ${rev}" git push upstream HEAD:gh-pages <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model; use phootwork\collection\Map; use phootwork\collection\Set; interface PropertiesInterface { /** * Sets a collection of properties * * @param PhpProperty[] $properties * @return $this */ public function setProperties(array $properties); /** * Adds a property * * @param PhpProperty $property * @return $this */ public function addProperty(PhpProperty $property); /** * Removes a property * * @param PhpProperty|string $nameOrProperty property name or instance * @throws \InvalidArgumentException If the property cannot be found * @return $this */ public function removeProperty($nameOrProperty); /** * Checks whether a property exists * * @param PhpProperty|string $nameOrProperty property name or instance * @return bool `true` if a property exists and `false` if not */ public function hasProperty($nameOrProperty): bool; /** * Returns a property * * @param string $nameOrProperty property name * @throws \InvalidArgumentException If the property cannot be found * @return PhpProperty */ public function getProperty($nameOrProperty): PhpProperty; /** * Returns a collection of properties * * @return Map */ public function getProperties(): Map; /** * Returns all property names * * @return Set */ public function getPropertyNames(): Set; /** * Clears all properties * * @return $this */ public function clearProperties(); } <file_sep><?php namespace gossi\codegen\tests\generator; use gossi\codegen\generator\ModelGenerator; use gossi\codegen\model\PhpTrait; use PHPUnit\Framework\TestCase; /** * @group generator */ class TraitGeneratorTest extends TestCase { public function testSignature() { $expected = 'trait MyTrait {' . "\n" . '}'; $trait = PhpTrait::create('MyTrait'); $generator = new ModelGenerator(); $code = $generator->generate($trait); $this->assertEquals($expected, $code); } } <file_sep><?php namespace gossi\codegen\tests\generator; use gossi\codegen\config\CodeFileGeneratorConfig; use gossi\codegen\generator\CodeFileGenerator; use gossi\codegen\model\PhpClass; use gossi\codegen\model\PhpConstant; use gossi\codegen\model\PhpFunction; use gossi\codegen\model\PhpMethod; use gossi\codegen\model\PhpParameter; use gossi\codegen\model\PhpProperty; use gossi\codegen\tests\Fixtures; use gossi\codegen\tests\parts\TestUtils; use PHPUnit\Framework\TestCase; /** * @group generator */ class CodeFileGeneratorTest extends TestCase { use TestUtils; public function testStrictTypesDeclaration() { $expected = "<?php\ndeclare(strict_types=1);\n\nfunction fn(\$a) {\n}\n"; $fn = PhpFunction::create('fn')->addParameter(PhpParameter::create('a')); $codegen = new CodeFileGenerator(['generateDocblock' => false, 'generateEmptyDocblock' => false, 'declareStrictTypes' => true]); $code = $codegen->generate($fn); $this->assertEquals($expected, $code); } public function testExpression() { $class = new PhpClass('ClassWithExpression'); $class ->setConstant(PhpConstant::create('FOO', 'BAR')) ->addProperty(PhpProperty::create('bembel') ->setExpression("['ebbelwoi' => 'is eh besser', 'als wie' => 'bier']") ) ->addMethod(PhpMethod::create('getValue') ->addParameter(PhpParameter::create('arr') ->setExpression('[self::FOO => \'baz\']') )); $codegen = new CodeFileGenerator(['generateDocblock' => false]); $code = $codegen->generate($class); $this->assertEquals($this->getGeneratedContent('ClassWithExpression.php'), $code); } public function testDocblocks() { $generator = new CodeFileGenerator([ 'headerComment' => 'hui buuh', 'headerDocblock' => 'woop' ]); $class = new PhpClass('Dummy'); $code = $generator->generate($class); $this->assertEquals($this->getGeneratedContent('Dummy.php'), $code); } public function testEntity() { $class = Fixtures::createEntity(); $generator = new CodeFileGenerator(['generateDocblock' => true, 'generateEmptyDocblock' => false]); $code = $generator->generate($class); $this->assertEquals($this->getFixtureContent('Entity.php'), $code); } public function testConfig() { $generator = new CodeFileGenerator(null); $this->assertTrue($generator->getConfig() instanceof CodeFileGeneratorConfig); $config = new CodeFileGeneratorConfig(); $generator = new CodeFileGenerator($config); $this->assertSame($config, $generator->getConfig()); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\builder; use gossi\codegen\generator\builder\parts\TypeBuilderPart; use gossi\codegen\generator\builder\parts\ValueBuilderPart; use gossi\codegen\model\AbstractModel; class ParameterBuilder extends AbstractBuilder { use ValueBuilderPart; use TypeBuilderPart; public function build(AbstractModel $model): void { $type = $this->getType($model, $this->config->getGenerateScalarTypeHints(), $this->config->getGenerateNullableTypes()); if ($type !== null) { $this->writer->write($type . ' '); } if ($model->isPassedByReference()) { $this->writer->write('&'); } $this->writer->write('$' . $model->getName()); if ($model->hasValue()) { $this->writer->write(' = '); $this->writeValue($model); } } } <file_sep><?php /* * Copyright 2011 <NAME> <<EMAIL>> * * 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. */ declare(strict_types=1); namespace gossi\codegen\model; use gossi\codegen\model\parts\DocblockPart; use gossi\codegen\model\parts\LongDescriptionPart; use gossi\codegen\model\parts\QualifiedNamePart; use gossi\codegen\utils\TypeUtils; use gossi\docblock\Docblock; use phootwork\collection\Map; use phootwork\collection\Set; /** * Represents an abstract php structure (class, trait or interface). * * @author <NAME> <<EMAIL>> * @author <NAME> */ abstract class AbstractPhpStruct extends AbstractModel implements NamespaceInterface, DocblockInterface { use DocblockPart; use LongDescriptionPart; use QualifiedNamePart; /** @var Map|string[] */ private $useStatements; /** @var Set|string[] */ private $requiredFiles; /** @var Map|PhpMethod[] */ private $methods; /** * Creates a new struct * * @param string $name the fqcn * @return static */ public static function create(?string $name = null) { return new static($name); } public static function fromName(string $name): self { $ref = new \ReflectionClass($name); return static::fromFile($ref->getFileName()); } /** * Creates a new struct * * @param string $name the fqcn */ public function __construct(?string $name = null) { $this->setQualifiedName($name); $this->docblock = new Docblock(); $this->useStatements = new Map(); $this->requiredFiles = new Set(); $this->methods = new Map(); } /** * Sets requried files * * @param array $files * @return $this */ public function setRequiredFiles(array $files) { $this->requiredFiles = new Set($files); return $this; } /** * Adds a new required file * * @param string $file * @return $this */ public function addRequiredFile(string $file) { $this->requiredFiles->add($file); return $this; } /** * Returns required files * * @return Set collection of filenames */ public function getRequiredFiles(): Set { return $this->requiredFiles; } /** * Sets use statements * * @see #addUseStatement * @see #declareUses() * @param array $useStatements * @return $this */ public function setUseStatements(array $useStatements) { $this->useStatements->clear(); foreach ($useStatements as $alias => $useStatement) { $this->addUseStatement($useStatement, $alias); } return $this; } /** * Adds a use statement with an optional alias * * @param string|PhpTypeInterface $qualifiedName * @param null|string $alias * @return $this */ public function addUseStatement($qualifiedName, string $alias = null) { if ($qualifiedName instanceof PhpTypeInterface) { $qualifiedName = $qualifiedName->getQualifiedName(); } if (TypeUtils::isGlobalQualifiedName($qualifiedName) || TypeUtils::isNativeType($qualifiedName)) { return $this; } if (preg_replace('#\\\\[^\\\\]+$#', '', $qualifiedName) === $this->getNamespace()) { return $this; } if (!is_string($alias)) { if (false === strpos($qualifiedName, '\\')) { $alias = $qualifiedName; } else { $alias = substr($qualifiedName, strrpos($qualifiedName, '\\') + 1); } } $qualifiedName = str_replace('[]', '', $qualifiedName); $this->useStatements->set($alias, $qualifiedName); return $this; } /** * Clears all use statements * * @return $this */ public function clearUseStatements() { $this->useStatements->clear(); return $this; } /** * Declares multiple use statements at once. * * @param ... use statements multiple qualified names * @return $this */ public function declareUses(string ...$uses) { foreach ($uses as $name) { $this->declareUse($name); } return $this; } /** * Declares a "use $fullClassName" with " as $alias" if $alias is available, * and returns its alias (or not qualified classname) to be used in your actual * php code. * * If the class has already been declared you get only the set alias. * * @param string $qualifiedName * @param null|string $alias * @return string the used alias */ public function declareUse(string $qualifiedName, string $alias = null) { $qualifiedName = trim($qualifiedName, '\\'); if (!$this->hasUseStatement($qualifiedName)) { $this->addUseStatement($qualifiedName, $alias); } return $this->getUseAlias($qualifiedName); } /** * Returns whether the given use statement is present * * @param string $qualifiedName * @return bool */ public function hasUseStatement(string $qualifiedName): bool { return $this->useStatements->contains($qualifiedName); } /** * Returns the usable alias for a qualified name * * @param string $qualifiedName * @return string the alias */ public function getUseAlias(string $qualifiedName): string { return $this->useStatements->getKey($qualifiedName); } /** * Removes a use statement * * @param string $qualifiedName * @return $this */ public function removeUseStatement(string $qualifiedName) { $this->useStatements->remove($this->useStatements->getKey($qualifiedName)); return $this; } /** * Returns all use statements * * @return Map collection of use statements */ public function getUseStatements(): Map { return $this->useStatements; } /** * Sets a collection of methods * * @param PhpMethod[] $methods * @return $this */ public function setMethods(array $methods) { foreach ($this->methods as $method) { $method->setParent(null); } $this->methods->clear(); foreach ($methods as $method) { $this->addMethod($method); } return $this; } /** * Adds a method * * @param PhpMethod $method * @return $this */ public function addMethod(PhpMethod $method) { $method->setParent($this); $this->methods->set($method->getName(), $method); $types = $method->getTypes(); if ($types) { foreach ($types as $type) { $this->addUseStatement($type); $method->addType($type); } } foreach ($method->getParameters() as $parameter) { $types = $parameter->getTypes(); if ($types) { foreach ($types as $type) { $this->addUseStatement($type); $parameter->addType($type); } } } return $this; } /** * Removes a method * * @param string|PhpMethod $nameOrMethod method name or Method instance * @throws \InvalidArgumentException if the method cannot be found * @return $this */ public function removeMethod($nameOrMethod) { if ($nameOrMethod instanceof PhpMethod) { $nameOrMethod = $nameOrMethod->getName(); } if (!$this->methods->has($nameOrMethod)) { throw new \InvalidArgumentException(sprintf('The method "%s" does not exist.', $nameOrMethod)); } $m = $this->methods->get($nameOrMethod); $m->setParent(null); $this->methods->remove($nameOrMethod); return $this; } /** * Checks whether a method exists or not * * @param string|PhpMethod $nameOrMethod method name or Method instance * @return bool `true` if it exists and `false` if not */ public function hasMethod($nameOrMethod): bool { if ($nameOrMethod instanceof PhpMethod) { $nameOrMethod = $nameOrMethod->getName(); } return $this->methods->has($nameOrMethod); } /** * Returns a method * * @param string $nameOrMethod the methods name * @throws \InvalidArgumentException if the method cannot be found * @return PhpMethod */ public function getMethod($nameOrMethod): PhpMethod { if ($nameOrMethod instanceof PhpMethod) { $nameOrMethod = $nameOrMethod->getName(); } if (!$this->methods->has($nameOrMethod)) { throw new \InvalidArgumentException(sprintf('The method "%s" does not exist.', $nameOrMethod)); } return $this->methods->get($nameOrMethod); } /** * Returns all methods * * @return Map|PhpMethod[] collection of methods */ public function getMethods(): Map { return $this->methods; } /** * Returns all method names * * @return Set */ public function getMethodNames(): Set { return $this->methods->keys(); } /** * Clears all methods * * @return $this */ public function clearMethods() { foreach ($this->methods as $method) { $method->setParent(null); } $this->methods->clear(); return $this; } /** * Generates a docblock from provided information * * @return $this */ public function generateDocblock() { $docblock = $this->getDocblock(); $docblock->setShortDescription($this->getDescription()); $docblock->setLongDescription($this->getLongDescription()); foreach ($this->methods as $method) { $method->generateDocblock(); } return $this; } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\builder; use gossi\codegen\generator\builder\parts\RoutineBuilderPart; use gossi\codegen\model\AbstractModel; use gossi\codegen\model\PhpInterface; class MethodBuilder extends AbstractBuilder { use RoutineBuilderPart; public function build(AbstractModel $model): void { $this->buildDocblock($model); if ($model->isFinal()) { $this->writer->write('final '); } if ($model->isAbstract()) { $this->writer->write('abstract '); } $this->writer->write($model->getVisibility() . ' '); if ($model->isStatic()) { $this->writer->write('static '); } $this->writeFunctionStatement($model); if ($model->isAbstract() || $model->getParent() instanceof PhpInterface) { $this->writer->writeln(';'); return; } $this->writeBody($model); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator; use gossi\codegen\config\CodeGeneratorConfig; use gossi\codegen\model\GenerateableInterface; /** * Code generator * * Generates code for any generateable model * * @author <NAME> */ class CodeGenerator { const SORT_USESTATEMENTS_DEFAULT = 'default'; const SORT_CONSTANTS_DEFAULT = 'default'; const SORT_PROPERTIES_DEFAULT = 'default'; const SORT_METHODS_DEFAULT = 'default'; /** @var CodeGeneratorConfig */ protected $config; /** @var ModelGenerator */ protected $generator; /** * * @param CodeGeneratorConfig|array $config */ public function __construct($config = null) { $this->configure($config); $this->generator = new ModelGenerator($this->config); } protected function configure($config = null) { if (is_array($config)) { $this->config = new CodeGeneratorConfig($config); } else if ($config instanceof CodeGeneratorConfig) { $this->config = $config; } else { $this->config = new CodeGeneratorConfig(); } } /** * Returns the used configuration * * @return CodeGeneratorConfig */ public function getConfig() { return $this->config; } /** * Generates code from a given model * * @param GenerateableInterface $model * @return string the generated code */ public function generate(GenerateableInterface $model): string { return $this->generator->generate($model); } } <file_sep><?php namespace gossi\codegen\tests\generator; use gossi\codegen\generator\ModelGenerator; use gossi\codegen\model\PhpConstant; use gossi\codegen\model\PhpProperty; use PHPUnit\Framework\TestCase; /** * @group generator */ class PropertyGeneratorTest extends TestCase { public function testPublic() { $expected = 'public $foo;' . "\n"; $prop = PhpProperty::create('foo'); $generator = new ModelGenerator(); $code = $generator->generate($prop); $this->assertEquals($expected, $code); } public function testProtected() { $expected = 'protected $foo;' . "\n"; $prop = PhpProperty::create('foo')->setVisibility(PhpProperty::VISIBILITY_PROTECTED); $generator = new ModelGenerator(); $code = $generator->generate($prop); $this->assertEquals($expected, $code); } public function testPrivate() { $expected = 'private $foo;' . "\n"; $prop = PhpProperty::create('foo')->setVisibility(PhpProperty::VISIBILITY_PRIVATE); $generator = new ModelGenerator(); $code = $generator->generate($prop); $this->assertEquals($expected, $code); } public function testStatic() { $expected = 'public static $foo;' . "\n"; $prop = PhpProperty::create('foo')->setStatic(true); $generator = new ModelGenerator(); $code = $generator->generate($prop); $this->assertEquals($expected, $code); } public function testValues() { $generator = new ModelGenerator(); $prop = PhpProperty::create('foo')->setValue('string'); $this->assertEquals('public $foo = \'string\';' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setValue(300); $this->assertEquals('public $foo = 300;' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setValue(162.5); $this->assertEquals('public $foo = 162.5;' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setValue(true); $this->assertEquals('public $foo = true;' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setValue(false); $this->assertEquals('public $foo = false;' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setValue(null); $this->assertEquals('public $foo = null;' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setValue(PhpConstant::create('BAR')); $this->assertEquals('public $foo = BAR;' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setExpression("['bar' => 'baz']"); $this->assertEquals('public $foo = [\'bar\' => \'baz\'];' . "\n", $generator->generate($prop)); } } <file_sep><?php class MyCollection extends phootwork\collection\AbstractCollection implements phootwork\collection\Collection { } <file_sep><?php namespace gossi\codegen\tests\fixtures; class HelloWorld { public function sayHello() { return 'Hello World!'; } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\generator\comparator; use gossi\codegen\model\PhpConstant; use phootwork\lang\Comparator; /** * Default property comparator * * Orders them by lower cased first, then upper cased */ class DefaultConstantComparator implements Comparator { private $comparator; public function __construct() { $this->comparator = new DefaultUseStatementComparator(); } /** * @param PhpConstant $a * @param PhpConstant $b */ public function compare($a, $b) { return $this->comparator->compare($a->getName(), $b->getName()); } } <file_sep><?php namespace gossi\codegen\tests\parser; use gossi\codegen\model\PhpClass; use gossi\codegen\tests\parts\ValueTests; use PHPUnit\Framework\TestCase; /** * @group parser */ class ParameterParserTest extends TestCase { use ValueTests; public function testValuesFromFile() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/ValueClass.php'); $this->assertValueClass($class); } protected function assertValueClass(PhpClass $class) { $values = $class->getMethod('values'); $this->isValueString($values->getParameter('paramString')); $this->isValueInteger($values->getParameter('paramInteger')); $this->isValueFloat($values->getParameter('paramFloat')); $this->isValueBool($values->getParameter('paramBool')); $this->isValueNull($values->getParameter('paramNull')); } } <file_sep><?php namespace gossi\codegen\tests\fixtures; trait VeryDummyTrait { } <file_sep><?php namespace gossi\codegen\tests\generator; use gossi\codegen\generator\CodeFileGenerator; use gossi\codegen\generator\CodeGenerator; use gossi\codegen\generator\ModelGenerator; use gossi\codegen\model\PhpClass; use gossi\codegen\tests\Fixtures; use gossi\codegen\tests\parts\TestUtils; use PHPUnit\Framework\TestCase; /** * @group generator */ class ClassGeneratorTest extends TestCase { use TestUtils; public function testSignature() { $expected = 'class MyClass {' . "\n" . '}'; $class = PhpClass::create('MyClass'); $generator = new ModelGenerator(); $code = $generator->generate($class); $this->assertEquals($expected, $code); } public function testAbstract() { $expected = 'abstract class MyClass {' . "\n" . '}'; $class = PhpClass::create('MyClass')->setAbstract(true); $generator = new ModelGenerator(); $code = $generator->generate($class); $this->assertEquals($expected, $code); } public function testFinal() { $expected = 'final class MyClass {' . "\n" . '}'; $class = PhpClass::create('MyClass')->setFinal(true); $generator = new ModelGenerator(); $code = $generator->generate($class); $this->assertEquals($expected, $code); } public function testInterfaces() { $generator = new ModelGenerator(); $expected = 'class MyClass implements \Iterator {' . "\n" . '}'; $class = PhpClass::create('MyClass')->addInterface('\Iterator'); $this->assertEquals($expected, $generator->generate($class)); $expected = 'class MyClass implements \Iterator, \ArrayAccess {' . "\n" . '}'; $class = PhpClass::create('MyClass')->addInterface('\Iterator')->addInterface('\ArrayAccess'); $this->assertEquals($expected, $generator->generate($class)); } public function testParent() { $expected = 'class MyClass extends MyParent {' . "\n" . '}'; $class = PhpClass::create('MyClass')->setParentClassName('MyParent'); $generator = new ModelGenerator(); $code = $generator->generate($class); $this->assertEquals($expected, $code); } public function testUseStatements() { $class = new PhpClass('Foo\\Bar'); $class->addUseStatement('Bam\\Baz'); $codegen = new CodeFileGenerator(['generateDocblock' => false, 'generateEmptyDocblock' => false]); $code = $codegen->generate($class); $this->assertEquals($this->getGeneratedContent('FooBar.php'), $code); $class = new PhpClass('Foo\\Bar'); $class->addUseStatement('Bam\\Baz', 'BamBaz'); $codegen = new CodeFileGenerator(['generateDocblock' => false, 'generateEmptyDocblock' => false]); $code = $codegen->generate($class); $this->assertEquals($this->getGeneratedContent('FooBarWithAlias.php'), $code); $class = new PhpClass('Foo'); $class->addUseStatement('Bar'); $generator = new ModelGenerator(); $code = $generator->generate($class); $expected = 'class Foo {' . "\n" . '}'; $this->assertEquals($expected, $code); } public function testABClass() { $class = Fixtures::createABClass(); $modelGenerator = new ModelGenerator(); $modelCode = $modelGenerator->generate($class); $this->assertEquals($this->getGeneratedContent('ABClass.php'), $modelCode); $generator = new CodeGenerator(['generateDocblock' => false]); $code = $generator->generate($class); $this->assertEquals($modelCode, $code); $modelGenerator = new ModelGenerator(['generateDocblock' => true]); $modelCode = $modelGenerator->generate($class); $this->assertEquals($this->getGeneratedContent('ABClassWithComments.php'), $modelCode); $generator = new CodeGenerator(['generateDocblock' => true]); $code = $generator->generate($class); $this->assertEquals($modelCode, $code); } public function testRequireTraitsClass() { $class = PhpClass::create('RequireTraitsClass') ->addRequiredFile('FooBar.php') ->addRequiredFile('ABClass.php') ->addTrait('Iterator'); $generator = new ModelGenerator(); $code = $generator->generate($class); $this->assertEquals($this->getGeneratedContent('RequireTraitsClass.php'), $code); } public function testMyCollection() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/MyCollection.php'); $generator = new CodeFileGenerator(['generateDocblock' => false]); $code = $generator->generate($class); $this->assertEquals($this->getFixtureContent('MyCollection.php'), $code); } public function testMyCollection2() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/MyCollection2.php'); $generator = new CodeFileGenerator(['generateDocblock' => false]); $code = $generator->generate($class); $this->assertEquals($this->getFixtureContent('MyCollection2.php'), $code); } public function testClassWithTypes() { $class = PhpClass::fromFile(__DIR__ . '/../fixtures/ClassWithTypes.php'); $generator = new CodeFileGenerator( [ 'profile' => 'psr-2', 'generateDocblock' => false, 'generateReturnTypeHints' => true, 'generateNullableTypes' => true, 'generateScalarTypeHints' => true, ] ); $code = $generator->generate($class); $this->assertEquals($this->getFixtureContent('ClassWithTypes.php'), $code); } } <file_sep><?php namespace gossi\codegen\tests\config; use gossi\code\profiles\Profile; use gossi\codegen\config\CodeFileGeneratorConfig; use gossi\codegen\config\CodeGeneratorConfig; use gossi\codegen\generator\CodeGenerator; use gossi\docblock\Docblock; use phootwork\lang\ComparableComparator; use phootwork\lang\Comparator; use PHPUnit\Framework\TestCase; /** * @group config */ class ConfigTest extends TestCase { public function testCodeGeneratorConfigDefaults() { $config = new CodeGeneratorConfig(); $this->assertTrue($config->getGenerateDocblock()); $this->assertTrue($config->getGenerateEmptyDocblock()); $this->assertFalse($config->getGenerateScalarTypeHints()); $this->assertFalse($config->getGenerateReturnTypeHints()); $this->assertTrue($config->isSortingEnabled()); $this->assertFalse($config->isFormattingEnabled()); $this->assertTrue($config->getProfile() instanceof Profile); $this->assertEquals(CodeGenerator::SORT_USESTATEMENTS_DEFAULT, $config->getUseStatementSorting()); $this->assertEquals(CodeGenerator::SORT_CONSTANTS_DEFAULT, $config->getConstantSorting()); $this->assertEquals(CodeGenerator::SORT_PROPERTIES_DEFAULT, $config->getPropertySorting()); $this->assertEquals(CodeGenerator::SORT_METHODS_DEFAULT, $config->getMethodSorting()); } public function testCodeGeneratorConfigDisableDocblock() { $config = new CodeGeneratorConfig(['generateDocblock' => false]); $this->assertFalse($config->getGenerateDocblock()); $this->assertFalse($config->getGenerateEmptyDocblock()); $this->assertFalse($config->getGenerateScalarTypeHints()); $this->assertFalse($config->getGenerateReturnTypeHints()); } public function testCodeGeneratorConfigSetters() { $config = new CodeGeneratorConfig(); $config->setProfile('psr-2'); $this->assertTrue($config->getProfile() instanceof Profile); $config->setGenerateDocblock(false); $this->assertFalse($config->getGenerateDocblock()); $this->assertFalse($config->getGenerateEmptyDocblock()); $config->setGenerateEmptyDocblock(true); $this->assertTrue($config->getGenerateDocblock()); $this->assertTrue($config->getGenerateEmptyDocblock()); $config->setGenerateEmptyDocblock(false); $this->assertTrue($config->getGenerateDocblock()); $this->assertFalse($config->getGenerateEmptyDocblock()); $config->setGenerateReturnTypeHints(true); $this->assertTrue($config->getGenerateReturnTypeHints()); $config->setGenerateScalarTypeHints(true); $this->assertTrue($config->getGenerateScalarTypeHints()); $config->setGenerateNullableTypes(true); $this->assertTrue($config->getGenerateNullableTypes()); $config->setUseStatementSorting(false); $this->assertFalse($config->getUseStatementSorting()); $config->setConstantSorting('abc'); $this->assertEquals('abc', $config->getConstantSorting()); $config->setPropertySorting(new ComparableComparator()); $this->assertTrue($config->getPropertySorting() instanceof Comparator); $cmp = function ($a, $b) { return strcmp($a, $b); }; $config->setMethodSorting($cmp); $this->assertSame($cmp, $config->getMethodSorting()); $config->setSortingEnabled(false); $this->assertFalse($config->isSortingEnabled()); $config->setFormattingEnabled(true); $this->assertTrue($config->isFormattingEnabled()); } public function testCodeFileGeneratorConfigDefaults() { $config = new CodeFileGeneratorConfig(); $this->assertNull($config->getHeaderComment()); $this->assertNull($config->getHeaderDocblock()); $this->assertTrue($config->getBlankLineAtEnd()); $this->assertFalse($config->getDeclareStrictTypes()); } public function testCodeFileGeneratorConfigDeclareStrictTypes() { $config = new CodeFileGeneratorConfig(['declareStrictTypes' => true]); $this->assertTrue($config->getDeclareStrictTypes()); $this->assertTrue($config->getGenerateReturnTypeHints()); $this->assertTrue($config->getGenerateScalarTypeHints()); } public function testCodeFileGeneratorConfigSetters() { $config = new CodeFileGeneratorConfig(); $docblock = new Docblock(); $this->assertSame($docblock, $config->setHeaderDocblock($docblock)->getHeaderDocblock()); $this->assertFalse($config->setBlankLineAtEnd(false)->getBlankLineAtEnd()); $this->assertTrue($config->setDeclareStrictTypes(true)->getDeclareStrictTypes()); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\parser; use gossi\codegen\parser\visitor\ParserVisitorInterface; use phootwork\collection\Set; use phootwork\file\exception\FileNotFoundException; use phootwork\file\File; use PhpParser\Node; use PhpParser\NodeTraverser; use PhpParser\NodeVisitorAbstract; use PhpParser\Parser; class FileParser extends NodeVisitorAbstract { private $visitors; private $filename; public function __construct($filename) { $this->filename = $filename; $this->visitors = new Set(); } public function addVisitor(ParserVisitorInterface $visitor) { $this->visitors->add($visitor); return $this; } public function removeVisitor(ParserVisitorInterface $visitor) { $this->visitors->remove($visitor); return $this; } public function hasVisitor(ParserVisitorInterface $visitor): bool { return $this->visitors->contains($visitor); } /** * @throws FileNotFoundException */ public function parse() { $file = new File($this->filename); if (!$file->exists()) { throw new FileNotFoundException(sprintf('File (%s) does not exist.', $this->filename)); } $parser = $this->getParser(); $traverser = new NodeTraverser(); $traverser->addVisitor($this); $traverser->traverse($parser->parse($file->read())); } private function getParser(): Parser { $factory = new \PhpParser\ParserFactory(); return $factory->create(\PhpParser\ParserFactory::PREFER_PHP7); } public function enterNode(Node $node) { foreach ($this->visitors as $visitor) { switch ($node->getType()) { case 'Stmt_Namespace': $visitor->visitNamespace($node); break; case 'Stmt_UseUse': $visitor->visitUseStatement($node); break; case 'Stmt_Class': $visitor->visitStruct($node); $visitor->visitClass($node); break; case 'Stmt_Interface': $visitor->visitStruct($node); $visitor->visitInterface($node); break; case 'Stmt_Trait': $visitor->visitStruct($node); $visitor->visitTrait($node); break; case 'Stmt_TraitUse': $visitor->visitTraitUse($node); break; case 'Stmt_ClassConst': $visitor->visitConstants($node); break; case 'Stmt_Property': $visitor->visitProperty($node); break; case 'Stmt_ClassMethod': $visitor->visitMethod($node); break; } } } } <file_sep><?php namespace gossi\codegen\tests\fixtures; class ClassWithValues { private $arr = ['papagei' => ['name' => 'Mr. <NAME>']]; private $bar = false; private $baz = true; private $furz = 'bumbesje'; private $magic = __LINE__; private $null = null; private $number = 5; public function foo($bar = null, $baz = false) { } } <file_sep><?php namespace gossi\codegen\tests\generator; use gossi\codegen\generator\ModelGenerator; use gossi\codegen\model\PhpMethod; use gossi\codegen\model\PhpParameter; use PHPUnit\Framework\TestCase; /** * @group generator */ class MethodGeneratorTest extends TestCase { public function testPublic() { $expected = "public function foo() {\n}\n"; $method = PhpMethod::create('foo'); $generator = new ModelGenerator(); $code = $generator->generate($method); $this->assertEquals($expected, $code); } public function testProtected() { $expected = "protected function foo() {\n}\n"; $method = PhpMethod::create('foo')->setVisibility(PhpMethod::VISIBILITY_PROTECTED); $generator = new ModelGenerator(); $code = $generator->generate($method); $this->assertEquals($expected, $code); } public function testPrivate() { $expected = "private function foo() {\n}\n"; $method = PhpMethod::create('foo')->setVisibility(PhpMethod::VISIBILITY_PRIVATE); $generator = new ModelGenerator(); $code = $generator->generate($method); $this->assertEquals($expected, $code); } public function testStatic() { $expected = "public static function foo() {\n}\n"; $method = PhpMethod::create('foo')->setStatic(true); $generator = new ModelGenerator(); $code = $generator->generate($method); $this->assertEquals($expected, $code); } public function testAbstract() { $expected = "abstract public function foo();\n"; $method = PhpMethod::create('foo')->setAbstract(true); $generator = new ModelGenerator(); $code = $generator->generate($method); $this->assertEquals($expected, $code); } public function testReferenceReturned() { $expected = "public function & foo() {\n}\n"; $method = PhpMethod::create('foo')->setReferenceReturned(true); $generator = new ModelGenerator(); $code = $generator->generate($method); $this->assertEquals($expected, $code); } public function testParameters() { $generator = new ModelGenerator(); $method = PhpMethod::create('foo')->addParameter(PhpParameter::create('bar')); $this->assertEquals("public function foo(\$bar) {\n}\n", $generator->generate($method)); $method = PhpMethod::create('foo') ->addParameter(PhpParameter::create('bar')) ->addParameter(PhpParameter::create('baz')); $this->assertEquals("public function foo(\$bar, \$baz) {\n}\n", $generator->generate($method)); } public function testReturnType() { $expected = "public function foo(): int {\n}\n"; $generator = new ModelGenerator(['generateReturnTypeHints' => true, 'generateDocblock' => false]); $method = PhpMethod::create('foo')->addType('int'); $this->assertEquals($expected, $generator->generate($method)); } public function testNullableReturnType() { $expected = "public function foo(): ?int {\n}\n"; $generator = new ModelGenerator([ 'generateReturnTypeHints' => true, 'generateDocblock' => false, 'generateNullableTypes' => true ]); $method = PhpMethod::create('foo')->addType('int')->setNullable(true); $this->assertEquals($expected, $generator->generate($method)); } } <file_sep><?php declare(strict_types=1); namespace gossi\codegen\model; /** * Represents models that can have traits * * @author <NAME> */ interface TraitsInterface { /** * Adds a trait. * * If the trait is passed as PhpTrait object, * the trait is also added as use statement. * * @param PhpTrait|string $trait trait or qualified name * @return $this */ public function addTrait($trait); /** * Returns a collection of traits * * @return string[] */ public function getTraits(); /** * Checks whether a trait exists * * @param PhpTrait|string $trait * @return bool `true` if it exists and `false` if not */ public function hasTrait($trait): bool; /** * Removes a trait. * * If the trait is passed as PhpTrait object, * the trait is also removed from use statements. * * @param PhpTrait|string $trait trait or qualified name * @return $this */ public function removeTrait($trait); /** * Sets a collection of traits * * @param PhpTrait[] $traits * @return $this */ public function setTraits(array $traits); } <file_sep><?php namespace gossi\codegen\tests\fixtures; class ClassWithConstants { const BAR = self::FOO; const FOO = 'bar'; const NMBR = 300; }
b8b4104865765239daee37aa390a1bcb92dbd6d6
[ "Markdown", "PHP", "reStructuredText", "Shell" ]
106
reStructuredText
sidux/php-code-generator
763b8b824ab850fe6986df93fb0c520d8dac3291
381e4b0d310970f44d373ce4cacc7ec626aa96d8
refs/heads/main
<repo_name>rotcrus/spaghetticoders<file_sep>/risk-assessment_v0.1.md - Risk-Assessment_v0.1 # Μέλη ομάδας ```  1058120 ΜΑΡΙΟΣ ΚΑΡΙΠΗΣ  1041729 ΓΕΩΡΓΙΟΣ ΔΑΒΟΥΛΟΣ  1054372 ΤΖΟΥΔΑΣ ΠΑΝΑΓΙΩΤΗΣ  1040641 ΕΥΑΓΓΕΛΟΣ ΔΗΜΟΠΟΥΛΟΣ  1054414 ΑΝΔΡΙΑΝΟΣ ΛΟΥΓΚΙA ``` Risk-assessment editor : _Ανδριανός Λούγκια_ , _Καρίπης Μάριος_ **Εργαλεία :** Microsoft word , Microsoft Excel ## Διαχείριση κινδύνου Η διαχείριση κινδύνου, που είναι ένα σημαντικό κομμάτι της διαχείρισης του έργου, αφορά τον εντοπισμό πιθανών ρίσκων νωρίς, ώστε να μπορούμε να αποφασίσουμε πώς να τα χειριστούμε. **Ρίσκο** για το έργο μας καθορίζουμε οτιδήποτε απρόσμενο μπορεί να συμβεί που μπορεί να επηρεάσει θετικά ή αρνητικά το έργο που αναλαμβάνουμε. Μας δίνει επίσης τη δυνατότητα να παρακολουθούμε τους κινδύνους με την πάροδο του χρόνου για να μπορούμε να δούμε αν και πώς αλλάζουν. Για τα ρίσκα αυτά μας ενδιαφέρει καταρχάς το ποιόν τους και η επίδραση που θα έχουν στη δουλειά μας, το πότε πιθανολογούμε να συμβούν, η πιθανότητα να προκύψουν, το αντίκτυπό τους πάνω στο έργο μας καθώς και τους παράγοντες που μπορεί να τα ενεργοποιήσουν. **(εικόνα 1)** Εδώ αξιοποιούμε τα λεγόμενα Risk-Registers **(εικόνα 1)** τα οποία στοχεύουν στην αναγνώριση, καταχώρηση και παρακολούθηση πιθανών ρίσκων για το έργο μας. Για τα περισσότερα μικρά έργα, η ευθύνη για τη δημιουργία του Risk-Register βαρύνει τον διαχειριστή του έργου. Αυτό δεν σημαίνει ότι ο διαχειριστής κινδύνου (συνήθως σε μεγάλα έργα/εταιρίες) ή ο διαχειριστής έργου είναι υπεύθυνος για τον εντοπισμό ή τη λήψη μέτρων έναντι όλων των κινδύνων. Όλοι στην ομάδα του έργου και ενδεχομένως επηρεασμένοι από την έκβαση του έργου θα πρέπει να βοηθήσουν στον εντοπισμό και την αξιολόγηση των κινδύνων. Για παράδειγμα, ο πελάτης ή ο χορηγός μπορεί να εντοπίσει ένα πιθανό πρόβλημα που κανείς στην ομάδα δεν γνώριζε. Κάθε φορά που κάποιος εντοπίζει κάτι που μπορεί να έχει αντίκτυπο στην εργασία μας, θα πρέπει να αξιολογηθεί από την ομάδα και να καταγραφεί στον Risk-Register. Αξιολόγηση Ρίσκων Συγκεκριμένα, όταν εντοπίζεται για πρώτη φορά ένας κίνδυνος, μπορούμε να τον θεωρήσουμε τόσο απίθανο ώστε να μην σπαταλήσουμε πόρους ώστε να κάνουμε κάτι για αυτόν. Αλλά, τι γίνεται αν, καθώς προχωρά το έργο, ο κίνδυνος γίνεται πολύ πιο πιθανό να συμβεί; Παρακολουθώντας τους κινδύνους μπορούμε να παρατηρήσουμε τέτοιες αλλαγές αρκετά νωρίς για να λάβουμε μέτρα με τη χρήση ενός μητρώου ρίσκου **(εικόνα 2)**. **(εικόνα 2)** Μερικοί κίνδυνοι που μπορεί να φαίνονται μικροί ή απίθανοι, στην αρχή, ενέχουν την πιθανότητα να διογκωθούν και να επηρεάσουν το έργο μας αργότερα, όπως: ➢ Απώλεια δεδομένων (από χρήση τοπικών μέσων αποθήκευσης) ➢ Έλλειψη ασφάλειας (παραβίαση ή κλοπή υλικού) ➢ Νομικοί κίνδυνοι (αλλαγές στη νομοθεσία που επηρεάζουν το έργο) ➢ Καταστροφικό συμβάν (πυρκαγιά, πλημμύρες, ζημιές από καταιγίδες) ➢ Διαταραχές στη διαδικασία παραγωγής Βάση του συγκεκριμένου έργου, καταλήξαμε στα δικά μας πρότυπα , Risk-Registers γιατί, καθώς τo έργο μας θα προχωρά και θα γίνεται εκτενέστερο, πιο μακροπρόθεσμο και περίπλοκο, θα γίνεται όλο και πιο δύσκολο να διατηθεί η εποπτεία όλων των κινδύνων. Εάν οι κίνδυνοι δεν παρακολουθούνται σε σταθερή βάση με τακτικούς επανελέγχους, μπορεί η παραμικρή λεπτομέρεια που θα διαφύγει της προσοχής μας να αποτελέσει εμπόδιο. *Risk-Register: a) Μοναδικός κωδικός για καθε ρίσκο (για γρήγορη αναφορά/ταυτοποίηση) b) Τίτλος/περιγραφή ρίσκου c) Κατηγοριοποίηση ρίσκων^1 d) Πιθανότητα e) Αντίκτυπος f) Προτεραιότητα g) Προσέγγιση (θα παρακολουθούμε το ρίσκο, θα προσπαθούμε να το μετριάσουμε, να το αποφύγουμε κ.λπ.) h) Δράση (εάν σκοπεύουμε να μετριάσουμε ή να αποφύγουμε τον κίνδυνο, ποια είναι τα βήματα που εμπλέκονται και πότε θα συμβούν) i) Υπεύθυνος για την επίβλεψη ή τον μετριασμό του κινδύνου j) Σχόλια (^1) Ύστερα από έρευνα καταλήξαμε στις εξής **κατηγορίες** που μπορεί να εμπίπτει ένα **ρίσκο:** 1. ΕΠΙΤΕΛΙΚΌ 2. ΠΡΟΣΑΝΑΤΟΛΙΣΜΟΎ ΤΟΥ ΕΡΓΟΥ 3. ΔΙΑΧΕΙΡΙΣΗΣ ΚΟΣΤΟΥΣ 4. ΔΙΑΧΕΙΡΙΣΗΣ ΚΡΙΣΙΜΩΝ ΑΛΛΑΓΩΝ 5. ΣΥΝΕΡΓΑΤΙΚΟ 6. ΕΠΙΚΟΙΝΩΝΙΑΚΟ 7. ΠΟΡΩΝ & ΕΡΓΑΤΙΚΟΥ ΔΥΝΑΜΙΚΟΥ 8. ΑΡΧΙΤΕΚΤΟΝΙΚΟ 9. ΣΧΕΔΙΑΣΤΙΚΟ 10. ΤΕΧΝΙΚΟ 11. ΕΝΣΩΜΆΤΩΣΗΣ ΤΟΥ ΈΡΓΟΥ ΣΤΗΝ ΕΠΙΧΕΙΡΗΣΗ ΤΟΥ ΠΕΛΑΤΗ 12. ΑΠΑΙΤΗΣΕΩΝ 13. ΑΠΟΦΑΣΕΩΝ & ΛΥΣΕΩΝ 14. ΣΥΜΒΟΛΑΙΟΓΡΑΦΙΚΟ 15. ΑΔΕΙΟΔΌΤΙΚΌ 16. ΕΞΟΥΣΙΟΔΟΤΙΚΌ 17. ΕΞΩΤΕΡΙΚΌ 18. ΔΙΑΧΕΙΡΗΣΗΣ PROJECT 19. ΑΠΟΔΟΧΗΣ ΑΠΟ ΤΟ ΧΡΗΣΤΗ 20. ΕΜΠΟΡΙΚΌ Παρακάτω παρατίθενται κάποια βασικά ρίσκα που συνδέονται με την ανάληψη και την αποπεράτωση του έργου. **Τίτλος ρίσκου: Καθυστερήσεις έγκρισης κονδυλίων** **Κωδικος Ρίσκου:** 0103 ``` Υπεύθυνος αντιμετώπισης: Λούγκια Α. ``` ``` Κατηγορία : ΑΔΕΙΕΣ ``` ``` Προτεραιότητα: ``` **Περιγραφή κινδύνου:** Ρίσκο καθυστέρησης οικονομικών εγκρίσεων για την απελευθέρωση χρηματοδότησης του έργου **Ημερομηνία: 20/03/21 Σχόλια:** ΟΙ ΣΧΕΤΙΚΕΣ ΗΜ/ΝΙΕΣ ΑΝΑΓΡΑΦΟΝΤΑΙ ΣΤΗ ΣΥΜΒΑΣΗ ΤΟΥ ΕΡΓΟΥ **Αντίκτυπος: Πιθανότητα:** **Προσέγγιση:** ΠΑΡΑΚΟΛΟΥΘΟΥΜΕ ΤΟ ΡΙΣΚΟ ΜΕ ΤΗ ΒΟΗΘΕΙΑ ΛΟΓΙΣΤΗ **Δράση:** ΑΜΕΣΗ ΕΠΙΚΟΙΝΩΝΙΑ ΜΕ ΤΗΝ ΑΡΜΟΔΙΑ ΥΠΗΡΕΣΙΑ ΣΕ ΠΕΡΙΠΤΩΣΗ ΚΡΑΤΙΚΏΝ/ΕΥΡΩΠΑΪΚΩΝ ΚΟΝΔΥΛΙΩΝ ή ΑΠΕΥΘΕΙΑΣ ΜΕ ΤΟΝ ΕΡΓΟΔΟΤΗ ΚΑΙ ΤΟΝ ΟΙΚΟΝΟΜΙΚΟ ΥΠΕΥΘΥΝΟ ΤΟΥ ΔΣ ``` πολύ υψηλή υψηλή ``` ``` 1 2 3 4 1 2 3 4 ``` ``` αυξημένη κανονική ``` **Τίτλος ρίσκου: Μη ακριβής πρόβλεψη κόστους** **Κωδικος Ρίσκου:** 0011 ``` Υπεύθυνος αντιμετώπισης: Λούγκια Α. ``` ``` Κατηγορία : ΔΙΑΧΕΙΡΗΣΗ ΚΟΣΤΟΥΣ ``` ``` Προτεραιότητα: ``` **Περιγραφή κινδύνου:** Οι προβλέψεις για ορισμένα έξοδα ξεπερνούν το αναμενόμενο **Ημερομηνία: 20/03/21 Σχόλια:** **Αντίκτυπος: Πιθανότητα:** **Προσέγγιση:** ΠΡΟΣΠΑΘΕΙΑ ΕΞΙΣΟΡΡΟΠΗΣΗΣ ΤΩΝ ΕΞΟΔΩΝ ΑΠΌ ΑΛΛΟΥΣ ΤΟΜΕΙΣ ΜΕ ΑΝΤΙΜΕΤΡΑ, ΕΒΔΟΜΑΔΙΑΙΟΣ ΟΙΚΟΝΟΜΙΚΟΣ ΕΛΕΓΧΟΣ **Δράση:** ΣΕ ΠΕΡΙΠΤΩΣΗ ΠΡΟΒΛΕΨΗΣ ΑΔΥΝΑΜΙΑΣ ΣΥΝΕΧΙΣΗΣ ΤΟΥ ΕΡΓΟΥ ΠΡΟΤΕΙΝΕΤΑΙ Η ΑΠΕΥΘΥΝΣΗ ΣΕ ΧΟΡΗΓΟΥΣ Ή ΚΡΑΤΙΚΑ ΠΡΟΓΡΑΜΜΑΤΑ ΣΤΗΡΙΞΗΣ ``` πολύ υψηλή υψηλή ``` ``` 1 2 3 4 1 2 3 4 ``` ``` αυξημένη κανονική ``` **Τίτλος ρίσκου: Απόρριψη του προτοτύπου από τον χρήστη** **Κωδικος Ρίσκου:** 0119 ``` Υπεύθυνος αντιμετώπισης: Τζούδας Π. ``` ``` Κατηγορία : ΑΠΟΔΟΧΗ ΧΡΗΣΤΗ ``` ``` Προτεραιότητα: ``` **Περιγραφή κινδύνου:** Το προτότυπο απορρίπτεται ή χρίζει σοβαρής ανακατασκευής από τον χρήστη **Ημερομηνία: 20/03/21 Σχόλια:** **Αντίκτυπος: Πιθανότητα:** **Προσέγγιση:** ΠΑΡΑΘΕΤΟΥΜΕ ΠΟΛΛΑΠΛΑ ΠΡΩΤΟΤΥΠΑ ΣΤΟΥΣ ΧΡΗΣΤΕΣ **Δράση:** ΕΠΑΝΑΚΑΤΑΣΚΕΥΗ ΜΕΡΟΥΣ ΤΟΥ ΕΡΓΟΥ ΒΑΣΗ ΤΗΣ ΚΡΙΤΙΚΗΣ ΑΠΌ ΤΟΝ ΧΡΗΣΤΗ ``` πολύ υψηλή υψηλή ``` ``` 1 2 3 4 1 2 3 4 ``` ``` αυξημένη κανονική ``` **Τίτλος ρίσκου: Υπερβολικές αλλαγές στο έργο** **Κωδικος Ρίσκου:** 0013 ``` Υπεύθυνος αντιμετώπισης: Δάβουλος Γ. ``` ``` Κατηγορία : ΔΙΑΧΕΙΡΙΣΗ ΚΡΙΣΙΜΩΝ ΑΛΛΑΓΩΝ ``` ``` Προτεραιότητα: ``` **Περιγραφή κινδύνου:** Μεγάλος αριθμός νέων απαιτήσεων μπορεί να αυξήσει την πολυπλοκότητα του έργου και να αποσπάσει σημαντικούς πόρους. **Ημερομηνία: 20/03/21 Σχόλια:** **Αντίκτυπος: Πιθανότητα:** **Προσέγγιση:** ΠΡΟΣΠΑΘΟΥΜΕ ΝΑ ΑΠΟΦΥΓΟΥΜΕ ΤΟ ΡΙΣΚΟ ΜΕ ΣΩΣΤΟ ΠΡΟΓΡΑΜΜΑΤΙΣΜΌ ΚΑΙ ΚΑΛΗ ΑΡΧΙΚΗ ΕΠΙΚΟΙΝΩΝΙΑ ΜΕ ΤΟΝ ΠΕΛΑΤΗ **Δράση:** ΕΓΚΥΡΗ ΕΝΗΜΕΡΩΣΗ ΤΙΣ ΟΜΑΔΑΣ ΓΙΑ ΤΙΣ ΝΕΕΣ ΑΛΛΑΓΕΣ ΚΑΙ ΕΠΑΝΑΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ ΤΟΥ ΧΡΟΝΟΥ ΠΕΡΑΤΩΣΗΣ ΤΩΝ ΝΕΩΝ ΔΙΕΡΓΑΣΙΩΝ ``` πολύ υψηλή υψηλή ``` ``` 1 2 3 4 1 2 3 4 ``` ``` αυξημένη κανονική ``` <file_sep>/Use-cases-v0.2.md [Use-cases-v0.2.pdf](https://github.com/rotcrus/spaghetticoders/files/6510591/Use-cases-v0.2.pdf) <file_sep>/Team-Risk-Assessment-v0.1 .md - Team-Risk-Assessment-v0.1 **ΜΕΛΗ ΟΜΑΔΑΣ** ```  1058120 ΜΑΡΙΟΣ ΚΑΡΙΠΗΣ  1041729 ΓΕΩΡΓΙΟΣ ΔΑΒΟΥΛΟΣ  1054372 ΤΖΟΥΔΑΣ ΠΑΝΑΓΙΩΤΗΣ  1040641 ΕΥΑΓΓΕΛΟΣ ΔΗΜΟΠΟΥΛΟΣ  1054414 ΑΝΔΡΙΑΝΟΣ ΛΟΥΓΚΙA ``` **Risk-assessment editor :** Ανδριανός Λούγκια , Καρίπης Μάριος **Εργαλεία :** Microsoft word , Microsoft Excel , Το Project μας ονομάζεται “smart drive “ και σε αυτό το τεχνικό κείμενο θα αναλύσουμε τα ρίσκα-κίνδυνους της ομάδας. Η διαχείριση κίνδυνου της ομάδας αποτελεί ένα πολύ σημαντικό κομμάτι της διαχείρισης του Project. Αφορά τον εντοπισμό πιθανών ρίσκων νωρίς ώστε να μπορούμε να αποφασίσουμε πως να τα χειριστούμε. Καθορίζουμε ως ρίσκο για το Project οτιδήποτε απρόσμενο μπορεί να συμβεί το οποίο θα επηρεάσει θετικά η αρνητικά το Project που υλοποιούμε. Επιπλέον μας δίνεται η δυνατότητα να παρακολουθούμε τους κίνδυνους με την πάροδο του χρόνου για να μπορούμε να δούμε αν και πως αλλάζουν. Για αυτά τα ρίσκα μας ενδιαφέρει η επίδραση που θα έχουν στην δουλειά μας, το ποτέ πιθανολογούμε να συμβούν, η πιθανότητα να προκύψουν το αντίκτυπο τους πάνω στο Project καθώς και τους παράγοντες οι οποίοι μπορούν να τους ενεργοποιήσουν. Για την καλύτερη αντιμετώπιση των πιθανών κίνδυνων δημιουργήσαμε ένα πρότυπο , δηλαδή μια φόρμα αναφοράς (εικόνα 1 ).Έτσι είμαστε σε θέση να αντιμετωπίζουμε πολύ γρηγορά το οποιοδήποτε ρίσκο- κίνδυνο μπορεί να βρεθεί. ``` Τίτλος ρίσκου: ``` ``` Ημερομηνία: Σχόλια: ``` ``` Αντίκτυπος: Πιθανότητα: ``` ``` Προσέγγιση: ``` ``` Δράση: ``` ``` Κωδικος Ρίσκου: Υπεύθυνος αντιμετώπισης: Κατηγορία : Προτεραιότητα: ``` ``` Περιγραφή κινδύνου: ΑΠΟΧΩΡΗΣΗ ΜΕΛΛΟΥΣ ``` ``` πολύ υψηλή υψηλή ``` ``` 1 2 3 4 1 2 3 4 ``` ``` αυξημένη κανονική ``` Εικόνα 1 Σχεδιάσαμε ένα risk matrix (εικόνα 2) με το οποίο έχουμε μετρήσει τους κίνδυνους και τους έχουμε κατηγοριοποίηση ανάλογα με το αντίκτυπο που έχουν σε συνδυασμό με την πιθανότητα που υπάρχει να προκύψουν. Τέλος έχουμε βγάλει τα αντίστοιχα αποτελέσματα τα οποία μας δείχνουν τι προτεραιότητα έχουν οι κίνδυνοι αυτοί. Εικόνα 2 Πράσινο χρώμα κανονική Κίτρινο χρώμα αυξημένη Πορτοκαλί χρώμα υψηλή Κοκκίνο χρώμα πολύ υψηλή **Σύμφωνα με την αναφορά της εικόνας 1 αναλύσαμε 5 ομάδες κίνδυνων- ρίσκων** 1) ## 2) ``` Τίτλος ρίσκου: Αποχώρηση μελλους ``` ``` Ημερομηνία: 20/03/2021 Σχόλια: ``` ``` Αντίκτυπος: Πιθανότητα: ``` ``` Προσέγγιση: ΣΥΧΝΗ ΕΠΙΚΟΙΝΩΝΙΑ ``` ``` Δράση: ΕΓΚΥΡΗ ΕΝΗΜΕΡΩΣΗ ΤΙΣ ΟΜΑΔΑΣ ΓΙΑ ΤΙΣ ΝΕΕΣ ΑΛΛΑΓΕΣ ΚΑΙ ΑΝΑΘΕΣΗ ΝΕΩΝ ΑΡΜΟΔΙΩΤΙΤΩΝ ``` ``` Κωδικος Ρίσκου: 0001 ``` ``` Υπεύθυνος αντιμετώπισης: Δάβουλος Γ. ``` ``` Κατηγορία : ΔΙΑΧΕΙΡΙΣΗ ΚΡΙΣΙΜΩΝ ΑΛΛΑΓΩΝ ``` ``` Προτεραιότητα: ``` ``` Περιγραφή κινδύνου: ΑΠΟΧΩΡΗΣΗ ΜΕΛΛΟΥΣ ``` ``` πολύ υψηλή υψηλή ``` ``` 1 2 3 4 1 2 3 4 ``` ``` αυξημένη κανονική ``` ``` Τίτλος ρίσκου: Διαφωνία στον καταμερισμό εργασίας ``` ``` Ημερομηνία: 20/03/2021 Σχόλια: ``` ``` Αντίκτυπος: Πιθανότητα: ``` ``` Προσέγγιση: ΕΠΙΚΟΙΝΩΝΙΑ ΜΕ ΌΛΑ ΤΑ ΜΕΛΗ ΤΗΣ ΟΜΑΔΑΣ ΚΑΙ ΔΗΜΟΚΡΑΤΙΚΗ ΕΠΙΛΟΓΗ ΠΟΣΤΩΝ ``` ``` Δράση: ΕΚΤΑΚΤΗ ΣΥΝΑΝΤΗΣΗ ΚΑΙ ΣΥΖΗΤΗΣΗ ΚΑΙ ΝΕΟΣ ΔΙΑΧΩΡΙΣΜΟΣ ΑΡΜΟΔΙΩΤΙΤΩΝ ``` ``` Κωδικος Ρίσκου: 0005 ``` ``` Υπεύθυνος αντιμετώπισης: Δάβουλος Γ. ``` ``` Κατηγορία : ΕΠΙΚΟΙΝΩΝΙΑ ``` ``` Προτεραιότητα: ``` ``` Περιγραφή κινδύνου: ΔΙΑΦΩΝΙΑ ΣΤΟΝ ΚΑΤΑΜΕΡΙΣΜΟ ΕΡΓΑΣΙΑΣ ``` ``` πολύ υψηλή υψηλή ``` ``` 1 2 3 4 1 2 3 4 ``` ``` αυξημένη κανονική ``` ## 3) ## 4) ``` Τίτλος ρίσκου: Διαφωνίες σε κρίσημα σημεία ``` ``` Ημερομηνία: 19/03/2021 Σχόλια: ``` ``` Αντίκτυπος: Πιθανότητα: ``` ``` Προσέγγιση: ΣΥΧΝΕΣ ΣΥΝΑΝΤΗΣΕΙΣ ``` ``` Δράση: ΔΙΑΛΟΓΟΣ ΜΕΤΑΞΥ ΤΩΝ ΜΕΛΩΝ ΏΣΤΕ ΝΑ ΒΓΕΙ ΜΙΑ ΚΟΙΝΗ ΑΠΟΦΑΣΗ ``` ``` Κωδικος Ρίσκου: 0003 ``` ``` Υπεύθυνος αντιμετώπισης: Δάβουλος Γ. ``` ``` Κατηγορία : ΟΡΓΑΝΩΣΗ ``` ``` Προτεραιότητα: ``` ``` Περιγραφή κινδύνου: ΔΙΑΦΩΝΙΑ ΣΤΟΝ ΤΡΟΠΟ ΑΝΤΙΜΕΤΟΠΙΣΗΣ ΕΝΩΣ ΘΕΜΑΤΟΣ ``` ``` πολύ υψηλή υψηλή ``` ``` 1 2 3 4 1 2 3 4 ``` ``` αυξημένη κανονική ``` ## 5) ``` Τίτλος ρίσκου: 'Ελληψη υποδομών ``` ``` Ημερομηνία: 20/03/2021 Σχόλια: ``` ``` Αντίκτυπος: Πιθανότητα: ``` ``` Προσέγγιση: ΣΥΧΝΟΣ ΕΛΕΝΧΟΣ ΕΞΟΠΛΙΣΜΟΥ ``` ``` Δράση: ΠΑΡΑΧΩΡΗΣΗ ΥΠΟΛΟΓΙΣΤΗ ΑΠΌ ΆΛΛΟ ΜΕΛΛΟΣ ΤΗΣ ΟΜΑΔΑΣ ``` ``` Κωδικος Ρίσκου: 0004 ``` ``` Υπεύθυνος αντιμετώπισης: Δάβουλος Γ. ``` ``` Κατηγορία : ΤΕΧΝΙΚΑ ``` ``` Προτεραιότητα: ``` ``` Περιγραφή κινδύνου: ΑΔΥΝΑΜΙΑ ΧΡΗΣΗΣ ΥΠΟΛΟΓΙΣΤΗ ΜΕΛΛΟΥΣ ``` ``` πολύ υψηλή υψηλή ``` ``` 1 2 3 4 1 2 3 4 ``` ``` αυξημένη κανονική ``` <file_sep>/smartdrive.py import tkinter as tk import requests HEIGHT = 500 WIDTH = 600 def test_function(entry): print("This is the entry:", entry) root = tk.Tk() canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH) canvas.pack() background_image = tk.PhotoImage(file='landscape.png') background_label = tk.Label(root, image=background_image) background_label.place(relwidth=1, relheight=1) frame = tk.Frame(root, bg='#80c1ff', bd=5) frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n') entry = tk.Entry(frame, font=40) entry.place(relwidth=0.65, relheight=1) button = tk.Button(frame, text="Calculate Cost", font=40, command=lambda: test_function(entry.get())) button.place(relx=0.7, relheight=1, relwidth=0.3) fuel_button = tk.Button(frame, text ="Enter Fuel Type",font=40 , fg ="green") #fuel_button.place(rely=2,relx=0.7, relheight=1, relwidth=0.3) moto_button = tk.Button(frame, text ="Enter Moto Type", font=40 , fg ="red") #moto_button.place(rely=3,relx=0.7, relheight=1, relwidth=0.3) destination_button = tk.Button(frame, text ="Enter Destination",font=40 , fg ="green") #destination_button.place(rely=4,relx=0.7, relheight=1, relwidth=0.3) #lower_frame = tk.Frame(root, bg='#80c1ff', bd=10) #lower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.7, anchor='n') #label = tk.Label(lower_frame) #label.place(relwidth=1, relheight=1) root.mainloop()<file_sep>/README.md # Προγραμματισμός Διεπαφής Χρήστη για την εφαρμογή Smart Trip Planner! Η Διεπαφή είναι ακόμα σε πιλοτικό στάδιο, και θα παραμείνει με κουμπια "dummy", μέχρι να αποφασιστεί το πλήρες έυρος των λειτουργιών, που θα έχει ο χρήστης διαθέσιμες. ================================================================= Το framework tkinter, επιλέχθηκε έναντι άλλων, κυρίως για το καλογραμμένο documentation, και την πλήρη συμβατότητα με εκδόσεις python 3.7 + ================================================================== <file_sep>/Project_Plan-v0.1 .md ## SMART TRIP PLANNER # PROJECT # Team-plan-v0.1 ## ΟΝΟΜΑΤΕΠΩΝΥΜΟ ΑΜ - Δάβουλος Γιώργος - Δημόπουλος Βαγγέλης - Καρίπης Μάριος - Λούγκια Ανδριανός - Τζούδας Παναγιώτης Σύνθεση ομάδας ``` Ονοματεπώνυμο ΑΜ Έτος Δάβουλος Γιώργος 1041729 7 ο^ Δημόπουλος Βαγγέλης 1040641 11 ο Καρίπης Μάριος 1058120 5 ο^ Λούγκια Ανδριανός 1054414 5 ο^ Τζούδας Παναγιώτης 1054372 5 ο^ ``` Μέθοδος εργασίας της ομάδας Αποφασίσαμε να δουλέψουμε σύμφωνα με τη μέθοδο Scrum του μοντέλου Agile. Η συγκεκριμένη μέθοδος ταιριάζει στα χαρακτηριστικά που έχει το project μας αφού δεν έχουμε ένα παραδοτέο, αλλά πολλά. Επίσης, τα τεχνικά κείμενα του κάθε παραδοτέου ανανεώνονται μέσα από τα διάφορα versions, πράγμα που έρχεται να εξυπηρετήσει η εξελικτική ανάπτυξη – επαναληπτική παράδοση τμημάτων του έργου. Από την άλλη, η συγκεκριμένη μέθοδος πρόκειται να μας εξυπηρετήσει και ως ομάδα, αφού δεν έχουμε ξαναδουλέψει σε κάποιο project με παρόμοια χαρακτηριστικά. Πράγμα το οποίο αντιμετωπίζει η συγκεκριμένη μέθοδος αφού στα διάφορα meetings θα έχουμε τη δυνατότητα μέσω του feedback να κατακτήσουμε καλύτερη συνεννόηση αλλά και να αντιληφθούμε πράγματα τα οποία ίσως να μην έχουμε κατανοήσει από την αρχή. Ειδικά για το project μας και τις συνθήκες ανάπτυξης τμημάτων του έργου ορίζουμε τα εξής: - 6 sprint cycles κι 6 milestones (όσα τα παραδοτέα). - Sprints διάρκειας 17-18 ημερών (η χρονική διάρκεια μεταξύ κάθε παραδοτέου). - Συνολικός αριθμός meetings ανά sprint cycle: 5 (2 meetings τη βδομάδα, τα οποία θα ορίζονται «αλυσιδωτά», το ένα μετά το πέρας του άλλου). - Scrum Master: Δάβουλος Γιώργος (ταυτόχρονα θα είναι και developer, part-time Scrum Master). - Development Team: Δάβουλος Γιώργος, Δημόπουλος Βαγγέλης, Καρίπης Μάριος, Λούγκια Ανδριανός, Τζούδας Παναγιώτης. Αρχικός χρονοπρογραμματισμός Παρακάτω φαίνεται μέσω του Gantt chart ο αρχικός χρονοπρογραμματισμός του project για την ομάδα μας, σύμφωνα και με όσα εξηγήθηκαν παραπάνω... ...και το Pert chart Βασικά εργαλεία - Editing: Συγγραφή κι επεξεργασία τεχνικών κειμένων σε _Word_. - OO_lang: Ανάπτυξη έργου σε _Python_ με αντικειμενοστραφή προσανατολισμό. - IDEs: Σύνταξη του κώδικα σε _Visual Studio Code_ και σε _Pycharm_. - Charts & Diagrams: _Visual Paradigm_. Ρόλοι στο κείμενο ``` Editor: Τζούδας Παναγιώτης ``` ``` Contributor: Δημόπουλος Βαγγέλης ``` ``` Peer reviewers: Δάβουλος Γιώργος, Καρίπης Μάριος, Λούγκια Ανδριανός ``` <file_sep>/project description v0.1.md - Project Description v0.1 # Μέλη ομάδας ```  1058120 ΜΑΡΙΟΣ ΚΑΡΙΠΗΣ  1041729 ΓΕΩΡΓΙΟΣ ΔΑΒΟΥΛΟΣ  1054372 ΤΖΟΥΔΑΣ ΠΑΝΑΓΙΩΤΗΣ  1040641 ΕΥΑΓΓΕΛΟΣ ΔΗΜΟΠΟΥΛΟΣ  1054414 ΑΝΔΡΙΑΝΟΣ ΛΟΥΓΚΙA ``` Project description editor : _Δάβουλος Γιώργος_ **Εργαλεία :** Microsoft word , PDF , Draw 3 D _( δημιουργία_ logo _και_ mock-up) **Εισαγωγή** Η βασική ιδέα πάνω στην οποία η ομάδα μας θα απασχοληθεί στο παρακάτω project είναι η δημιουργία μιας εφαρμογής η οποία θα υπολογίζει κάποιους παράγοντες στην μετακίνηση ενός ανθρώπου (ταξιδιώτη ή καθημερινού οδηγού). Αυτοί οι παράγοντες θα βοηθούν στον οικονομικό προγραμματισμό του όσον αφορά την μετακίνηση, την καλύτερη δυνατή εξοικονόμηση ενέργειας και πόρων, καθώς και στην διευκόλυνση του να υπολογίσει το κόστος ενός μεγάλου ταξιδιού σε συνδυασμό με τα εργαλεία που θα διαθέτει (μέσο μετακίνησης, καλύτερη διαδρομή, πιο εύκολη οδήγηση σε μια διαδρομή, συνολική εικόνα των εξόδων μεταφοράς του). **Γιατί επιλέγουμε αυτό το θέμα** ; Η βασική σκέψη και ιδέα προήλθε από το γεγονός ότι μεγάλο κομμάτι της κοινωνίας δυσκολεύεται να υπολογίσει άμεσα πολλούς παράγοντες για να μπορέσει να πάρει την απόφαση να ξεφύγει και να χαλαρώσει από μια καθημερινότητα πηγαίνοντας μια μικρή ή μεγάλη βόλτα. Πολλές φορές ο κόσμος βρίσκεται αντιμέτωπος με εμπόδια στα οποία δεν μπορεί να βρει μια χειροπιαστή λύση (πόσο θα πληρώσω να πάω Πράγα; , πόση βενζίνη πρέπει να βάλω; , πόσα διόδια θα μου βγούνε ;) η οποία να ανταποκρίνεται βέβαια και στις οικονομικές του δυνατότητες. Η αμεσότητα και η συγκέντρωση στοιχείων από μια τέτοια ιδέα μπορεί πραγματικά να διευκολύνει την ζωή ενός ανθρώπου και να δώσει πραγματικό κίνητρο. Επιπλέον επιλέξαμε αυτή την ιδέα γιατί το κομμάτι της μετακίνησης και της δαπάνης χρημάτων είναι κάτι μη-στατικό και υπολογίσιμο από την πλειοψηφία των ανθρώπων .Την ώρα λοιπόν που άμεσα ένας χρήστης υπολογίζει το κόστος ενός μεγάλου ταξιδιού θα μπορεί άμεσα να εξετάζει τα πάγια έξοδα του στην μεταφορά σε συνδυασμό με τις καθημερινές διαδρομές που κάνει στην δουλειά του και την αποδοτικότητα του μέσου μεταφοράς που διαθέτει. ``` Περιγραφή του project ``` ``` Υποστήριξη : smartphones , tablets ``` ``` Το βασικό στοιχείο είναι ότι ο χρήστης αρχικά θα πρέπει να δίνει συγκεκριμένα στοιχεία τα οποία θα αποτελούν τη βάση για να μπορεί αυτόματα να κάνει τις ταξιδιωτικές του δραστηριότητες και να αποτελούν τα πάγια εργαλεία που έχει στα χέρια του. Αυτά αποτελούνται από π.χ. τα προσωπικά του δεδομένα, το μεταφορικό του μέσο (αυτοκίνητο, μηχανή , μη ύπαρξη μεταφορικού μέσου ) , το ιστορικό των ταξιδιών του , η επιλογή του πρατηρίου (για να μπορέσει να υπολογιστή το κόστος του καυσίμου ή προτεινόμενα πρατήρια καυσίμου). Εδώ θα δοθεί μεγαλύτερη βαρύτητα στο μεταφορικό μέσο , τα χαρακτηριστικά του (καύσιμο, απόδοση λίτρων/ χλμ εμπειρικά ) για να μπορέσει να εξασφαλιστεί άμεσα το κόστος. Η βασική λειτουργία είναι ο προγραμματισμός ενός ταξιδιού ο χρήστης θα μπορεί να επιλέξει , το μέσο που επιθυμεί να ταξιδέψει , τον προορισμό του και άμεσα να υπολογίζεται το συνολικό κόστος της μεταφοράς που χρειάζεται να ξοδευτεί .Εκεί μπορούν να μπουν πολλοί παράμετροι προς επεξεργασία .Κυρίως αξιοποιούμε σαν δεδομένα του χάρτες που υπάρχουν ήδη , την άμεσα μετατροπή της απόστασης σε κόστος με βάση το μεταφορικό μέσο. Επίσης προτείνουμε τρόπους και προορισμούς για τον ταξιδιώτη στην περίπτωση που δεν έχει θέσει σας περιορισμό , το budget του ταξιδιού του και μόνο. Μια άλλη βασική λειτουργία είναι ότι θα μπορεί ο χρήστης να ελέγχει τα έξοδα μετακίνησης του στη διάρκεια ενός μήνα. Αυτά τα στοιχεία θα συλλέγονται καθημερινά με βάση τις μεταφορές του πράγμα το οποίο θα τον βοηθά να έχει μια εποπτική εικόνα των εξόδων του. ``` **Κάποια πρώτα βασικά** mock-up screens <file_sep>/Domain-model-v0.1.md # Domain-model-v0.1 # SMART -TRIP –PLANNER ## Μέλη ομάδας #### • 1058120 ΜΑΡΙΟΣ ΚΑΡΙΠΗΣ #### • 1041729 ΓΕΩΡΓΙΟΣ ΔΑΒΟΥΛΟΣ #### • 1054372 ΤΖΟΥΔΑΣ ΠΑΝΑΓΙΩΤΗΣ #### • 1040641 ΕΥΑΓΓΕΛΟΣ ΔΗΜΟΠΟΥΛΟΣ #### • 1054414 ΑΝΔΡΙΑΝΟΣ ΛΟΥΓΚΙA Βασικά εργαλεία - Editing: MS word, docs.google.com - Diagrams: app.diagrams.net Ρόλοι στο κείμενο Editor: Καρίπης Μάριος, Λούγκια Ανδριανός Contributor: Δ<NAME> Peer reviewers: Δάβουλος Γιώργος Στην πρώτη εκδοχή του Domain Model θεωρήσαμε κάποιες βασικές ομάδες οντοτήτων (user, travel stats, public transportation, planner, location, map, utility) ώστε αρχικά να δώσουμε μια γενική μορφή στην ιδέα μας και στις χρήσεις της. Σε επόμενα στάδια θα γίνουν κρίσιμες αποφάσεις όπως για τη χρήση ΜΜΜ και την υλοποίηση του χάρτη. Για το λόγο αυτό θεωρούμε σαν γενικότερες οντότητες τις δύο αυτές κατηγορίες. ### Περιγραφή Domain 1. **User_Infο** : Οντότητα που αντιστοιχεί σε έναν χρήστη του συστήματος. 2. Vehicle: Οντότητα που αντιστοιχεί στα οχήματα που έχει στην διάθεση του ο χρήστης. 3. Check_List: Χρήσιμη λίστα για τα αντικείμενα που θα χρειαστεί να φέρει ο χρήστης κατά τη διάρκεια του ταξιδιού. 4. Travel_History: Οντότητα που αντιστοιχεί στο ιστορικό ταξιδιών του χρήστη. 5. User_Review: Οντότητα που αντιστοιχεί σε μια κριτική του χρήστη για το ταξίδι που πραγματοποίησε. 6. User_Budget: Οντότητα που αντιστοιχεί στον οικονομικό προϋπολογισμό του χρήστη για το ταξίδι. 7. Trip_Cost: Οντότητα που αντιστοιχεί στο κόστος της διαδρομής που επιλέγει ο χρήστης. 8. Total_Expenses: Οντότητα που αντιστοιχεί στα συνολικά μεταφορικά έξοδα. 9. Trip_Distance: Οντότητα που αντιστοιχεί στο μήκος σε χιλιόμετρα της διαδρομής. 10. Total_Distance: Οντότητα που αντιστοιχεί στα συνολικά χιλιόμετρα που έχει καλύψει ο χρήστης. 11. Route: Οντότητα που αντιστοιχεί στην διαδρομή που επιλέγει ο χρήστης. 12. Route_Issue: Θα πρόκειται για αναφορά του ίδιου του χρήστη από μια λίστα οδικών προβλημάτων που θα αποστέλλονται στο Danger_Ζone ανάλογα τη σοβαρότητα. 13. Danger_Zone: Οντότητα που θα επισημαίνει την προσοχή στον οδηγό για επικίνδυνα κομμάτια/σημεία της διαδρομής με βάση τις καιρικές συνθήκες, την ποιότητα του δρόμου, τα Route_Issues. 14. User_location: Οι γεωγραφικές συντεταγμένες του χρήστη. 15. Gas_Station: Πρατήρια καυσίμων. 16. Tolls: Σταθμοί διοδίων. 17. Resting_Points: Σημεία στάσης. 18. Suggestions: Προτεινόμενοι ταξιδιωτικοί προορισμοί με βάση την τοποθεσία του χρήστη και την εποχή με πρόταση προϋπολογισμού. 19. Emergency_Calls: Κλήσεις έκτακτης ανάγκης. 20. Calendar: Οντότητα ημερολόγιο όπου ο χρήστης θα μπορεί να καταχωρεί σχεδιασμένα ταξίδια και να βλέπει το κόστος των επικείμενων μεταφορών. (Ίσως σε αργότερο στάδιο αποφασίσουμε να κοινοποιεί τα σχέδια του με άλλους χρήστες της εφαρμογής ώστε να μπορούν να μοιράζονται τα κόστη μετακίνησης). 21. Co_Traveler: Πρόκειται για λίστα χρηστών της εφαρμογής τους οποίους προσθέτει ο χρήστης σαν συνταξιδιώτες ώστε να μοιράζονται τα κόστη και τα στατιστικά των ταξιδιών. 22. Public_Transortation: Οντότητα που αντιστοιχεί στα μέσα μαζικής μεταφοράς που μπορεί να χρειαστεί να χρησιμοποιήσει ο χρήστης. 23. Map: Οντότητα που αντιστοιχεί στο χάρτη. <file_sep>/Feasibillity_Study_-v0.1.md - Feasibillity Study v0.1 # Μέλη ομάδας ### • 1058120 ΜΑΡΙΟΣ ΚΑΡΙΠΗΣ ### • 1041729 ΓΕΩΡΓΙΟΣ ΔΑΒΟΥΛΟΣ ### • 1054372 ΤΖΟΥΔΑΣ ΠΑΝΑΓΙΩΤΗΣ ### • 1040641 ΕΥΑΓΓΕΛΟΣ ΔΗΜΟΠΟΥΛΟΣ ### • 1054414 ΑΝΔΡΙΑΝΟΣ ΛΟΥΓΚΙΑ ## Editors ### • 1058120 ΜΑΡΙΟΣ ΚΑΡΙΠΗΣ ### • 1041729 ΓΕΩΡΓΙΟΣ ΔΑΒΟΥΛΟΣ ### • 1054372 ΤΖΟΥΔΑΣ ΠΑΝΑΓΙΩΤΗΣ ### • 1040641 ΕΥΑΓΓΕΛΟΣ ΔΗΜΟΠΟΥΛΟΣ ### • 1054414 ΑΝΔΡΙΑΝΟΣ ΛΟΥΓΚΙΑ ## Peer Reviewer ### • 1058120 ΜΑΡΙΟΣ ΚΑΡΙΠΗΣ ### • 1041729 ΓΕΩΡΓΙΟΣ ΔΑΒΟΥΛΟΣ ### • 1054372 ΤΖΟΥΔΑΣ ΠΑΝΑΓΙΩΤΗΣ ### • 1040641 ΕΥΑΓΓΕΛΟΣ ΔΗΜΟΠΟΥΛΟΣ ### • 1054414 ΑΝΔΡΙΑΝΟΣ ΛΟΥΓΚΙΑ ## Εργαλεία Markdown, VSCode, GanttProject, Pandoc, Lightshot, Table generator, Mockflow, VisualParadigm, Diagrams.net ## Τεχνικές και Λειτουργικές Δυσκολίες - H ανάληψη του έργου από την ομάδα μας μπορεί να φαίνεται καλή ιδέα, αλλα προκειμένου να υλοποιηθεί με επιτυχία, θα πρέπει η ομάδα, σε σύντομο χρονικό διάστημα, να αποκτήσει γνώση στον τομέα των εφαρμογών android, τόσο στο τεχνικό κομμάτι, όσο και στο συνολικό κομμάτι που αφορά την αντίστοιχο κομμάτι της αγοράς που ασχολείται με αυτό, και προφανώς το target group αυτων των εφαρμογών. - Η σωστή οργάνωση και προγραμματισμός του έργου είναι κλειδιά για την ολοκλήρωση του. Μέρος της οργάνωσης είναι και το **Quallity Assurance** , το οποίο πρέπει να γίνεται κατά τη διάρκεια του έργου. Ωστόσο, το Feedback, απο χρήστες κατα την διάρκεια του beta-phase, κρίνεται απαραίτητο. - Η ομάδα πρέπει να μεριμνήσει για το **security** του έργου. Αυτό θα γίνει με ένα security plan το οποίο θα είναι σε ισχύ από την αρχή του έργου και θα αφορά όλα τα στάδια, όπως η επιλογή μίας γλώσσας προγραμματισμού με **built in** security features, ύστερα **system** και **security** testing. **Οικονομικά Εμπόδια** Η υποστήριξη του έργου, κατά την υλοποίηση και κατά τη συντήρηση, χρειάζεται ένα _budget_ το οποίο αναλύεται στο **Project Plan**. Ωστόσο, θα πρέπει να υπολογιστούν και τα τελικά οικονομικά οφέλη από το έργο. **Νομικές υποθέσεις** Η ομάδα πρέπει να μεριμνήσει για τις νομικές προεκτάσεις του έργου. Δηλαδή, θα πρέπει να απευθυνθεί σε κάποιον νομικό σύμβουλο, ώστε να υπάρχει σιγουριά για την τήρηση των _πνευματικών δικαιωμάτων απο την πλευρά της εταιρείας_ , αλλα και τις προστασίας των προσωπικών δεδομένων, σύμφωνα με τις επιταγές των κανονισμών του GDPR, απο την πλευρά των χρηστών. **Σωστός σχεδιασμός** Η ανάγκη για σωστό αρχικό σχεδιασμό και χρονοπρογραμματισμό μπορεί να αποβεί κομβική για την μετέπειτα υλοποίηση. H ομάδα πρέπει να συμπεριλάβει στη σύνθεση της άτομα με εμπειρία στο **project management** , οι οποίοι θα έχουν μια ξεκάθαρη εικόνα για το πώς πρέπει να λειτουργήσει η ομάδα με σωστό τρόπο, για να τηρήσει τους χρονικούς περιορισμούς.
dd36a37a6f3b1ffd4fd8de8af1120aa0951b750d
[ "Markdown", "Python" ]
9
Markdown
rotcrus/spaghetticoders
07583d355adc8b56de4b65af725836467b1e9c99
90f3f49728e218737eb971a7cf9e95a1c04e04d0
refs/heads/master
<repo_name>alexung/redux-egghead<file_sep>/ep-14-reducer-composition-with-objects.js // === REDUCER COMPOSITION WITH OBJECTS === const todo = (state, action) => { switch (action.type) { case 'ADD_TODO': return { id: action.id, text: action.text, completed: false }; case 'TOGGLE_TODO': if (state.id !== action.id) { return todo; } return { ...state, completed: !state.completed }; default: return state; } }; const todos = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, todo(undefined, action) ]; case 'TOGGLE_TODO': return state.map(t => todo(t, action)); default: return state; } }; // visibilityFilter function defined with 2 args: // 1. state which defaults to 'SHOW_ALL' // 2. action, where we look at the action.type and see which filter // we're trying to toggle const visibilityFilter = ( state = 'SHOW_ALL', action ) => { switch (action.type) { case 'SET_VISIBILITY_FILTER': return action.filter; default: return state; } }; const todoApp = (state = {}, action) => { return { todos: todos( state.todos, action ), // combined reducers, visibilityFilter + todos work together to combine results // into new, single state object visibilityFilter: visibilityFilter( state.visibilityFilter, action ) }; }; const { createStore } = Redux; const store = createStore(todoApp); store.dispatch({ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_COMPLETED' })<file_sep>/ep-7-implementing-store-from-scratch.js // below is not the whole app, just createStore written from scratch // understanding how createStore works from scratch below: const createStore = (reducer) => { let state; const getState = () => state; const dispatch = (action) => { state = reducer(state, action); listeners.forEach(listener => listener()); }; const subscribe = (listener) => { listeners.push(listener); // below is basically an unsubscribe method within the greater subscribe method return () => { listeners = listeners.filter(l => l !== listener); }; }; dispatch({}); return { getState, dispatch, subscribe }; }; const store = createStore(counter);<file_sep>/ep-11-writing-todo-list-reducer-to-add-todo.js // === THIS IS A REDUCER, ADD TODO === // todos takes an action and basically (doesn't mutate) but puts it into the // state arr, with completed: false because you just added the todo item const todos = (state = [], action) => { // the action.type, ADD_TODO, that we have below matches the case statement // spread operator combines state and the action into a new arr of objects switch (action.type) { case 'ADD_TODO': return [ ...state, { id: action.id, text: action.text, completed: false } ]; default: return state; } }; const testAddTodo = () => { const stateBefore = []; // actions on reducers are the new object you want to replace the old one with const action = { type: 'ADD_TODO', id: 0, text: 'Learn Redux' }; const stateAfter = [ { id: 0, text: 'Learn Redux', completed: false } ] deepFreeze(stateBefore); deepFreeze(action); expect( todos(stateBefore, action) ).toEqual(stateAfter) }; testAddTodo(); console.log('All tests passed.');<file_sep>/ep-20-extracting-presentational-components-todo-todolist.js // === REACT TODO LIST EXAMPLE (EXTRACTING PRESENTATIONAL COMPONENTS LIKE Todo, TodoList) === // === INTRO TO PRESENTATIONAL COMPONENTS === // All in all, summary of what's happening // 1. class TodoApp calls the TodoList component // 2. TodoList component has an onTodoClick property that we defined as an arg // for the component. Directly in the class TodoApp, we're including the // store.dispatch({}) where we have id being passed as an arg // 3. TodoList calls Todo, which then will either cross out or uncross out the item // bc of the switch/case statements we have in const todo // 4. const todo = (state, action) => { switch (action.type) { case 'ADD_TODO': return { id: action.id, text: action.text, completed: false }; case 'TOGGLE_TODO': if (state.id !== action.id) { return state; } return { ...state, completed: !state.completed }; default: return state; } }; const todos = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, todo(undefined, action) ]; case 'TOGGLE_TODO': return state.map(t => todo(t, action)); default: return state; } }; const visibilityFilter = ( state = 'SHOW_ALL', action ) => { switch (action.type) { case 'SET_VISIBILITY_FILTER': return action.filter; default: return state; } }; const { combineReducers } = Redux; // below is our root reducer const todoApp = combineReducers({ todos, visibilityFilter }); const { createStore } = Redux; const store = createStore(todoApp); const { Component } = React; const FilterLink = ({ filter, currentFilter, children }) => { if (filter === currentFilter) { return <span>{children}</span>; } return ( <a href="#" onClick={e => { e.preventDefault(); store.dispatch({ type: 'SET_VISIBILITY_FILTER', // so filter knows which filter is being picked filter }); }} > {children} </a> ); }; // extracting this from the 'class TodoApp extends Component' and creating a separate component for it // DON'T explicitly pass the object through this presentational component, rather pass it args that relate to what the DOM element needs to render so that it's not concerned about the type of whatever you pass through const Todo = ({ onClick, completed, text }) => ( // we can remove the key={todo.id} bc it's only necessary when enumerating through an arr. we'll need it later <li onClick={onClick} style={{ textDecoration: completed ? 'line-through' : 'none' }} > {text} </li> ); // we also create a TodoList to render a todo component for each todo // === IMPORTANT === // because this is presentational, we don't want to hardcode logic in so we create // an 'onTodoClick' arg which is called by the onClick, so we can customize what happens // on click const TodoList = ({ todos, onTodoClick }) => ( <ul> {todos.map(todo => <Todo key={todo.id} {...todo} onClick={() => onTodoClick(todo.id)} /> )} </ul> ); const getVisibleTodos = ( todos, filter ) => { switch (filter) { case 'SHOW_ALL': return todos; case 'SHOW_COMPLETED': return todos.filter( t => t.completed ); case 'SHOW_ACTIVE': return todos.filter( t => !t.completed ); } } let nextTodoId = 0; // global var that we'll keep incrementing class TodoApp extends Component { render() { const { todos, visibilityFilter } = this.props; // above is so we can access the todos/visibilityFilters without this.props every time const visibleTodos = getVisibleTodos( todos, visibilityFilter ); return ( <div> <input ref={node => { // ref above is a function that gets the node corresponding to the ref // saving the value of this input to this.input this.input = node; }} /> <button onClick={() => { store.dispatch({ type: 'ADD_TODO', // text below references the input above text: this.input.value, id: nextTodoId++ }); this.input.value = ''; }}> Add Todo </button> <TodoList // here, we create a TodoList component that we defined above // ====IMPORTANT==== // the args for the presentational component above are defined as attrs // on this react component we've created todos={visibleTodos} onTodoClick={id => store.dispatch({ type: 'TOGGLE_TODO', id }) } /> <p> Show: {' '} <FilterLink filter="SHOW_ALL" currentFilter={visibilityFilter} > All </FilterLink> {' '} <FilterLink filter="SHOW_ACTIVE" currentFilter={visibilityFilter} > Active </FilterLink> {' '} <FilterLink filter="SHOW_COMPLETED" currentFilter={visibilityFilter} > Completed </FilterLink> </p> </div> ); } } // because we are subscribed via store.subscribe(render) // every store change, the getState() is called on the <TodoApp /> component // making sure it's up to date const render = () => { ReactDOM.render( <TodoApp // this makes it so every state field in state object is passed // as prop to TodoApp component {...store.getState()} />, document.getElementById('root') ); }; store.subscribe(render); // console.log(store.subscribe(render)); render();<file_sep>/ep-16-implementing-combineReducers-from-scratch.js // === IMPLEMENTING combineReducers() FROM SCRATCH === // reduce() via the mozilla docs: // arr.reduce(callback[, initialValue]) // so {} is the initial value (we cannot mutate things in redux), which is why it's // the second arg in reduce() const combineReducers = (reducers) => { return (state = {}, action) => { return Object.keys(reducers).reduce( (nextState, key) => { nextState[key] = reducers[key]( state[key], action ); return nextState; }, {} ); }; };<file_sep>/ep-9-avoiding-array-mutatations-concat-slice-spread.js // === Avoiding array mutuations with concat(), slice(), and ...spread === // NOTES: // .slice vs .splice // .slice returns copy // .splice edits actual array (CANNOT MUTATE ARRAYS IN REDUX) // Also, deepFreeze protects you from mutation in your tests. good to use in testing // END NOTES const addCounter = (list) => { // list.push(0); // return list; // instead of above syntax, whic will cause a mutation of the list and error out, // we can use spread operator or the syntax commented below // return list.concat([0]); return [...list, 0]; }; const removeCounter = () => { // CAN'T USE SPLICE (BC IT'S A MUTATING METHOD) in redux! // list.splice(index, 1); // return list; // return list // .slice(0, index) // .concat(list.slice(index + 1)); // or can use ES6 spread operator // IMPORTANT!! // this return is concatenating the parts before the index // you want to skip and after the index you want to skip // to get a new array! return [ ...list.slice(0, index), ...list.slice(index + 1) ]; }; const IncrementCounter = (list, index) => { return [ ...list.slice(0, index), list[index] + 1, ...list.slice(index + 1) ]; }; const testAddCounter = () => { const listBefore = []; const listAfter = [0]; deepFreeze(listBefore); expect( addCounter(listBefore) ).toEqual(listAfter); }; const testRemoveCounter = () => { const listBefore = [0, 10, 20]; const listAfter = [0, 20]; expect( removeCounter(listBefore, 1) ).toEqual(listAfter); }; const testIncrementCounter = () => { const listBefore = [0, 10, 20]; const listAfter = [0, 11, 20]; deepFreeze(listBefore); // when deepFreezing things, we cannot mutate the array. this is how // redux works expect( incrementCounter(listBefore, 1) ).toEqual(listAfter); }; testAddCounter(); testRemoveCounter(); // you can add this console log to see if things passed // bc js will run from top to bottom and freeze if there // are errors. so if there's an error, this message will // not show console.log('All tests passed.')<file_sep>/ep-22-extracting-container-components-filterlink.js // === REACT TODO LIST EXAMPLE -- EXTRACTING CONTAINER COMPONENTS LIKE FilterLink === // === INTRO TO CONTAINER COMPONENTS === // filter link container component that is subscribed to the Redux chore // // We want to break out container component into separate pieces so that the presentational // components don't need to know all these tidbits of data that their children need, // bc it's not really separation of concerns // We don't want to pass a lot of props down the tree when intermediate components don't use them // Want to extract a few more container components, just like how we extracted the presentational components // i.e. (footer has unnecessary attrs it's just trying to pass to filterlink) const todo = (state, action) => { switch (action.type) { case 'ADD_TODO': return { id: action.id, text: action.text, completed: false }; case 'TOGGLE_TODO': if (state.id !== action.id) { return state; } return { ...state, completed: !state.completed }; default: return state; } }; const todos = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, todo(undefined, action) ]; case 'TOGGLE_TODO': return state.map(t => todo(t, action)); default: return state; } }; const visibilityFilter = ( state = 'SHOW_ALL', action ) => { switch (action.type) { case 'SET_VISIBILITY_FILTER': return action.filter; default: return state; } }; const { combineReducers } = Redux; // below is our root reducer const todoApp = combineReducers({ todos, visibilityFilter }); const { createStore } = Redux; const store = createStore(todoApp); const { Component } = React; const Link = ({ active, children, onClick }) => { if (active) { return <span>{children}</span>; } return ( <a href="#" onClick={e => { e.preventDefault(); onClick(); }} > {children} </a> ); }; // this FilterLink is in the footer and calls the store.dispatch so that footer, // which is not really responsible for toggling links, doesn't have to class FilterLink extends Component { componentDidMount() { this.unsubscribe = store.subscribe(() => this.forceUpdate() ); } componentWillUnmount() { this.unsubscribe(); } render() { const props = this.props; // this is to look for the redux store state, NOT the react state const state = store.getState(); return ( <Link active={ // it's active, so the link changes its css to be just plain text IF // the props.filter === state.visibilityFilter props.filter === state.visibilityFilter } onClick={() => store.dispatch({ type: 'SET_VISIBILITY_FILTER', filter: props.filter }) } > {props.children} </Link> ); } } // Footer is a presentational component, and is self sufficient // =====IMPORTANT===== // Footer component is simple and decoupled from what its child components need because // the redux store.dispatch({}) is put into one of the children of this container // component, rather than straight into the TodoApp component itself. // can remove props for currentFilter onFilterClick because it's not using them.. // it's simply passing them on the FilterLink const Footer = () => ( <p> Show: {' '} <FilterLink filter="SHOW_ALL" > All </FilterLink> {', '} <FilterLink filter="SHOW_ACTIVE" > Active </FilterLink> {', '} <FilterLink filter="SHOW_COMPLETED" > Completed </FilterLink> </p> ); // DON'T explicitly pass the object through this presentational component, rather pass it args that relate to what the DOM element needs to render so that it's not concerned about the type of whatever you pass through const Todo = ({ onClick, completed, text }) => ( // we can remove the key={todo.id} bc it's only necessary when enumerating through an arr. we'll need it later <li // when the li is clicked, calls onClick property onClick={onClick} style={{ textDecoration: completed ? 'line-through' : 'none' }} > {text} </li> ); const TodoList = ({ todos, onTodoClick }) => ( <ul> {todos.map(todo => <Todo key={todo.id} {...todo} onClick={() => onTodoClick(todo.id)} /> )} </ul> ); // ===IMPORTANT=== // We're encasing this in a div because we need components to be in a single // html root element const AddTodo = ({ onAddClick }) => { let input; return ( <div> <input ref={node => { // ref above is a function that gets the node corresponding to the ref // saving the value of this input to this.input input = node; }} /> <button onClick={() => { onAddClick(input.value); input.value = ''; }}> Add Todo </button> </div> ); }; const getVisibleTodos = ( todos, filter ) => { switch (filter) { case 'SHOW_ALL': return todos; case 'SHOW_COMPLETED': return todos.filter( t => t.completed ); case 'SHOW_ACTIVE': return todos.filter( t => !t.completed ); } } let nextTodoId = 0; // global var that we'll keep incrementing // === IMPORTANT === // So we define our components above // shove them into this TodoApp master componnet, which we call with render // then we put in redux store.dispatch({}) into it // We can remove props from the footer component before because it doesn't // actually use them, it merely passes them along to FilterLink const TodoApp = ({ todos, visibilityFilter }) => ( <div> <AddTodo onAddClick={text => store.dispatch({ type: 'ADD_TODO', id: nextTodoId++, text }) } /> <TodoList todos={ getVisibleTodos( todos, visibilityFilter ) } onTodoClick={id => store.dispatch({ type: 'TOGGLE_TODO', id }) } /> <Footer /> </div> ); // because we are subscribed via store.subscribe(render) // every store change, the getState() is called on the <TodoApp /> component // making sure it's up to date const render = () => { ReactDOM.render( <TodoApp // this makes it so every state field in state object is passed // as prop to TodoApp component {...store.getState()} />, document.getElementById('root') ); }; store.subscribe(render); // console.log(store.subscribe(render)); render();<file_sep>/ep-23-extracting-container-components-visibletodolist-addtodo.js // === REDUX: EXTRACTING CONTAINER COMPONENTS LIKE VisibleTodoList and AddTodo === // === INTRO TO CONTAINER COMPONENTS === // continue extracting container components from the top level container components // like the TodoList component. // I want to keep the TodoList presentational component, but I want to encapsulate // within the currently visible Todos into a separate container component that connects // the TodoList to the redux chore. Going to call this component the visible TodoList. const todo = (state, action) => { switch (action.type) { case 'ADD_TODO': return { id: action.id, text: action.text, completed: false }; case 'TOGGLE_TODO': if (state.id !== action.id) { return state; } return { ...state, completed: !state.completed }; default: return state; } }; const todos = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, todo(undefined, action) ]; case 'TOGGLE_TODO': return state.map(t => todo(t, action)); default: return state; } }; const visibilityFilter = ( state = 'SHOW_ALL', action ) => { switch (action.type) { case 'SET_VISIBILITY_FILTER': return action.filter; default: return state; } }; const { combineReducers } = Redux; // below is our root reducer const todoApp = combineReducers({ todos, visibilityFilter }); const { createStore } = Redux; const store = createStore(todoApp); const { Component } = React; // Presentational component const Link = ({ active, children, onClick }) => { if (active) { return <span>{children}</span>; } return ( <a href="#" onClick={e => { e.preventDefault(); onClick(); }} > {children} </a> ); }; // CONTAINER COMPONENT, will display the presentational component 'link' class FilterLink extends Component { componentDidMount() { this.unsubscribe = store.subscribe(() => this.forceUpdate() ); } componentWillUnmount() { this.unsubscribe(); } render() { const props = this.props; const state = store.getState(); return ( <Link active={ props.filter === state.visibilityFilter } onClick={() => store.dispatch({ type: 'SET_VISIBILITY_FILTER', filter: props.filter }) } > {props.children} </Link> ); } } // PRESENTATIONAL COMPONENT const Footer = () => ( <p> Show: {' '} <FilterLink filter="SHOW_ALL" > All </FilterLink> {', '} <FilterLink filter="SHOW_ACTIVE" > Active </FilterLink> {', '} <FilterLink filter="SHOW_COMPLETED" > Completed </FilterLink> </p> ); const Todo = ({ onClick, completed, text }) => ( <li onClick={onClick} style={{ textDecoration: completed ? 'line-through' : 'none' }} > {text} </li> ); const TodoList = ({ todos, onTodoClick }) => ( <ul> {todos.map(todo => <Todo key={todo.id} {...todo} onClick={() => onTodoClick(todo.id)} /> )} </ul> ); let nextTodoId = 0; // BOTH CONTAINER AND PRESENTATIONAL COMPONENT // below is kind of combining container component AND presentational component // but it's okay for this because we can't really envision this component // being used for any other purpose and so reusability may be kind of pointless. // we'll consider putting this into a different component in future const AddTodo = () => { let input; return ( <div> <input ref={node => { input = node; }} /> <button onClick={() => { store.dispatch({ type: 'ADD_TODO', id: nextTodoId++, text: input.value }) input.value = ''; }}> Add Todo </button> </div> ); }; const getVisibleTodos = ( todos, filter ) => { switch (filter) { case 'SHOW_ALL': return todos; case 'SHOW_COMPLETED': return todos.filter( t => t.completed ); case 'SHOW_ACTIVE': return todos.filter( t => !t.completed ); } } // Container component, subscribes to the store and rerenders it anytime store state changes class VisibleTodoList extends Component { componentDidMount() { this.unsubscribe = store.subscribe(() => this.forceUpdate() ); } componentWillUnmount() { this.unsubscribe(); } render() { const props = this.props; const state = store.getState(); return( <TodoList todos={ getVisibleTodos( state.todos, state.visibilityFilter ) } onTodoClick={id => store.dispatch({ type: 'TOGGLE_TODO', id }) } /> ); } } // none of container below needs props passed in as args, so we can remove them // and just have an empty () const TodoApp = () => ( <div> <AddTodo /> <VisibleTodoList /> <Footer /> </div> ); // ==== IMPORTANT ==== // because we've extracted the logic from each of the components we've added in // to TodoApp, we can simply remove: // 1. the render function that used to be here // 2. store.subscribe(render); // 3. render(); // because we don't need to keep track of state here, that's all being done in // the individual components we've built // we need this render call though! ReactDOM.render( <TodoApp />, document.getElementById('root') );<file_sep>/ep-15-reducer-composition-with-combineReducers.js // === REDUCER COMPOSITION WITH combineReducers() === const todo = (state, action) => { switch (action.type) { case 'ADD_TODO': return { id: action.id, text: action.text, completed: false }; case 'TOGGLE_TODO': if (state.id !== action.id) { return todo; } return { ...state, completed: !state.completed }; default: return state; } }; const todos = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, todo(undefined, action) ]; case 'TOGGLE_TODO': return state.map(t => todo(t, action)); default: return state; } }; const visibilityFilter = ( state = 'SHOW_ALL', action ) => { switch (action.type) { case 'SET_VISIBILITY_FILTER': return action.filter; default: return state; } }; // MUST DEFINE COMBINE REDUCERS AS BELOW BEFORE YOU USE IT const { combineReducers } = Redux; // IMPORTANT // combineReducers allow you to avoid writing this code by hand and generates // top level code for you. // ==replace with below, they behave the same, but below is easier to write== // const todoApp = (state = {}, action) => { // return { // todos: todos( // state.todos, // action // ), // visibilityFilter: visibilityFilter( // state.visibilityFilter, // action // ) // }; // }; const todoApp = combineReducers({ // ====== // keys correspond with the things we append to state. (i.e. state.visibilityFilter) // values correspond with the reducers it should call to update the corresponding // fields (i.e. const visibilityFilter) // todos: todos, // visibilityFilter: visibilityFilter // ====== // bc key and value names are same, with ES6 we can just call the shorthand as below: todos, visibilityFilter }); const { createStore } = Redux; const store = createStore(todoApp); <file_sep>/ep-21-extracting-presentational-components-addtodo-footer-filterlink.js // === REACT TODO LIST EXAMPLE (EXTRACTING PRESENTATIONAL COMPONENTS LIKE AddTodo, Footer, FilterLink) === // === INTRO TO PRESENTATIONAL COMPONENTS === const todo = (state, action) => { switch (action.type) { case 'ADD_TODO': return { id: action.id, text: action.text, completed: false }; case 'TOGGLE_TODO': if (state.id !== action.id) { return state; } return { ...state, completed: !state.completed }; default: return state; } }; const todos = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, todo(undefined, action) ]; case 'TOGGLE_TODO': return state.map(t => todo(t, action)); default: return state; } }; const visibilityFilter = ( state = 'SHOW_ALL', action ) => { switch (action.type) { case 'SET_VISIBILITY_FILTER': return action.filter; default: return state; } }; const { combineReducers } = Redux; // below is our root reducer const todoApp = combineReducers({ todos, visibilityFilter }); const { createStore } = Redux; const store = createStore(todoApp); const { Component } = React; const FilterLink = ({ filter, currentFilter, children, onClick }) => { if (filter === currentFilter) { return <span>{children}</span>; } return ( <a href="#" onClick={e => { e.preventDefault(); onClick(filter); }} > {children} </a> ); }; const Footer = ({ visibilityFilter, onFilterClick }) => ( <p> Show: {' '} <FilterLink filter="SHOW_ALL" currentFilter={visibilityFilter} onClick={onFilterClick} > All </FilterLink> {', '} <FilterLink filter="SHOW_ACTIVE" currentFilter={visibilityFilter} onClick={onFilterClick} > Active </FilterLink> {', '} <FilterLink filter="SHOW_COMPLETED" currentFilter={visibilityFilter} onClick={onFilterClick} > Completed </FilterLink> </p> ); // DON'T explicitly pass the object through this presentational component, rather pass it args that relate to what the DOM element needs to render so that it's not concerned about the type of whatever you pass through const Todo = ({ onClick, completed, text }) => ( // we can remove the key={todo.id} bc it's only necessary when enumerating through an arr. we'll need it later <li // when the li is clicked, calls onClick property onClick={onClick} style={{ textDecoration: completed ? 'line-through' : 'none' }} > {text} </li> ); const TodoList = ({ todos, onTodoClick }) => ( <ul> {todos.map(todo => <Todo key={todo.id} {...todo} onClick={() => onTodoClick(todo.id)} /> )} </ul> ); // ===IMPORTANT=== // We're encasing this in a div because we need components to be in a single // html root element const AddTodo = ({ onAddClick }) => { let input; return ( <div> <input ref={node => { // ref above is a function that gets the node corresponding to the ref // saving the value of this input to this.input input = node; }} /> <button onClick={() => { onAddClick(input.value); input.value = ''; }}> Add Todo </button> </div> ); }; const getVisibleTodos = ( todos, filter ) => { switch (filter) { case 'SHOW_ALL': return todos; case 'SHOW_COMPLETED': return todos.filter( t => t.completed ); case 'SHOW_ACTIVE': return todos.filter( t => !t.completed ); } } let nextTodoId = 0; // global var that we'll keep incrementing // === IMPORTANT === // So we define our components above // shove them into this TodoApp master componnet, which we call with render // then we put in redux store.dispatch({}) into it const TodoApp = ({ todos, visibilityFilter }) => ( <div> <AddTodo onAddClick={text => store.dispatch({ type: 'ADD_TODO', id: nextTodoId++, text }) } /> <TodoList todos={ getVisibleTodos( todos, visibilityFilter ) } onTodoClick={id => store.dispatch({ type: 'TOGGLE_TODO', id }) } /> <Footer visibilityFilter={visibilityFilter} onFilterClick={filter => store.dispatch({ type: 'SET_VISIBILITY_FILTER', filter }) } /> </div> ); // because we are subscribed via store.subscribe(render) // every store change, the getState() is called on the <TodoApp /> component // making sure it's up to date const render = () => { ReactDOM.render( <TodoApp // this makes it so every state field in state object is passed // as prop to TodoApp component {...store.getState()} />, document.getElementById('root') ); }; store.subscribe(render); // console.log(store.subscribe(render)); render();
7afa59cffd25ffcf9c360eb7ea545116021d1621
[ "JavaScript" ]
10
JavaScript
alexung/redux-egghead
886b0045025744e743bd79703232ea0052661736
8686dfa23af6bc2d6b8b265b67c8e7009da0463a
refs/heads/master
<repo_name>benbulen/Test<file_sep>/bin/proj3_shiny.R # # This is a Shiny web application. You can run the application by clicking # the 'Run App' button above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # install.packages('shiny') library(shiny) args = commandArgs(trailingOnly=TRUE) df <- read.csv(args[1], header=TRUE, row.names=1) names <-rownames(df) # Define UI for application that draws a histogram ui <- fluidPage( # Application title titlePanel("Top 10 UNC Collaborators by University"), # Sidebar with a slider input for number of bins sidebarLayout( sidebarPanel( selectInput("Collaborator", "University:", choices=colnames(df)), hr(), helpText("Doctored Collaboration Data to Work on Shiny App") ), # Show a plot of the generated distribution mainPanel( plotOutput("barPlot") ) ) ) # Define server logic required to draw a histogram server <- function(input, output) { output$barPlot <- renderPlot({ barplot(df[,input$Collaborator], main=input$Collaborator, ylab="Number of Collaborations", xlab="Purpose of Collaboration", names.arg=names, ylim=c(0,1.5*max(unlist(df[,input$Collaborator])))) }) } # Run the application shinyApp(ui = ui, server = server)
e119af06e12e86b8d4ac2e1ffd33342017fb4f14
[ "R" ]
1
R
benbulen/Test
998263dc1d9ef2bf44e8fb57aac9286c12d7a9b2
0a0f2340fa1351fff5fb14e519ce12ae18d66a76
refs/heads/master
<repo_name>bpolaszek/webpush-js<file_sep>/src/webpush-sw.js self.addEventListener('push', event => { try { const Notification = event.data.json(); event.waitUntil( self.registration.showNotification(Notification.title || '', Notification.options || {}) ); } catch (e) { try { const Notification = event.data.text(); event.waitUntil( self.registration.showNotification('Notification', {body: Notification}) ); } catch (e) { event.waitUntil( self.registration.showNotification('') ); } } }); self.addEventListener('notificationclick', event => { event.notification.close(); const url = event.notification.data.link || ''; if (url.length > 0) { event.waitUntil( clients.matchAll({ type: 'window' }) .then(windowClients => { for (const client of windowClients) { if (client.url === url && 'focus' in client) { return client.focus(); } } if (clients.openWindow) { return clients.openWindow(url); } }) ); } }); <file_sep>/README.md # WebPush Client Handles subscription / unsubscription of Webpush notifications in sync with a remote server. ## Installation The library ships with both a client and a service worker. ### In a browser * Copy `dist/webpush-client.min.js` and `dist/webpush-sw.js` in your project. ### In a JS project * Run `yarn add webpush-client` or `npm install --save webpush-client` ## Configuration ### In a browser ```html <script src="/js/webpush-client.js"></script> <script> var WebPushClient; if (WebPushClientFactory.isSupported()) { WebPushClientFactory.create({ serviceWorkerPath: '/js/webpush-sw.js', // Public path to the service worker serverKey: 'my_server_key', // https://developers.google.com/web/fundamentals/push-notifications/web-push-protocol#application_server_keys subscribeUrl: '/webpush', // Optionnal - your application URL to store webpush subscriptions }) .then(Client => { WebPushClient = Client; }) ; } </script> ``` ### In a JS project ```javascript import Webpush from 'webpush-client' Webpush.create({ serviceWorkerPath: '/js/webpush-sw.js', // Public path to the service worker serverKey: 'my_server_key', // https://developers.google.com/web/fundamentals/push-notifications/web-push-protocol#application_server_keys subscribeUrl: '/webpush', // Optionnal - your application URL to store webpush subscriptions }) .then(WebPushClient => { // do stuff with WebPushClient }) ; ``` ## Usage * `WebPushClient.isSupported()` > Return whether or not the browser AND the server both support Push notifications. * `WebPushClient.getPermissionState()` > Return if Push notifications are allowed for your domain. _Possible values: `prompt`, `granted`, `denied`_ * `WebPushClient.getSubscription()` > Will return null if not subscribed or a `PushSubscription` object. * `WebPushClient.subscribe([options])` > Subscribe browser to Push Notifications. The browser will ask for permission if needed. Return a Promise which resolves to the `PushSubscription` object (or will be rejected in case of access denied) * `WebPushClient.unsubscribe([options])` > Subscribe browser to Push Notifications. The browser will ask for permission if needed. Return a Promise which resolves to the `PushSubscription` object (or will be rejected in case of access denied) #### subscribeUrl When the `subscribeUrl` option is provided, `WebPushClient.subscribe([options])` will POST a JSON containing both the `PushSubscription` and the `options` objects: ```json { "subscription": { "endpoint": "http://endpoint", "keys": { "p256dh": "public key", "auth": "private key" } }, "options": {} } ``` The request will include current credentials allowing you to associate the current user logged in to the `PushSubscription` object and an optionnal, arbitrary `options` object of your own. `WebPushClient.unsubscribe([options])` will issue a DELETE request on `subscribeUrl` with the same body. It's now up to you to handle these infos properly on the server side. Have a look at [the RemoteStorage class](https://github.com/bpolaszek/webpush-js/blob/master/src/webpush-client.js#L50) to check out how these requests are generated. If your application runs on Symfony, you can have a look at [bentools/webpush-bundle](https://github.com/bpolaszek/webpush-bundle) for which this JS was originally designed for. <file_sep>/index.js require('./src/webpush-client.js'); module.exports = window.WebPushClientFactory;<file_sep>/webpack.config.js const Encore = require('@symfony/webpack-encore'); Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'production'); Encore .setOutputPath('dist') .setPublicPath('/') .addEntry('webpush-client.min', './src/webpush-client.js') .addEntry('webpush-sw.min', './src/webpush-sw.js') .enableSourceMaps(false) .enableVersioning(false) ; // export the final configuration module.exports = Encore.getWebpackConfig();
06b83747d2ffeca438d5dd623d6618c3164564bf
[ "JavaScript", "Markdown" ]
4
JavaScript
bpolaszek/webpush-js
d6f24e2cb5600f75646d06a158e3b111c1a8a24d
c97f5a7f471b49d91a2bb94f0d83b18d2542c580
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class InventoryClick : MonoBehaviour { public bool boll; public Transform item; public Transform canvas; void Update() { if (boll == true) { item.position = Input.mousePosition; } } public void CLick(Transform t) { if (item == null) { if (t.childCount > 0) { item = t.GetChild(0); item.SetParent(canvas); boll = true; } } else { if (t.childCount > 0) { item.SetParent(t); item.position = t.position; item = t.GetChild(0); item.SetParent(canvas); } else { item.SetParent(t); item.position = t.position; item = null; boll = false; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ItemSwitch : MonoBehaviour { public Transform item; public void CLick(Transform T) { if (T.childCount > 0) { item = T.GetChild(0); item.SetParent(transform); item.position = T.position; } } }
78ac8b52b0a748192c0b68a4c21cf83f2ebef7f4
[ "C#" ]
2
C#
GMD1AJoachimRook/Project-4-Inventory
00f070a3dcdaadcf7036bb86d4d344defdf7ecdc
3a287670087d2a385bdf4ce2caad79d8b6bbaa46
refs/heads/master
<file_sep>#ifndef HANGUL_CONST_H #define HANGUL_CONST_H extern char hangul[0x0000227e]; // static int tempUnionCode; // static int oldKey; // static int keyCode; // static int Double_Jung(void) { // static byte Jung_Table[7][3] = { // { 0xad, 0xa3, 0xae }, /* ㅗ, ㅏ, ㅘ */ // { 0xad, 0xa4, 0xaf }, /* ㅗ, ㅐ, ㅙ */ // { 0xad, 0xbd, 0xb2 }, /* ㅗ, ㅣ, ㅚ */ // { 0xb4, 0xa7, 0xb5 }, /* ㅜ, ㅓ, ㅝ */ // { 0xb4, 0xaa, 0xb6 }, /* ㅜ, ㅔ, ㅞ */ // { 0xb4, 0xbd, 0xb7 }, /* ㅜ, ㅣ, ㅟ */ // { 0xbb, 0xbd, 0xbc } /* ㅡ, ㅣ, ㅢ */ // }; // int i; // for (i = 0; i < 7; i++) { // if (Jung_Table[i][0] == oldKey && Jung_Table[i][1] == keyCode) // return ((keyCode = Jung_Table[i][2])); // } // return 0; // } // static int Double_Jong(void) { // static byte Jong_Table[11][3] = { // { 0x82, 0x8b, 0xc4 }, /* ㄱ, ㅅ*/ // { 0x84, 0x8e, 0xc6 }, /* ㄴ, ㅈ*/ // { 0x84, 0x94, 0xc7 }, /* ㄴ, ㅎ*/ // { 0x87, 0x82, 0xca }, /* ㄹ, ㄱ*/ // { 0x87, 0x88, 0xcb }, /* ㄹ, ㅁ*/ // { 0x87, 0x89, 0xcc }, /* ㄹ, ㅂ*/ // { 0x87, 0x8b, 0xcd }, /* ㄹ, ㅅ*/ // { 0x87, 0x92, 0xce }, /* ㄹ, ㅌ*/ // { 0x87, 0x93, 0xcf }, /* ㄹ, ㅍ*/ // { 0x87, 0x94, 0xd0 }, /* ㄹ, ㅎ*/ // { 0x89, 0x8b, 0xd4 } /* ㅂ, ㅅ*/ // }; // int i; // for (i = 0; i < 11; i++) { // if (Jong_Table[i][0] == oldKey && Jong_Table[i][1] == keyCode) // return (keyCode = Jong_Table[i][2]); // } // return 0; // } // int hanAutomata2(int key) { // int chKind, canBeJongsung = FALSE; // /* 초성코드에 대응하는 종성 코드 */ // static byte Cho2Jong[] = { // 0xc2, /* 기역 */ // 0xc3, /* 쌍기역 */ // 0xc5, /* 니은 */ // 0xc8, /* 디귿 */ // 0x00, /* 쌍디귿 (해당 없음) */ // 0xc9, /* 리을 */ // 0xd1, /* 미음 */ // 0xd3, /* 비읍 */ // 0x00, /* 상비읍 (해당 없음) */ // 0xd5, /* 시옷 */ // 0xd6, /* 쌍시옷 */ // 0xd7, /* 이응 */ // 0xd8, 지읒 // 0x00, /* 쌍지읒 (해당 없음) */ // 0xd9, /* 치읓 */ // 0xda, /* 키읔 */ // 0xdb, /* 티읕 */ // 0xdc, /* 피읖 */ // 0xdd /* 히읗 */ // }; // unsigned char HangulKey; // typedef HANGUL_STATE_FUNC (*HANGUL_STATE_FUNC)(char* input) // HANGUL_STATE_FUNC KeyGet(char *input); // HANGUL_STATE_FUNC HangulStart(char *input); // HANGUL_STATE_FUNC ChoState(char *input); // HANGUL_STATE_FUNC JungState(char *input); // HANGUL_STATE_FUNC D_JungState(char *input); // HANGUL_STATE_FUNC S_JungState(char *input); // HANGUL_STATE_FUNC JongState(char *input); // HANGUL_STATE_FUNC D_JongState(char *input); // HANGUL_STATE_FUNC FirstFinal(char *input); // HANGUL_STATE_FUNC SecondFinal(char *input); // HANGUL_STATE_FUNC KeyGet(char *input) //영어 키보드로 자음과 모음을 나눔 // { // if(input=="Q"&&input=="W"&&input=="E"&&input=="R"&&input=="T"&&input=="A"&&input=="S"&&input=="D"&&input=="F"&&input=="G"&&input=="Z"&&input=="X"&&input=="C"&&input=="V"){ // return HangulKey = 0; // }else if(input=="Y"&&input=="U"&&input=="I"&&input=="O"&&input=="P"&&input=="H"&&input=="J"&&input=="K"&&input=="L"&&input=="B"&&input=="N"&&input=="M"){ // return HangulKey = 1; // } // } // HANGUL_STATE_FUNC HangulStart(char *input)//한글 처음 입력, 0일때 초성, 1일 때 모음 상태 // { // if(HangulKey==0) // return ChoState; // else if(HangulKey==1) // return S_JungState; // } // HANGUL_STATE_FUNC ChoState(char *input) // { // if(HangulKey==1) // return JungState; // else // return FirstFinal; // } // HANGUL_STATE_FUNC JungState(char *input) // { // if(HangulKey==0&&canBeJongsung) // return JongState; // else if(HangulKey==1&&Double_Jung) // return D_JungState; // } // HANGUL_STATE_FUNC JongState(char *input) // { // if(HangulKey==0&&Double_Jong) // return D_JongState; // else if(HangulKey==1) // return SecondFinal; // } // HANGUL_STATE_FUNC D_JongState(char *input) // { // if(HangulKey==1) // return SecondFinal; // else // return FirstFinal; // } //조합형 한글 매핑 규칙 unsigned char Hangulcode_table[3][28] = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 0, 0, 0, 0, 0, 0, 0} , //초성 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 0, 0, 0, 0, 0, 0}, //중성 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27} //종성 }; unsigned char jung_table[2][20] = { {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1}, //종성이 없을 때, 초성에 따른 중성의 벌 수 결정 {0, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3} //종성이 존재할 때, 초성에 따른 중성의 벌 수 결정 }; unsigned char cho_jong_table[3][22] = { {0, 0, 2, 0, 2, 1, 2, 1, 2, 3, 0, 2, 1, 3, 3, 1, 2, 1, 3, 3, 1, 1}, //중성에 따른 종성의 벌 수 결정 {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 3, 3, 1, 2, 4, 4, 4, 2, 1, 3, 0}, //종성이 없을 때, 중성에 따른 초성의 벌 수 결정 {0, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 6, 6, 7, 7, 7, 6, 6, 7, 5} //종성이 존재할 때, 중성에 따른 초성의 벌 수 결정 }; #endif<file_sep>/* 그래픽 처리 관계 */ #include "bootpack.h" void init_palette(void) { static unsigned char table_rgb[16 * 3] = { 0x00, 0x00, 0x00, /* 0:흑 */ 0xff, 0x00, 0x00, /* 1:밝은 빨강 */ 0x00, 0xff, 0x00, /* 2:밝은 초록 */ 0xff, 0xff, 0x00, /* 3:밝은 황색 */ 0x00, 0x00, 0xff, /* 4:밝은 파랑 */ 0xff, 0x00, 0xff, /* 5:밝은 보라색 */ 0x00, 0xff, 0xff, /* 6:밝은 물색 */ 0xff, 0xff, 0xff, /* 7:흰색 */ 0xc6, 0xc6, 0xc6, /* 8:밝은 회색 */ 0x84, 0x00, 0x00, /* 9:어두운 빨강 */ 0x00, 0x84, 0x00, /* 10:어두운 초록 */ 0x84, 0x84, 0x00, /* 11:어두운 황색 */ 0x00, 0x00, 0x84, /* 12:어두운 파랑 */ 0x84, 0x00, 0x84, /* 13:어두운 보라색 */ 0x00, 0x84, 0x84, /* 14:어두운 물색 */ 0x84, 0x84, 0x84 /* 15:어두운 회색 */ }; set_palette(0, 15, table_rgb); return; /* static char 명령은 데이터 밖에 사용할 수 없지만 DB명령에 상당 */ } void set_palette(int start, int end, unsigned char *rgb) { int i, eflags; eflags = io_load_eflags(); /* 인터럽트 허가 플래그의 값을 기록한다 */ io_cli(); /* 허가 플래그를 0으로 해 인터럽트 금지로 한다 */ io_out8(0x03c8, start); for (i = start; i <= end; i++) { io_out8(0x03c9, rgb[0] / 4); io_out8(0x03c9, rgb[1] / 4); io_out8(0x03c9, rgb[2] / 4); rgb += 3; } io_store_eflags(eflags); /* 인터럽트 허가 플래그를 원래대로 되돌린다 */ return; } void boxfill8(unsigned char *vram, int xsize, unsigned char c, int x0, int y0, int x1, int y1) { int x, y; for (y = y0; y <= y1; y++) { for (x = x0; x <= x1; x++) vram[y * xsize + x] = c; } return; } void init_screen8(char *vram, int x, int y) { boxfill8(vram, x, COL8_008484, 0, 0, x - 1, y - 29); boxfill8(vram, x, COL8_C6C6C6, 0, y - 28, x - 1, y - 28); boxfill8(vram, x, COL8_FFFFFF, 0, y - 27, x - 1, y - 27); boxfill8(vram, x, COL8_C6C6C6, 0, y - 26, x - 1, y - 1); boxfill8(vram, x, COL8_FFFFFF, 3, y - 24, 59, y - 24); boxfill8(vram, x, COL8_FFFFFF, 2, y - 24, 2, y - 4); boxfill8(vram, x, COL8_848484, 3, y - 4, 59, y - 4); boxfill8(vram, x, COL8_848484, 59, y - 23, 59, y - 5); boxfill8(vram, x, COL8_000000, 2, y - 3, 59, y - 3); boxfill8(vram, x, COL8_000000, 60, y - 24, 60, y - 3); boxfill8(vram, x, COL8_848484, x - 47, y - 24, x - 4, y - 24); boxfill8(vram, x, COL8_848484, x - 47, y - 23, x - 47, y - 4); boxfill8(vram, x, COL8_FFFFFF, x - 47, y - 3, x - 4, y - 3); boxfill8(vram, x, COL8_FFFFFF, x - 3, y - 24, x - 3, y - 3); return; } void putfont8(char *vram, int xsize, int x, int y, char c, char *font) { int i; char *p, d /* data */; for (i = 0; i < 16; i++) { p = vram + (y + i) * xsize + x; d = font[i]; if ((d & 0x80) != 0) { p[0] = c; } if ((d & 0x40) != 0) { p[1] = c; } if ((d & 0x20) != 0) { p[2] = c; } if ((d & 0x10) != 0) { p[3] = c; } if ((d & 0x08) != 0) { p[4] = c; } if ((d & 0x04) != 0) { p[5] = c; } if ((d & 0x02) != 0) { p[6] = c; } if ((d & 0x01) != 0) { p[7] = c; } } return; } void putfonts8_asc(char *vram, int xsize, int x, int y, char c, unsigned char *s) { extern char hankaku[4096]; extern char hangul[8800]; for (; *s != 0x00; s++) { // 만약 첫 비트가 1이면 hangul 을 쓰고 아니면 기존 hankaku를 사용한다. unsigned char firstbit = *s >> 7; if(firstbit==1){ short int character_korean = (*s << 8) + *(++s); int first = (character_korean >> 10) & 0x1f; int sec = (character_korean >> 5) & 0x1f; int third = character_korean & 0x1f; //조합형 한글 매핑 규칙 unsigned char Hangulcode_table[3][28] = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 0, 0, 0, 0, 0, 0, 0} , //초성 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 0, 0, 0, 0, 0, 0}, //중성 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27} //종성 }; unsigned char jung_table[2][20] = { {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1}, //종성이 없을 때, 초성에 따른 중성의 벌 수 결정 {0, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3} //종성이 존재할 때, 초성에 따른 중성의 벌 수 결정 }; unsigned char cho_jong_table[3][22] = { {0, 0, 2, 0, 2, 1, 2, 1, 2, 3, 0, 2, 1, 3, 3, 1, 2, 1, 3, 3, 1, 1}, //중성에 따른 종성의 벌 수 결정 {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 3, 3, 1, 2, 4, 4, 4, 2, 1, 3, 0}, //종성이 없을 때, 중성에 따른 초성의 벌 수 결정 {0, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 6, 6, 7, 7, 7, 6, 6, 7, 5} //종성이 존재할 때, 중성에 따른 초성의 벌 수 결정 }; char idx_cho = Hangulcode_table[0][first]; char idx_jung = Hangulcode_table[1][sec]; char idx_jong = Hangulcode_table[2][third]; char cho_bul, jung_bul, jong_bul; if(third==0){ //종성이 없을 때 cho_bul = cho_jong_table[1][idx_jung]; //중성에 따른 초성 벌 수 결정 switch(cho_bul){ //각 벌 수에 따른 오프셋 설정 case 0:first = first*2 + 0;break; //초성 1벌 받침 없는 ㅏㅐㅑㅒㅓㅔㅕㅖㅣ결합 case 1:first = first*2 + 0x28;break;//초성 2벌 받침 없는 ㅗㅛㅡ와 결합 case 2:first = first*2 + 0x50;break;//초성 3벌 받침 없는 ㅜㅠ 와 결합 case 3:first = first*2 + 0x78;break;//초성 4벌 받침 없는 ㅘㅙㅚㅢ 와 결합 case 4:first = first*2 + 0xa0;break;//초성 5벌 받침 없는 ㅝㅞㅟ와 결합 } jung_bul = jung_table[0][idx_cho]; //초성에 따른 중성 벌 수 결정 switch(jung_bul){ case 0:sec = sec*2 + 0x140;break; //중성 1벌 ㄱㅋ와 결합 case 1:sec = sec*2 + 0x16c;break; //중성 2벌 ㄱㅋ이외의 결합 } jong_bul = 0; }else{ cho_bul = cho_jong_table[2][idx_jung]; //중성에 따른 초벌 벌 수 결정 switch(cho_bul){ case 5:first = first*2 + 0xc8;break;//초성 6벌 받침 있는 ㅏㅐㅑㅒㅓㅔㅕㅖㅣ와 결합 case 6:first = first*2 + 0xf0;break;//초성 7벌 받침 있는 ㅗㅛㅜㅠㅡ와 결합 case 7:first = first*2 + 0x118;break;//초성 8벌 받침있는 ㅘㅙㅚㅢㅝㅞㅟ와 결합 } jung_bul = jung_table[1][idx_cho];//초성에 따른 중성 벌 수 결정 switch(jung_bul){ case 2:sec = sec*2 + 0x198;break;//중성 3벌 받침 있는 ㄱㅋ와 결합 case 3:sec = sec*2 + 0x1c4;break;//중성 4벌 받침있는 ㄱㅋ이외의 결합 } jong_bul = cho_jong_table[0][idx_jung]; //중성에 따른 종성 벌 수 결정 switch(jong_bul){ case 0:third = third*2 + 0x1f0;break;//종성 1벌 ㅏㅑㅘ와 결합 case 1:third = third*2 + 0x228;break;//종성 2벌 ㅓㅕㅚㅝㅟㅢㅣ와 결합 case 2:third = third*2 + 0x260;break;//종성 3벌 ㅐㅒㅔㅖㅙㅞ와 결합 case 3:third = third*2 + 0x298;break;//종성 4벌 ㅗㅛㅜㅠㅡ와 결합 } } putfont8(vram, xsize, x, y, c, hangul + first * 16); putfont8(vram, xsize, x+8, y, c, hangul + (first + 1) * 16); putfont8(vram, xsize, x, y, c, hangul + sec * 16); putfont8(vram, xsize, x+8, y, c, hangul + (sec+1) * 16); putfont8(vram, xsize, x, y, c, hangul + third * 16); putfont8(vram, xsize, x+8, y, c, hangul + (third+1) * 16); }else{ putfont8(vram, xsize, x, y, c, hankaku + *s * 16); x += 8; } } return; } void init_mouse_cursor8(char *mouse, char bc) /* 마우스 커서를 준비(16 x16) */ { static char cursor[16][16] = { "**************..", "*OOOOOOOOOOO*...", "*OOOOOOOOOO*....", "*OOOOOOOOO*.....", "*OOOOOOOO*......", "*OOOOOOO*.......", "*OOOOOOO*.......", "*OOOOOOOO*......", "*OOOO**OOO*.....", "*OOO*..*OOO*....", "*OO*....*OOO*...", "*O*......*OOO*..", "**........*OOO*.", "*..........*OOO*", "............*OO*", ".............***" }; int x, y; for (y = 0; y < 16; y++) { for (x = 0; x < 16; x++) { if (cursor[y][x] == '*') { mouse[y * 16 + x] = COL8_000000; } if (cursor[y][x] == 'O') { mouse[y * 16 + x] = COL8_FFFFFF; } if (cursor[y][x] == '.') { mouse[y * 16 + x] = bc; } } } return; } void putblock8_8(char *vram, int vxsize, int pxsize, int pysize, int px0, int py0, char *buf, int bxsize) { int x, y; for (y = 0; y < pysize; y++) { for (x = 0; x < pxsize; x++) { vram[(py0 + y) * vxsize + (px0 + x)] = buf[y * bxsize + x]; } } return; } <file_sep>/* bootpack의 메인 */ #include "bootpack.h" #include <stdio.h> void HariMain(void) { struct BOOTINFO *binfo = (struct BOOTINFO *) ADR_BOOTINFO; unsigned char s[40], mcursor[256]; int mx, my; init_gdtidt(); init_pic(); io_sti(); /* IDT/PIC의 초기화가 끝났으므로 CPU의 인터럽트 금지를 해제 */ init_palette(); init_screen8(binfo->vram, binfo->scrnx, binfo->scrny); mx = (binfo->scrnx - 16) / 2; /* 화면 중앙이 되도록 좌표 계산 */ my = (binfo->scrny - 28 - 16) / 2; init_mouse_cursor8(mcursor, COL8_008484); putblock8_8(binfo->vram, binfo->scrnx, 16, 16, mx, my, mcursor, 16); //한글 문자 출력을 위한 배열 (1배열 = 1글자) unsigned char s1[20], s2[20], s3[20], s4[20], s5[20], s6[20], s7[20], s8[20], s9[20], s10[20], s11[20], s12[20], s13[20], s14[20], s15[20], s16[20], s17[20], s18[20], s19[20], k1[2], k2[2], k3[2]; // ㄱ~ㅎ ㅑ(3) ㄹㅁ(10) // 1 [000/10] [00/011] [0/1010] 한글비트 s1[0] = 0x84, s1[1] = 0x6a; s2[0] = 0x88, s2[1] = 0x6a; s3[0] = 0x8c, s3[1] = 0x6a; s4[0] = 0x90, s4[1] = 0x6a; s5[0] = 0x94, s5[1] = 0x6a; s6[0] = 0x98, s6[1] = 0x6a; s7[0] = 0x9c, s7[1] = 0x6a; s8[0] = 0xa0, s8[1] = 0x6a; s9[0] = 0xa4, s9[1] = 0x6a; s10[0] = 0xa8, s10[1] = 0x6a; s11[0] = 0xac, s11[1] = 0x6a; s12[0] = 0xb0, s12[1] = 0x6a; s13[0] = 0xb4, s13[1] = 0x6a; s14[0] = 0xb8, s14[1] = 0x6a; s15[0] = 0xbc, s15[1] = 0x6a; s16[0] = 0xc0, s16[1] = 0x6a; s17[0] = 0xc4, s17[1] = 0x6a; s18[0] = 0xc8, s18[1] = 0x6a; s19[0] = 0xcc, s19[1] = 0x6a; putfonts8_asc(binfo->vram, binfo->scrnx, 0, 0, COL8_FFFFFF, s1); putfonts8_asc(binfo->vram, binfo->scrnx, 16, 0, COL8_FFFFFF, s2); putfonts8_asc(binfo->vram, binfo->scrnx, 32, 0, COL8_FFFFFF, s3); putfonts8_asc(binfo->vram, binfo->scrnx, 48, 0, COL8_FFFFFF, s4); putfonts8_asc(binfo->vram, binfo->scrnx, 64, 0, COL8_FFFFFF, s5); putfonts8_asc(binfo->vram, binfo->scrnx, 80, 0, COL8_FFFFFF, s6); putfonts8_asc(binfo->vram, binfo->scrnx, 96, 0, COL8_FFFFFF, s7); putfonts8_asc(binfo->vram, binfo->scrnx, 112, 0, COL8_FFFFFF, s8); putfonts8_asc(binfo->vram, binfo->scrnx, 128, 0, COL8_FFFFFF, s9); putfonts8_asc(binfo->vram, binfo->scrnx, 144, 0, COL8_FFFFFF, s10); putfonts8_asc(binfo->vram, binfo->scrnx, 160, 0, COL8_FFFFFF, s11); putfonts8_asc(binfo->vram, binfo->scrnx, 176, 0, COL8_FFFFFF, s12); putfonts8_asc(binfo->vram, binfo->scrnx, 192, 0, COL8_FFFFFF, s13); putfonts8_asc(binfo->vram, binfo->scrnx, 208, 0, COL8_FFFFFF, s14); putfonts8_asc(binfo->vram, binfo->scrnx, 224, 0, COL8_FFFFFF, s15); putfonts8_asc(binfo->vram, binfo->scrnx, 240, 0, COL8_FFFFFF, s16); putfonts8_asc(binfo->vram, binfo->scrnx, 256, 0, COL8_FFFFFF, s17); putfonts8_asc(binfo->vram, binfo->scrnx, 272, 0, COL8_FFFFFF, s18); putfonts8_asc(binfo->vram, binfo->scrnx, 288, 0, COL8_FFFFFF, s19); k1[0] = 0x84, k1[1] = 0x00; //ㄱ k2[0] = 0x80, k2[1] = 0x40; //ㅏ k3[0] = 0x80, k2[1] = 0x00; //fill putfonts8_asc(binfo->vram, binfo->scrnx, 0, 32, COL8_FFFFFF, k1); putfonts8_asc(binfo->vram, binfo->scrnx, 16, 32, COL8_FFFFFF, k2); io_out8(PIC0_IMR, 0xf9); /* PIC1와 키보드를 허가(11111001) */ io_out8(PIC1_IMR, 0xef); /* 마우스를 허가(11101111) */ for (;;) { io_hlt(); } }
1dd8ab3488a6cb3e8af2e70c14d507ef80662ffb
[ "C" ]
3
C
Chrisaor/haribote_for_hangul
8752e9b7c22f82067a5bb8921f626024e5c79957
b71ccc2261e24c6fc0aaa87801b594edebeb711e
refs/heads/master
<file_sep>let express = require('express'); let router = express.Router(); const controlador = require('../controller/indexController'); router.get('/' , (req,res) => { //leo todo el array de productos en el controlador homeController const products = controlador.leerTodos(); //envio el array prodcut a la vista para que la recorra EJS console.log("Volvi del controlador") res.render('index' , {products}); }) module.exports = router;<file_sep>const express = require('express'); const { dirname } = require('path'); const app = express(); const path = require ('path'); const puerto = process.env.PORT; app.use(express.static('public')); //dodnde estan los gerentes de ruteo const indexRouter = require('./routes/indexRouter'); /* const userRouter = require('./routes/userRouter'); const productRouter = require('./routes/productRouter'); */ app.set('view engine', 'ejs'); // llamo al ruteo app.use('/' , indexRouter); /* app.use('/' , userRouter); app.use('/' , productRouter); */ app.listen(puerto || 3000, () => { console.log("Servidor corriendo en el puerto 3000"); });<file_sep>const visitados = require('../data/datosProductos'); let controlador = { leerTodos : function (){ console.log('leo productos desde data'); return visitados; } } module.exports = controlador;
09048348c881f4f0a4285d15ec87e45d1bb7e7c6
[ "JavaScript" ]
3
JavaScript
Marc319-jr/MercadoLiebreM51
ead183db593fa322e3badabcef004bf2cfad8a6d
2d1f29606a628156ef8c94fbd8f0fd774c514a89
refs/heads/master
<repo_name>willemwouters/orangepi_uboot<file_sep>/tools/pack/make2.sh cp -fv chips/sun8iw7p1/bin/u-boot-sun8iw7p1.bin out/u-boot.fex pctools/linux/mod_update/update_uboot out/u-boot.fex out/sys_config.bin <file_sep>/tools/pack/make.sh # Copy fex file cp -fv chips/sun8iw7p1/configs/dolphin-p1/sys_config.fex out/sys_config.fex # Copy boot0 cp -fv chips/sun8iw7p1/bin/boot0_sdcard_sun8iw7p1.bin out/boot0_sdcard.fex # Fex file compiler requires fex file in CRLF format unix2dos out/sys_config.fex # Compile fex file pctools/linux/mod_update/script out/sys_config.fex fex2bin out/sys_config.fex out/sys_config.bin pctools/linux/mod_update/update_boot0 out/boot0_sdcard.fex out/sys_config.bin SDMMC_CARD <file_sep>/build.sh #!/bin/bash set -e PLATFORM="sun8iw3p1" MODE="" show_help() { printf "\nbuild.sh - Top level build scritps\n" echo "Valid Options:" echo " -h Show help message" echo " -p <platform> platform, e.g. sun5i, sun6i, sun8iw1p1, sun8iw3p1, sun9iw1p1" echo " -m <mode> mode, e.g. ota_test" printf "\n\n" } build_uboot() { cd u-boot-2011.09/ make distclean if [ "x$MODE" = "xota_test" ] ; then export "SUNXI_MODE=ota_test" fi make ${PLATFORM}_config make -j16 if [ ${PLATFORM} = "sun8iw6p1" ] || [ ${PLATFORM} = "sun8iw7p1" ] || [ ${PLATFORM} = "sun8iw8p1" ] || [ ${PLATFORM} = "sun9iw1p1" ] || [ ${PLATFORM} = "sun8iw5p1" ] ; then make spl fi cd - 1>/dev/null } while getopts p:m: OPTION do case $OPTION in p) PLATFORM=$OPTARG ;; m) MODE=$OPTARG ;; *) show_help exit ;; esac done build_uboot
d70760aca6e8f1e211b10f603491f2a3a6eda393
[ "Shell" ]
3
Shell
willemwouters/orangepi_uboot
41dcebbb934d65023abde3237100da9d0b428b90
9c0867405e3623ea0ffa01215de4435b62aaba21
refs/heads/master
<file_sep>// Schema describes data in the graph const graphql = require('graphql'); const _ = require('lodash'); const Book = require('../models/book'); const Author = require('../models/author'); // Dummy data removed. // Define type. const { GraphQLObjectType, GraphQLString, GraphQLSchema, GraphQLID, GraphQLInt, GraphQLList, GraphQLNonNull } = graphql; const BookType = new GraphQLObjectType({ name: 'Book', // Fields need to have a function value. fields: () => ({ id: {type: GraphQLID}, name: {type: GraphQLString}, genre: {type: GraphQLString}, author: { type: AuthorType, resolve(parent, args){ // resolve function finds in the author array // an author with an id called id that is the SAME // as the parent.authorId OR current book we just queried author ID. // console.log(parent); // return _.find(authors, {id: parent.authorId}); return Author.findById(parent.authorId) } } }) }); const AuthorType = new GraphQLObjectType({ name: 'Author', // Fields need to have a function value. fields: () => ({ id: {type: GraphQLID}, name: {type: GraphQLString}, age: {type: GraphQLInt}, books: { type: new GraphQLList(BookType), resolve(parent, args){ // return books.filter(bk => bk.authorId === parent.id) return Book.find({ authorId: parent.id }) } } }) }); // Root queries. Graph data entry point. // How we initially jump into the graph. // We'll have multiple root queries eventually. const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', // One root query can be to get a book, one to get an author // one to get all books, and another for all authors. // NOT in a function unlike above. fields: { // Book query book: { // Type of data is a BookType. // Having args mean that the query will require arguments to be passed along. type: BookType, args: {id: {type: GraphQLID}}, resolve(parent, args){ // CODE TO GET DATA FROM DB / OTHER SOURCE // we return what we want to send back. // return _.find(books, {id: args.id}); return Book.findById(args.id); } }, // Author query author: { type: AuthorType, args: {id: {type: GraphQLID}}, resolve(parent, args){ // return _.find(authors, {id: args.id}); return Author.findById(args.id); } }, // BookS Query (FOR A LIST OF BOOKS) books: { type: new GraphQLList(BookType), resolve(parent, args){ // return books; // No query object means return everything return Book.find({}); } }, // AuthorS query authors: { type: new GraphQLList(AuthorType), resolve(parent, args){ // return authors; return Author.find({}); } } } }); const Mutation = new GraphQLObjectType({ name: 'Mutation', fields: { addAuthor: { type: AuthorType, args: { name: {type: new GraphQLNonNull(GraphQLString)}, age: {type: new GraphQLNonNull(GraphQLInt)} }, resolve(parent, args){ let author = new Author({ name: args.name, age: args.age }); return author.save(); } }, addBook: { type: BookType, args: { name: {type: new GraphQLNonNull(GraphQLString)}, genre: {type: new GraphQLNonNull(GraphQLString)}, authorId: {type: new GraphQLNonNull(GraphQLID)} }, resolve(parent, args){ let book = new Book({ name: args.name, genre: args.genre, authorId: args.authorId }); return book.save(); } } } }) module.exports = new GraphQLSchema({ query: RootQuery, mutation: Mutation });<file_sep>const express = require('express'); const graphqlHTTP = require('express-graphql'); const mongoose = require('mongoose'); const cors = require('cors'); // import schema const schema = require('./schema/schema'); const app = express(); // Allow cross-origin requests app.use(cors()); // Connect to mLab database // Make sure to replace my DB string and Creds with my own. mongoose.connect('mongodb+srv://nexticus_gql:<EMAIL>.<EMAIL>/test?retryWrites=true&w=majority'); mongoose.connection.once('open', () => { console.log('Connected to database!'); }) // Middleware // Because JS doesn't inherently understand GraphQL, make express use a middleware that will // pass all graphql queries made into the /graphql route TO the graphqlHTTP function. app.use('/graphql', graphqlHTTP({ // Options (REQUIRED) schema, graphiql: true, })) app.listen(4000, () => { console.log('Listening for requests on port 4000!'); })
6a403fb2859967a11bd6801bb27c564fbc1cf7bb
[ "JavaScript" ]
2
JavaScript
nexticodes/GraphQL-Reading-List
c9f961603380148168bf993a07a63eeba2b2829c
44ed605242bab2bcb523a86c511470dbf325ae01
refs/heads/master
<repo_name>manuelprg/quiz-2015<file_sep>/controllers/quiz_controller.js exports.question = function(req, res) { res.render('quizes/question', {pregunta:'Capital de Italia'}); } exports.answer = function(req, res) { if (req.query.respuesta === 'Roma') { res.render('quizes/answer', {respuesta:'Respuesta Correcta'}); } else { res.render('quizes/answer', {respuesta:'Respuesta Incorrecta'}); } }
c32ce762fe018724fde8115116142459f60254a6
[ "JavaScript" ]
1
JavaScript
manuelprg/quiz-2015
9c0f3f3d4a123c0b75465b1bb150da8b5ef4f084
28cc34ac79b8acb53035d09e4a67b046e73b6836
refs/heads/master
<file_sep>namespace naive_bayes { using System.Collections.Generic; public interface Segment { IEnumerable<string> Process(string input); } } <file_sep>namespace naive_bayes { using System; using System.Collections.Generic; public class LengthTokenFilter : Segment { public LengthTokenFilter(Func<int, bool> predicate) { this.predicate = predicate; } private readonly Func<int, bool> predicate; public IEnumerable<string> Process(string input) { if (predicate(input.Length)) yield return input; } } } <file_sep>namespace naive_bayes { using System.Collections.Generic; using System.Linq; public class Tokenizer : Segment { public Tokenizer(params Segment[] segments) { this.segments = segments.ToList(); } private readonly List<Segment> segments; public IEnumerable<string> Process(string input) { IEnumerable<string> result = new[] { input }; foreach (var t in segments) { result = result.SelectMany(s => t.Process(s)); } return result; } } } <file_sep>namespace naive_bayes { using System.Collections.Generic; public class EmptyTokenFilter : Segment { public EmptyTokenFilter() { } public IEnumerable<string> Process(string input) { if (!string.IsNullOrWhiteSpace(input)) yield return input; } } } <file_sep>namespace naive_bayes { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Accord.MachineLearning.Bayes; using F23.StringSimilarity; using TinyCsvParser; using TinyCsvParser.Mapping; public class BrandRecord { public string Input { get; set; } public string ClassName { get; set; } public string SubClassName { get; set; } } public class BrandRecordMapping : CsvMapping<BrandRecord> { public BrandRecordMapping() : base() { MapProperty(0, x => x.Input); MapProperty(1, x => x.ClassName); MapProperty(2, x => x.SubClassName); } } class Program { static void Main(string[] args) { CsvParserOptions csvParserOptions = new CsvParserOptions(true, ';'); BrandRecordMapping csvMapper = new BrandRecordMapping(); CsvParser<BrandRecord> csvParser = new CsvParser<BrandRecord>(csvParserOptions, csvMapper); Tokenizer tokenizer = new Tokenizer( new SymbolTokenizer(' ', '.', ',', ';', '`', '+', '[', '?', ']', '*', '\\', ')'), new RegexFilter(@"\W+"), new LowercaseFilter(), new AsciiFoldingFilter(), // new LengthTokenFilter(len => len > 1), new EmptyTokenFilter() ); var dataset = csvParser .ReadFromFile(@"training.csv", Encoding.UTF8) .Where(x => x.IsValid) .Select(x => x.Result) .ToArray(); NaiveBayes topPredictor = new NaiveBayes(tokenizer); topPredictor.Fit(dataset.Select(row => (row.Input, row.ClassName))); Dictionary<string, NaiveBayes> subPredictor = new Dictionary<string, NaiveBayes>(); foreach (var className in topPredictor.ClassList) { var subDataset = dataset .Where(row => row.ClassName == className) .Select(row => (row.Input, row.SubClassName)); var predictor = new NaiveBayes(tokenizer); predictor.Fit(subDataset); subPredictor[className] = predictor; } int okBrand = 0; int okModel = 0; Parallel.ForEach(dataset, row => { var classNames = topPredictor.Predict(row.Input); var topClassName = classNames.First().Item1; var subClassNames = subPredictor[topClassName].Predict(row.Input); var topSubClassName = subClassNames.First().Item1; if (topClassName == row.ClassName) Interlocked.Increment(ref okBrand); if (topSubClassName == row.SubClassName) Interlocked.Increment(ref okModel); }); Console.WriteLine($"Brand: {okBrand / (double) dataset.Length * 100}%"); Console.WriteLine($"Model: {okModel / (double) dataset.Length * 100}%"); } } } <file_sep>namespace naive_bayes { using System.Collections.Generic; using System.Linq; public class SymbolTokenizer : Segment { public SymbolTokenizer(params char[] symbols) { this.symbols = symbols; } private readonly char[] symbols; public IEnumerable<string> Process(string input) { return input.Split(symbols).Where(x => !string.IsNullOrWhiteSpace(x)); } } } <file_sep>namespace naive_bayes { using System.Collections.Generic; using System.Text.RegularExpressions; public class RegexFilter : Segment { public RegexFilter(string pattern) { this.pattern = new Regex(pattern); } private readonly Regex pattern; public IEnumerable<string> Process(string input) { var s = pattern.Replace(input, ""); if (!string.IsNullOrWhiteSpace(s)) yield return s; } } } <file_sep>namespace naive_bayes { using System.Collections.Generic; public class LowercaseFilter : Segment { public IEnumerable<string> Process(string input) { yield return input.ToLowerInvariant(); } } } <file_sep>namespace naive_bayes { using System.Collections.Generic; using System.Globalization; using System.Text; public class AsciiFoldingFilter : Segment { public IEnumerable<string> Process(string input) { yield return RemoveDiacritics(input, true); } public static IEnumerable<char> RemoveDiacriticsEnum(string src, bool compatNorm) { foreach(char c in src.Normalize(compatNorm ? NormalizationForm.FormKD : NormalizationForm.FormD)) switch(CharUnicodeInfo.GetUnicodeCategory(c)) { case UnicodeCategory.NonSpacingMark: case UnicodeCategory.SpacingCombiningMark: case UnicodeCategory.EnclosingMark: break; default: yield return c; break; } } public static string RemoveDiacritics(string src, bool compatNorm) { StringBuilder sb = new StringBuilder(); foreach(char c in RemoveDiacriticsEnum(src, compatNorm)) sb.Append(c); return sb.ToString(); } } } <file_sep>namespace naive_bayes { using System; using System.Collections.Generic; using System.Linq; public class NaiveBayes { public NaiveBayes(Tokenizer tokenizer) { this.tokenizer = tokenizer; } private readonly Tokenizer tokenizer; public int TotalRecordCount; public readonly List<string> ClassList = new List<string>(); public readonly List<int> ClassCount = new List<int>(); public readonly List<Dictionary<string, int>> ClassTokenCount = new List<Dictionary<string, int>>(); public double[] ClassPropb; public readonly HashSet<string> Vocab = new HashSet<string>(); public void Fit(IEnumerable<(string text, string className)> records) { foreach (var rec in records) { TotalRecordCount++; var tokens = tokenizer.Process(rec.text).ToArray();; Vocab.UnionWith(tokens); var classIndex = ClassList.IndexOf(rec.className); if (classIndex < 0) { ClassList.Add(rec.className); ClassCount.Add(0); ClassTokenCount.Add(new Dictionary<string, int>()); classIndex = ClassList.Count - 1; } ClassCount[classIndex]++; var tc = ClassTokenCount[classIndex]; foreach (var t in tokens) { if (!tc.ContainsKey(t)) tc[t] = 0; tc[t]++; } } ClassPropb = new double[ClassList.Count]; for (var i = 0; i < ClassPropb.Length; i++) { ClassPropb[i] = Math.Log(ClassCount[i] / (double) TotalRecordCount); } } public (string, double)[] Predict(string input) { (int inClass, int outClass) getTokenCount(int classIndex, string token) { var inClass = 0; var outClass = 0; for (var i = 0; i < ClassList.Count; i++) { if (i == classIndex) { inClass += ClassTokenCount[i].TryGetValue(token, out var cnt) ? cnt : 0; } else { outClass += ClassTokenCount[i].TryGetValue(token, out var cnt) ? cnt : 0; } } return (inClass, outClass); } var tokens = tokenizer.Process(input).ToArray(); double[] scoreYes = new double[ClassList.Count]; double[] scoreNo = new double[ClassList.Count]; Array.Fill(scoreYes, 0.0); Array.Fill(scoreNo, 0.0); foreach (var t in tokens) { if (!Vocab.Contains(t)) continue; for (var i = 0; i < ClassList.Count; i++) { var (yesClassTokenCount, noClassTokenCount) = getTokenCount(i, t); var yesClassTotalCount = ClassCount[i]; var noClassTotalCount = TotalRecordCount - yesClassTotalCount; var yesP = Math.Log((yesClassTokenCount + 1) / (double) (yesClassTotalCount + Vocab.Count)); var noP = Math.Log((noClassTokenCount + 1) / (double) (noClassTotalCount + Vocab.Count)); scoreYes[i] += yesP; scoreNo[i] += noP; } } // adjust result with class porbabilities // for (var i = 0; i < ClassList.Count; i++) { // scoreYes[i] += ClassPropb[i]; // scoreNo[i] += ClassPropb.Where((_, j) => i != j).Sum(); // } return scoreYes.Zip(scoreNo, (yes, no) => { var total = Math.Abs(yes) + Math.Abs(no); return (yes + total) / (yes + no + total * 2); }) .Select((p, i) => (ClassList[i], p)) .OrderByDescending(x => x.Item2) .ToArray(); } } }
8ca954d559609c72de52f0bbb41c9ddcd2cf939d
[ "C#" ]
10
C#
valdisz/naive-bayes
30f21b1e561c16c6f6989679c2729da81f4c1d6d
702a0a8973ef473b14da99bf81638ac57f93e689
refs/heads/master
<file_sep>package com.rilixtech; /** * Created by hbb20 on 11/1/16. * * Clean up and moving all Country related code to {@link CountryUtils}. * a pojo should be a pojo and no more. * * Updated by Joielechong 13 May 2017 */ public class Country { private String nameCode; private String phoneCode; private String name; public Country(String nameCode, String phoneCode, String name) { this.nameCode = nameCode; this.phoneCode = phoneCode; this.name = name; } public String getNameCode() { return nameCode; } public void setNameCode(String nameCode) { this.nameCode = nameCode; } public String getPhoneCode() { return phoneCode; } public void setPhoneCode(String phoneCode) { this.phoneCode = phoneCode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getFlagDrawableResId() { return CountryUtils.getFlagDrawableResId(this); } /** * If country have query word in name or name code or phone code, this will return true. */ public boolean isEligibleForQuery(String query) { query = query.toLowerCase(); return getName().toLowerCase().contains(query) || getNameCode().toLowerCase().contains(query) || getPhoneCode().toLowerCase().contains(query); } }
a415fb48adfa7a9c8bdc3b680d3603e6f77ff3b7
[ "Java" ]
1
Java
tazmaniane/CountryCodePicker
0c887078b6c865854d261ee81f9d45985e3095d7
797ba3af8432ae1dd663abf545191a8cdcc76521
refs/heads/master
<file_sep># created at 2020-10-26 04:58:59 +0900 # /mnt/c/Dropbox/www/crawle/data 5 # /mnt/c/Dropbox/www/crawle/node_modules 186 # /mnt/c/Dropbox/www/fancy-date/node_modules 405 # /mnt/c/Dropbox/www/giji-fire-new/node_modules 1189 # /mnt/c/Dropbox/www/giji-next/functions/node_modules 498 # /mnt/c/Dropbox/www/giji-next/node_modules 807 # /mnt/c/Dropbox/www/giji/node_modules 228 # /mnt/c/Dropbox/www/giji_assets_chr_add/node_modules 649 # /mnt/c/Dropbox/www/memory-orm/node_modules 1148 # /mnt/c/Dropbox/www/nextjs-blog/node_modules 509 # /mnt/c/Dropbox/www/react-petit-hooks/node_modules 1095 # /mnt/c/Dropbox/www/rfc6238/node_modules 55 # /mnt/c/Dropbox/www/sequence-await/node_modules 721 # /mnt/c/Dropbox/www/vue-petit-store/node_modules 811 # empty. /mnt/c/Dropbox/www/DefinitelyTyped/node_modules # empty. /mnt/c/Dropbox/www/giji-fire-new/functions/node_modules # empty. /mnt/c/Dropbox/www/giji-fire/functions/node_modules # empty. /mnt/c/Dropbox/www/giji-fire/node_modules # empty. /mnt/c/Dropbox/www/markdown-loader/node_modules # empty. /mnt/c/Dropbox/www/mermaid/node_modules # empty. /mnt/c/Dropbox/www/test-react-app/node_modules # empty. /mnt/c/Dropbox/www/trix/node_modules # empty. /mnt/c/Dropbox/www/vue-markup/node_modules # /mnt/c/Dropbox/www/giji-gatsby/node_modules -> /mnt/c/Documents/www/giji-gatsby/node_modules # mkdir -p /mnt/c/Documents/www/giji-gatsby/node_modules # rm -rf /mnt/c/Dropbox/www/giji-gatsby/node_modules ln -s /mnt/c/Documents/www/giji-gatsby/node_modules /mnt/c/Dropbox/www/giji-gatsby/node_modules # /mnt/c/Dropbox/www/sow-giji/cabala/data -> /mnt/c/Documents/www/sow-giji/cabala/data # mkdir -p /mnt/c/Documents/www/sow-giji/cabala/data # rm -rf /mnt/c/Dropbox/www/sow-giji/cabala/data ln -s /mnt/c/Documents/www/sow-giji/cabala/data /mnt/c/Dropbox/www/sow-giji/cabala/data # /mnt/c/Dropbox/www/sow-giji/master/data -> /mnt/c/Documents/www/sow-giji/master/data # mkdir -p /mnt/c/Documents/www/sow-giji/master/data # rm -rf /mnt/c/Dropbox/www/sow-giji/master/data ln -s /mnt/c/Documents/www/sow-giji/master/data /mnt/c/Dropbox/www/sow-giji/master/data # /mnt/c/Dropbox/www/sow-giji/node_modules -> /mnt/c/Documents/www/sow-giji/node_modules # mkdir -p /mnt/c/Documents/www/sow-giji/node_modules # rm -rf /mnt/c/Dropbox/www/sow-giji/node_modules ln -s /mnt/c/Documents/www/sow-giji/node_modules /mnt/c/Dropbox/www/sow-giji/node_modules # /mnt/c/Dropbox/www/sow-giji/show-fix/data -> /mnt/c/Documents/www/sow-giji/show-fix/data # mkdir -p /mnt/c/Documents/www/sow-giji/show-fix/data # rm -rf /mnt/c/Dropbox/www/sow-giji/show-fix/data ln -s /mnt/c/Documents/www/sow-giji/show-fix/data /mnt/c/Dropbox/www/sow-giji/show-fix/data <file_sep># -*- encoding: utf-8 -*- # set RUBYOPT=-EUTF-8 class Media::Copy < Media::Base PICTURE = ".{jpg,jpeg,png}" def self.photo_scan(globbed) list = [] globbed.each do |src| list.push new(src) end list end def initialize(src) ext = src[/\.[^.]+$/] @src = src media_path out_path + ext end def do_deploy if @dir %Q|mkdir "#{@dir}"| end end def do_release nil end def do_encode if File.exists?(@work) nil else %Q|cp "#{@src}" "#{@work}"| end end end <file_sep># -*- encoding: utf-8 -*- # set RUBYOPT=-EUTF-8 require "open3" require "./task/HandBrake/lib/media" class Packer AUDIO = ".{wma,flac}" COPY = ".{mp3,jpg,jpeg,png,zip}" ARC = ".{lzh,rar}" def initialize @sources = [] @deploys = [] @commands = [] @releases = [] end def add(list) @sources += list end def encode end def do_exec(log, cmd) return unless cmd log.puts cmd puts cmd o, e, s = Open3.capture3 cmd puts e s end def exec open(ENV.deploy_log, "w") do |f| @sources.map {|item| item.do_deploy }.compact.uniq.sort.each do |cmd| do_exec f, cmd end @releases = [] @sources.each do |item| begin cmd = item.do_encode if cmd if do_exec(f, cmd).success? @releases.push item.do_release end else @releases.push item.do_release end rescue Interrupt => e sleep 1 do_exec f, item.do_reject raise e end end end open(ENV.release_log, "w") do |f| @releases.compact.uniq.sort.each do |cmd| do_exec f, cmd end end end end <file_sep>require 'open-uri' require 'yaml' OUTPUT = "../giji/app/yaml/work_namedb_ancient.yml" IS_DONE = {} URL_HEAD = "http://www.efendi.jp/rq/script/languages/ancient/names/" COUNTRYS = [ # ["ALLAH" , "神", "allah_names.html"], ["EGY" , "古アラブ", "arab_names.html"], ["EGY" , "古カナアン", "canaanite_names.html"], ["CHN" , "古中国", "chinese_names.html"], ["CZE" , "古クロアチア", "croatian_names.html"], ["CZE" , "古チェコ", "czech_names.html"], ["DEN" , "古デンマーク", "danish_names.html"], ["NED" , "古オランダ", "dutch_names.html"], ["USA" , "古イギリス", "english_names.html"], ["FIN" , "古フィンランド", "finnish_names.html"], ["FRA" , "古フランス", "french_names.html"], ["GER" , "古ドイツ", "german_names.html"], ["GRE" , "古ギリシャ", "greek_names.html"], ["ISR" , "古ヘブライ", "hebrew_names.html"], ["HUN" , "古ハンガリー", "hungarian_names.html"], ["IND" , "古インド", "indian_names.html"], ["ITA" , "古イタリア", "italian_names.html"], ["CHN" , "古韓国", "korean_names.html"], ["ITA" , "古ローマ", "latin_names.html"], ["NOR" , "古ノルウェー", "norwegian_names.html"], ["IRI" , "古ペルシア", "persian_names.html"], ["POL" , "古ポーランド", "polish_names.html"], ["POR" , "古ポルトガル", "portuguese_names.html"], ["RUS" , "古ロシア", "russian_names.html"], ["ESP" , "古スペイン", "spanish_names.html"], ["SWE" , "古スウェーデン", "swedish_names.html"], ["THA" , "古タイ", "thai_names.html"], ["TUR" , "古トルコ", "turkish_names.html"], ] $CODES = { 'nbsp' => "\u00A0", 'lt' => '<', 'gt' => '>', 'amp' => '&', 'quot' => '\"', 'apos' => '\'', 'iexcl' => '¡', # 00A1 0161 &iexcl; 逆立ち感嘆符 'cent' => '¢', # 00A2 0162 &cent; セント記号 'pound' => '£', # 00A3 0163 &pound; 英貨ポンド記号 'curren' => '¤', # 00A4 0164 &curren; 一般通貨記号 'yen' => '¥', # 00A5 0165 &yen; 円記号 'brvbar' => '¦', # 00A6 0166 &brvbar; 縦破線 'sent' => '§', # 00A7 0167 &sect; 節記号 'uml' => '¨', # 00A8 0168 &uml; ウムラウト 'copy' => '©', # 00A9 0169 &copy; 著作権記号 'ordf' => 'ª', # 00AA 0170 &ordf; 順序の指示(女性形) 'laquo' => '«', # 00AB 0171 &laquo; 左角引用符 'not' => '¬', # 00AC 0172 &not; 否定記号 'shy' => "\u00ad", # 0173 &shy; ソフトハイフン 'reg' => '®', # 00AE 0174 &reg; 登録商標 'macr' => '¯', # 00AF 0175 &macr; マクロン 'deg' => '°', # 00B0 0176 &deg; 度記号 'plusmn' => '±', # 00B1 0177 &plusmn; プラスマイナス記号 'sup2' => '²', # 00B2 0178 &sup2; 上付き数字の2、平方 'sup3' => '³', # 00B3 0179 &sup3; 上付き数字の3、立方 'acute' => '´', # 00B4 0180 &acute; 鋭アクセント 'micro' => 'µ', # 00B5 0181 &micro; ミクロン記号 'para' => '¶', # 00B6 0182 &para; 段落記号 'middot' => '·', # 00B7 0183 &middot; 中黒 'cedil' => '¸', # 00B8 0184 &cedil; セディーユ 'sup1' => '¹', # 00B9 0185 &sup1; 上付き数字の1 'ordm' => 'º', # 00BA 0186 &ordm; 順序の指示(男性形) 'raquo' => '»', # 00BB 0187 &raquo; 右角引用符 'frac14' => '¼', # 00BC 0188 &frac14; 分数1/4 'frac12' => '½', # 00BD 0189 &frac12; 分数1/2 'frac34' => '¾', # 00BE 0190 &frac34; 分数3/4 'iquest' => '¿', # 00BF 0191 &iquest; 逆立ち疑問符 'Agrave' => 'À', # 00C0 0192 &Agrave; 大文字 A(重アクセント記号付) 'Aacute' => 'Á', # 00C1 0193 &Aacute; 大文字 A(鋭アクセント付) 'Acirc' => 'Â', # 00C2 0194 &Acirc; 大文字 A(曲折アクセント記号付) 'Atilde' => 'Ã', # 00C3 0195 &Atilde; 大文字 A(ティルデ付) 'Auml' => 'Ä', # 00C4 0196 &Auml; 大文字 A(ウムラウト付) 'Aring' => 'Å', # 00C5 0197 &Aring; 大文字 A(輪付) 'AElig' => 'Æ', # 00C6 0198 &AElig; 大文字 AE 二重母音(合字) 'Ccedil' => 'Ç', # 00C7 0199 &Ccedil; 大文字 C(セディーユ付) 'Egrave' => 'È', # 00C8 0200 &Egrave; 大文字 E(重アクセント記号付) 'Eacute' => 'É', # 00C9 0201 &Eacute; 大文字 E(鋭アクセント記号付) 'Ecirc' => 'Ê', # 00CA 0202 &Ecirc; 大文字 E(曲折アクセント付) 'Euml' => 'Ë', # 00CB 0203 &Euml; 大文字 E(ウムラウト付) 'Igrave' => 'Ì', # 00CC 0204 &Igrave; 大文字 I(重アクセント記号付) 'Iacute' => 'Í', # 00CD 0205 &Iacute; 大文字 I(鋭アクセント記号付) 'Icirc' => 'Î', # 00CE 0206 &Icirc; 大文字 I(曲折アクセント付) 'Iuml' => 'Ï', # 00CF 0207 &Iuml; 大文字 I(ウムラウト付) 'ETH' => 'Ð', # 00D0 0208 &ETH; 大文字エズ 'Ntilde' => 'Ñ', # 00D1 0209 &Ntilde; 大文字 N(ティルデ付) 'Ograve' => 'Ò', # 00D2 0210 &Ograve; 大文字 O(重アクセント記号付) 'Oacute' => 'Ó', # 00D3 0211 &Oacute; 大文字 O(鋭アクセント記号付) 'Ocirc' => 'Ô', # 00D4 0212 &Ocirc; 大文字 O(曲折アクセント記号付) 'Otilde' => 'Õ', # 00D5 0213 &Otilde; 大文字 O (ティルデ付) 'Ouml' => 'Ö', # 00D6 0214 &Ouml; 大文字 O(ウムラウト付) 'times' => '×', # 00D7 0215 &times; 乗算記号 'Oslash' => 'Ø', # 00D8 0216 &Oslash; 大文字 O(スラッシュ付) 'Ugrave' => 'Ù', # 00D9 0217 &Ugrave; 大文字 U(重アクセント記号付) 'Uacute' => 'Ú', # 00DA 0218 &Uacute; 大文字 U(鋭アクセント記号付) 'Ucirc' => 'Û', # 00DB 0219 &Ucirc; 大文字 U(曲折アクセント記号付) 'Uuml' => 'Ü', # 00DC 0220 &Uuml; 大文字 U(ウムラウト付) 'Yacute' => 'Ý', # 00DD 0221 &Yacute; 大文字 Y(鋭アクセント記号付) 'THORN' => 'Þ', # 00DE 0222 &THORN; 大文字ソーン 'szlig' => 'ß', # 00DF 0223 &szlig; ドイツ語の小文字鋭 s(sz 合字) 'agrave' => 'à', # 00E0 0224 &agrave; 小文字 a(重アクセント記号付) 'aacute' => 'á', # 00E1 0225 &aacute; 小文字 a(鋭アクセント記号付) 'acirc' => 'â', # 00E2 0226 &acirc; 小文字 a(曲折アクセント記号付) 'atilde' => 'ã', # 00E3 0227 &atilde; 小文字 a(ティルデ付) 'auml' => 'ä', # 00E4 0228 &auml; 小文字 a(ウムラウト付) 'aring' => 'å', # 00E5 0229 &aring; 小文字 a(輪付) 'aelig' => 'æ', # 00E6 0230 &aelig; 小文字 ae 二重母音(合字) 'ccedil' => 'ç', # 00E7 0231 &ccedil; 小文字 c(セディーユ付) 'egrave' => 'è', # 00E8 0232 &egrave; 小文字 e(重アクセント記号付) 'eacute' => 'é', # 00E9 0233 &eacute; 小文字 e(鋭アクセント記号付) 'ecirc' => 'ê', # 00EA 0234 &ecirc; 小文字 e(曲折アクセント記号付) 'euml' => 'ë', # 00EB 0235 &euml; 小文字 e(ウムラウト付) 'igrave' => 'ì', # 00EC 0236 &igrave; 小文字 i(重アクセント記号付) 'iacute' => 'í', # 00ED 0237 &iacute; 小文字 i(鋭アクセント記号付) 'icirc' => 'î', # 00EE 0238 &icirc; 小文字 i(曲折アクセント記号付) 'iuml' => 'ï', # 00EF 0239 &iuml; 小文字 i(ウムラウト付) 'eth' => 'ð', # 00F0 0240 &eth; 小文字エズ 'ntilde' => 'ñ', # 00F1 0241 &ntilde; 小文字 n(ティルデ付) 'ograve' => 'ò', # 00F2 0242 &ograve; 小文字 o(重アクセント記号付) 'oacute' => 'ó', # 00F3 0243 &oacute; 小文字 o(鋭アクセント記号付) 'ocirc' => 'ô', # 00F4 0244 &ocirc; 小文字 o(曲折アクセント記号付) 'otilde' => 'õ', # 00F5 0245 &otilde; 小文字 o(ティルデ付) 'ouml' => 'ö', # 00F6 0246 &ouml; 小文字 o(ウムラウト付) 'divide' => '÷', # 00F7 0247 &divide; 除算記号 'oslash' => 'ø', # 00F8 0248 &oslash; 小文字 o(斜線付) 'ugrave' => 'ù', # 00F9 0249 &ugrave; 小文字 u(重アクセント記号付) 'uacute' => 'ú', # 00FA 0250 &uacute; 小文字 u(鋭アクセント記号付) 'ucirc' => 'û', # 00FB 0251 &ucirc; 小文字 u(曲折アクセント記号付) 'uuml' => 'ü', # 00FC 0252 &uuml; 小文字 u(ウムラウト付) 'yacute' => 'ý', # 00FD 0253 &yacute; 小文字 y(鋭アクセント記号付) 'thorn' => 'þ', # 00FE 0254 &thorn; 小文字ソーン 'yuml' => 'ÿ', # 00FF 0255 &yuml; 小文字 y(ウムラウト付) } def decodeHTML(text) text .gsub('<sup>a</sup>','ª') .gsub('<sup>e</sup>','ᵉ') .gsub('<sup>o</sup>','ᵒ') .gsub('Benoicirc;t','Benoît') .gsub('&oumul;','ö') .gsub(/&[^;]+;/) do |code| if '#' == code[1] case code[2] when 'x','X' val = code[3..].to_i(16) case val when 0x80..0x9f val.chr("cp1252").encode("UTF-8") else val.chr("UTF-8") end else code[2..].to_i(10).chr("UTF-8") end else $CODES[code[1..-2]] || raise(code) end end end def scan_names( leaf_key, key, mark ) URI.open( URL_HEAD + leaf_key ) do |f| p f.base_uri IS_DONE[leaf_key] = f.last_modified bodys = f.read.encode("UTF-8", "UTF-8").scan %r|<td valign="top">\s+<p>(.+?)</p>\s+</td>|m bodys.each_with_index do |body, idx| body = decodeHTML body[0] body = body.split(%r| *<br /> *\n*|).map do |s| s.strip.split(/<span class=".+">|<\/span>|[ \(\)()]+/).reject {|s| [nil, ""].member? s } end last_comment = [] body.each do |(name, spell, *comment)| p [name, spell, *comment] if spell == "<span" if " >" == name name = spell spell = comment[0] else last_comment = comment end if ! name && ! spell p name, spell, comment next end yml = YAML.dump([{ "spell" => spell, "name" => name, "side" => ["男", "女", "姓"][idx], "mark" => mark, "comment" => last_comment.join(" "), "key" => key, }]) File.open(OUTPUT, "a") do |f| f.write yml[4..] end end end end end File.open(OUTPUT,"w") do |f| YAML.dump({ "by" => "http://www.efendi.jp/rq/indices/languages/ancient/names/index.html", "name" => nil, }, f) end COUNTRYS.each do |(key, mark, leaf_key)| scan_names( leaf_key, key, mark ) end yml = YAML.dump({ "timestamp" => IS_DONE, }) File.open(OUTPUT,"a") do |f| f.write yml[4..] end YAML.load_file(OUTPUT) <file_sep>#!/usr/bin/env ruby PATH = { IPAD_CP: "/Users/7korobi/Pictures/iPad*", QTIME: "/Users/7korobi/Movies/QUICK", NAS_QT: "/Volumes/media/Album/Videos/QUICK", CAM_JPG: "/Volumes/*/DCIM/*", PHOTO: "/Users/7korobi/Pictures/CAMERA", ARDRONE: "/Volumes/*/media_*", CAMERA: "/Volumes/*/AVCHD/*/STREAM", STORE: "/Users/7korobi/Movies/AVCHD", NAS_SRC: "/Volumes/media/Album/Videos/AVCHD", ENCODE: "/Users/7korobi/Movies/HandBrake", NAS_JPG: "/Volumes/media/Album/Photo", NAS_DST: "/Volumes/media/Album/Videos/iPad", } handbrake_format = %w[ /bin/HandBrakeCLI -f mp4 -4 --verbose=1 --pfr --detelecine --decomb --crop 0:0:0:0 --encopts level=4.2:ref=6:weightp=1:subq=2:rc-lookahead=10:trellis=2:8x8dct=0:bframes=5:b-adapt=2 -e x264 -q 23 -r 60 -N jpn -E ffac3 -6 5point1 -R Auto -B 256 -D 2.0 -i %s -o %s ] def execute_for_file(src_path, format, match = "/**/*.*") cmds = ["mkdir -p #{src_path.inspect}"] Dir.glob(src_path + match).each do |src_fname| target = yield(src_fname) path = target.split("/") path.pop cmds.push "mkdir -p #{path.join("/").inspect}" cmds.push format % [src_fname.inspect, target.inspect] end cmds.uniq.each do |cmd| puts cmd system cmd end end COMMENTS = {} def comment(name, item) datestamp = item.mtime.strftime("%Y-%m-%d") COMMENTS[datestamp] ||= begin since_birth = item.mtime - Time.new(2013,6,24,5) time_of_day = 1 * 24*60*60 puts "### input comment at #{datestamp} ( = #{(since_birth/time_of_day).ceil} days.) ###" `open "#{name}"` gets.chomp end end dirs = [] dirs += `cd #{PATH[:IPAD_CP]} && find . -type d | grep -v AppleDouble`.split("¥n") dirs += `cd #{PATH[:QTIME ]} && find . -type d | grep -v AppleDouble`.split("¥n") dirs += `cd #{PATH[:STORE ]} && find . -type d | grep -v AppleDouble`.split("¥n") puts dirs.uniq.sort execute_for_file(PATH[:CAM_JPG], "mv -f %s %s") do |name| item = File::Stat.new(name) timestamp = item.mtime.strftime("%Y-%m-%d.%H.%M.%S") ext = name.split(".")[-1] "#{PATH[:PHOTO]}/#{comment(name, item)}/#{timestamp}_.#{ext}" end execute_for_file(PATH[:IPAD_CP], "mv -f %s %s", "/**/*.jpg") do |name| item = File::Stat.new(name) timestamp = item.mtime.strftime("%Y-%m-%d.%H.%M.%S") ext = name.split(".")[-1] "#{PATH[:PHOTO]}/#{comment(name, item)}/#{timestamp}_.#{ext}" end execute_for_file(PATH[:IPAD_CP], "mv -f %s %s", "/**/*.JPG") do |name| item = File::Stat.new(name) timestamp = item.mtime.strftime("%Y-%m-%d.%H.%M.%S") ext = name.split(".")[-1] "#{PATH[:PHOTO]}/#{comment(name, item)}/#{timestamp}_.#{ext}" end puts "=== from : #{PATH[:CAM_JPG]}" puts "=== from : #{PATH[:IPAD_CP]}" puts "=== to : #{PATH[:PHOTO]}" execute_for_file(PATH[:ARDRONE], "mv -f %s %s") do |name| item = File::Stat.new(name) timestamp = item.mtime.strftime("%Y-%m-%d.%H.%M.%S") ext = name.split(".")[-1] "#{PATH[:STORE]}/#{comment(name, item)}/#{timestamp}_.#{ext}" end execute_for_file(PATH[:CAMERA], "mv -f %s %s") do |name| item = File::Stat.new(name) timestamp = item.mtime.strftime("%Y-%m-%d.%H.%M.%S") ext = name.split(".")[-1] "#{PATH[:STORE]}/#{comment(name, item)}/#{timestamp}_.#{ext}" end puts "=== from : #{PATH[:ARDRONE]}" puts "=== from : #{PATH[:CAMERA]}" puts "=== to : #{PATH[:STORE]}" execute_for_file(PATH[:IPAD_CP], "mv -f %s %s", "/**/*.mov") do |name| item = File::Stat.new(name) timestamp = item.mtime.strftime("%Y-%m-%d.%H.%M.%S") ext = name.split(".")[-1] "#{PATH[:QTIME]}/#{comment(name, item)}/#{timestamp}_.#{ext}" end execute_for_file(PATH[:IPAD_CP], "mv -f %s %s", "/**/*.MOV") do |name| item = File::Stat.new(name) timestamp = item.mtime.strftime("%Y-%m-%d.%H.%M.%S") ext = name.split(".")[-1] "#{PATH[:QTIME]}/#{comment(name, item)}/#{timestamp}_.#{ext}" end puts "=== from : #{PATH[:IPAD_CP]}" puts "=== to : #{PATH[:QTIME]}" puts "### copy to local-store release camera OK. ###" puts "### encode movie files by HandBrakeCLI. ###" execute_for_file(PATH[:STORE], handbrake_format.join(" ")) do |name| target_postfix = name.gsub(PATH[:STORE], "") ary = target_postfix.split("/") if ary.size > 2 ary.shift target_postfix = "#{ary.shift}/#{ary.join("-")}" end ext = target_postfix.split(".")[-1] target_postfix[".#{ext}"] = ".mp4" "#{PATH[:ENCODE]}/#{target_postfix}" end execute_for_file(PATH[:QTIME], handbrake_format.join(" ")) do |name| target_postfix = name.gsub(PATH[:QTIME], "") ary = target_postfix.split("/") if ary.size > 2 ary.shift target_postfix = "#{ary.shift}/#{ary.join("-")}" end ext = target_postfix.split(".")[-1] target_postfix[".#{ext}"] = ".mp4" "#{PATH[:ENCODE]}/#{target_postfix}" end puts "=== from : #{PATH[:STORE]}" puts "=== from : #{PATH[:QTIME]}" puts "=== to : #{PATH[:ENCODE]}" puts "### copy to nas-strage. ###" execute_for_file(PATH[:PHOTO], "mv -f %s %s") do |name| target_postfix = name.gsub(PATH[:PHOTO], "") "#{PATH[:NAS_JPG]}/#{target_postfix}" end puts "=== from : #{PATH[:PHOTO]}" puts "=== to : #{PATH[:NAS_JPG]}" execute_for_file(PATH[:ENCODE], "mv -f %s %s") do |name| target_postfix = name.gsub(PATH[:ENCODE], "") "#{PATH[:NAS_DST]}/#{target_postfix}" end puts "=== from : #{PATH[:ENCODE]}" puts "=== to : #{PATH[:NAS_DST]}" execute_for_file(PATH[:STORE], "mv -f %s %s") do |name| target_postfix = name.gsub(PATH[:STORE], "") "#{PATH[:NAS_SRC]}/#{target_postfix}" end puts "=== from : #{PATH[:STORE]}" puts "=== to : #{PATH[:NAS_SRC]}" execute_for_file(PATH[:QTIME], "mv -f %s %s") do |name| target_postfix = name.gsub(PATH[:QTIME], "") "#{PATH[:NAS_QT]}/#{target_postfix}" end puts "=== from : #{PATH[:QTIME]}" puts "=== to : #{PATH[:NAS_QT]}" puts "### cleanup local-store. ###" system "rmdir -p #{PATH[:STORE]}/*/*/*" system "rmdir -p #{PATH[:STORE]}/*/*" system "rmdir -p #{PATH[:STORE]}/*" system "rmdir -p #{PATH[:ENCODE]}/*/*/*" system "rmdir -p #{PATH[:ENCODE]}/*/*" system "rmdir -p #{PATH[:ENCODE]}/*" <file_sep>require 'open-uri' require "net/http" require 'zip' require 'yaml' require 'json' FNAME_GEOCODE_ZIP = "data/tmp/geolist.zip" FNAME_ZIPCODE_ZIP = "data/tmp/zipcode.zip" FNAME_GEOCODE = "data/geolist_utf8.csv" FNAME_ZIPCODE = "data/zipcode_sjis.csv" FNAME_SNAP_HD = "../giji/yaml/work_geo_" FNAME_OUTPUT_YAML = "../giji/yaml/work_geo.yml" POSTS_JIS_ZIP = {} POSTS_ZIP = {} POSTS_JIS = {} ORM = {} ORM_CODE = {} GEOS = [] NAME_GEOS = {} ETCS = {} NAMES = {} LABELS = {} DIC = {} TO_PREFECTURE = {} PAST_DIC = YAML.load_file(FNAME_SNAP_HD + "dic.yml") PAST_DIC.each do |prefecture, dic| PAST_DIC['chk'][prefecture]&.each do |key, size| if 1 < size # 北町南町など。2以上ある場合はグルーピング対象。 PAST_DIC[prefecture]['dic'].unshift key end end dic['dic'] ||= [] dic['cut'] ||= [] if 0 < dic['cut'].size r1 = /^(#{dic['cut'].join("|")})(東|西|南|北|..+)$/ dic['dic'].reject! {|s| r1 === s } end # 異常値は固有名詞の辞書登録をしない。 r2 = /^(市市|区区|町町|村村|郡郡|都都|道道|府府|県県|市|区|町|村|郡|都|道|府|県)$/ dic['dic'].reject! {|s| r2 === s } end def find_header(*args) ( 1 .. args.map(&:size).min ).reverse_each do |idx| return args[0][0..idx] if 1 == args.map {|arg| arg[0..idx] }.uniq.size end nil end def cut(src, r, sep, gap, safe ) saves = src.scan(safe) saves.each_with_index {|saved, idx| src.sub!(saved,"@#{idx}@") } hit = src[r] if hit src[r] = "" list = hit.tr(sep,"").split(gap) if saves saves.each_with_index do |saved, idx| list.each do |s| s.sub!("@#{idx}@", saved) end end end else list = [] if saves saves.each_with_index do |saved, idx| src.sub!("@#{idx}@", saved) end end end list.uniq.select {|s| ! [nil,""].member? s } end def to_etc(sep, *ary) ary.map {|s| s.tr(sep,"") }.uniq.select {|s| ! [nil, ""].member? s } end def label_reduce(root, checker = {}, dest = {}) root.each do |key, item| dest[key] = LABELS[key] check = checker[LABELS[key]] if 0 == item || 0 == item.size check = checker[LABELS[key]] = 0 else unless Hash === check check = checker[LABELS[key]] = {} end label_reduce(item, check, dest) end end dest end def name_reduce!(root) news = {} root.each do |key, item| next if 0 == item next if 0 == item.size if 1 == item.size new_key = item.keys[0] new_val = item.values[0] news[new_key] = new_val LABELS[new_key] = LABELS[key] root.delete(key) else item.replace name_reduce!(item).sort.to_h end end news.each do |key, val| root[key] = val end if 0 < news.size name_reduce!(root) end root end CHK1 = {} REG_NUMBER_FT = /[東西南北]$|(「)?(第)?[0-9].+$|[東西南北]?[0-9一二三四五六七八九十廿~]+(条通り|番町|条町|日市|ノ宮|条|線|番|区)$/ REG_NUMBER_HD = /^.+?[堂寺院](ノ前|門前)?|^[東西南北]?[0-9一二三四五六七八九十廿~]+(条通り|番町|条町|日市(場町|町中地)?|ノ宮|条|線|区)/ def label_set(list, name, label) prefecture = list[0] chk = PAST_DIC[prefecture]['dic'] DIC[prefecture] ||= {'dic' => chk, 'cut' => PAST_DIC[prefecture]['cut']} dic = DIC[prefecture]['dic'] cut = DIC[prefecture]['cut'] # 分割しすぎた市区町村を、名前に付け戻す。結合nameは変化しないので注意。 if /^(ノ[上]|ノ[^ァ-ヶ]+町|ノ坪|町区|地区|[都府県市郡区村町])$/ === label list.pop head = list[-1] list[-1] = label = head + label dic.push label unless dic.member? label end # check. if /.{2,}[東西南北元中上下新][町村郡区]$/ === label head = label[0..-3] unless /(の|ノ|之)$/ === head CHK1[prefecture] ||= Hash.new(0) CHK1[prefecture][label[0..-3]] += 1 end end # check. if /^(市市|区区|町町|村村|郡郡|都都|道道|府府|県県)$/ === label puts ["d...", list].join(" ") end if /#{label}.#{label}$/ === name LABELS[name] = label unit = nil else (LABELS[name], unit) = label.split(/(町区$|地区$|[都府県市郡区村町]$)/) end _id = list.join("-") ORM[name] = { "_id" => _id, "name" => name, "label" => LABELS[name], "unit" => unit, } return if unit == label label.tr!("()()","") unit.tr!("()()","") if unit DIC[prefecture][unit || 'etc'] ||= [] DIC[prefecture][unit || 'etc'].push label unless DIC[prefecture][unit || 'etc'].member? label return unless unit return if PAST_DIC[label] unless dic.member? label if /[都道府県島市郡区村町寺院].+/ === label dic.push label end end if REG_NUMBER_FT === label head = label.sub(REG_NUMBER_FT,"") foot = label[REG_NUMBER_FT] is_nocut = ( 0 == head.size || 0 == foot.size || 1 == head.size || !(/^(東|西|南|北)$/ === foot) || /^ノ[^ァ-ヶ]/ === foot ) if is_nocut dic.push label unless dic.member? label else puts [prefecture, "2...", head, foot, " ", list].join(" ") cut.push head unless cut.member? head dic.push head unless dic.member? head end end if REG_NUMBER_HD === label foot = label.sub(REG_NUMBER_HD,"") head = label[REG_NUMBER_HD] is_nocut = ( 0 == head.size || 0 == foot.size || 1 == head.size || !(/^(東|西|南|北)$/ === foot) || /^ノ[^ァ-ヶ]/ === foot ) if is_nocut dic.push label unless dic.member? label else puts [prefecture, "4...", head, foot, " ", list].join(" ") cut.push head unless cut.member? head dic.push head unless dic.member? head end end end def name_set(names, *dirty) (*args, tail) = dirty.select {|s| s != "" } head = "" list = [] args.each_with_index do |arg, idx| head = head + arg list.push arg unless Hash === names[head] names[head] = {} end names = names[head] label_set(list, head, arg) end if tail.start_with? head full = tail else if ["#{head[-1]}庁","#{head[-1]}役所"].member? tail full = head + tail[1..] else full = head + tail end list.push tail end names[full] ||= 0 label_set(list, full, tail) full end # katakana to hiragana for utf-8 def to_hiragana(src) src .tr("ァ-ヶヽヾヿ","ぁ-ゖゝゞゟ") .gsub("ヷ","わ゙") .gsub("ヸ","い゙") .gsub("ヹ","え゙") .gsub("ヺ","を゙") end # hiragana to katakana for utf-8 def to_katakana(src) src .gsub("わ゙","ヷ") .gsub("い゙","ヸ") .gsub("え゙","ヹ") .gsub("を゙","ヺ") .tr("ぁ-ゖゝゞゟ","ァ-ヶヽヾヿ") end =begin uri = URI.parse("http://www.amano-tec.com/data/download.php") http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Post.new(uri.path) req.set_form_data({ name: "", email: "", org: "", usage: "", mail_set: 'confirm_submit', filenumber: '3', x: '78', y: '12', httpReferer: 'http://www.amano-tec.com/data/localgovernments.html' }) req.initialize_http_header({ "Accept" => "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Accept-Encoding" => "gzip, deflate", "Accept-Language" => "ja,en-US;q=0.9,en;q=0.8", "Cache-Control" => "max-age=0", "Connection" => "keep-alive", "Cookie" => "_ga=GA1.2.1709699922.1566976834; _gid=GA1.2.889992052.1566976834; i18next=ja; _gat=1", "Origin" => "http://www.amano-tec.com", "Referer" => "http://www.amano-tec.com/data/download.php", "User-Agent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36", }) res = http.request(req) File.open(FNAME_GEOCODE_ZIP,'w') do |fw| fw.write res.body end Zip::File.open(FNAME_GEOCODE_ZIP) do |zip| zip.each do |entry| if "h3010puboffice_utf8.csv" == entry.name zip.extract(entry, FNAME_GEOCODE) { true } end end end URI.open('https://www.post.japanpost.jp/zipcode/dl/oogaki/zip/ken_all.zip') do |fr| File.open(FNAME_ZIPCODE_ZIP,'w') do |fw| fw.write fr.read end end =end Zip::File.open(FNAME_ZIPCODE_ZIP) do |zip| zip.each do |entry| if "KEN_ALL.CSV" == entry.name zip.extract(entry, FNAME_ZIPCODE) { true } end end end puts "...ZIPCODE scan" URI.open(FNAME_ZIPCODE) do |f| f.read.encode("UTF-8","Shift_JIS").split("\n").each do |line| (jiscode, zipcode5, zipcode, ruby1, ruby2, ruby3, prefecture, city, town, is_duplicate_town, is_duplicate_won, has_town_code, has_multi_won, is_news, change_code ) = line.split(/"?,"?/) jiszipcode = jiscode + zipcode if old = POSTS_JIS_ZIP[jiszipcode] if old[4]["("] && ! old[4][")"] town.gsub!("その他)", ")") town.gsub!("(次のビルを除く)","") ruby3.gsub!("ソノタ\)", ")") ruby3.gsub!("(ツギノビルヲノゾク)","") old[4] += town old[8] += ruby3 old[5] = cut(old[4], /(.*)/,"()","、", /「.+?を除く」|「.+?」以外/) old[9] = cut(old[8], /\(.*\)/,"()","、", /<.+?ヲノゾク>|<.+?>イガイ/) elsif m = town.match(/^#{old[4]}((.+))/) mr = ruby3.match(/^#{old[8]}\((.+)\)/) old[5] = [*old[5],m[1]].uniq old[9] = [*old[9],mr[1]].uniq elsif hd = find_header(town, old[4]) if rubyhd = find_header(ruby3, old[8]) old[5] = to_etc "()", *[old[4], *old[5], town].map {|s| s.gsub(hd, "") } old[4] = hd old[9] = to_etc "()", *[old[8], *old[9], ruby3].map {|s| s.gsub(rubyhd, "") } old[8] = rubyhd else puts [[old[3], old[4], old[8]].join(" "),[city, town, ruby3].join(" ")].join(" - ") end else old[5] = to_etc "()", old[4], *old[5], town old[4] = "" old[9] = to_etc "()", old[8], *old[9], ruby3 old[8] = "" end next end if /以下に掲載がない場合|の次に番地がくる場合$/ === town town = ruby3 = "" end town.gsub!("その他)", ")") town.gsub!("(次のビルを除く)","") ruby3.gsub!("ソノタ\)", ")") ruby3.gsub!("(ツギノビルヲノゾク)","") etc = cut(town, /(.*)/,"()","、", /「.+?を除く」|「.+?」以外/) ruby4 = cut(ruby3, /\(.*\)/,"()","、", /<.+?ヲノゾク>|<.+?>イガイ/) POSTS_JIS_ZIP[jiszipcode] = POSTS_ZIP[zipcode] = POSTS_JIS[jiscode] = [zipcode, jiscode, prefecture, city, town, etc, ruby1, ruby2, ruby3, ruby4] TO_PREFECTURE[city] = TO_PREFECTURE[prefecture] ||= [prefecture, ruby1] end end puts "...ZIPCODE structure" POSTS_JIS_ZIP.each do |code, data| (zipcode, jiscode, prefecture, city, town, etc, ruby1, ruby2, ruby3, ruby4) = data puts ORM_CODE[jiscode + zipcode] if ORM_CODE[jiscode + zipcode] dic = PAST_DIC[prefecture]['dic'].map{|s| s + '|'}.join("") gap = "村|町|市|郡|区|)" towns = town.split(/(#{dic}.+?(?:区|町|村))/) town_tail = towns.pop if town_tail town_tail_split = town_tail.split(/([東西南北]$)/) if town_tail_split towns.push *town_tail_split else towns.push town_tail end end cities = city.split(/(#{dic}.+?(?:#{gap})(?!#{gap}))/) name = name_set( NAMES, prefecture, ) ORM[name]["ruby"] = to_hiragana [ruby1].join("").unicode_normalize(:nfkc) unless ORM[name]["ruby"] name = name_set( NAMES, prefecture, *cities, ) ORM[name]["ruby"] = to_hiragana [ruby1,ruby2].join("").unicode_normalize(:nfkc) unless ORM[name]["ruby"] name = name_set( NAMES, prefecture, *cities, *towns, ) ORM[name]["ruby"] = to_hiragana [ruby1,ruby2,ruby3].join("").unicode_normalize(:nfkc) unless ORM[name]["ruby"] case etc.size when 0 ORM[name]["zipcode"] = zipcode ORM[name]["jiscode"] = jiscode ORM_CODE[jiscode + zipcode] = [ORM[name]] else etc.each_with_index do |etc_item, idx| ruby4_item = ruby4[idx] name = name_set( NAMES, prefecture, *cities, *towns, "(#{etc_item})" ) ORM[name]["ruby"] = to_hiragana [ruby1,ruby2,ruby3,ruby4_item].join("").unicode_normalize(:nfkc) end if etc.size == 1 ORM[name]["zipcode"] = zipcode ORM[name]["jiscode"] = jiscode end ETCS[name] = etc end end puts "...GEOCODE scan" URI.open(FNAME_GEOCODE) do |f| f.read.encode("UTF-8","UTF-8").split("\n").each do |line| ( jiscode, label, ruby, building, zipcode, address, tel, source, lat, lon, note ) = line.split("\t") address.tr!("0-9","0-9") next if 'jiscode' == jiscode lat = lat.to_f lon = lon.to_f jiscode = jiscode.rjust(5,"0") zipcode = zipcode.tr("-",'') post = POSTS_ZIP[zipcode] || POSTS_JIS[jiscode] if post (_zipcode, _jiscode, prefecture, city, town, etc, ruby1, ruby2, ruby3, ruby4) = post dic = PAST_DIC[prefecture]['dic'].map{|s| s + '|'}.join("") gap = "村|町|市|郡|区|)" towns = town.split(/(#{dic}.+?(?:区|町|村))/) town_tail = towns.pop if town_tail town_tail_split = town_tail.split(/([東西南北]$)/) if town_tail_split towns.push *town_tail_split else towns.push town_tail end end cities = city.split(/(#{dic}.+?(?:#{gap})(?!#{gap}))/) name = name_set( NAME_GEOS, prefecture, *cities, *towns, ) (ORM_CODE[jiscode + zipcode] || []).each do |orm| orm["on"] = [lat, lon] orm["tel"] = tel orm["address"] = address end ETCS[name] = etc if 0 < etc.size kata = [ruby1,ruby2,ruby3].join("").unicode_normalize(:nfkc) hira = to_hiragana(kata) else label_key = TO_PREFECTURE.keys.find {|s| s.start_with? label } (prefecture, ruby1) = TO_PREFECTURE[label_key] if label == prefecture # 都道府県庁の場合 hira = ruby + "ちょう" name = name_set( NAME_GEOS, prefecture, building[-2..] ) ORM[name]["zipcode"] = zipcode ORM[name]["jiscode"] = jiscode ORM[name]["ruby"] = hira ORM[name]["on"] = [lat, lon] ORM[name]["tel"] = tel ORM[name]["address"] = address else # 市役所の場合 ruby1 = ruby1.unicode_normalize(:nfkc) ruby1 = to_hiragana(ruby1) hira = [ruby1, ruby].join("") if building["市役所"] name = name_set( NAME_GEOS, prefecture, building.gsub(/役所$/, ""), "市役所" ) else name = name_set( NAME_GEOS, prefecture, building, ) end ORM[name]["zipcode"] = zipcode ORM[name]["jiscode"] = jiscode ORM[name]["ruby"] = hira ORM[name]["on"] = [lat, lon] ORM[name]["tel"] = tel ORM[name]["address"] = address end kata = to_katakana(hira) end GEOS.push({ "_id" => jiscode, "zip" => zipcode, "on" => [lat, lon], "name" => name, "label" => label, "hira" => hira, "kata" => kata, "tel" => tel, "address" => address, }) end end CHECK_GEOS = {} geo = { "zips" => GEOS, "names" => name_reduce!(NAME_GEOS), "labels" => label_reduce(NAME_GEOS, CHECK_GEOS).sort.to_h, } CHECKS = {} File.open(FNAME_OUTPUT_YAML,"w") do |f| f.write YAML.dump geo end DIC.each do |key, dic| dic.each do |k, d| dic[k] = d.sort_by {|o| [- o.size, o] }.uniq end DIC[key] = dic.sort.to_h end DIC['chk'] = CHK1 File.open(FNAME_SNAP_HD + "dic.yml","w") do |f| f.write YAML.dump DIC end File.open(FNAME_SNAP_HD + "orm.yml","w") do |f| f.write YAML.dump ORM.values.sort_by {|o| o["zipcode"] || "" } end File.open(FNAME_SNAP_HD + "etc.yml","w") do |f| f.write YAML.dump ETCS end File.open(FNAME_SNAP_HD + "name.yml","w") do |f| f.write YAML.dump name_reduce!(NAMES) end File.open(FNAME_SNAP_HD + "label.yml","w") do |f| f.write YAML.dump label_reduce(NAMES, CHECKS).sort.to_h end # data structure check. YAML.load_file(FNAME_OUTPUT_YAML) YAML.load_file(FNAME_SNAP_HD + "name.yml") YAML.load_file(FNAME_SNAP_HD + "label.yml") YAML.load_file(FNAME_SNAP_HD + "etc.yml") YAML.load_file(FNAME_SNAP_HD + "dic.yml") YAML.load_file(FNAME_SNAP_HD + "orm.yml") <file_sep>export interface ChrsetsYAML { chr_set: ChrSet; chr_npc: ChrNpc[]; chr_job: ChrJob[]; } export interface ChrJob { face_id: string; job: string; comment?: string; } export interface ChrNpc { label: string; csid: string; face_id: string; say_0: string; say_1: string; _id?: string; } export interface ChrSet { _id: string; admin: string; maker: string; label: string; } export interface ChrFaceYml { _id: string; name: string; comment?: null | string; order: number; tag_ids: string[]; } export interface ChrTagYml { label: string; long: string; tag_id?: TagID; chr_set_id: string; face_sort: FaceSort[]; order: number; _id: string; head?: Head; } export enum FaceSort { Asc = "asc", FaceOrder = "face.order", FaceQHead = "face.q.head", } export enum Head { 人狼議事テーマ別 = "人狼議事-テーマ別", 人狼議事年齢別 = "人狼議事-年齢別", 帰還者議事テーマ別 = "帰還者議事-テーマ別", } export enum TagID { All = "all", Giji = "giji", Travel = "travel", } export interface Index { stories: StoryElement[]; faces: Face[]; } export interface Face { _id: ID; date_min: Date; date_max: Date; story_ids: string[]; } export interface ID { face_id: string; } export interface StoryElement { _id: string; _type: StoryType; card: Card; folder: Folder; is_epilogue: boolean; is_finish: boolean; name: string; options: Option[]; rating: null | string; sow_auth_id: string; timer: StoryTimer; type: TypeClass; upd: StoryUpd; vid: number; vpl: number[]; is_full_commit?: boolean; comment?: string; } export enum StoryType { SowVillage = "SowVillage", } export interface Card { discard: Array<number | string>; event: string[]; config: USERIDADMINElement[]; } export enum USERIDADMINElement { Admin = "admin", Alchemist = "alchemist", Alive = "alive", Aprilfool = "aprilfool", Aura = "aura", Aurawolf = "aurawolf", Bat = "bat", Bind = "bind", Bitch = "bitch", Childwolf = "childwolf", Clamor = "clamor", Cointoss = "cointoss", Cpossess = "cpossess", Curse = "curse", Cursed = "cursed", Cursewolf = "cursewolf", Cwolf = "cwolf", Decide = "decide", Dipsy = "dipsy", Dish = "dish", Doctor = "doctor", Droop = "droop", Dying = "dying", Dyingpixi = "dyingpixi", Dyingpossess = "dyingpossess", Dyingwolf = "dyingwolf", Eclipse = "eclipse", Elder = "elder", Entry = "entry", Epilogue = "epilogue", Escape = "escape", Executed = "executed", Fairy = "fairy", Fan = "fan", Fanatic = "fanatic", Feared = "feared", Fink = "fink", Fire = "fire", Fm = "fm", Follow = "follow", Force = "force", Gamemaster = "gamemaster", Ghost = "ghost", Girl = "girl", Glass = "glass", Grave = "grave", Guard = "guard", Guru = "guru", Hamster = "hamster", Hate = "hate", Hatedevil = "hatedevil", Headless = "headless", Hide = "hide", Hunter = "hunter", Intwolf = "intwolf", Invalid = "invalid", Jammer = "jammer", Juror = "juror", Leave = "leave", Live = "live", Lonewolf = "lonewolf", Lost = "lost", Love = "love", Loveangel = "loveangel", Lover = "lover", Main = "main", Master = "master", Medium = "medium", Mediumrole = "mediumrole", Mediumwin = "mediumwin", Memo = "memo", Mimicry = "mimicry", Miracle = "miracle", Mob = "mob", Muppeting = "muppeting", Necromancer = "necromancer", Nightmare = "nightmare", None = "none", Nothing = "nothing", Ogre = "ogre", Oracle = "oracle", Oura = "oura", Passion = "passion", Possess = "possess", Prince = "prince", Prologue = "prologue", Prophecy = "prophecy", Rightwolf = "rightwolf", Robber = "robber", Scapegoat = "scapegoat", Seance = "seance", Seer = "seer", Seeronce = "seeronce", Seerrole = "seerrole", Seerwin = "seerwin", Semiwolf = "semiwolf", Shield = "shield", Silentwolf = "silentwolf", Snatch = "snatch", Sorcerer = "sorcerer", Start = "start", Stigma = "stigma", Suddendead = "suddendead", Suicide = "suicide", Sympathy = "sympathy", Tangle = "tangle", Trickster = "trickster", Turnfairy = "turnfairy", Turnfink = "turnfink", Victim = "victim", Villager = "villager", Visiter = "visiter", Walpurgis = "walpurgis", Werebat = "werebat", Weredog = "weredog", Whitewolf = "whitewolf", Wisper = "wisper", Witch = "witch", Wolf = "wolf", } export enum Folder { Allstar = "ALLSTAR", Braid = "BRAID", Cabala = "CABALA", Ciel = "CIEL", Crazy = "CRAZY", Lobby = "LOBBY", LobbyOld = "LOBBY_OLD", Morphe = "MORPHE", Offparty = "OFFPARTY", Pan = "PAN", Perjury = "PERJURY", PerjuryOld = "PERJURY_OLD", Pretense = "PRETENSE", Rp = "RP", Soybean = "SOYBEAN", Test = "TEST", Ultimate = "ULTIMATE", Union = "UNION", Wolf = "WOLF", Xebec = "XEBEC", } export enum Option { AimingTalk = "aiming-talk", Entrust = "entrust", RandomTarget = "random-target", SelectRole = "select-role", SeqEvent = "seq-event", UndeadTalk = "undead-talk", } export interface StoryTimer { updateddt: Date; nextupdatedt: Date; nextchargedt: Date; nextcommitdt: Date; scraplimitdt: Date; } export interface TypeClass { say: SayElement; vote: Vote; roletable: Roletable; mob: USERIDADMINElement | null; game: Game | null; } export enum Game { LiveMillerhollow = "LIVE_MILLERHOLLOW", LiveTabula = "LIVE_TABULA", Millerhollow = "MILLERHOLLOW", Mistery = "MISTERY", Secret = "SECRET", Tabula = "TABULA", Trouble = "TROUBLE", } export enum Roletable { Custom = "custom", Default = "default", Hamster = "hamster", Lover = "lover", Mistery = "mistery", Random = "random", Test1St = "test1st", Test2Nd = "test2nd", Ultimate = "ultimate", WbbsC = "wbbs_c", WbbsF = "wbbs_f", WbbsG = "wbbs_g", } export enum SayElement { Euro = "euro", Infinity = "infinity", InfinityBraid = "infinity_braid", Juna = "juna", JunaBraid = "juna_braid", Lobby = "lobby", Saving = "saving", Say1 = "say1", Say5 = "say5", Say5X200 = "say5x200", Say5X300 = "say5x300", Sow = "sow", Tiny = "tiny", Vulcan = "vulcan", VulcanBraid = "vulcan_braid", Wbbs = "wbbs", Weak = "weak", WeakBraid = "weak_braid", } export enum Vote { Anonymity = "anonymity", Sign = "sign", } export interface StoryUpd { interval: number; hour: number; minute: number; } export interface Plan { plans: PlanElement[]; } export interface PlanElement { _id: string; link: string; title: string; write_at: Date; name: string; state: null | string; chip: null | string; sign: null | string; card: string[]; upd: PlanUpd; lock: any[]; flavor: string[]; options: string[]; tags: Array<string[]>; } export interface PlanUpd { description: null; time: null | string; interval: null | string; prologue: null; start: null | string; } export interface RandomYml { tarot: { [key: string]: Tarot }; zodiac: { [key: string]: Zodiac }; Ptolemaic: { [key: string]: Bayer }; Lacaille: { [key: string]: Bayer }; Bayer: { [key: string]: Bayer }; Plancius: Plancius; Hevelius: Hevelius; planet: { [key: string]: Planet }; chess: { [key: string]: Chess }; weather: { [key: string]: Chess }; coin: Coin; eto10: Eto10; eto12: Eto12; } export interface Bayer { types: TypeElement[]; label: string; ratio: number; } export enum TypeElement { Iau = "IAU", } export interface Hevelius { "Canes Venatici": Bayer; Lacerta: Bayer; "Leo Minor": Bayer; Lynx: Bayer; Scutum: Bayer; Sextans: Bayer; Vulpecula: Bayer; } export interface Plancius { Camelopardalis: Bayer; Columba: Bayer; Crux: Bayer; Monoceros: Bayer; } export interface Chess { ratio: number; symbol: string; label: string; } export interface Coin { front: Back; back: Back; stand: Back; } export interface Back { ratio: number; label: string; } export interface Eto10 { 甲: 丁; 乙: 丁; 丙: 丁; 丁: 丁; 戊: 丁; 己: 丁; 庚: 丁; 辛: 丁; 壬: 丁; 癸: 丁; } export interface 丁 { name: string; } export interface Eto12 { 子: 丁; 丑: 丁; 寅: 丁; 卯: 丁; 辰: 丁; 巳: 丁; 午: 丁; 未: 丁; 申: 丁; 酉: 丁; 戌: 丁; 亥: 丁; } export interface Planet { symbol: string; label: string; } export interface Tarot { name: string; label: string; hebrew: string; } export interface Zodiac { types: TypeElement[]; symbol: string; label: string; hebrew: string; ratio?: number; name?: string; } export interface RuleYml { nation: Maker; village: Maker; maker: Maker; player: Maker; } export interface Maker { head: string; list: List[]; } export interface List { head: string; log: string; } export interface SetAblesYml { group?: Group; at?: string; cmd?: string; btn?: string; change?: string; help: null | string; _id: string; sw?: string; pass?: string; for?: string; targets?: string; target?: string; require?: string; label?: string; hide?: string[]; disable?: string[]; text?: Text[]; } export enum Group { Gm = "GM", Potof = "POTOF", Status = "STATUS", } export enum Text { Act = "act", Memo = "memo", Talk = "talk", } export interface SetActionsYml { index?: number; text: string; target?: boolean; } export interface SetEventsYml { label: string; _id: USERIDADMINElement; } export interface SetLocaleYml { sow_locale_id?: SowLocaleID; label: string; _id: string; help?: string; intro?: string[]; } export enum SowLocaleID { All = "all", Complexx = "complexx", Heavy = "heavy", Millerhollow = "millerhollow", Regend = "regend", Secret = "secret", Sow = "sow", Star = "star", Tabula = "tabula", Ultimate = "ultimate", } export interface SetMarkYml { label?: string; path: string; _id: string; enable?: boolean; } export interface SowRoletablesYml { label: string; help?: string; _id: string; cmd?: SetOptionYmlCmd | null; disabled?: boolean; role_ids_list?: Array<USERIDADMINElement[] | null>; } export enum SetOptionYmlCmd { Trap = "trap", } export interface SetRolesYml { label: string; win: null | string; able_ids: string[]; help?: string; _id: USERIDADMINElement; group?: null | string; able?: string; cmd?: SetRolesYmlCmd; } export enum SetRolesYmlCmd { Role = "role", } export interface SetSaysYml { label: string; help?: string; count?: { [key: string]: number }; max?: Max; recovery?: string; _id: SayElement; all?: { [key: string]: number }; disabled?: boolean; } export interface Max { size: number; word: number; line: number; } export interface SetWinnerYml { label: string; group: string; order: number; help?: string; _id: string; label_human?: string; } export interface SowFolderYml { config?: Config; _id: string; story?: SowFolderYmlStory; nation?: string; folder?: Folder; vid_code?: string; server?: string; oldlog?: string; livelog?: string; info_url?: string; epi_url?: string; } export interface Config { csid?: string[]; path?: Path; enable?: Enable; trsid?: SowLocaleID[]; game?: Game[]; erb?: Erb; cd_default?: CDDefault; maxsize?: Maxsize; saycnt?: SayElement[]; cfg?: CFG; pl?: string; is_angular?: string; } export enum CDDefault { 戦 = "戦", 演 = "演", } export interface CFG { TYPE: Type; RULE: Folder; USERID_NPC: USERIDADMINElement; USERID_ADMIN: USERIDADMINElement; ENABLED_VMAKE: number; TIMEOUT_ENTRY: number; TIMEOUT_SCRAP: number; TOPPAGE_INFO: ToppageInfo; BASEDIR_CGI: BasedirCGI; BASEDIR_DAT: BasedirDAT; BASEDIR_DOC: string; URL_SW?: string; BASEDIR_CGIERR?: string; NAME_HOME?: string; MAX_VILLAGES?: number; MAX_LOG?: number; } export enum BasedirCGI { Empty = ".", } export enum BasedirDAT { Data = "./data", } export enum ToppageInfo { InfoPl = "./_info.pl", SowInfoPl = "../sow/_info.pl", } export enum Type { Braid = "BRAID", Cabala = "CABALA", Cheat = "CHEAT", } export interface Enable { DEFAULT_VOTETYPE: DefaultVotetype[]; ENABLED_DELETED: Array<ENABLEDDELETEDEnum | number>; ENABLED_WINNER_LABEL: Array<ENABLEDWINNERLABELEnum | number>; ENABLED_MAX_ESAY: Array<ENABLEDMAXESAYEnum | number>; ENABLED_RANDOMTARGET: Array<ENABLEDRANDOMTARGETEnum | number>; ENABLED_SUDDENDEATH: Array<ENABLEDSUDDENDEATHEnum | number>; ENABLED_BITTY: Array<ENABLEDBITTYEnum | number>; ENABLED_PERMIT_DEAD: Array<ENABLEDPERMITDEADEnum | number>; ENABLED_UNDEAD: Array<ENABLEDUNDEADEnum | number>; ENABLED_AIMING: Array<ENABLEDAIMINGEnum | number>; ENABLED_MOB_AIMING: Array<ENABLEDMOBAIMINGEnum | number>; ENABLED_AMBIDEXTER: Array<ENABLEDAMBIDEXTEREnum | number>; ENABLED_SUICIDE_VOTE: Array<ENABLEDSUICIDEVOTEEnum | number>; ENABLED_SEQ_EVENT?: Array<number | string>; ENABLED_TEST_ROLE?: Array<number | string>; } export enum DefaultVotetype { Anonymity = "anonymity", 標準の投票方法Sign記名Anonymity無記名 = "標準の投票方法(sign: 記名、anonymity:無記名)", } export enum ENABLEDAIMINGEnum { The1対象を指定した発言内緒話を含める = "1:対象を指定した発言(内緒話)を含める", } export enum ENABLEDAMBIDEXTEREnum { The1狂人の裏切りを認める狂人は人狼陣営ではなく裏切りの陣営村が負ければよい = "1:狂人の裏切りを認める(狂人は、人狼陣営ではなく裏切りの陣営=村が負ければよい)", } export enum ENABLEDBITTYEnum { 少女や交霊者ののぞきみがひらがなのみ = "少女や交霊者ののぞきみがひらがなのみ。", } export enum ENABLEDDELETEDEnum { 削除発言を表示するかどうか = "削除発言を表示するかどうか", } export enum ENABLEDMAXESAYEnum { エピローグを発言制限対象に0しない1する = "エピローグを発言制限対象に 0:しない、1:する", } export enum ENABLEDMOBAIMINGEnum { The1見物人が内緒話を使える = "1:見物人が内緒話を使える。", } export enum ENABLEDPERMITDEADEnum { 墓下の人狼共鳴者コウモリ人間が囁きを見られるかどうか = "墓下の人狼/共鳴者/コウモリ人間が囁きを見られるかどうか", } export enum ENABLEDRANDOMTARGETEnum { The1投票・能力先にランダムを含める = "1:投票・能力先に「ランダム」を含める", } export enum ENABLEDSUDDENDEATHEnum { The1突然死あり = "1:突然死あり", } export enum ENABLEDSUICIDEVOTEEnum { The1自殺投票 = "1:自殺投票", } export enum ENABLEDUNDEADEnum { The1幽界トーク村を設定可能 = "1:幽界トーク村を設定可能", } export enum ENABLEDWINNERLABELEnum { The1勝利者表示をする = "1:勝利者表示をする。", } export enum Erb { AssetSowGijiPlErb = "./asset/sow/giji.pl.erb", AssetSowPanPlErb = "./asset/sow/pan.pl.erb", } export interface Maxsize { MAXSIZE_ACTION: number; MAXSIZE_MEMOCNT: number; MAXSIZE_MEMOLINE: number; } export interface Path { DIR_LIB: DirLIB; DIR_HTML: DirHTML; DIR_RS: DirRs; DIR_VIL: DirVil; DIR_USER: DirUser; } export enum DirHTML { CabalaHTML = "../cabala/html", HTML = "./html", TestbedHTML = "../testbed/html", } export enum DirLIB { CabalaLIB = "../cabala/lib", LIB = "./lib", TestbedLIB = "../testbed/lib", } export enum DirRs { CabalaRs = "../cabala/rs", Rs = "./rs", TestbedRs = "../testbed/rs", } export enum DirUser { DIRUSERDataUser = "../data/user", DataUser = "./data/user", SowDataUser = "../sow/data/user", } export enum DirVil { CafeDataVil = "../cafe/data/vil", DataVil = "./data/vil", JksyDataVil = "../jksy/data/vil", } export interface SowFolderYmlStory { evil: Evil; role_play: boolean; } export enum Evil { Evil = "EVIL", Wolf = "WOLF", } export interface Villages { stories: StoryElement[]; messages?: Message[]; events: Event[]; potofs?: Potof[]; } export interface Event { _id: EventIDEnum; _type: EventType; name?: Name; story_id: StoryID; turn: number; winner: Winner; created_at: Date; updated_at: Date; eclipse?: string[]; epilogue?: number; grudge?: number; riot?: number; say?: Say; scapegoat?: number; seance?: string[]; event?: null; } export enum EventIDEnum { Cabala2310 = "cabala-231-0", Cabala2311 = "cabala-231-1", Cabala2312 = "cabala-231-2", Cabala2313 = "cabala-231-3", Cabala2314 = "cabala-231-4", Cabala2315 = "cabala-231-5", Cabala2316 = "cabala-231-6", Cabala440 = "cabala-44-0", Cabala441 = "cabala-44-1", Cabala442 = "cabala-44-2", Cabala443 = "cabala-44-3", Cabala444 = "cabala-44-4", Cabala445 = "cabala-44-5", Cabala446 = "cabala-44-6", Ciel10 = "ciel-1-0", Ciel11 = "ciel-1-1", Ciel12 = "ciel-1-2", Ciel13 = "ciel-1-3", Ciel14 = "ciel-1-4", Ciel15 = "ciel-1-5", Ciel16 = "ciel-1-6", Ciel190 = "ciel-19-0", Ciel191 = "ciel-19-1", Ciel192 = "ciel-19-2", Ciel193 = "ciel-19-3", Ciel194 = "ciel-19-4", Ciel620 = "ciel-62-0", Ciel621 = "ciel-62-1", Ciel622 = "ciel-62-2", Ciel623 = "ciel-62-3", Ciel624 = "ciel-62-4", Ciel625 = "ciel-62-5", Ciel626 = "ciel-62-6", Ciel627 = "ciel-62-7", Ciel628 = "ciel-62-8", Ciel640 = "ciel-64-0", Ciel641 = "ciel-64-1", Ciel642 = "ciel-64-2", Ciel643 = "ciel-64-3", Ciel644 = "ciel-64-4", Ciel645 = "ciel-64-5", Crazy2710 = "crazy-271-0", Crazy2711 = "crazy-271-1", Crazy2712 = "crazy-271-2", Crazy2713 = "crazy-271-3", Offparty20 = "offparty-2-0", Offparty21 = "offparty-2-1", Rp330 = "rp-33-0", Rp331 = "rp-33-1", Rp3310 = "rp-33-10", Rp3311 = "rp-33-11", Rp3312 = "rp-33-12", Rp3313 = "rp-33-13", Rp332 = "rp-33-2", Rp333 = "rp-33-3", Rp334 = "rp-33-4", Rp335 = "rp-33-5", Rp336 = "rp-33-6", Rp337 = "rp-33-7", Rp338 = "rp-33-8", Rp339 = "rp-33-9", Ultimate690 = "ultimate-69-0", Ultimate691 = "ultimate-69-1", Ultimate692 = "ultimate-69-2", Ultimate693 = "ultimate-69-3", Ultimate694 = "ultimate-69-4", Ultimate695 = "ultimate-69-5", Ultimate696 = "ultimate-69-6", Wolf1160 = "wolf-116-0", Wolf1161 = "wolf-116-1", Wolf11610 = "wolf-116-10", Wolf1162 = "wolf-116-2", Wolf1163 = "wolf-116-3", Wolf1164 = "wolf-116-4", Wolf1165 = "wolf-116-5", Wolf1166 = "wolf-116-6", Wolf1167 = "wolf-116-7", Wolf1168 = "wolf-116-8", Wolf1169 = "wolf-116-9", Xebec2750 = "xebec-275-0", Xebec2751 = "xebec-275-1", Xebec2752 = "xebec-275-2", Xebec2753 = "xebec-275-3", Xebec2754 = "xebec-275-4", Xebec2755 = "xebec-275-5", Xebec2756 = "xebec-275-6", Xebec2830 = "xebec-283-0", Xebec2831 = "xebec-283-1", Xebec2832 = "xebec-283-2", Xebec2833 = "xebec-283-3", Xebec2834 = "xebec-283-4", Xebec2835 = "xebec-283-5", Xebec2836 = "xebec-283-6", Xebec2837 = "xebec-283-7", Xebec2838 = "xebec-283-8", Xebec2950 = "xebec-295-0", Xebec2951 = "xebec-295-1", Xebec2952 = "xebec-295-2", Xebec2953 = "xebec-295-3", Xebec2954 = "xebec-295-4", Xebec2955 = "xebec-295-5", Xebec2956 = "xebec-295-6", Xebec3030 = "xebec-303-0", Xebec3031 = "xebec-303-1", Xebec3032 = "xebec-303-2", Xebec3033 = "xebec-303-3", Xebec3034 = "xebec-303-4", Xebec3035 = "xebec-303-5", Xebec3036 = "xebec-303-6", Xebec3037 = "xebec-303-7", Xebec3038 = "xebec-303-8", } export enum EventType { SowTurn = "SowTurn", } export enum Name { エピローグ = "エピローグ", プロローグ = "プロローグ", } export interface Say { modifiedsay: Date; modifiedwsay: Date; modifiedgsay: Date; modifiedspsay: Date; modifiedxsay: Date; modifiedvsay?: Date; } export enum StoryID { Cabala231 = "cabala-231", Cabala44 = "cabala-44", Ciel1 = "ciel-1", Ciel19 = "ciel-19", Ciel62 = "ciel-62", Ciel64 = "ciel-64", Crazy271 = "crazy-271", Offparty2 = "offparty-2", Rp33 = "rp-33", Ultimate69 = "ultimate-69", Wolf116 = "wolf-116", Xebec275 = "xebec-275", Xebec283 = "xebec-283", Xebec295 = "xebec-295", Xebec303 = "xebec-303", } export enum Winner { WinHuman = "WIN_HUMAN", WinNone = "WIN_NONE", WinPixi = "WIN_PIXI", WinWolf = "WIN_WOLF", } export interface Message { _id: string; story_id: StoryID; event_id: EventIDEnum | null; logid: string; sow_auth_id: string; date: Date; log: null | string; subid: Subid; face_id: FaceID | null; csid: Csid | null; style: Style | null; mestype: Mestype; name: string; size?: number; to?: To; } export enum Csid { All = "all", Animal = "animal", Changed = "changed", Ririnra = "ririnra", RirinraC20 = "ririnra_c20", RirinraC51 = "ririnra_c51", RirinraC67 = "ririnra_c67", School = "school", Time = "time", TimeT21 = "time_t21", TimeT44 = "time_t44", TimeT48 = "time_t48", TimeT48Wash = "time_t48_wash", TimeT49 = "time_t49", TimeT49Wash = "time_t49_wash", Wa = "wa", } export enum FaceID { Admin = "admin", All = "all", B44 = "b44", B49 = "b49", C01 = "c01", C02 = "c02", C03 = "c03", C04 = "c04", C05 = "c05", C06 = "c06", C07 = "c07", C08 = "c08", C09 = "c09", C10 = "c10", C101 = "c101", C104 = "c104", C105 = "c105", C11 = "c11", C110 = "c110", C112 = "c112", C119 = "c119", C12 = "c12", C122 = "c122", C123 = "c123", C124 = "c124", C125 = "c125", C127 = "c127", C129 = "c129", C13 = "c13", C130 = "c130", C135 = "c135", C136 = "c136", C138 = "c138", C139 = "c139", C14 = "c14", C15 = "c15", C16 = "c16", C18 = "c18", C19 = "c19", C20 = "c20", C21 = "c21", C22 = "c22", C23 = "c23", C24 = "c24", C25 = "c25", C26 = "c26", C27 = "c27", C28 = "c28", C29 = "c29", C30 = "c30", C31 = "c31", C32 = "c32", C33 = "c33", C34 = "c34", C35 = "c35", C36 = "c36", C37 = "c37", C38 = "c38", C39 = "c39", C40 = "c40", C41 = "c41", C42 = "c42", C43 = "c43", C44 = "c44", C45 = "c45", C46 = "c46", C47 = "c47", C48 = "c48", C49 = "c49", C50 = "c50", C51 = "c51", C52 = "c52", C53 = "c53", C54 = "c54", C55 = "c55", C57 = "c57", C58 = "c58", C59 = "c59", C60 = "c60", C62 = "c62", C63 = "c63", C64 = "c64", C65 = "c65", C66 = "c66", C67 = "c67", C68 = "c68", C70 = "c70", C71 = "c71", C72 = "c72", C73 = "c73", C76 = "c76", C79 = "c79", C80 = "c80", C81 = "c81", C85 = "c85", C87 = "c87", C99 = "c99", F000 = "f000", F15 = "f15", F18 = "f18", F2 = "f2", F20 = "f20", F21 = "f21", F23 = "f23", F25 = "f25", F26 = "f26", F27 = "f27", F28 = "f28", F5 = "f5", F8 = "f8", F9 = "f9", Fw01 = "fw01", Fw02 = "fw02", G04 = "g04", G07 = "g07", G09 = "g09", M04 = "m04", M06 = "m06", M09 = "m09", M14 = "m14", M16 = "m16", M19 = "m19", M20 = "m20", Mad01 = "mad01", Mad02 = "mad02", Mad03 = "mad03", Mad04 = "mad04", Mad06 = "mad06", Mad09 = "mad09", Maker = "maker", Sf026 = "sf026", Sf033 = "sf033", Sf035 = "sf035", Sf039 = "sf039", Sf04 = "sf04", Sf10 = "sf10", Sf16 = "sf16", Sf17 = "sf17", T01 = "t01", T02 = "t02", T03 = "t03", T06 = "t06", T08 = "t08", T10 = "t10", T11 = "t11", T12 = "t12", T14 = "t14", T15 = "t15", T17 = "t17", T20 = "t20", T24 = "t24", T28 = "t28", T34 = "t34", T41 = "t41", T42 = "t42", T43 = "t43", T44 = "t44", T45 = "t45", T47 = "t47", T49 = "t49", T50 = "t50", T51 = "t51", T53 = "t53", T54 = "t54", T55 = "t55", T56 = "t56", T58 = "t58", T59 = "t59", T63 = "t63", T65 = "t65", T66 = "t66", T69 = "t69", T70 = "t70", T72 = "t72", T73 = "t73", T74 = "t74", T75 = "t75", T76 = "t76", T86 = "t86", T87 = "t87", T89 = "t89", T90 = "t90", T93 = "t93", T99 = "t99", W03 = "w03", W04 = "w04", W05 = "w05", W06 = "w06", W07 = "w07", W08 = "w08", W10 = "w10", W11 = "w11", W12 = "w12", W13 = "w13", W15 = "w15", W17 = "w17", W20 = "w20", W24 = "w24", W26 = "w26", W27 = "w27", W29 = "w29", W31 = "w31", W35 = "w35", W37 = "w37", W38 = "w38", W39 = "w39", W40 = "w40", W45 = "w45", W52 = "w52", W53 = "w53", } export enum Mestype { Admin = "ADMIN", Aim = "AIM", Bsay = "BSAY", Cast = "CAST", Deleted = "DELETED", Gsay = "GSAY", Infonom = "INFONOM", Infosp = "INFOSP", Infowolf = "INFOWOLF", Maker = "MAKER", Msay = "MSAY", Say = "SAY", Spsay = "SPSAY", Tsay = "TSAY", Vsay = "VSAY", Wsay = "WSAY", Xsay = "XSAY", } export enum Style { Head = "head", Mono = "mono", } export enum Subid { A = "A", B = "B", I = "I", M = "M", S = "S", } export enum To { FSM団ミナカタ = "FSM団 ミナカタ", Mi18エリ = "MI:18 エリ", R団タカモト = "R団 タカモト", いしくボリス = "いしく ボリス", おひめさまタルト = "おひめさま タルト", お使いハナ = "お使い ハナ", お散歩隊長アシモフ = "お散歩隊長 アシモフ", かみさまRパルック1 = "かみさま R-パルック-1", かみさまパルック = "かみさま パルック", げぼくショコラ = "げぼく ショコラ", こあくとうドナルド = "こあくとう ドナルド", すくみずアオイ = "すくみず アオイ", りゅうきへいアーサー = "りゅうきへい アーサー", ラプターニジノ = "ラプター ニジノ", 七星拳ナツミ = "七星拳 ナツミ", 人工知能研DRコトリン = "人工知能研 Dr.コトリン", 会堂長老会ワタル = "会堂長老会 ワタル", 保安技師ナユタ = "保安技師 ナユタ", 公安部カガ = "公安部 カガ", 刻字座ヴェルヌイユ = "刻字座 ヴェルヌイユ", 剪毛工レナータ = "剪毛工 レナータ", 厭世家サイモン = "厭世家 サイモン", 双子夕顔 = "双子 夕顔", 双子朝顔 = "双子 朝顔", 双生児オスカー = "双生児 オスカー", 双生児ホリー = "双生児 ホリー", 営利政府トレイル = "営利政府 トレイル", 団子屋たまこ = "団子屋 たまこ", 地下鉄道フランク = "地下鉄道 フランク", 墓守ヨーランダ = "墓守 ヨーランダ", 奴隷運びヌヴィル = "奴隷運び ヌヴィル", 子守り日向 = "子守り 日向", 宝珠コーラ = "宝珠 コーラ", 小娘ゾーイ = "小娘 ゾーイ", 少年探偵団ガーディ = "少年探偵団 ガーディ", 幸運の科学リッキィ = "幸運の科学 リッキィ", 幽閉児ジャック = "幽閉児 ジャック", 店番ソフィア = "店番 ソフィア", 弁務官ジャーディン = "弁務官 ジャーディン", 憑依呪術師ケトゥートゥ = "憑依呪術師 ケトゥートゥ", 掃除夫ラルフ = "掃除夫 ラルフ", 教え子シメオン = "教え子 シメオン", 明仄暁星クロエ = "明仄∴暁星 クロエ", 時間貯蓄銀行ヤカモト = "時間貯蓄銀行 ヤカモト", 更なる前進ココア = "更なる前進 ココア", 朝茶会ソウスケ = "朝茶会 ソウスケ", 本屋ベネット = "本屋 ベネット", 架空惑星レン = "架空惑星 レン", 樫の樹の子らリツ = "樫の樹の子ら リツ", 歌舞伎座キランディ = "歌舞伎座 キランディ", 死ね死ね団サミュエル = "死ね死ね団 サミュエル", 水商売ローズマリー = "水商売 ローズマリー", 流浪者ペラジー = "流浪者 ペラジー", 漂白工ピッパ = "漂白工 ピッパ", 炉の番チトフ = "炉の番 チトフ", 猫の集会クシャミ = "猫の集会 クシャミ", 珊瑚宮連邦ルリ = "珊瑚宮連邦 ルリ", 留守番ジョージ = "留守番 ジョージ", 病人エリアス = "病人 エリアス", 病人キャサリン = "病人 キャサリン", 聖歌隊員レティーシャ = "聖歌隊員 レティーシャ", 良家の末娘ポーチュラカ = "良家の末娘 ポーチュラカ", 若者テッド = "若者 テッド", 薔薇十字ススム = "薔薇∴十字 ススム", 薬屋サイラス = "薬屋 サイラス", 蝋燭職人フェルゼ = "蝋燭職人 フェルゼ", 蟻塚崩しエルゴット = "蟻塚崩し エルゴット", 覆面嫉妬団ミルフィ = "覆面嫉妬団 ミルフィ", 親方ダン = "親方 ダン", 記者イアン = "記者 イアン", 読書家ケイト = "読書家 ケイト", 辣醤醸造ガルム = "辣醤醸造 ガルム", 迷い人ヘザー = "迷い人 ヘザー", 酸味探しドリベル = "酸味探し ドリベル", 鉄血の福音セイカ = "鉄血の福音 セイカ", 長老の孫マーゴ = "長老の孫 マーゴ", 門下生一平太 = "門下生 一平太", 隣席座りカナビス = "隣席座り カナビス", 雲水ハロ = "雲水 ハロ", 露店巡りシーシャ = "露店巡り シーシャ", 青い鳥デメテル = "青い鳥 デメテル", 靴磨きトニー = "靴磨き トニー", 飾り職ミッシェル = "飾り職 ミッシェル", 鳥使いフィリップ = "鳥使い フィリップ", 鷹の爪団マドカ = "鷹の爪団 マドカ", } export interface Potof { _id: string; _type: PotofType; bonds: string[]; clearance?: number; csid: Csid; deathday: number; event_id: EventID; face_id: FaceID; history: null | string; jobname: null; live: USERIDADMINElement; name?: string; overhear: any[]; pno?: null; point: Point; pseudobonds: string[]; role: Array<USERIDADMINElement | null>; rolestate?: number | null; say: { [key: string]: number | null }; select: USERIDADMINElement | number | null; sow_auth_id: string; story_id: StoryID; timer: PotofTimer; zapcount?: number; pseudolove?: USERIDADMINElement | null; love?: USERIDADMINElement | null; commit?: boolean; sheep?: null | string; } export enum PotofType { SowUser = "SowUser", } export enum EventID { Cabala2316 = "cabala-231-6", Cabala446 = "cabala-44-6", Ciel16 = "ciel-1-6", Ciel195 = "ciel-19-5", Ciel629 = "ciel-62-9", Ciel646 = "ciel-64-6", Crazy2710 = "crazy-271-0", Crazy2714 = "crazy-271-4", Offparty21 = "offparty-2-1", Rp339 = "rp-33-9", Ultimate696 = "ultimate-69-6", Wolf1169 = "wolf-116-9", Xebec2757 = "xebec-275-7", Xebec2839 = "xebec-283-9", Xebec2957 = "xebec-295-7", Xebec3039 = "xebec-303-9", } export interface Point { actaddpt: number; saidcount: number; saidpoint: number; } export interface PotofTimer { entrieddt: Date; limitentrydt: Date; } <file_sep># -*- encoding: utf-8 -*- # set RUBYOPT=-EUTF-8 module Media class Base BADWORDS = %w[ FLSNOW RBF QTS LxyLab Lxy Lab A.A ReinForce ANK-raws Kuroi-raws Yousei-raws HorribleSubs philosophy-raws VCB-studio JPN 720P 1080P TrueHD 720x960 960x720 1080x1448 1080x1920 1440x1080 1448x1080 1920x816 1920x1080 H264 x264 x264_aac x264-CHD.chs Hi10P 320kbps FLAC FLACx2 ALAC AVC AC3 AAC 2.0+2.0 DTS DTS-ES6.1 BD BDrip BluRay Blu-ray ] NUMBERS = %w[ Part BOX Vol\\. Vol ] TAIL = /\.[^.]+$/i NOIZE = /[_,']|[\[\]\(\)\{\}「」]/i POST_PREFIX = Regexp.new "\\b(#{NUMBERS.join("|")})(\\d*)\\b", Regexp::IGNORECASE POST_TRIM = Regexp.new "\\b(#{BADWORDS.join("|")})\\b", Regexp::IGNORECASE attr_accessor :src, :work, :target, :dir, :codec, :audio, :ext def self.filter(src) src = src.gsub(TAIL,"").gsub(NOIZE," ").gsub(POST_TRIM," ").gsub(/^-| -|- |-$/," ").gsub(POST_PREFIX,"\\2").gsub(/ +/," ").strip src = src.gsub(/\bIV\b/, "4").gsub(/\bVI\b/, "6").gsub(/\bV\b/, "5").gsub(/\bIII\b/, "3").gsub(/\bII\b/, "2") end def media_path(fname) paths = fname.split("/").reject {|str| [nil, ""].member? str } @work = ([ENV.work_dir] + paths[0..-1]).join("/") @dir = ([ENV.work_dir] + paths[0..-2]).join("/") if paths.size > 1 end def do_deploy raise "not implement" end def do_release raise "not implement" end def do_reject %Q|rm "#{@work}"| end def do_encode raise "not implement" end end end <file_sep>require 'fileutils' DST = '/mnt/c/Dropbox' SRC = '/mnt/c/Documents' FILES = { BAT: nil, SH: nil, } def init(path) FILES[:BAT] = open("#{path}.bat", "wb") FILES[:SH] = open("#{path}.sh", "w") FILES[:BAT].puts "rem created at #{Time.now}" FILES[:SH].puts "# created at #{Time.now}" end def crawle(tails, paths) list = [] paths.each do |rule| tails.each do |tail| Dir.glob("#{SRC}/www/*").each do |src| src = "#{src}/#{tail}" dest = src.gsub /^#{SRC}/, DST list.push [dest, src, tail] end Dir.glob("#{SRC}/#{rule}/#{tail}").each do |src| dest = src.gsub /^#{SRC}/, DST list.push [dest, src, tail] end Dir.glob("#{DST}/#{rule}/#{tail}").each do |dest| src = dest.gsub /^#{DST}/, SRC list.push [dest, src, tail] end end end list.sort.uniq.map do |dest, src, tail| mode = yield dest, src, tail [mode, dest, src] end.sort end def ls(paths) list = [] [SRC,DST].each do |hd| paths.each do |tl| list.push "#{hd}/#{tl}" end end puts `ls -ld #{list.join(' ')}` end def win(str) str.gsub("/mnt/c/","C:\\").gsub("/","\\") end def comment(msg) FILES[:SH].puts FILES[:SH].puts "# #{msg}" FILES[:BAT].puts FILES[:BAT].puts "rem #{win msg}" end def rmtree(tgt) FileUtils.rmtree(tgt) FILES[:SH].puts "# rm -rf #{ tgt }" FILES[:BAT].puts "rem rd /s /Q #{win tgt}" end def rm(tgts) tgts.each do |tgt| FileUtils.rm(tgt) FILES[:SH].puts "# rm -f #{ tgt }" FILES[:BAT].puts "rem del /s /Q #{win tgt}" end end def mkpath(tgt) FileUtils.mkpath(tgt) FILES[:SH].puts "# mkdir -p #{ tgt }" FILES[:BAT].puts "rem mkdir -p #{win tgt}" end def symlink(src, dest) # FileUtils.symlink(src, dest) FILES[:SH].puts "ln -s #{src} #{dest}" FILES[:BAT].puts "mklink /D #{win dest} #{win src}" end <file_sep># -*- encoding: utf-8 -*- # set RUBYOPT=-EUTF-8 require "./lib/packer" ENV.win class Media::Base def self.scan_path "/mnt/c/MEDIA/BitTorrent/**" end def head_path @src[/^.*\/BitTorrent/] end end pack = Packer.new pack.add Media::Movie.glob pack.encode pack.exec <file_sep># -*- encoding: utf-8 -*- # set RUBYOPT=-EUTF-8 TAGS = {} def move_temp(src_dir) tmp = ENV.tmp_dir + "/" Dir.glob(src_dir).each do |src| puts " ... copy by #{src.path}" time = File.mtime src `mv #{src.path} #{tmp.path}` File.utime time, time, tmp end end module Media::Album def tag(mtime) datestamp = mtime.strftime("%Y-%m-%d") TAGS[datestamp] ||= begin time_of_day = 1 * 24*60*60 minami = ((mtime - Time.new(2013, 6,24, 5)) / time_of_day).ceil tomohiro = ((mtime - Time.new(1978, 7,25, 4)) / time_of_day).ceil mika = ((mtime - Time.new(1980,11, 6,12)) / time_of_day).ceil puts "### input comment at #{datestamp} minami:#{minami}days. mika:#{mika}days. tomohiro:#{tomohiro}days. ###" `open #{@src.path}` gets.chomp end end def out_path mtime = File.mtime(@src) timestamp = mtime.strftime("%Y-%m-%d.%H.%M.%S") tag(mtime) + "-" + timestamp end end class Media::AlbumPhoto < Media::Copy include Media::Album def self.glob move_temp(scan_path + "/*" + Media::Copy::PICTURE) globbed = Dir.glob(ENV.tmp_dir + "/**/*" + Media::Copy::PICTURE) photo_scan globbed end def do_release %Q|rm #{@src.path}| end end class Media::AlbumAVCHD < Media::Copy include Media::Album def self.glob globbed = Dir.glob(ENV.tmp_dir + "**/*" + Media::Handbrake::MOVIE) photo_scan globbed end def do_release %Q|rm #{@src.path}| end end class Media::AlbumMovie < Media::Handbrake include Media::Album def self.glob move_temp(scan_path + "/*" + Media::Handbrake::MOVIE) globbed = Dir.glob(ENV.tmp_dir + "/**/*" + Media::Handbrake::MOVIE) track_scan globbed end def initialize_sd @codec = %Q|-q 28 --detelecine -e x265_12bit --h264-level="4.2"| @audio = %Q|-E ca_aac -6 dpl2 -R Auto -B 64 -D 0 --gain 0| end def initialize_hd @codec = %Q|-q 23 -e x264 --h264-level="4.2" --h264-profile=high --vfr --encopts ref=6:weightp=1:subq=2:rc-lookahead=10:trellis=2:8x8dct=0:bframes=5:b-adapt=2| @audio = %Q|-E ca_aac -6 5point1 -R Auto -B 256 --audio-copy-mask aac| end end <file_sep># -*- encoding: utf-8 -*- # set RUBYOPT=-EUTF-8 require "open3" class Media::BDMV < Media::Handbrake def self.glob globbed = Dir.glob(scan_path + "/BDMV/index.bdmv").map {|s| s.gsub("/BDMV/index.bdmv","") } track_scan globbed end def out_path @src.gsub(head_path,"").split("/").map{|str| Media::Base.filter str }.join("/") end def initialize_sd @codec = %Q|-q 28 --detelecine -e x265_12bit --h264-level="4.2"| @audio = %Q|-E av_aac -6 dpl2 -R Auto -B 80 -D 0 --gain 0| end def initialize_hd # @codec = %Q|-q 24 -e x264 --h264-level="4.2" --h264-profile=high --vfr --encopts ref=6:weightp=1:subq=2:rc-lookahead=10:trellis=2:8x8dct=0:bframes=5:b-adapt=2| @codec = %Q|-q 23 -e x265_12bit --vfr --encoder-preset slower --encoder-tune "ssim" --encoder-profile main12 | @audio = %Q|-E av_aac -6 5point1 -R Auto --aq 127 --audio-copy-mask aac| end end <file_sep># -*- encoding: utf-8 -*- # set RUBYOPT=-EUTF-8 Encoding.default_external = "utf-8" require "open3" class Media::HEVC < Media::Handbrake def self.glob globbed = Dir.glob(scan_path + "/*" + Media::Handbrake::MOVIE) track_scan globbed end def self.track_scan(globbed) list = [] globbed.each do |src| cmd = %Q|#{ENV.cli} -i #{src.path} --main-feature --scan| puts "scan... #{src}" o, e, s = Open3.capture3 cmd titles = e.scrub.split(/\+ title /i) main = titles.find{|s| s[/ \+ Main Feature/] } || titles.find{|s| s[/^1\:/] }.gsub("\r\n","\n") next unless main video, audio, subtitle = main.split(/ \+ audio tracks:\n| \+ subtitle tracks:\n/) title = main[/^\d+:/].to_i __, width, height = video.match(/ \+ size: (\d+)x(\d+)/).to_a.map(&:to_i) if width < 800 && height < 500 size = :SD else size = :HD end langs = [] audios = [] subtitles = [] invalid = true all_audios = audio.split("\n") all_subs = subtitle.split("\n") begin subtitles.push all_subs.grep(/Japanese|日本語/)[0].match(/\+ (\d+)/)[1].to_i audios.push all_audios.grep(/Chinese|中文/)[0].match(/\+ (\d+)/)[1].to_i langs.push "ch" invalid = false rescue StandardError => e end begin subtitles.push all_subs.grep(/Japanese|日本語/)[0].match(/\+ (\d+)/)[1].to_i audios.push all_audios.grep(/English/)[0].match(/\+ (\d+)/)[1].to_i langs.push "en" invalid = false rescue StandardError => e end begin audios.push all_audios.grep(/Japanese|日本語/)[0].match(/\+ (\d+)/)[1].to_i langs.push "ja" rescue StandardError => e if invalid && all_audios.size > 0 audios.push all_audios[0].match(/\+ (\d+)/)[1].to_i else puts " not find Japanese audio" end end list.push new(src, langs.reverse, title, size, audios.reverse, subtitles.reverse) end list end def initialize(src, langs, title, size, audios, subtitles) case size when :HD initialize_hd when :SD initialize_sd end @ext = %Q|--markers --title #{title} --audio #{audios.uniq.join(",")}| @ext += %Q| --subtitle #{subtitles.uniq.join(",")}| if 0 < subtitles.length @src = src media_path out_path + "-#{langs.join(",")}.mkv" puts " found #{size}#{langs}. #{@ext} " end def format %Q|-f av_mkv --vfr --loose-anamorphic --modulus 4| end def out_path @src.gsub(head_path,"").split("/").map{|str| Media::Base.filter str }.join("/") end def initialize_sd @codec = %Q|-q 26 -e x265_12bit --encoder-preset faster --encoder-tune "ssim" --encoder-profile main12 --detelecine | @audio = %Q|-E av_aac -6 dpl2 -R Auto --aq 80 --audio-copy-mask aac| end def initialize_hd @codec = %Q|-q 23 -e x265_12bit --encoder-preset faster --encoder-tune "ssim" --encoder-profile main12 | @audio = %Q|-E av_aac -6 5point1 -R Auto --aq 127 --audio-copy-mask aac| end end <file_sep># -*- encoding: utf-8 -*- # set RUBYOPT=-EUTF-8 require "./task/HandBrake/lib/packer" ENV.win class Media::Base def self.scan_path "/mnt/c/MEDIA/BitTorrent/**" end def head_path @src[/^.*\/BitTorrent/] end end class Media::HEVC def initialize_hd @codec = %Q|-q 25 -e x265_12bit --encoder-preset veryfast --encoder-tune "ssim" --encoder-profile main12 | @audio = %Q|-E av_aac -6 5point1 -R Auto --aq 127 --audio-copy-mask aac| end end pack = Packer.new pack.add Media::HEVC.glob pack.encode pack.exec <file_sep># -*- encoding: utf-8 -*- # set RUBYOPT=-EUTF-8 require "./task/HandBrake/lib/media/base" require "./task/HandBrake/lib/media/copy" require "./task/HandBrake/lib/media/handbrake" require "./task/HandBrake/lib/media/bdmv" require "./task/HandBrake/lib/media/album" require "./task/HandBrake/lib/media/movie" require "./task/HandBrake/lib/media/hevc" STAMP = Time.now.strftime("%Y-%m-%d.%H") ENV = Struct.new(:cli, :tmp_dir, :work_dir, :deploy_log, :release_log).new def ENV.win ENV.cli = "/mnt/c/Document/bin/HandBrakeCLI.exe" ENV.work_dir = "/mnt/c/MEDIA/WORK" ENV.deploy_log = "/mnt/c/MEDIA/bat/#{STAMP}-encode.bat" ENV.release_log = "/mnt/c/MEDIA/bat/#{STAMP}-release.bat" def ENV.path(str) win = str.gsub(%r[^/mnt/c/],'C:/').gsub(%r[/],'\\') %Q|"#{win}"| end end def ENV.mac ENV.cli = "/www/bin/HandBrakeCLI" ENV.work_dir = "" ENV.deploy_log = "/tmp/#{STAMP}-encode.bat" ENV.release_log = "/tmp/#{STAMP}-release.bat" def ENV.path(str) %Q|"#{str}"| end end class String def path ENV.path(self) end end <file_sep># -*- encoding: utf-8 -*- # set RUBYOPT=-EUTF-8 require "./lib/packer" ENV.win class Media::Base def self.scan_path "S://MEDIA/DVD/**" end def head_path @src[/^.*\/DVD/] end end class Media::HEVC def initialize(src, langs, title, size, audios, subtitles) case size when :HD initialize_hd @ext = %Q|--markers --title #{title} --audio #{audios.uniq.join(",")}| @ext += %Q| --subtitle #{subtitles.uniq.join(",")}| if 0 < subtitles.length when :SD initialize_sd @ext = %Q|--markers --audio 1,2,3,4,5,6,7,8,9 --subtitle 1,2,3,4,5,6,7,8,9 | end @src = src media_path out_path + "-#{langs.join(",")}.mp4" puts " found #{size}#{langs}. #{@ext} " end def initialize_sd @codec = %Q|-q 27 -e x265_12bit --encoder-preset faster --encoder-tune "ssim" --encoder-profile main12 | @audio = %Q|-E av_aac -6 dpl2 -R Auto --aq 80 --audio-copy-mask aac| end end pack = Packer.new pack.add Media::HEVC.glob pack.encode pack.exec <file_sep>#! rbenv exec ruby # -*- encoding: utf-8 -*- require "./lib/packer" ENV.win head = %r=^Z:/Album/(Photo|Videos/AVCHD)/= glob = %Q|Z:/Album/{Photo,Videos/AVCHD}/**/| puts Dir.glob(glob).map{|o| o.gsub(head,"").chop }.uniq.sort class Media::AlbumMovie def self.scan_path "S:/AVCHD/*/STREAM/**" end def head_path @src[/^.*\/STREAM/] end end class Media::AlbumPhoto def self.scan_path "F:/DCIM/**" end def head_path @src[/^.*\/DCIM/] end end pack = Packer.new ENV.tmp_dir = "S:/MEDIA/PIC" ENV.work_dir = "Z:/Album/Photo" pack.add Media::AlbumPhoto.glob ENV.tmp_dir = "S:/MEDIA/MOV/AVCHD" ENV.work_dir = "S:/MEDIA/MOV/HandBrake" pack.add Media::AlbumMovie.glob ENV.work_dir = "Z:/Album/Videos/AVCHD" pack.add Media::AlbumAVCHD.glob pack.encode pack.exec <file_sep># created at 2020-09-19 00:55:45 +0900 # /mnt/c/Dropbox/www/crawle/node_modules 186 # /mnt/c/Dropbox/www/fancy-date/node_modules 405 # /mnt/c/Dropbox/www/giji-fire-new/node_modules 1216 # /mnt/c/Dropbox/www/giji-gatsby/functions/node_modules 296 # /mnt/c/Dropbox/www/giji-gatsby/node_modules 1605 # /mnt/c/Dropbox/www/giji-next/functions/node_modules 498 # /mnt/c/Dropbox/www/giji-next/node_modules 857 # /mnt/c/Dropbox/www/giji_assets_chr_add/node_modules 959 # /mnt/c/Dropbox/www/memory-orm/node_modules 1119 # /mnt/c/Dropbox/www/nextjs-blog/node_modules 509 # /mnt/c/Dropbox/www/react-petit-hooks/node_modules 1109 # /mnt/c/Dropbox/www/rfc6238/node_modules 55 # /mnt/c/Dropbox/www/sequence-await/node_modules 721 # /mnt/c/Dropbox/www/vue-petit-store/node_modules 719 # empty. /mnt/c/Dropbox/www/DefinitelyTyped/node_modules # empty. /mnt/c/Dropbox/www/giji-fire-new/functions/node_modules # empty. /mnt/c/Dropbox/www/giji-fire/functions/node_modules # empty. /mnt/c/Dropbox/www/giji-fire/node_modules # empty. /mnt/c/Dropbox/www/markdown-loader/node_modules # empty. /mnt/c/Dropbox/www/mermaid/node_modules # empty. /mnt/c/Dropbox/www/test-react-app/node_modules # empty. /mnt/c/Dropbox/www/trix/node_modules # empty. /mnt/c/Dropbox/www/vue-markup/node_modules <file_sep># -*- encoding: utf-8 -*- # set RUBYOPT=-EUTF-8 class Media::Handbrake < Media::Base MOVIE = ".{AVI,WMV,MKV,MOV,MP4,M4V,F4V,TS,MTS,M2TS,3GP,FLV,ISO,avi,wmv,mkv,mov,mp4,m4v,f4v,ts,mts,m2ts,3gp,flv,iso}" def self.track_scan(globbed) list = [] globbed.each do |src| cmd = %Q|#{ENV.cli} -i #{src.path} --main-feature --scan| puts "scan... #{src}" o, e, s = Open3.capture3 cmd titles = e.scrub.split(/\+ title /i) main = titles.find{|s| s[/ \+ Main Feature/] } || titles.find{|s| s[/^1\:/] }.gsub("\r\n","\n") next unless main video, audio, subtitle = main.split(/ \+ audio tracks:\n| \+ subtitle tracks:\n/) title = main[/^\d+:/].to_i __, width, height = video.match(/ \+ size: (\d+)x(\d+)/).to_a.map(&:to_i) if width < 800 && height < 500 size = :SD else size = :HD end ja = "" en = "" ch = "" begin jpn_subtitle = subtitle.split("\n").grep(/Japanese/)[0].match(/\+ (\d+)/)[1].to_i chi_audio = audio.split("\n").grep(/Chinese/)[0].match(/\+ (\d+)/)[1].to_i ch = "-ch" list.push new(src, ch, title, size, chi_audio, jpn_subtitle) ja = "-ja" rescue StandardError => e end begin jpn_subtitle = subtitle.split("\n").grep(/Japanese/)[0].match(/\+ (\d+)/)[1].to_i eng_audio = audio.split("\n").grep(/English/)[0].match(/\+ (\d+)/)[1].to_i en = "-en" list.push new(src, en, title, size, eng_audio, jpn_subtitle) ja = "-ja" rescue StandardError => e end begin jpn_audio = audio.split("\n").grep(/Japanese/)[0].match(/\+ (\d+)/)[1].to_i list.push new(src, ja, title, size, jpn_audio) rescue StandardError => e if "" == en && "" == ch jpn_audio = audio.split("\n")[0].match(/\+ (\d+)/)[1].to_i list.push new(src, ja, title, size, jpn_audio) else puts " not find Japanese audio" end end end list end def initialize(src, lang, title, size, audio, subtitle = nil) case size when :HD initialize_hd when :SD initialize_sd end @ext = %Q|--markers --title #{title} --audio #{audio}| @ext += %Q| --subtitle #{subtitle} --subtitle-burned| if subtitle @src = src # @target = %Q|//utage.family.jp/media/iPad/Videos/[映画] BD-src/#{paths[-1]}| media_path out_path + "#{lang}.mp4" puts " found #{size}#{lang}. #{@ext} " end def format %Q|-f mp4 -4 --vfr --loose-anamorphic --modulus 4| end def do_deploy if @dir %Q|mkdir "#{@dir}"| end end def do_release nil end def do_encode if File.exists?(@work) nil else %Q|#{ENV.cli} -i #{@src.path} -o #{@work.path} #{@ext} #{format} #{@audio} #{@codec} --verbose=1| end end end <file_sep>#! wsl /home/giji/.rvm/wrappers/default/ruby require_relative '../../lib/file' NOP = -1 COMPLETE = 0 EMPTY = 1 LINK = 2 init('./cmd/symlink') crawle(['node_modules', 'data'], [ 'www/*/*', 'www/*', ]) do |dest, src, tail| if File.symlink?(dest) && File.directory?(src) if 0 < Dir.glob("#{src}/*").size COMPLETE else EMPTY end else case tail when 'data' if File.directory?(src) LINK else NOP end when 'node_modules' LINK end end end.each do |mode, dest, src| case mode when COMPLETE size = Dir.glob("#{src}/*").size comment " #{ dest } #{ size }" when EMPTY comment " empty. #{ dest }" when LINK comment " #{ dest } -> #{ src }" mkpath src rmtree dest symlink src, dest end end <file_sep>require 'nokogiri' require 'open-uri' require 'yaml' OUTPUT = "../giji/app/yaml/work_namedb_jpn.yml" IS_DONE = {} URL_HEAD = "http://myoujijiten.web.fc2.com/todouhuken/" COUNTRYS = [ ["CHN", "hokkaido.htm", "北海道"], ["CHN", "aomori.htm", "青森"], ["CHN", "iwate.htm", "岩手"], ["CHN", "miyagi.htm", "宮城"], ["CHN", "akita.htm", "秋田"], ["CHN", "yamagata.htm", "山形"], ["CHN", "fukushima.htm", "福島"], ["CHN", "ibaraki.htm", "茨城"], ["CHN", "tochigi.htm", "栃木"], ["CHN", "gumma.htm", "群馬"], ["CHN", "saitama.htm", "埼玉"], ["CHN", "chiba.htm", "千葉"], ["CHN", "tokyo.htm", "東京"], ["CHN", "kanagawa.htm", "神奈川"], ["CHN", "niigata.htm", "新潟"], ["CHN", "nagano.htm", "長野"], ["CHN", "yamanashi.htm", "山梨"], ["CHN", "shizuoka.htm", "静岡"], ["CHN", "aichi.htm", "愛知"], ["CHN", "gifu.htm", "岐阜"], ["CHN", "mie.htm", "三重"], ["CHN", "toyama.htm", "富山"], ["CHN", "ishikawa.htm", "石川"], ["CHN", "fukui.htm", "福井"], ["CHN", "shiga.htm", "滋賀"], ["CHN", "kyoto.htm", "京都"], ["CHN", "osaka.htm", "大阪"], ["CHN", "hyogo.htm", "兵庫"], ["CHN", "nara.htm", "奈良"], ["CHN", "wakayama.htm", "和歌山"], ["CHN", "tottori.htm", "鳥取"], ["CHN", "shimane.htm", "島根"], ["CHN", "okayama.htm", "岡山"], ["CHN", "hiroshima.htm", "広島"], ["CHN", "yamaguchi.htm", "山口"], ["CHN", "tokushima.htm", "徳島"], ["CHN", "kagawa.htm", "香川"], ["CHN", "ehime.htm", "愛媛"], ["CHN", "kochi.htm", "高知"], ["CHN", "fukuoka.htm", "福岡"], ["CHN", "saga.htm", "佐賀"], ["CHN", "nagasaki.htm", "長崎"], ["CHN", "kumamoto.htm", "熊本"], ["CHN", "oita.htm", "大分"], ["CHN", "miyazaki.htm", "宮崎"], ["CHN", "kagoshima.htm", "鹿児島"], ["CHN", "okinawa.htm", "沖縄"], ] $CODES = { 'nbsp' => "\u00A0", 'lt' => '<', 'gt' => '>', 'amp' => '&', 'quot' => '\"', 'apos' => '\'', 'iexcl' => '¡', # 00A1 0161 &iexcl; 逆立ち感嘆符 'cent' => '¢', # 00A2 0162 &cent; セント記号 'pound' => '£', # 00A3 0163 &pound; 英貨ポンド記号 'curren' => '¤', # 00A4 0164 &curren; 一般通貨記号 'yen' => '¥', # 00A5 0165 &yen; 円記号 'brvbar' => '¦', # 00A6 0166 &brvbar; 縦破線 'sent' => '§', # 00A7 0167 &sect; 節記号 'uml' => '¨', # 00A8 0168 &uml; ウムラウト 'copy' => '©', # 00A9 0169 &copy; 著作権記号 'ordf' => 'ª', # 00AA 0170 &ordf; 順序の指示(女性形) 'laquo' => '«', # 00AB 0171 &laquo; 左角引用符 'not' => '¬', # 00AC 0172 &not; 否定記号 'shy' => "\u00ad", # 0173 &shy; ソフトハイフン 'reg' => '®', # 00AE 0174 &reg; 登録商標 'macr' => '¯', # 00AF 0175 &macr; マクロン 'deg' => '°', # 00B0 0176 &deg; 度記号 'plusmn' => '±', # 00B1 0177 &plusmn; プラスマイナス記号 'sup2' => '²', # 00B2 0178 &sup2; 上付き数字の2、平方 'sup3' => '³', # 00B3 0179 &sup3; 上付き数字の3、立方 'acute' => '´', # 00B4 0180 &acute; 鋭アクセント 'micro' => 'µ', # 00B5 0181 &micro; ミクロン記号 'para' => '¶', # 00B6 0182 &para; 段落記号 'middot' => '·', # 00B7 0183 &middot; 中黒 'cedil' => '¸', # 00B8 0184 &cedil; セディーユ 'sup1' => '¹', # 00B9 0185 &sup1; 上付き数字の1 'ordm' => 'º', # 00BA 0186 &ordm; 順序の指示(男性形) 'raquo' => '»', # 00BB 0187 &raquo; 右角引用符 'frac14' => '¼', # 00BC 0188 &frac14; 分数1/4 'frac12' => '½', # 00BD 0189 &frac12; 分数1/2 'frac34' => '¾', # 00BE 0190 &frac34; 分数3/4 'iquest' => '¿', # 00BF 0191 &iquest; 逆立ち疑問符 'Agrave' => 'À', # 00C0 0192 &Agrave; 大文字 A(重アクセント記号付) 'Aacute' => 'Á', # 00C1 0193 &Aacute; 大文字 A(鋭アクセント付) 'Acirc' => 'Â', # 00C2 0194 &Acirc; 大文字 A(曲折アクセント記号付) 'Atilde' => 'Ã', # 00C3 0195 &Atilde; 大文字 A(ティルデ付) 'Auml' => 'Ä', # 00C4 0196 &Auml; 大文字 A(ウムラウト付) 'Aring' => 'Å', # 00C5 0197 &Aring; 大文字 A(輪付) 'AElig' => 'Æ', # 00C6 0198 &AElig; 大文字 AE 二重母音(合字) 'Ccedil' => 'Ç', # 00C7 0199 &Ccedil; 大文字 C(セディーユ付) 'Egrave' => 'È', # 00C8 0200 &Egrave; 大文字 E(重アクセント記号付) 'Eacute' => 'É', # 00C9 0201 &Eacute; 大文字 E(鋭アクセント記号付) 'Ecirc' => 'Ê', # 00CA 0202 &Ecirc; 大文字 E(曲折アクセント付) 'Euml' => 'Ë', # 00CB 0203 &Euml; 大文字 E(ウムラウト付) 'Igrave' => 'Ì', # 00CC 0204 &Igrave; 大文字 I(重アクセント記号付) 'Iacute' => 'Í', # 00CD 0205 &Iacute; 大文字 I(鋭アクセント記号付) 'Icirc' => 'Î', # 00CE 0206 &Icirc; 大文字 I(曲折アクセント付) 'Iuml' => 'Ï', # 00CF 0207 &Iuml; 大文字 I(ウムラウト付) 'ETH' => 'Ð', # 00D0 0208 &ETH; 大文字エズ 'Ntilde' => 'Ñ', # 00D1 0209 &Ntilde; 大文字 N(ティルデ付) 'Ograve' => 'Ò', # 00D2 0210 &Ograve; 大文字 O(重アクセント記号付) 'Oacute' => 'Ó', # 00D3 0211 &Oacute; 大文字 O(鋭アクセント記号付) 'Ocirc' => 'Ô', # 00D4 0212 &Ocirc; 大文字 O(曲折アクセント記号付) 'Otilde' => 'Õ', # 00D5 0213 &Otilde; 大文字 O (ティルデ付) 'Ouml' => 'Ö', # 00D6 0214 &Ouml; 大文字 O(ウムラウト付) 'times' => '×', # 00D7 0215 &times; 乗算記号 'Oslash' => 'Ø', # 00D8 0216 &Oslash; 大文字 O(スラッシュ付) 'Ugrave' => 'Ù', # 00D9 0217 &Ugrave; 大文字 U(重アクセント記号付) 'Uacute' => 'Ú', # 00DA 0218 &Uacute; 大文字 U(鋭アクセント記号付) 'Ucirc' => 'Û', # 00DB 0219 &Ucirc; 大文字 U(曲折アクセント記号付) 'Uuml' => 'Ü', # 00DC 0220 &Uuml; 大文字 U(ウムラウト付) 'Yacute' => 'Ý', # 00DD 0221 &Yacute; 大文字 Y(鋭アクセント記号付) 'THORN' => 'Þ', # 00DE 0222 &THORN; 大文字ソーン 'szlig' => 'ß', # 00DF 0223 &szlig; ドイツ語の小文字鋭 s(sz 合字) 'agrave' => 'à', # 00E0 0224 &agrave; 小文字 a(重アクセント記号付) 'aacute' => 'á', # 00E1 0225 &aacute; 小文字 a(鋭アクセント記号付) 'acirc' => 'â', # 00E2 0226 &acirc; 小文字 a(曲折アクセント記号付) 'atilde' => 'ã', # 00E3 0227 &atilde; 小文字 a(ティルデ付) 'auml' => 'ä', # 00E4 0228 &auml; 小文字 a(ウムラウト付) 'aring' => 'å', # 00E5 0229 &aring; 小文字 a(輪付) 'aelig' => 'æ', # 00E6 0230 &aelig; 小文字 ae 二重母音(合字) 'ccedil' => 'ç', # 00E7 0231 &ccedil; 小文字 c(セディーユ付) 'egrave' => 'è', # 00E8 0232 &egrave; 小文字 e(重アクセント記号付) 'eacute' => 'é', # 00E9 0233 &eacute; 小文字 e(鋭アクセント記号付) 'ecirc' => 'ê', # 00EA 0234 &ecirc; 小文字 e(曲折アクセント記号付) 'euml' => 'ë', # 00EB 0235 &euml; 小文字 e(ウムラウト付) 'igrave' => 'ì', # 00EC 0236 &igrave; 小文字 i(重アクセント記号付) 'iacute' => 'í', # 00ED 0237 &iacute; 小文字 i(鋭アクセント記号付) 'icirc' => 'î', # 00EE 0238 &icirc; 小文字 i(曲折アクセント記号付) 'iuml' => 'ï', # 00EF 0239 &iuml; 小文字 i(ウムラウト付) 'eth' => 'ð', # 00F0 0240 &eth; 小文字エズ 'ntilde' => 'ñ', # 00F1 0241 &ntilde; 小文字 n(ティルデ付) 'ograve' => 'ò', # 00F2 0242 &ograve; 小文字 o(重アクセント記号付) 'oacute' => 'ó', # 00F3 0243 &oacute; 小文字 o(鋭アクセント記号付) 'ocirc' => 'ô', # 00F4 0244 &ocirc; 小文字 o(曲折アクセント記号付) 'otilde' => 'õ', # 00F5 0245 &otilde; 小文字 o(ティルデ付) 'ouml' => 'ö', # 00F6 0246 &ouml; 小文字 o(ウムラウト付) 'divide' => '÷', # 00F7 0247 &divide; 除算記号 'oslash' => 'ø', # 00F8 0248 &oslash; 小文字 o(斜線付) 'ugrave' => 'ù', # 00F9 0249 &ugrave; 小文字 u(重アクセント記号付) 'uacute' => 'ú', # 00FA 0250 &uacute; 小文字 u(鋭アクセント記号付) 'ucirc' => 'û', # 00FB 0251 &ucirc; 小文字 u(曲折アクセント記号付) 'uuml' => 'ü', # 00FC 0252 &uuml; 小文字 u(ウムラウト付) 'yacute' => 'ý', # 00FD 0253 &yacute; 小文字 y(鋭アクセント記号付) 'thorn' => 'þ', # 00FE 0254 &thorn; 小文字ソーン 'yuml' => 'ÿ', # 00FF 0255 &yuml; 小文字 y(ウムラウト付) } # hiragana to katakana for utf-8 def to_katakana(src) src .gsub("わ゙","ヷ") .gsub("い゙","ヸ") .gsub("え゙","ヹ") .gsub("を゙","ヺ") .tr("ぁ-ゖゝゞゟ","ァ-ヶヽヾヿ") end def decodeHTML(text) text .gsub(' align="left"', '') .gsub(' align="center"', '') .gsub(' align="right"', '') .gsub('<FONT size="-1">', '') .gsub('<FONT size="-2">', '') .gsub('</FONT>', '') .gsub(' (表末の注参照)', '') .gsub(%r|<IMG src="[^"]+"[^>]+>|, '@') .gsub(/&[^;]+;/) do |code| if '#' == code[1] case code[2] when 'x','X' val = code[3..].to_i(16) case val when 0x80..0x9f val.chr("cp1252").encode("UTF-8") else val.chr("UTF-8") end else code[2..].to_i(10).chr("UTF-8") end else $CODES[code[1..-2]] end end end def scan_names( key, leaf_key, mark ) URI.open( URL_HEAD + leaf_key ) do |f| p f.base_uri IS_DONE[leaf_key] = f.last_modified doc = Nokogiri::HTML.parse( decodeHTML( f.read.encode("UTF-8", "UTF-8") ), nil, 'UTF-8' ) table = doc.css('table[border]')[0] table.css('tr').each do |tr| (spellTag,namesTag,countTag,spotTag) = tr.css('td') next unless spotTag spell = spellTag.text count = countTag.text.to_i names = namesTag.text.split(" ").reject {|s| [nil, ""].member? s } spot = spotTag.text if spellTag.css('font[color]')[0] comment = "#{count}%住 多 #{spot}" else comment = "#{count}%住 #{spot}" end names.each do |name| yml = YAML.dump([{ "spell" => spell, "name" => to_katakana(name), "side" => "姓", "mark" => mark, "comment" => comment, "key" => key, }]) File.open(OUTPUT, "a") do |f| f.write yml[4..] end end end end end File.open(OUTPUT,"w") do |f| YAML.dump({ "by" => "http://myoujijiten.web.fc2.com/todouhuken.html", "name" => nil, }, f) end COUNTRYS.each do |(key, leaf_key, mark)| scan_names( key, leaf_key, mark ) end yml = YAML.dump({ "timestamp" => IS_DONE, }) File.open(OUTPUT,"a") do |f| f.write yml[4..] end YAML.load_file(OUTPUT) <file_sep>#! wsl /home/giji/.rvm/wrappers/default/ruby require_relative '../../lib/file' init('./cmd/clean') rm Dir.glob("#{DST}/**/*の競合コピー*")<file_sep>#! /bin/bash ~/.rvm/wrappers/default/ruby $*<file_sep> require 'yaml' require 'json' OUTPUT = "./data/giji-json/" FNAME_SNAP_HD = "../giji/yaml/work_geo_" FNAME_OUTPUT_YAML = "../giji/yaml/work_geo.yml" YAML.load_file(FNAME_OUTPUT_YAML) YAML.load_file(FNAME_SNAP_HD + "name.yml") YAML.load_file(FNAME_SNAP_HD + "label.yml") YAML.load_file(FNAME_SNAP_HD + "etc.yml") YAML.load_file(FNAME_SNAP_HD + "dic.yml") YAML.load_file(FNAME_SNAP_HD + "orm.yml") villages = [] chrsets = [] Dir.glob('./data/giji-json-vil/*').each do |path| File.open(path,'r') do |f| villages.push f.read end end Dir.glob('../giji-next/src/yaml/*').each do |path| fname = path.split("/").last next if %r[/work_] === path data = YAML.load_file path if Hash === data && !( %r[/cs_|/random|/rule] === path ) list = [] data.each do |id, o| o[:_id] = id list.push o end data = list end str = JSON.generate data if %r[/cs_] === path chrsets.push str next end File.open(OUTPUT + fname + ".json", 'w') do |f| f.print str end end json_chrsets = "[#{chrsets.join(',')}]" File.open(OUTPUT + "chrsets.yaml.json", 'w') do |f| f.print json_chrsets end json_villages = "[#{villages.join(',')}]" File.open(OUTPUT + "villages.json", 'w') do |f| f.print json_villages end
c0510146e62a861e3b6ef6dbca4fc3e4cc4e5d9b
[ "TypeScript", "Ruby", "Shell" ]
24
Shell
7korobi/crawle
bd3deb6296a09763189e837eebbb230f6fb07819
9804f1ae42ca4f9c42e6d5047ec13b1cc64c88bb
refs/heads/master
<file_sep># Stack_Applications Implementing prefix and postfix notations using stacks with linked lists <file_sep>#include<iostream> using namespace std; template<class T> class pre { T a[100]; int maxsize,sp; public: pre(int m) { sp=-1; maxsize=m; } int isfull() { return (sp==maxsize-1); } int isempty() { return (sp==-1); } void push(T ); T pop(); int precedence(T); void convert(); }; template<class T> void pre<T>::push(T c) { if(!isfull()) a[++sp]=c; else cout<<"stak owerflow:\n"; } template<class T> T pre<T>::pop() { if(!isempty()) { T c; c=a[sp--]; return c; } cout<<"stak under flow:\n"; } template<class T> int pre<T>::precedence(T ch) { switch(ch) { case '*': case '/': case '%': return 3; case '+': case '-': return 2; case ')': return 1; case '#': return 0; } } template<class T> void pre<T>::convert() { push('#'); T infix[100],prefix[100],ch,reverse[100]; cout<<"enter the infix expression:\n"; cin>>infix; int f=0,k=0; while(infix[f]!='\0') { k++; f++; } int g=0; for(f=k;f>0;f--) { reverse[g]=infix[f]; g++; cout<<reverse; } for(int j=0;j<k;j++) { infix[j]=reverse[j]; } int i=0,p=0; while(infix[i]!='\0') { ch=infix[i]; if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||(ch>='0'&&ch<='9')) prefix[p]=ch; else if(ch==')') push(ch); else if(ch=='(') { while(a[sp]!=')') { T c; c=pop(); prefix[++p]=c; } pop(); } else { int pre1=precedence(ch); int pre2=precedence(a[sp]); if(pre1>=pre2) push(ch); else { T c; c=pop(); push(ch); prefix[++p]=c; } } i++; } int j=0; for(int s=k;s>=0;s--) { reverse[j]=prefix[s]; j++; } for(int s=0;s<k;s++) { prefix[s]=reverse[s]; } prefix[++p]='\0'; cout<<"the prefix expression is:\n"; for(i=0;i<k;i++) cout<<prefix[i]; } int main() { pre<char>z(100); z.convert(); int d; cin>>d; }
95a86c0eb086f7e87726852fcc6c650040baa082
[ "Markdown", "C++" ]
2
Markdown
Prasant-Jillella/Stack_Applications
56174f85c73c3d334cda11bc0d4d1dc5c787dd7f
b5f5bb82eca478e187f5b1c69f7a0ef15b9b590a
refs/heads/master
<file_sep>package it.ra.librettounivesitario.exception; public class IllegalVotoException extends Exception { public IllegalVotoException() { super(); } public IllegalVotoException(String message) { super(message); } } <file_sep> package it.ra.librettounivesitario.exception; public class IllegalDocenteException extends Exception { public IllegalDocenteException() { super(); } public IllegalDocenteException(String message) { super(message); } } <file_sep>package it.ra.librettounivesitario.exception; public class IllegalCorsoException extends Exception { public IllegalCorsoException() { super(); } public IllegalCorsoException(String message) { super(message); } }
f0e50e64c3009d57690eb16bb6930d9701261a90
[ "Java" ]
3
Java
venflon1/librettoUniversitarioDemo
ee570d6ed97b526233c1d2ccfa49e34bb5c6f7ee
549cef94b9fda88f471298ca6f5fe40824f06854
refs/heads/master
<file_sep>host=? name=? username=? pass=?<file_sep><?php session_start(); if(!isset($_SESSION['userid'])){ die("You must be logged in!"); } include('../dbinfo.php'); //get data $name = $_POST['name']; $memory = $_POST['memory']; $load = $_POST['load']; $timeout = $_POST['timeout']; $num_jobs = $_POST['num_jobs']; $jobs = json_decode($_POST["jobs"]); $program = $_POST["program"]; $preprocessor = $_POST["preprocessor"]; $parameters = $_POST["parameters"]; $servers = $_POST["selected_servers"]; //connect to database $mysql_conn = mysqli_connect(HOST, USER, PASS, DB) or die("Cannot connect to DB" . mysqli_error($mysql_conn)); $date = date('Y-m-d H:i:s'); $user_id = $_SESSION['userid']; ////////////////////////////// CREATE TASK ////////////////////////////// //add task to database and get the ID of the added task $query = mysqli_query($mysql_conn, "INSERT INTO Tasks (user_id, task_name, start_time, max_load, max_memory, timeout, total_jobs) VALUES('$user_id', '$name','$date','$load','$memory','$timeout','$num_jobs')"); $task_id = mysqli_insert_id($mysql_conn); ////////////////////////////// CREATE JOBS ////////////////////////////// ignore_user_abort(TRUE); set_time_limit(600); //loop number of program configurations for ($i = 0; $i < count($program); $i++) { //loop problem files and insert job into Jobs table foreach ($jobs as $key => $value) { $query = mysqli_query($mysql_conn, "INSERT INTO Jobs (task_id, program, input_file, job_parameters, pre_processor) VALUES('$task_id', '$program[$i]', '$value', '$parameters[$i]', '$preprocessor[$i]')"); } } //close database connection mysqli_close($mysql_conn); ////////////////////////////// CREATE DIRECTORY ////////////////////////////// $path = '../logs/'.$user_id.'/'.$task_id; mkdir($path, 0711, true); ////////////////////////////// CONNECT TO SERVER ////////////////////////////// //load ip address of server from file $host = file_get_contents('../ip.txt', FILE_USE_INCLUDE_PATH); $port = "8191"; //timeout in seconds $timeout = 4; //message to send to server $task_string = "0@".$task_id."@".$user_id."@".count($servers); //concatenate each client to the string for ($i = 0; $i < count($servers); $i++) { $task_string = $task_string."@".$servers[$i]; } //setup socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_nonblock($socket); //get current time $time = time(); //attempt to connect to socket while (!@socket_connect($socket, $host, $port)) { $err = socket_last_error($socket); if ($err == 115 || $err == 114) { //check if timeout is reached if ((time() - $time) >= $timeout) { socket_close($socket); } sleep(1); continue; } //could not connect, add task string to recovery file instead addToRecoveryFile($task_string); } //send task string to server and close socket socket_write($socket, $task_string, strlen($task_string)); socket_close($socket); echo "Started Task ".$task_id; ////////////////////////////// ADD TASK STRING TO RECOVERY FILE ////////////////////////////// //function to add task string to the end of recovery.txt function addToRecoveryFile($task) { $file = '../recovery.txt'; $myfile = file_put_contents($file, $task ."\r\n" , FILE_APPEND | LOCK_EX); echo "Server Offline, Task will start when server is started!"; die(); } ?><file_sep><?php $pattern = $_GET['pattern']; $directory = $_GET['directory']; $files = array(); //no pattern input, return empty array if($pattern == ''){} else if($directory == 'ALL FOLDERS') { //iterate through all directories within the 'problems' folder $directory = 'problems'; $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory,RecursiveDirectoryIterator::SKIP_DOTS)); //loop through each file path and check if pattern is found foreach($objects as $name => $object) { if (fnmatch($pattern, $name)) { $files[] = substr($name, 9); //remove /problems/ from file location string } } } else { //iterate through all directories within the selected directory folder chdir('problems'); $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory,RecursiveDirectoryIterator::SKIP_DOTS)); //loop through each file path and check if pattern is found foreach($objects as $name => $object) { if (fnmatch($pattern, $name)) { $files[] = $name; } } } //sort files sort($files, SORT_NATURAL | SORT_FLAG_CASE); echo json_encode($files); ?><file_sep><?php $IP = $_POST['IP']; exec('cd ../;./start-server-ip.sh '.$IP.' ', $out, $status); ?><file_sep>$( document ).ready(function() { //load necessary info from database loadClients(); loadPreProcessors(); loadPrograms(); setupModals(); //remove row from programs/configuration table when cross button is clicked $("#configurationTable").on('click', '.btn-delete', function () { $(this).closest('tr').remove(); }); //toggle all clients when all clients radio button is changed $('#allServersOption').change( function() { $(".server_group").prop("checked",true); } ); //untoggle all clients when no clients radio button is changed $('#noServersOption').change( function() { $(".server_group").prop("checked",false); } ); //hide warnings for each section $( "#fileWarning" ).fadeOut(); $( "#serverWarning" ).fadeOut(); $( "#programWarning" ).fadeOut(); //when a key is pressed with the parameters field focussed $("#parametersInput").on("keydown", function(event) { //don't navigate away from the field on tab when selecting an item if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete( "instance" ).menu.active){ event.preventDefault(); } }) .autocomplete({ minLength: 0, source: function(request, response) { //delegate back to autocomplete, but extract the last term response($.ui.autocomplete.filter( configFiles, extractLast( request.term))); }, focus: function() { //prevent value inserted on focus return false; }, select: function( event, ui ) { var terms = split(this.value); //remove the current input terms.pop(); //add the selected item terms.push( ui.item.value ); //seperate terms with space this.value = terms.join(" "); return false; } }); }); var clients; //array of clients var preprocessors; //array of preprocessors var programs; //array of programs var numLoadedTables = 0; //number of tables loaded from database var jobsArray = []; var configFiles = []; //function to setup interactions for the help buttons (info buttons on each card) function setupModals() { //when help button clicked $(".show-dialog").click(function(){ var dialogId = $(this).attr('id'); var modal; if(dialogId=="problemsModalBtn"){ modal = document.getElementById('problemsModal'); modal.style.display = "block"; //display modal } else if(dialogId=="programsModalBtn"){ modal = document.getElementById('programsModal'); modal.style.display = "block"; //display modal } else if(dialogId=="optionsModalBtn"){ modal = document.getElementById('optionsModal'); modal.style.display = "block"; //display modal } //close modal when user clicks anywhere on the page window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } //close modal when close button is clicked $(".close").click(function(){ modal.style.display = "none"; }); }); } //function to add clients to the clients area function displayServers(){ var div = document.getElementById('serversCardArea'); for(var j=0;j<clients.length;j++) { //add new checkbox with value client_id and text client_name div.innerHTML = div.innerHTML + "<label><input type='checkbox' class='server_group' name='clients' value='"+clients[j].client_id+"'/><span>"+clients[j].client_name+"</span></label>"; } } //function to load config files and handle the dropdown box for the parameters input field function loadConfigFiles(selectedProgram){ console.log("loading config files for "+selectedProgram); $.ajax({ type: "GET", url: "functions/LoadConfigFiles.php", cache: false, data: {program : selectedProgram}, dataType: "json", success: function (data) { console.log("Loaded config files "+data); configFiles = data; } }); } function split(val) { return val.split( / \s*/ ); } function extractLast(term) { return split(term).pop(); } //function to populate the dropdown boxes boxes for the program and preprocessors and update //the preprocessor based on the program selected function updateProgramOptions(){ //get the dropdown boxes var programSelect = document.getElementById("program-select"); var preProcessorSelect = document.getElementById("preprocessor-select"); var parametersInput = document.getElementById("parametersInput"); //add default empty option var option = document.createElement("option"); programSelect.add(option); //add all of the programs to the drop down for(var i=0;i<programs.length;i++) { var option = document.createElement("option"); option.text = programs[i].program_name; option.value = programs[i].program_id; programSelect.add(option); } //when a program is selected programSelect.addEventListener("change", function() { loadConfigFiles(programSelect.options[programSelect.selectedIndex].text); //empty the preprocessors and select first item $("#preprocessor-select").empty(); $('#preprocessor-select').val(0); //check if program is selected if(programSelect.options[programSelect.selectedIndex].value!='') { //set default parameters parametersInput.value=programs[programSelect.selectedIndex-1].program_parameters; } //loop through preprocessors for(var i=0;i<preprocessors.length;i++) { //add preprocessor option if it is designed for the current program if(preprocessors[i].program_id==programSelect.options[programSelect.selectedIndex].value) { var option = document.createElement("option"); option.text = preprocessors[i].pre_processor_name; option.value = preprocessors[i].pre_processor_id; preProcessorSelect.add(option); } } }); } //function to get the ID's of the selected server checkboxes and return as an array function getSelectedClients() { var selectedServers = []; //for each selected server_group checkbox $("input:checkbox[class='server_group']:checked").each(function(){ selectedServers.push($(this).val()); }); return selectedServers; } function isDouble(num){ var val = parseFloat(num); if(isNaN(val)) return false; else return true; } //function to check if an input is an integer function isInteger(x) { return x % 1 === 0; } //function to validate the option fields function validateAndStart(){ var valid = true; document.getElementById("startTaskBtn").disabled = true; //get values from option fields var theName = document.getElementById("nameField").value; var theMemory = document.getElementById("memoryField").value; var theLoad = document.getElementById("loadField").value; var theTimeout = document.getElementById("timeoutField").value; //disable start button and hide option errors //document.getElementById("startTaskBtn").disabled = true; document.getElementById("memoryError").style.display = 'none'; document.getElementById("loadError").style.display = 'none'; document.getElementById("timeoutError").style.display = 'none'; //check fields are valid if(theMemory=="" || theMemory>8000 || theMemory<0 || !isInteger(theMemory)) { document.getElementById("memoryError").style.display = 'inline-block'; valid = false; } if(theLoad=="" || theLoad>8 || theLoad<1 || !isDouble(theLoad)) { document.getElementById("loadError").style.display = 'inline-block'; valid = false; } if(theTimeout=="" || theTimeout>72000 || theTimeout< 1|| !isInteger(theTimeout)) { document.getElementById("timeoutError").style.display = 'inline-block'; valid = false; } //check at least one server is selected if(getSelectedClients().length==0) { valid = false; var tempServers = $( "#serverWarning" ).get(0); tempServers.innerHTML = ' <div class="isa_warning"> <i class="fa fa-warning"></i>Must select at least one client</div>'; $( "#serverWarning" ).fadeIn(); } else { $( "#serverWarning" ).fadeOut(); } //check at least 1 file has been included var includedListDiv = document.getElementById("includedFilesList"); if(includedListDiv.options.length==0) { var tempJob = $( "#fileWarning" ).get(0); tempJob.innerHTML = ' <div class="isa_warning"> <i class="fa fa-warning"></i>Must select at least one problem file</div>'; $( "#fileWarning" ).fadeIn(); valid = false; } else { $( "#fileWarning" ).fadeOut(); } //check at least 1 configuration has been added var numPrograms = document.getElementById("configurationTable").rows.length; if(numPrograms<2){ valid = false; $( "#programWarning" ).fadeIn(); var tempProgram = $( "#programWarning" ).get(0); tempProgram.innerHTML = ' <div class="isa_warning"> <i class="fa fa-warning"></i>Must select at least one program</div>'; } else{ $( "#programWarning" ).fadeOut(); } //begin process of starting the task if(valid==true) { getProblemFiles(); } else { document.getElementById("startTaskBtn").disabled = false; } } //function to create task (with webserver) function createTask(numJobs) { //display loading circle document.getElementById("processingTask").style.display = 'inline-block'; //get option field data var theMemory = document.getElementById("memoryField").value; var theLoad = document.getElementById("loadField").value; var theTimeout = document.getElementById("timeoutField").value; var theName = document.getElementById("nameField").value; var tableRef = document.getElementById("configurationTable"); var theProgram = []; var thePreprocessor = []; var theParameters = []; //load configuration table into arrays for(var i=1; i<tableRef.rows.length;i++){ theProgram.push(tableRef.rows[i].cells[1].value); thePreprocessor.push(tableRef.rows[i].cells[0].value); theParameters.push(tableRef.rows[i].cells[2].value); } //load id's of selected clients var selectedClientsArray = getSelectedClients(); //request to create task+jobs in database, create log directory and contact the distribution server to start the task $.ajax({ type: "POST", url: "functions/StartTask.php", data: {name : theName, memory : theMemory, load : theLoad, timeout : theTimeout, num_jobs : numJobs, jobs : JSON.stringify(jobsArray), program : theProgram, preprocessor : thePreprocessor, parameters : theParameters, selected_servers : selectedClientsArray}, cache: false, dataType: "text", success: function (data) { displayNotification(data); //hide loading bar and enable start button document.getElementById("processingTask").style.display = 'none'; document.getElementById("startTaskBtn").disabled = false; } }); } //function to load all of the included problems into an array function getProblemFiles() { //clear array jobsArray = []; var includedListDiv = document.getElementById("includedFilesList"); var numPrograms = document.getElementById("configurationTable").rows.length; //add each included problem to array for(var i=0;i<includedListDiv.options.length;i++) { jobsArray.push(includedListDiv.options[i].value); //console.log(includedListDiv.options[i].value); } numPrograms = numPrograms-1; //call function to create task createTask(jobsArray.length*numPrograms); } //function to load all of the clients into an array function loadClients(){ console.log("attempting to load clients"); //request to load clients table from database $.ajax({ type: "POST", url: "functions/LoadTables.php", data: {tableName : 'Clients'}, dataType: "json", success: function (data) { console.log(JSON.stringify(data)); clients=data; numLoadedTables++; displayServers(); checkTablesLoaded(); } }); } //function to load all of the preprocessors into an array function loadPreProcessors(){ console.log("attempting to load preprocessors"); //request to load preprocessors table from database $.ajax({ type: "POST", url: "functions/LoadTables.php", data: {tableName : 'PreProcessors'}, dataType: "json", success: function (data) { console.log(JSON.stringify(data)); preprocessors=data; numLoadedTables++; checkTablesLoaded(); } }); } //function to load all of the programs into an array function loadPrograms(){ console.log("attempting to load programs"); //request to load programs table from database $.ajax({ type: "POST", url: "functions/LoadTables.php", data: {tableName : 'Programs'}, dataType: "json", success: function (data) { console.log(JSON.stringify(data)); programs=data; numLoadedTables++; checkTablesLoaded(); } }); } //function to check if all tables from database have loaded function checkTablesLoaded() { if(numLoadedTables==3) { updateProgramOptions(); } } /*function to add a program/pre-processor/parameters configuration to the table and check the configuration is valid and does not already exist*/ function addConfiguration(){ var valid = true; var selectedPreProcessor = document.getElementById("preprocessor-select"); var selectedProgram = document.getElementById("program-select"); var chosenParameters = document.getElementById("parametersInput").value; var errorText = document.getElementById("programsError"); errorText.style.display = 'none'; //check program/preprocessor has been selected try { var preText = selectedPreProcessor.options[selectedPreProcessor.selectedIndex].text; var proText = selectedProgram.options[selectedProgram.selectedIndex].text; } catch(err) { errorText.innerHTML = 'Invalid Configuration'; errorText.style.display = 'inline-block'; return; } if(chosenParameters.length>1024) { errorText.innerHTML = 'Invalid Parameters'; errorText.style.display = 'inline-block'; return; } //loop through the configuration table and check if the configuration already exists var tableRef = document.getElementById("configurationTable"); var newID = proText+preText+chosenParameters; for(var i=1; i<tableRef.rows.length;i++) { var oldID = ""; oldID = tableRef.rows[i].cells[0].innerHTML + tableRef.rows[i].cells[1].innerHTML + tableRef.rows[i].cells[2].innerHTML; if (newID == oldID) { valid = false; } } //configuration does not exist, add to table if(valid==true) { var newRow = tableRef.insertRow(tableRef.rows.length); var cell0 = newRow.insertCell(0); var cell1 = newRow.insertCell(1); var cell2 = newRow.insertCell(2); var cell3 = newRow.insertCell(3); var text = document.createTextNode(proText); cell0.className = 'mdl-data-table__cell--non-numeric'; cell0.value = selectedPreProcessor.value; cell0.appendChild(text); var text = document.createTextNode(preText); cell1.className = 'mdl-data-table__cell--non-numeric'; cell1.value = selectedProgram.value; cell1.appendChild(text); var text = document.createTextNode(chosenParameters); cell2.className = 'mdl-data-table__cell--non-numeric'; cell2.value = chosenParameters; cell2.appendChild(text); cell3.innerHTML = '<a class="btn-delete mdl-button mdl-button--icon"><i class="fa fa-times" style="color:red" ></i></a>' } else //configuration exists, display error { console.log("error"); document.getElementById("programsError").innerHTML = 'Configuration Exists'; document.getElementById("programsError").style.display = 'inline-block'; } } <file_sep>#!/bin/sh # # Example use: # ./runKSP ../samples/lwb/k_branch_p.0002.ksp -c ~/provers/ksp-2016-02-01/snf++#negative4.conf DIR=$( dirname "$(readlink -f "$0")" ) FILE="${!#}" set -- "${@:1:$(($#-1))}" echo "PROVER : KSP" echo "OPTIONS: -b $@" echo "FILE : $FILE" #echo "$DIR/ksp -b $@ -i $FILE" /usr/bin/time $DIR/ksp -b $@ -i $FILE<file_sep><?php include('functions/Authenticate.php'); ?> <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Distribute tasks to remote machines</title> <script src="js/jquery-3.1.1.min.js"></script> <link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css"/> <link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/material.min.css"/> <link rel="stylesheet" href="css/mystyle.css"/> <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> <link rel="stylesheet" href="css/material.min.css"/> <link rel="stylesheet" href="css/mystyle.css"/> <script src="js/material.min.js"></script> <script src="js/manage.js"></script> <script src="js/notification.js"></script> </head> <body> <div class="header-area"> <?php include_once 'navigation.php'; ?> </div> <div class="wrapper"> <!---------------------- Modals ----------------------> <div id="manageServersModal" class="modal"> <div class="modal-content"> <a class="close">&times;</a> <b> Start Server with IP: </b> Starts the distribution software on the machine provided in the text field. <br><br> <b> Start Server on webserver: </b> Starts the distribution software using the webserver. <br><br> <b> Stop Server: </b> Stops the distribution software on the machine it is currently running on. <br><br> <b> Start Clients: </b> Starts the client software on all of the clients. <br><br> <b> Stop Clients: </b> Stops the client software running on all of the clients. </div> </div> <div id="clientsModal" class="modal"> <div class="modal-content"> <a class="close">&times;</a> <p><b>Load:</b> From left to right, these numbers show you the average load of the client over the last one minute, the last five minutes, and the last fifteen minutes.</b><br> A completely idle client has an average load of 0.0.<br> For a client with 4 cores an average load of >4 would mean that the processor was overburdened.<br> One job/problem file should produce an average load of 1 during its execution.</p> <p>Available/online clients will be displayed in <span style="color: #4CAF50;">green</span>.<br> Unavailable/offline clients will be displayed in <span style="color: #F44336;">red</span>. </div> </div> <div class="card-wide mdl-card mdl-shadow--2dp"> <div class="mdl-card__title"> <h2 class="mdl-card__title-text mdl-color-text--primary">Manage Servers</h2> <button id="manageServersModalBtn" class="mdl-button mdl-js-button mdl-button--icon show-dialog"><i class="fa fa-info-circle" ></i> </div> <div id="manageCard"> <div class="selectDiv"> <b>IP Address/Machine name</b> <input type="text" name="ipField" id = "ipField"> </input> </div> <!--<div class="bottomButton">--> <br> <div id="manageButtonsArea" class="left"> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onclick="startDistributionServer()" id="startDistributionServer"> <i class="fa fa-play "></i> Start Server (With IP) </button> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onclick="startDistributionServerWeb()" id="startDistributionServerWeb"> <i class="fa fa-play "></i> Start Server (On Webserver) </button> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent" onclick="killDistributionServer()" id="killDistributionServer"> <i class="fa fa-stop "></i> Stop Server </button> <br><br> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onclick="startClients()" id="startClients"> <i class="fa fa-play "></i> Start Clients </button> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent" onclick="killClients()" id="killClients"> <i class="fa fa-stop "></i> Stop Clients </button> </div> </div> </div> <div class="card-wide mdl-card mdl-shadow--2dp" id="onlineClientsCard"> <div class="mdl-card__title"> <h2 class="mdl-card__title-text mdl-color-text--primary">Clients</h2> <button id="refreshClientsBtn" class="mdl-button mdl-js-button mdl-button--icon show-dialog" onclick="checkClientStatus()"><i class="fa fa-refresh" ></i> <button id="clientsModalBtn" class="mdl-button mdl-js-button mdl-button--icon show-clients-dialog"><i class="fa fa-info-circle" ></i> </div> <div id="clientsArea"> <div class="mdl-spinner mdl-spinner--single-color mdl-js-spinner is-active" id="clientsLoadingSpinner"></div> <table class="mdl-data-table mdl-js-data-table mdl-shadow--2dp" id="onlineClientlist"> <thead> <tr> <th class="mdl-data-table__cell--non-numeric largeTableFont">Client</th> <th class="mdl-data-table__cell--non-numeric largeTableFont">IP</th> <th class="mdl-data-table__cell--non-numeric largeTableFont">Load</th> </tr> <thead> </table> <!--<ul class="mdl-list success" id="onlineClientlist"></ul> <br> <ul class="mdl-list failure" id="offlineClientlist"></ul>--> </div> </div> </div> </div> <div id="toastBar" class="mdl-js-snackbar mdl-snackbar"> <div class="mdl-snackbar__text"></div> <button class="mdl-snackbar__action" type="button"></button> </div> </body> </html><file_sep>import java.text.SimpleDateFormat; import java.util.*; import java.sql.Timestamp; public class Load { //holds the start and finish times of the completed jobs in the last 60 seconds protected volatile ArrayList<times> finishedJobs = new ArrayList<times>(); //holds the start time of a job in progress by the current worker protected volatile long[] midProgressJobs; //number of threads for the client private int numWorkers = 0; public Load(int nW) { numWorkers = nW; midProgressJobs = new long[numWorkers]; } //method to calculate the offset for a client PCs load private double calcLoad() { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); //get the current time in milliseconds long current = timestamp.getTime(); //total number of milliseconds working over past 60000 milliseconds long totalMilliseconds = 0; //the load offset double loadOffset = 0.0; //loop through this clients finished jobs for (Iterator<times> iterator = finishedJobs.iterator(); iterator.hasNext();) { //get the next finished job times finishedJob = iterator.next(); //subtract 60000 milliseconds from the current time long timeCutoff = current - 60000; //check if the last job finished more than 60 seconds ago if(finishedJob.finish<=timeCutoff) { //remove job as it no longer has a load impact on the client iterator.remove(); } else if(finishedJob.start<=timeCutoff) //check if job started more than 60000 milliseconds ago { //add the jobs working time over the past 60000 milliseconds totalMilliseconds = totalMilliseconds + (finishedJob.finish-timeCutoff); } else //job started and finished within past 60000 milliseconds { //add jobs working time over the past 60000 milliseconds totalMilliseconds = totalMilliseconds + (finishedJob.finish-finishedJob.start); } } //get the the fraction of time working over the past 60000 milliseconds loadOffset = (double)totalMilliseconds/60000; loadOffset = loadOffset * -1.0; System.out.println("total load for past 60 seconds to subtract = "+loadOffset); //what the load is predicted to be from the current workers for(int i=0;i<numWorkers;i++) { //check if current worker is working if(midProgressJobs[i]!=0) { //get the current time in milliseconds timestamp = new Timestamp(System.currentTimeMillis()); current = timestamp.getTime(); //get the time working on the current job long millisecondsDuringJob = current - midProgressJobs[i]; //cap the time at 60000 milliseconds if(millisecondsDuringJob>60000) { millisecondsDuringJob = 60000; } //get the fraction of time working over the past 60000 milliseconds double load = (double)millisecondsDuringJob/60000; //subtract the load from 1 double predictedLoadIncrease = 1.0-load; System.out.println("predicted load increase = "+predictedLoadIncrease); loadOffset = loadOffset + predictedLoadIncrease; } } return loadOffset; } //method to check the memory and load requirements are met protected synchronized boolean checkRequirements(int clientMemory, double clientLoad, int maxMemory, double maxLoad, int workerNum) { if(clientMemory<maxMemory) { return false; } double newLoad = 0.0; midProgressJobs[workerNum] = 0; newLoad = clientLoad+calcLoad(); System.out.println("NEW LOAD IS "+newLoad); if(newLoad<maxLoad) { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); long current = timestamp.getTime(); midProgressJobs[workerNum] = current; return true; } else { return false; } } } //class to hold a start and finish time class times{ protected long start = 0; protected long finish = 0; public times(long s, long f) { start = s; finish = f; } } /*public Load() { } public void setStartTime() { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); startTime = timestamp.getTime(); System.out.println("load start time = "+startTime); } public void setFinishTime() { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); finishTime = timestamp.getTime(); } public double getLoadAverage() { if(startTime == 0) { return 0.0; } long secondsDuringJob = finishTime-startTime; //30 if(secondsDuringJob>60000) { secondsDuringJob = 60000; } double load = (double)secondsDuringJob/60000; System.out.println("secondsDuringJob = "+secondsDuringJob); System.out.println("double load = "+load); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); long current = timestamp.getTime(); long secondsSinceJob = current-finishTime; //10seconds ago System.out.println("secondsSinceJob = "+secondsSinceJob); double newLoad = (((double)secondsSinceJob-60000)/60000) * load; return newLoad; }*/ /* import java.text.SimpleDateFormat; import java.util.*; import java.sql.Timestamp; public class Load { public long startTime = 0; public long finishTime = 0; public ArrayList<times> finishedJobs = new ArrayList<times>(); public static int numWorking = 0; public static long[] midProgressJobs = new long[4]; public double calcLoad() { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); long current = timestamp.getTime(); double tempLoad = 0.0; for (Iterator<times> iterator = finishedJobs.iterator(); iterator.hasNext();) { times x = iterator.next(); if(current-x.finish>=60000) { iterator.remove(); } else { long secondsDuringJob = x.finish-x.start; if(secondsDuringJob>60000) { secondsDuringJob = 60000; } double load = (double)secondsDuringJob/60000; long secondsSinceJob = current-x.finish; //reverse double newLoad = ((60000-(double)secondsSinceJob)/60000) * load; tempLoad+=newLoad; } } for(int i=0;i<4;i++) { if(midProgressJobs[i]!=0) { timestamp = new Timestamp(System.currentTimeMillis()); current = timestamp.getTime(); long secondsDuringJob = current - midProgressJobs[i]; System.out.println("--------------------------------- current time = "+current/1000+" mid progress = "+midProgressJobs[i]/1000+" seconds during job = "+secondsDuringJob/1000); if(secondsDuringJob>60000) { secondsDuringJob = 60000; } double load = (double)secondsDuringJob/60000; double loadMinus = 1.0-load; tempLoad+=loadMinus; } } return tempLoad; } } class times{ long start = 0; long finish = 0; public times(long s, long f) { start = s; finish = f; } }*/<file_sep>$(document).ready(function() { $.fn.dataTable.ext.errMode = 'none'; loadJobs(); setupModals(); } ); //holds all of the jobs var loadedJobs; function setupModals() { //when help button clicked $(".show-dialog").click(function(){ modal = document.getElementById('jobsModal'); modal.style.display = "block"; //display modal //close modal when user clicks anywhere on the page window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } //close modal when close button is clicked $(".close").click(function(){ modal.style.display = "none"; }); }); } //function to load the tasks jobs from the database and setup the datatable function loadJobs() { //request jobs from database $.ajax({ type: "GET", url: "functions/LoadJobs.php", data: {none: "none"}, dataType: "json", success: function (data) { //console.log(data); //console.log(JSON.stringify(data)); loadedJobs = data; var paging = true; /*if(data.length>1400){ paging = true; }*/ //jquery datatable var table = $('#jobsTable').DataTable( { dom: 'Blfrtip', buttons: [ { extend: 'csvHtml5', //CSV button title: 'Jobs export' //name of exported file }, ], "iDisplayLength": 50, //set to 50 results per page by default "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]], //results per page values "pagingType": "full_numbers", "aaData": loadedJobs, // <-- your array of objects "aoColumns": [ //column row data {"mDataProp": "job_id"}, {"mDataProp": "start_time"}, {"mDataProp": "end_time"}, {"mDataProp": "pre_processor_name"}, {"mDataProp": "program_name"}, {"mDataProp": "input_file"}, {"mDataProp": "job_parameters"}, { //cell for the job status "mDataProp": "job_status", "fnCreatedCell": function(nTd, sData, oData, iRow, iCol){ //assign colours to the status text if(oData.job_status=="waiting") { $(nTd).css('color', '#FFB300'); //amber } else if(oData.job_status=="completed") { $(nTd).css('color', '#4CAF50'); //green } else if(oData.job_status=="timeout") { $(nTd).css('color', '#9C27B0'); //purple } else if(oData.job_status=="error") { $(nTd).css('color', '#0277BD'); //blue } else if(oData.job_status=="working") { $(nTd).css('color', '#FF5722'); //orange } else { $(nTd).css('color', '#F44336'); //red } } }, {"mDataProp": "client_name"}, { //set value of cell to log name mRender: function(nTd, sData, oData, iRow, iCol){ if(oData.log_name) { return "logs"+oData.log_name+".log"; } }, //cell for the log hyperlink "fnCreatedCell": function(nTd, sData, oData, iRow, iCol){ if(oData.log_name) { $(nTd).html("<a href='logs"+oData.log_name+".log' target='_blank' >View</a>"); } } } ], scrollY: '65vh', scrollX: true, scrollCollapse: true, paging: paging, } ); $('.dataTables_filter').addClass('auto-margin'); //$('.dataTables_lengthMenu').addClass('pull-left'); } }); } <file_sep><?php exec('cd ../;./start-clients.sh', $out, $status); if (0 === $status) { echo("Started Clients"); } else { echo "Command failed with status: $status"; } ?><file_sep>theIP=$1 #!/bin/bash nohup ssh -o 'StrictHostKeyChecking no' -o 'ConnectTimeout=5' -X $theIP 'cd public_html/server;java -cp .:mysql-connector-java-5.1.40-bin.jar MainServer;exit' <file_sep><?php //connect to DB include('../dbinfo.php'); $mysql_conn = mysqli_connect(HOST, USER, PASS, DB) or die("Error connecting to DB " . mysqli_error($mysql_conn)); $tableName = mysqli_real_escape_string($mysql_conn, $_POST['tableName']); //select data from table $query = mysqli_query( $mysql_conn, "SELECT * FROM `".$tableName."`"); $tableData = array(); //populate tableData array with query result while(($row = mysqli_fetch_assoc($query))) { $tableData[] = $row; } echo json_encode($tableData); ?><file_sep>import java.io.*; import java.net.*; import java.util.concurrent.*; public class ClientStart { private static ExecutorService workers; private static ServerSocket socket; private static int PORT_NUM = 8080; public static void main(String[] args) { Socket incoming = null; try { socket = new ServerSocket(PORT_NUM); //setup dynamic thread pool for connections workers = Executors.newCachedThreadPool(); System.out.println("Waiting for connections\n"); //wait for connections from distribution server and create new client threads for (;;) { incoming = socket.accept(); workers.execute(new ClientSession(incoming)); } } catch (IOException ioe) { System.err.println("socket already in use"); } } }<file_sep>#!/bin/bash for ip in $(cat hosts); do nohup ssh -o 'StrictHostKeyChecking no' -o 'ConnectTimeout=5' -X $ip 'cd public_html/client;java ClientStart' & done <file_sep><?php $host = file_get_contents('../ip.txt', FILE_USE_INCLUDE_PATH); $port = "8191"; $timeout = 4; //timeout in seconds $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Unable to create socket\n"); socket_set_nonblock($socket) or die("Unable to set nonblock on socket\n"); $time = time(); while (!@socket_connect($socket, $host, $port)) { $err = socket_last_error($socket); if ($err == 115 || $err == 114) { if ((time() - $time) >= $timeout) { socket_close($socket); die("Connection timed out.\n"); } sleep(1); continue; } die(socket_strerror($err) . "\n"); } if ($socket) { $message = "2"; socket_write($socket, $message, strlen($message)); echo "Server UP"; socket_close($socket); } else { echo "Server DOWN"; } ?><file_sep>user=u4lc1 #!/bin/bash for ip in $(cat hosts); do #gnome-terminal -e -t "ssh $user@$ip ls" > out.txt nohup ssh -o 'StrictHostKeyChecking no' -o 'ConnectTimeout=5' -X $user@$ip 'cd public_html/client;java ClientStart' & done <file_sep><?php include('../dbinfo.php'); session_start(); $mysql_conn = mysqli_connect(HOST, USER, PASS, DB) or die("Cannot connect to DB" . mysqli_error($mysql_conn)); $taskid = mysqli_real_escape_string($mysql_conn, $_POST['taskid']); //delete Task with given taskid $query = mysqli_query($mysql_conn, "DELETE FROM Tasks WHERE task_id='".$taskid."'"); $userid = $_SESSION['userid']; //get location of tasks folder $dirname = "../logs/".$userid."/".$taskid; //delete the log files within the tasks folder $dir = array_map('unlink', glob("$dirname/*.*")); closedir($dir); //delete the tasks folder itself rmdir($dirname); echo "Deleted Task ".$taskid; ?><file_sep>theIP=$1 #!/bin/bash ssh -o 'StrictHostKeyChecking no' -o 'ConnectTimeout=2' -X $theIP cat /proc/loadavg | awk '{print $1, $2, $3}'<file_sep>#!/bin/sh DIR=$( dirname "$(readlink -f "$0")" ) FILE="${!#}" set -- "${@:1:$(($#-1))}" echo "PROVER : InKreSAT" echo "OPTIONS: $@" echo "FILE : $FILE" /usr/bin/time $DIR/inkresat $@ $FILE <file_sep>$( document ).ready(function() { checkClientStatus(); setupModals(); }); /*function to make the information buttons display modals*/ function setupModals() { //when help button clicked $("#manageServersModalBtn").click(function(){ var modal = document.getElementById('manageServersModal'); modal.style.display = "block"; //display modal console.log("a"); //close modal when user clicks anywhere on the page window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } //close modal when close button is clicked $(".close").click(function(){ modal.style.display = "none"; }); }); $("#clientsModalBtn").click(function(){ var modal = document.getElementById('clientsModal'); modal.style.display = "block"; //display modal console.log("a"); //close modal when user clicks anywhere on the page window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } //close modal when close button is clicked $(".close").click(function(){ modal.style.display = "none"; }); }); } /*function to start the distribution server on the webserver. kills the old distribution server in the process*/ function startDistributionServerWeb() { var response = confirm("Are you sure you want to start the distribution server?\nWarning: This will stop the previous server"); if(response == true) { var startBtn = document.getElementById("startDistributionServerWeb"); startBtn.disabled = true; $.ajax({ type: "GET", url: "functions/KillDistributionServer.php", cache: false, dataType: "text", success: function (data) { checkServerStatus(); $.ajax({ type: "GET", url: "functions/StartDistributionServer.php", cache: false, timeout:3000, dataType: "text", error: function(){ //check the server status to update status label checkServerStatus(); displayNotification("distribution server started"); startBtn.disabled = false; }, success: function (data) { //check the server status to update status label checkServerStatus(); displayNotification("distribution server started"); startBtn.disabled = false; } }); } }); } } /*function to start the distribution server with given IP/name. kills the old distribution server in the process*/ function startDistributionServer() { var theIP = document.getElementById("ipField").value; //check IP/machine name has been entered if(theIP=="") { alert("Please enter an IP address or machine name"); } else { //confirm users choice var response = confirm("Are you sure you want to start the distribution server?\nWarning: This will stop the previous server"); if(response == true) { var startBtn = document.getElementById("startDistributionServer"); startBtn.disabled = true; //make ajax request to kill the (old) server $.ajax({ type: "GET", url: "functions/KillDistributionServer.php", cache: false, dataType: "text", success: function (data) { //check the server status to update status label checkServerStatus(); //make ajax request to start the (new) server $.ajax({ type: "POST", url: "functions/StartServerAdvanced.php", data: {IP : theIP}, timeout:3000, cache: false, dataType: "text", error: function(){ //check the server status to update status label console.log("started distribution server"); displayNotification("distribution server started"); checkServerStatus(); startBtn.disabled = false; }, success: function (data) { //check the server status to update status label console.log("started distribution server"); displayNotification("distribution server started"); checkServerStatus(); startBtn.disabled = false; } }); } }); } } } /*function to check the clients availabiliy and loads and populate the table*/ function checkClientStatus(){ var clientsLoadingSpinner = document.getElementById("clientsLoadingSpinner"); var refreshClientsBtn = document.getElementById("refreshClientsBtn"); var table = document.getElementById("onlineClientlist"); clientsLoadingSpinner.style.display='block'; //display loading spinner refreshClientsBtn.disabled=true; table.style.display='none'; //hide table $('#onlineClientlist tr').slice(1).remove(); //remove current table data $.ajax({ url: "functions/CheckRunning.php", cache: false, dataType: "json", success: function (data) { /*loop through the client data returned from the json request and add it to the table*/ for(var i = 0; i < data.length; i++) { var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell0 = row.insertCell(0); var cell1 = row.insertCell(1); var cell2 = row.insertCell(2); var rowClass; var load; //check client status if(data[i].status=="online") { rowClass = 'success'; load = data[i].client_load; } else { rowClass = 'failure'; load = "DOWN"; } var newText = document.createTextNode(data[i].client_name); cell0.className = 'mdl-data-table__cell--non-numeric'+' '+rowClass; cell0.appendChild(newText); var newText = document.createTextNode(data[i].client_ip); cell1.className = rowClass; cell1.appendChild(newText); var newText = document.createTextNode(load); cell2.className = 'mdl-data-table__cell--non-numeric'+' '+rowClass; cell2.appendChild(newText); } //hide loading spinner and display table clientsLoadingSpinner.style.display='none'; table.style.display='inline-block'; refreshClientsBtn.disabled=false; } }); } /*function to stop the distribution servers execution*/ function killDistributionServer() { var response = confirm("Are you sure you want to kill the distribution server?"); if(response == true) { var killBtn = document.getElementById("killDistributionServer"); killBtn.disabled = true; $.ajax({ type: "GET", url: "functions/KillDistributionServer.php", cache: false, dataType: "text", success: function (data) { //check the server status to update status label checkServerStatus(); displayNotification("distribution server killed"); killBtn.disabled = false; }, error: function(){ //check the server status to update status label checkServerStatus(); displayNotification("distribution server killed"); killBtn.disabled = false; } }); } } /*function to start the client software on all clients*/ function startClients() { var response = confirm("Are you sure you want to start all of the clients?"); if(response == true) { $.ajax({ type: "GET", url: "functions/StartClients.php", cache: false, dataType: "text", success: function (data) { }, error: function(){ } }); displayNotification("requests to start clients sent"); } } /*function to stop the client software from running on all clients*/ function killClients() { var response = confirm("Are you sure you want to kill all of the clients?"); if(response == true) { var killBtn = document.getElementById("killClients"); killBtn.disabled = true; $.ajax({ type: "GET", url: "functions/KillClients.php", cache: false, dataType: "text", success: function (data) { console.log("clients killed"); displayNotification("clients killed"); killBtn.disabled = false; }, error: function(){ console.log("clients killed"); displayNotification("clients killed"); killBtn.disabled = false; } }); } } <file_sep><?php //get IP address of distribution server $host = file_get_contents('../ip.txt', FILE_USE_INCLUDE_PATH); //distribution server port and timeout in seconds $port = "8191"; $timeout = 4; //create socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_nonblock($socket); $time = time(); while (!@socket_connect($socket, $host, $port)) { $err = socket_last_error($socket); if ($err == 115 || $err == 114) { if ((time() - $time) >= $timeout) { socket_close($socket); } sleep(1); continue; } //cannot connect to distribution server echo "Server is down!"; die(); } ?><file_sep><?php session_start(); if(!isset($_SESSION['userid'])){ die("You must be logged in!"); } include 'OpenSocket.php'; $task_id = $_POST['task_id']; /*send message with operation "1" (for task cancellations) followed by the task id to cancel*/ $message = "1@".$task_id; socket_write($socket, $message, strlen($message)); socket_close($socket); echo "Cancelled Task ".$task_id; ?><file_sep><?php include('../dbinfo.php'); session_start(); $jobs = json_decode($_POST["jobs"]); $program = $_POST["program"]; $preprocessor = $_POST["preprocessor"]; $parameters = $_POST["parameters"]; $mysql_conn = mysqli_connect(HOST, USER, PASS, DB) or die("Cannot connect to DB" . mysqli_error($mysql_conn)); $task_id = $_SESSION['task_id']; ignore_user_abort(TRUE); set_time_limit(600); for ($i = 0; $i < count($program); $i++) { foreach ($jobs as $key => $value) { $query = mysqli_query($mysql_conn, "INSERT INTO Jobs (task_id, program, input_file, job_parameters, pre_processor) VALUES('$task_id', '$program[$i]', '$value', '$parameters[$i]', '$preprocessor[$i]')"); } } echo "completed"; mysqli_close($mysql_conn); ?><file_sep>import java.util.*; import java.io.*; import java.net.*; import java.util.concurrent.*; import java.lang.management.*; /* MainServer class listens for connections from the webserver and forwards them to Server Threads. Handles the recovery file for incomplete tasks, providing methods to read, save and delete tasks to/from the file. Handles the IP Address of the machine and clients, providing methods to save them to files. */ public class MainServer { private static ExecutorService workers; private static ServerSocket server; private static int PORT_NUM = 8191; //locations for files private static String recoveryFileLocation = "../recovery.txt"; private static String ipFileLocation = "../ip.txt"; //holds the recovered tasks from recovery.txt private static ArrayList<String> workingTaskList = new ArrayList<String>(); public static void main(String[] args) { //setup dynamic thread pool for connections workers = Executors.newCachedThreadPool(); Socket incoming = null; //check if server is already running on this machine try { server = new ServerSocket(PORT_NUM); } catch (Exception e) { System.err.println("Socket already in use, shutting down"); System.exit(0); } getIP(); //get ip address of machine and save it to file saveClients(); //save clients to hosts file loadRecoveryFile(); //load the recovery tasks from recoveryFileLocation try { //loop through the workingTaskList and create server threads with the task string for(int i=0;i<workingTaskList.size();i++) { String task = workingTaskList.get(i); workers.execute(new Server(task)); } System.out.println("Waiting for connections\n\n"); //wait for connections from the webserver and create new server threads for (;;) { incoming = server.accept(); workers.execute(new Server(incoming)); } } catch (IOException ioe) { System.err.println(ioe.getMessage()); } finally { try {server.close();} catch (IOException e) {} System.exit(1); } } /*method to save the IP addresses of clients into a file called 'hosts' this will be used for scripts which start/shutdown the client software*/ private static void saveClients() { //connect to database to retrieve clients as an array DBConnect connect = new DBConnect(); Client[] usedClients = connect.getClientInfo(); connect.disconnectFromDB(); try { BufferedWriter outputWriter = null; outputWriter = new BufferedWriter(new FileWriter("../hosts")); //write each client IP address on a new line in the file for (int i = 0; i < usedClients.length; i++) { outputWriter.write(usedClients[i].getIP()+""); outputWriter.newLine(); } outputWriter.flush(); outputWriter.close(); } catch (IOException ioe) { System.err.println("Error saving clients"); System.err.println(ioe.getMessage()); } } //method to get the IPV4 address of the current machine private static void getIP() { try { InetAddress IP = InetAddress.getLocalHost(); System.out.println("IP of server is := "+IP.getHostAddress()); System.out.println("using port "+PORT_NUM); saveIP(IP.getHostAddress()); } catch (Exception se) { saveIP("Cannot load IP of server"); System.err.println("Error getting IP"); } } //method to save the IP address into a .txt file private static void saveIP(String IP) { BufferedWriter outputWriter = null; try { outputWriter = new BufferedWriter(new FileWriter(ipFileLocation)); outputWriter.write(IP); outputWriter.flush(); outputWriter.close(); System.out.println("Saved IP to file: "+ipFileLocation); } catch (IOException e) { System.err.println("Error writing to file: "+ipFileLocation); e.printStackTrace(); } } //method to save the workingTaskList to a text file at 'recoveryFileLocation' private static void saveRecoveryFile() { try { BufferedWriter outputWriter = new BufferedWriter(new FileWriter(recoveryFileLocation)); //write each task to a new line in the file for (int i = 0; i < workingTaskList.size(); i++) { outputWriter.write(workingTaskList.get(i)); outputWriter.newLine(); } outputWriter.flush(); outputWriter.close(); System.out.println("Saved file: "+recoveryFileLocation); } catch (IOException e) { System.err.println("Error writing to file: "+recoveryFileLocation); e.printStackTrace(); } } //method to load the contents of recovered tasks file into arraylist 'workingTaskList' protected static void loadRecoveryFile() { try { Scanner s = new Scanner(new File(recoveryFileLocation)); //loop until end of file while (s.hasNext()) { workingTaskList.add(s.next()); } s.close(); System.out.println("loaded "+workingTaskList.size()+" recovery tasks"); } catch (IOException ioe) { System.err.println("Error: cannot load "+recoveryFileLocation); ioe.printStackTrace(); } } //method to remove a task from arraylist 'workingTaskList' protected static synchronized void removeTask(String task) { //loop through arraylist for(int i=0;i<workingTaskList.size();i++) { String x = workingTaskList.get(i); //check if task matches provided task string and remove it from arraylist if(x.startsWith(task)) { workingTaskList.remove(i); System.out.println("Removed task "+task); break; } } //write workingTaskList to recovery file saveRecoveryFile(); } //method to add a new task string to the arraylist 'workingTaskList' protected static synchronized void addTask(String task) { System.out.println("Adding new task: "+task); workingTaskList.add(task); //write workingTaskList to recovery file saveRecoveryFile(); } }<file_sep>#!/bin/sh cat $1 | head -n -1 | tail -n +2 | \ sed -e 's/<->/<=>/g' -e 's/->/=>/g' -e 's/<r1>/<>/g' -e 's/\[r1\]/[]/g' -e 's/^/~(/g' -e 's/$/)/g' -e 's/false/False/g' -e 's/true/True/g' > "$2" <file_sep><?php include('../dbinfo.php'); $mysql_conn = mysqli_connect(HOST, USER, PASS, DB) or die("Login error" . mysqli_error($mysql_conn)); $query = mysqli_query( $mysql_conn, "SELECT * FROM Clients"); //load all clients into array $clients = array(); while(($row = mysqli_fetch_assoc($query))) { $clients[] = $row; } $checkedclients = array(); //loop through clients array foreach($clients as $item) { //get the IP address of client and run scripts to get the load on the pc $IP = $item['client_ip']; exec('cd ../;./check-clients.sh '.$IP.'', $out, $status); //client is online if ($out != null) { $checkedclients[] = array('status' => 'online', 'client_name' => $item['client_name'], 'client_ip' => $item['client_ip'], 'client_load' => $out); } //client is offline else { $checkedclients[] = array('status' => 'offline', 'client_name' => $item['client_name'], 'client_ip' => $item['client_ip'], 'client_load' => $out); } //clear out array unset($out); } echo json_encode($checkedclients); ?> <file_sep><?php session_start(); if(isset($_SESSION['login_user'])){ header("location: distribution.php"); } ?> <!DOCTYPE html> <html> <head> <title>Login</title> <link rel="stylesheet" href="css/w3.css"/> <link rel="stylesheet" href="css/loginstyle.css"/> <link rel="stylesheet" href="https://code.getmdl.io/1.2.1/material.indigo-pink.min.css"> <script src="js/jquery-3.1.1.min.js"></script> <script src="js/login.js"></script> </head> <body> <div class="w3-card-4" id="cardArea"> <div class="w3-card-4 loginCard noShadows" id="loginArea"> <div class="w3-container" > <h1 id = "title">Account Login</h1> <p> <form action="" method="post"> <label class="w3-text-grey">Email Address</label> <input class="w3-input w3-border w3-light-grey" name="username" type="text" id="name"> <br> <label class="w3-text-grey">Password</label> <input class="w3-input w3-border w3-light-grey" id="password" name="password" type="<PASSWORD>"> <br> <button type="button" class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" id = "loginBtn" value=" Login " onclick="login()"> Login </button> <br><br><br> <span id="errors" style="color: #F44336; font-size:18px"></span> <br> <span id="noCookie" style="color: #F44336; font-size:18px"></span> <script> if(!navigator.cookieEnabled){ document.getElementById("noCookie").innerHTML = "You must enable cookies to use this website"; } $("#name").keyup(function(event){ if(event.keyCode == 13){ $("#loginBtn").click(); } }); $("#password").keyup(function(event){ if(event.keyCode == 13){ $("#loginBtn").click(); } }); </script> </form> </p> </div> </div> </div> </body> </html> </div><file_sep>#!/bin/bash for ip in $(cat hosts); do nohup ssh -o 'StrictHostKeyChecking no' -o 'ConnectTimeout=5' -X $ip 'pgrep -f ClientStart | xargs kill -9' & done <file_sep>$(document).ready(function() { $.fn.dataTable.ext.errMode = 'none'; //loadJobs(); loadClients(); loadPreProcessors(); loadPrograms(); setupSelectionBoxes(); setupTable(); } ); var loadedJobs; var servers; var preprocessors; var programs; var table; //function to update the dropdown boxes with data loaded from the dtabase function setupSelectionBoxes() { var programSelect = document.getElementById("program-select"); var preProcessorSelect = document.getElementById("preprocessor-select"); //when a program is selected programSelect.addEventListener("change", function() { //empty the preprocessors and select first item $("#preprocessor-select").empty(); $('#preprocessor-select').val(0); if(programSelect.options[programSelect.selectedIndex].value == "none") { var option = document.createElement("option"); option.value = "none" preProcessorSelect.add(option); for(var i=0;i<preprocessors.length;i++) { var option = document.createElement("option"); option.text = preprocessors[i].pre_processor_name; option.value = preprocessors[i].pre_processor_id; preProcessorSelect.add(option); } } //loop through preprocessors for(var i=0;i<preprocessors.length;i++) { //add preprocessor option if it is designed for the current program if(preprocessors[i].program_id==programSelect.options[programSelect.selectedIndex].value) { var option = document.createElement("option"); option.text = preprocessors[i].pre_processor_name; option.value = preprocessors[i].pre_processor_id; preProcessorSelect.add(option); } } }); } //function to setup the results table function setupTable() { $('#jobsTable').dataTable().fnDestroy(); table = $('#jobsTable').DataTable( { dom: 'Blfrtip', buttons: [ { extend: 'csvHtml5', title: 'Query export' }, ], "iDisplayLength": 50, "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]], "pagingType": "full_numbers", "aaData": loadedJobs, // <-- your array of objects "aoColumns": [ {"mDataProp": "job_id"}, // <-- which values to use inside object {"mDataProp": "task_id"}, {"mDataProp": "task_name"}, {"mDataProp": "start_time"}, {"mDataProp": "end_time"}, // <-- which values to use inside object {"mDataProp": "pre_processor_name"}, {"mDataProp": "program_name"}, {"mDataProp": "input_file"}, {"mDataProp": "job_parameters"}, { "mDataProp": "job_status", "fnCreatedCell": function(nTd, sData, oData, iRow, iCol){ if(oData.job_status=="waiting") { $(nTd).css('color', '#FFB300'); } else if(oData.job_status=="completed") { $(nTd).css('color', '#4CAF50'); } else if(oData.job_status=="timeout") { $(nTd).css('color', '#9C27B0'); } else if(oData.job_status=="error") { $(nTd).css('color', '#0277BD'); } else if(oData.job_status=="working") { $(nTd).css('color', '#FF5722'); } else { $(nTd).css('color', '#F44336'); } } }, {"mDataProp": "client_name"}, { mRender: function(nTd, sData, oData, iRow, iCol){ if(oData.log_name) { return "logs"+oData.log_name+".log"; } }, //cell for the log hyperlink "fnCreatedCell": function(nTd, sData, oData, iRow, iCol){ if(oData.log_name) { $(nTd).html("<a href='logs"+oData.log_name+".log' target='_blank' >View</a>"); } } } ], scrollY: '65vh', scrollX: true, scrollCollapse: true, paging: true, } ); $('.dataTables_filter').addClass('auto-margin'); } //function to check if a value is an integer function isInteger(x) { return x % 1 === 0; } //function to query the database and update the results table function loadJobs() { var selectedProgram = document.getElementById("program-select").value; var selectedPreProcessor = document.getElementById("preprocessor-select").value; var selectedServer = document.getElementById("client-select").value; var selectedStatus = document.getElementById("status-select").value; var chosenTaskID = document.getElementById("taskIDInput").value; var chosenProblemFile = document.getElementById("problemFileInput").value; var queryBtn = document.getElementById("queryBtn"); if(isInteger(chosenTaskID) || chosenTaskID==""){ queryBtn.disabled = true; //send ajax request to query database $.ajax({ type: "GET", url: "functions/QueryDatabase.php", data: {program : selectedProgram, preProcessor : selectedPreProcessor, server : selectedServer, jobStatus : selectedStatus, taskID : chosenTaskID, problemFile : chosenProblemFile}, dataType: "json", success: function (data) { console.log(data); console.log(JSON.stringify(data)); queryBtn.disabled = false; table.clear().draw(); //remove old table data table.rows.add(data); //add new data table.columns.adjust().draw(); //redraw table } }); } } //function to load all of the clients from the database function loadClients(){ console.log("attempting to load clients"); $.ajax({ type: "POST", url: "functions/LoadTables.php", data: {tableName : 'Clients'}, dataType: "json", success: function (data) { console.log(JSON.stringify(data)); servers=data; var x = document.getElementById("client-select"); for(var i=0;i<servers.length;i++) { var option = document.createElement("option"); option.text = servers[i].client_name; option.value = servers[i].client_id; x.add(option); } } }); } //function to load all of the pre-processors from the database function loadPreProcessors(){ console.log("attempting to load preprocessors"); $.ajax({ type: "POST", url: "functions/LoadTables.php", data: {tableName : 'PreProcessors'}, dataType: "json", success: function (data) { console.log(JSON.stringify(data)); preprocessors=data; var x = document.getElementById("preprocessor-select"); for(var i=0;i<preprocessors.length;i++) { var option = document.createElement("option"); option.text = preprocessors[i].pre_processor_name; option.value = preprocessors[i].pre_processor_id; x.add(option); } } }); } //function to load all of the programs from the database function loadPrograms(){ console.log("attempting to load programs"); $.ajax({ type: "POST", url: "functions/LoadTables.php", data: {tableName : 'Programs'}, dataType: "json", success: function (data) { console.log(JSON.stringify(data)); programs=data; var x = document.getElementById("program-select"); for(var i=0;i<programs.length;i++) { var option = document.createElement("option"); option.text = programs[i].program_name; option.value = programs[i].program_id; x.add(option); } } }); } <file_sep>$( document ).ready(function() { //when ENTER is pressed, apply pattern $("#patternField").keyup(function(event){ if(event.keyCode == 13){ $("#applyPatternBtn").click(); } }); }); var numFilesExcluded = 0; /*function to get the input pattern and chosen directory, send it to the php script and populate the included files list with files matching the pattern*/ function applyPattern(){ //get data from html var thePattern = document.getElementById('patternField').value var excludedListDiv = document.getElementById("excludedFilesList"); var directories = document.getElementById("directorySelect"); var chosenDirectory = directories.options[directories.selectedIndex].text; //ajax request to submit pattern and directory to 'pattern.php' $.ajax({ type: "GET", url: "pattern.php", data: {pattern : thePattern, directory: chosenDirectory}, dataType: "json", success: function (data) { //check if script returned matches if(data.length >= 1) { /*clear excluded list and loop through the files, adding them to the excluded files list*/ excludedListDiv.innerHTML = ""; for (var i = 0; i < data.length; i++) { var opt = document.createElement('option'); opt.value = data[i]; opt.innerHTML = data[i]; excludedListDiv.appendChild(opt); } //update the number of excluded files and hide error updateExcludedLabel(); document.getElementById("noPatternFound").style.display = 'none'; } else { //display error document.getElementById("noPatternFound").style.display = 'inline'; } } }); } function clearExcludedList() { var excludedListDiv = document.getElementById("excludedFilesList"); excludedListDiv.innerHTML = ""; updateExcludedLabel() } function clearIncludedList() { var includedListDiv = document.getElementById("includedFilesList"); includedListDiv.innerHTML = ""; updateIncludedLabel(); } function updateIncludedLabel() { var includedListDiv = document.getElementById("includedFilesList"); var includedLabel = document.getElementById("includedLabel"); includedLabel.innerHTML = "<b>Files Included ("+includedListDiv.length+")</b>"; } function updateExcludedLabel() { var excludedListDiv = document.getElementById("excludedFilesList"); var excludedLabel = document.getElementById("excludedLabel"); excludedLabel.innerHTML = "<b>Files Excluded ("+excludedListDiv.length+")</b>"; } /*function to move selected files from one option list to another, prevents duplicates from being added*/ function moveRows(list1,list2) { var SelID = ''; var SelText = ''; var j; var list2Length = list2.options.length; //loop through list1 for (i = list1.options.length - 1; i>=0; i--) { //check if current option is selected if (list1.options[i].selected == true) { //loop through list 2 for(j=0; j<list2Length; j++) { //file exists in list2 if(list1.options[i].text == list2.options[j].text) { break; } } //check if whole of list2 search found 0 matches of file if(j==list2Length) { //add file from list1 to list2 and remove it from list1 SelID=list1.options[i].value; SelText=list1.options[i].text; var newRow = new Option(SelText,SelID); list2.options[list2.length] = newRow; list1.options[i] = null; } } } //update total labels for each list updateIncludedLabel(); updateExcludedLabel(); } function moveAllRows(list1,list2) { var SelID=''; var SelText=''; var j; var list2Length = list2.options.length; for (i=list1.options.length - 1; i>=0; i--) { for(j=0;j<list2Length;j++) { if(list1.options[i].text == list2.options[j].text) { //console.log("error "+list1.options[i].text+" already exists"); break; } } if(j==list2Length) { SelID=list1.options[i].value; SelText=list1.options[i].text; var newRow = new Option(SelText,SelID); list2.options[list2.length]=newRow; list1.options[i]=null; } } updateIncludedLabel(); updateExcludedLabel(); } <file_sep><?php include('functions/Authenticate.php'); ?> <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Distribute tasks to remote machines</title> <script src="js/jquery-3.1.1.min.js"></script> <link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.13/b-1.2.4/b-html5-1.2.4/r-2.1.1/datatables.min.css"/> <script type="text/javascript" src="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.13/b-1.2.4/b-html5-1.2.4/r-2.1.1/datatables.min.js"></script> <link rel="stylesheet" href="css/material.min.css"/> <link rel="stylesheet" href="css/mystyle.css"/> <script src="js/material.min.js"></script> <script src="js/query.js"></script> </head> <body> <div class="header-area"> <?php include_once 'navigation.php'; ?> </div> <div class="wrapper"> <!---------------------- query database ----------------------> <div class="card-wide mdl-card mdl-shadow--2dp" id = "programsCard"> <!-- title --> <div class="mdl-card__title"> <h2 class="mdl-card__title-text mdl-color-text--primary">Query Database</h2> </div> <!-- query actions --> <div class="mdl-card__actions"> <div id = "queryInputs"> <div id = "programSelect"class="left"><b>Program</b> <select id="program-select"> <option value="none"></option> </select> </div> <div id = "preProcessorSelect"class="left"><b>Pre-Processor</b> <select id="preprocessor-select"> <option value="none"></option> </select> </div> <div id = "clientSelect"class="left"><b>Client</b> <select id="client-select"> <option value="none"></option> </select> </div> <div id = "statusSelect"class="left"><b>Status</b> <select id="status-select"> <option value="none"></option> <option value="cancelled">cancelled</option> <option value="completed">completed</option> <option value="error">error</option> <option value="failed">failed</option> <option value="killed">killed</option> <option value="timeout">timeout</option> <option value="waiting">waiting</option> <option value="working">working</option> </select> </div> <div class="left"><b>Task ID</b> <input type="text" id = "taskIDInput"> </input> </div> <div class="left"><b>Problem File</b> <input type="text" id = "problemFileInput"> </input> </div> <br> <div class="left"> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" id="queryBtn" onclick="loadJobs()"> Query </button> </div> <br> <span id="programsError" style="color: #F44336; font-size:18px"> Invalid Task ID </span> </div> </div> <div class="mdl-card mdl-shadow--2dp" id="jobsTableArea"> <table id="jobsTable" class=" table table-striped table-bordered" cellspacing="0" width="100%"> <thead> <tr> <th class="mdl-data-table__cell--non-numeric">Job ID</th> <th class="mdl-data-table__cell--non-numeric">Task ID</th> <th class="mdl-data-table__cell--non-numeric">Task Name</th> <th class="mdl-data-table__cell--non-numeric">Start Time</th> <th class="mdl-data-table__cell--non-numeric">Finish Time</th> <th class="mdl-data-table__cell--non-numeric">Pre-Processor</th> <th class="mdl-data-table__cell--non-numeric">Program</th> <th class="mdl-data-table__cell--non-numeric">Input File</th> <th class="mdl-data-table__cell--non-numeric">Parameters</th> <th class="mdl-data-table__cell--non-numeric">Status</th> <th class="mdl-data-table__cell--non-numeric">Client PC</th> <th class="mdl-data-table__cell--non-numeric no-sort">Log</th> </tr> </thead> <tbody></tbody> </table> </div> </div> </div> </body> </html><file_sep><?php $program=$_GET['program']; chdir('../bin'); $files = glob("*".$program.".conf"); echo json_encode($files); ?><file_sep><?php if (isset($_POST['username'])) { $error = "Username or Password is invalid"; //check if username or password is empty if (empty($_POST['username']) || empty($_POST['password'])) { echo $error; } else { include('dbinfo.php'); $email=$_POST['username']; $password=$_POST['<PASSWORD>']; //setup sql connection using data from dbinfo file $mysql_conn = mysqli_connect(HOST, USER, PASS, DB) or die("Login error" . mysqli_error($mysql_conn)); //prepare statements to be run on database $stmt = $mysql_conn->prepare('SELECT * FROM Users WHERE user_email = ? AND user_password = ? LIMIT 1'); $stmt->bind_param('ss', $email,$password); $stmt->execute(); $result = $stmt->get_result(); //check if login is correct and start user session if(mysqli_num_rows($result) > 0) { $row = mysqli_fetch_assoc($result); session_start(); $_SESSION['login_user']=$email; $_SESSION['userid'] =$row['user_id']; $_SESSION['loggedin'] = true; echo "success"; } else { $error = "Username or Password is invalid"; echo $error; } mysql_close($mysql_conn); } } ?><file_sep>theIP=$1 #!/bin/bash ssh -o 'StrictHostKeyChecking no' -o 'ConnectTimeout=2' -X $theIP 'exit'<file_sep>theIP=`cat ip.txt` #!/bin/bash arrIN=(${theIP//:/ }) ssh -o 'StrictHostKeyChecking no' -o 'ConnectTimeout=5' -X $arrIN 'pgrep -f MainServer | xargs kill -9;' &<file_sep><?php include('functions/Authenticate.php'); ?> <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Distribute tasks to remote machines</title> <!--script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>--> <!--<link rel="stylesheet" href="https://code.getmdl.io/1.2.1/material.indigo-pink.min.css">--> <!--<script defer src="https://code.getmdl.io/1.2.1/material.min.js"></script>--> <!--<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>--> <!--<link rel="icon" href=""/>--> <link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/material.min.css"/> <link rel="stylesheet" href="css/mystyle.css"/> <!-- <link rel="stylesheet" href="css/combined.css"/> --> <script src="js/jquery-3.1.1.min.js"></script> <script src="js/material.min.js"></script> <script src="js/pattern.js"></script> <script src="js/distribution.js"></script> <script src="js/notification.js"></script> <script src="js/material.min.js"></script> <!-- auto complete --> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <div class="header-area"> <?php include_once 'navigation.php'; ?> </div> <div class = "wrapper"> <!---------------------- Modals ----------------------> <div id="problemsModal" class="modal"> <div class="modal-content"> <a class="close">&times;</a> <p> To select problem files you must first select the directory containing the files by using the dropdown box.<br><span style="color: #4CAF50;padding-left: 10% " >Note: All folders will search every directory</span></p> <p> Next apply a pattern. Input the pattern into the field and click 'Apply' to retrieve all of the files<br><span style="color: #4CAF50;padding-left: 10% " >Example: <i>*.txt'</i> retrieves all .txt files and <i>*</i> retrieves all files</span></p> <p> When a pattern match is found, files will be listed in the "Files Excluded" list.<br> You can select files from the lists by clicking (or shift clicking to select multiple).<br><br> Use the four control buttons to move files between lists. The Files included list contains the files which will be included for processing.</p> </div> </div> <div id="programsModal" class="modal"> <div class="modal-content"> <a class="close">&times;</a> <p> This section allows you to specify programs, pre-processors and parameters to be used in the execution of the problem files. </p> <p> You must first select a program before selecting a pre-processor. </p> <p> Leave the parameters blank to use the default parameters. </p> <p> Multiple configurations can be added. For example with 10 problem files using 3 program/pre-processor configurations will mean that each problem file is executed 3 times. </p> </div> </div> <div id="optionsModal" class="modal"> <div class="modal-content"> <a class="close">&times;</a> <p> To start a task you must first specify the following: </p> <ol> <li> <b>Task Name:</b> The name of a task e.g. 3CNF2-KSP <span style="color: #F44336;" ></span></li> <li> <b>Memory Requirement:</b> The free memory required on the client until the problem file should be solved. <span style="color: #F44336;" >Maximum 8000</span></li> <li> <b>Load Requirement:</b> The maximum load (over the past minute) on the client before it should be allocated a job. <span style="color: #F44336;" >Minimum 1, Maximum 8. *Recommended 4.</span></li> <li> <b>Timeout:</b> The maximum time each problem file can be executed for before it is terminated. <span style="color: #F44336;" >Minimum 0, Maximum 72000</span></li> </ol> <br> <p> The start button will create a new task which will contain jobs for all of the problem files using each program/pre-processor combination.</p> <p> You can view the progress of the task you just created on the View Tasks page. </p> </div> </div> <!---------------------- selecting problem files ----------------------> <div class="card-wide mdl-card mdl-shadow--2dp" id = "selectFilesCard"> <!-- title --> <div class="mdl-card__title"> <h2 class="mdl-card__title-text mdl-color-text--primary ">Select Problem Files</h2> <button id="problemsModalBtn" class="mdl-button mdl-js-button mdl-button--icon show-dialog"><i class="fa fa-info-circle" ></i> </div> <!-- content --> <div class="mdl-card__actions" id="selectFilesArea"> <div> <!-- selecting directory --> <div class="patternDiv"> <b>Directory</b> <select id="directorySelect"> <option value="">ALL FOLDERS</option> <?php include('functions/LoadDirectories.php'); ?> </select> </div> <!-- applying pattern --> <div class="patternDiv"> <b>Pattern</b> <input type="text" name="patternField" id = "patternField"> </input> </div> <div class="applyPatternDiv"> <br> <button id="applyPatternBtn" class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onclick="applyPattern()"> <i class="fa fa-search "></i> Apply </button> <span id="noPatternFound" style="color: #F44336; font-size:18px">No matches found</span> <br> </div> </div> <!-- files area --> <div id="flexDiv"> <!-- excluded files --> <div id="excludedListDiv" class="left"> <b id="excludedLabel">Files Excluded (0)</b> <select multiple size="0" class = "selectableList" id="excludedFilesList"></select> <button class="mdl-button mdl-js-button mdl-button--accent" onclick="clearExcludedList()" id="clearBtn"> Clear </button> </div> <!-- file action buttons --> <div id="moveFilesDiv"> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onclick="moveRows(excludedFilesList,includedFilesList)"> > </button> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onclick="moveAllRows(excludedFilesList,includedFilesList)"> >> </button> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onclick="moveRows(includedFilesList,excludedFilesList)"> < </button> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onclick="moveAllRows(includedFilesList,excludedFilesList)"> << </button> </div> <!-- included files --> <div id="includedListDiv" class="left"> <b id="includedLabel">Files Included (0)</b> <select multiple size="0" class = "selectableList" id="includedFilesList"></select> <button class="mdl-button mdl-js-button mdl-button--accent" onclick="clearIncludedList()" id="clearBtn"> Clear </button> </div> </div> </div> <div id = "fileWarning"></div> </div> <!---------------------- selecting programs/preprocessors/parameters ----------------------> <div class="card-wide mdl-card mdl-shadow--2dp" id = "programsCard"> <!-- title --> <div class="mdl-card__title"> <h2 class="mdl-card__title-text mdl-color-text--primary">Select Programs</h2> <button id="programsModalBtn" class="mdl-button mdl-js-button mdl-button--icon show-dialog"><i class="fa fa-info-circle" ></i> </div> <!-- content --> <div class="mdl-card__actions" id="programsCardArea"> <!-- setting configuration --> <div id="programsTopDiv"> <div class="left"><b>Program</b><select id="program-select"></select> </div> <div class="left"><b>Pre-Processor</b><select id="preprocessor-select"></select> </div> <div class="left"><b>Parameters</b><input id="parametersInput" size="35" type="text" name="parametersInput"></div> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onclick="addConfiguration()"> <i class="fa fa-plus "></i> Add </button> <span id="programsError" style="color: #F44336; font-size:18px">Configuration Exists</span> </div> <!-- configuration table --> <table class="mdl-data-table mdl-js-data-table mdl-shadow--2dp" id="configurationTable"> <thead> <tr> <th class="mdl-data-table__cell--non-numeric">Program</th> <th class="mdl-data-table__cell--non-numeric">Pre-Processor</th> <th class="mdl-data-table__cell--non-numeric">Parameters</th> <th>Remove</th> </tr> </thead> <tbody></tbody> </table> </div> <div id = "programWarning"></div> </div> <!---------------------- selecting clients ----------------------> <div class="card-wide mdl-card mdl-shadow--2dp" id = "serversCard"> <!-- title --> <div class="mdl-card__title"> <h2 class="mdl-card__title-text mdl-color-text--primary">Select Clients</h2> </div> <!-- server radio buttons --> <div id="serversRadioButtonsDiv"> <label class="mdl-radio mdl-js-radio" for="allServersOption"> <input type="radio" id="allServersOption" name="serverOptions" class="mdl-radio__button"> <span class="mdl-radio__label">All</span> </label> <label class="mdl-radio mdl-js-radio" for="noServersOption"> <input type="radio" id="noServersOption" name="serverOptions" class="mdl-radio__button" checked> <span class="mdl-radio__label">None</span> </label> </div> <!-- content --> <div class="mdl-card__actions" id="serversCardArea"></div> <div id = "serverWarning"></div> </div> <!---------------------- selecting options/starting task ----------------------> <div class="card-wide mdl-card mdl-shadow--2dp" id = "optionsCard"> <!-- title --> <div class="mdl-card__title "> <h2 class="mdl-card__title-text mdl-color-text--primary">Change Options & Start Task</h2> <button id="optionsModalBtn" class="mdl-button mdl-js-button mdl-button--icon show-dialog"><i class="fa fa-info-circle" ></i> </div> <!-- content --> <div class="mdl-card__supporting-text"> <div class="mdl-grid"> <!-- option fields --> <div class="mdl-cell mdl-cell--12-col"> <b>Task Name (optional)</b><br> <input type="text" class = "settingsField" name="nameField" id = "nameField"> </input> <br><br> <b>Memory Requirement (Mb)</b><br> <input type="text" class = "settingsField" name="memoryField" id = "memoryField"> </input> <span id="memoryError" style="color: #F44336; font-size:18px">Invalid Memory</span> <br><br> <b>Maximum Load</b><br> <input type="text" class = "settingsField" name="loadField" id = "loadField"> </input> <span id="loadError" style="color: #F44336; font-size:18px">Invalid Load</span> <br><br> <b>Timeout (s)</b><br> <input type="text" class = "settingsField" name="timeoutField" id = "timeoutField"> </input> <span id="timeoutError" style="color: #F44336; font-size:18px">Invalid Timeout</span> <br><br> </div> <!-- start button and loading spinner --> <div class="mdl-cell mdl-cell--12-col" id="startTaskArea"> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onclick="validateAndStart()" id="startTaskBtn"> Start Task </button> <div class="mdl-spinner mdl-spinner--single-color mdl-js-spinner is-active" id="processingTask"></div> </div> </div> </div> </div> </div> <!-- snackbar for notifications --> <div id="toastBar" class="mdl-js-snackbar mdl-snackbar"> <div class="mdl-snackbar__text"></div> <button class="mdl-snackbar__action" type="button"></button> </div> </body> </html><file_sep><?php exec('cd ../server;java -cp .:mysql-connector-java-5.1.40-bin.jar MainServer;', $out, $status); ?><file_sep><?php include('../dbinfo.php'); session_start(); $mysql_conn = mysqli_connect(HOST, USER, PASS, DB) or die("Cannot connect to DB" . mysqli_error($mysql_conn)); $id = $_SESSION['task_id']; $temp_id = $_SESSION['userid']; //check to see if the task was created by the current user $check = mysqli_query($mysql_conn, "SELECT user_id FROM Tasks where task_id='$id' LIMIT 1"); $temp_row = mysqli_fetch_assoc($check); if($temp_row[user_id] == $temp_id){ //get the job data $query = mysqli_query($mysql_conn, "SELECT j.job_id, prog.program_name, j.input_file, j.start_time, j.end_time, j.job_parameters, j.job_status, c.client_name, j.log_name, pre.pre_processor_name FROM Jobs AS j INNER JOIN Programs AS prog ON j.program = prog.program_id INNER JOIN PreProcessors AS pre ON j.pre_processor = pre.pre_processor_id LEFT JOIN Clients AS c ON j.client_id = c.client_id WHERE task_id = '$id'"); //load query results into array $jobs = array(); while(($row = mysqli_fetch_assoc($query))) { $jobs[] = $row; } echo json_encode($jobs); } mysqli_close($mysql_conn); ?><file_sep>import java.sql.*; import java.util.ArrayList; import java.util.List; import java.text.SimpleDateFormat; import java.util.Date; import java.text.DateFormat; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; import java.io.InputStream; import java.io.FileInputStream; public class DBConnect{ private static String DB_HOST; private static String DB_NAME; private static String DB_USERNAME; private static String DB_PASSWORD; private Connection con; private Statement st; private ResultSet rs; //connect to the database upon object creation public DBConnect() { getDBInfo(); boolean connected = false; while(!connected) { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://"+DB_HOST+"/"+DB_NAME+"?autoReconnect=true", DB_USERNAME, DB_PASSWORD); System.out.println("Connected to database!"); connected = true; } catch(Exception ex) //error connecting. retry in 30 seconds { System.err.println("Could not connect to database!"); try { Thread.sleep(30000); } catch (InterruptedException ie) { ie.printStackTrace(); } } } } public void checkConnection() { boolean connected = false; while(!connected) { try { //check connection is still valid with 5 second timeout if(con.isValid(5)) { connected = true; } else { con = DriverManager.getConnection( "jdbc:mysql://"+DB_HOST+"/"+DB_NAME+"?autoReconnect=true", DB_USERNAME, DB_PASSWORD); System.out.println("Connection established!"); connected = true; } } catch(Exception ex) { System.out.println("Error checking connection: "+ex); try { Thread.sleep(10000); } catch (InterruptedException ie) { ie.printStackTrace(); } } } } protected static void getDBInfo() { Properties prop = new Properties(); InputStream input = null; try { input = new FileInputStream("config.properties"); // load a properties file prop.load(input); DB_HOST = prop.getProperty("host"); DB_NAME = prop.getProperty("name"); DB_USERNAME = prop.getProperty("username"); DB_PASSWORD = prop.getProperty("pass"); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } } private String removeLastChar(String s) { if (s == null || s.length() == 0) { return s; } return s.substring(0, s.length()-1); } private String getCurrentTimeStamp() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()); } public Client[] getClients(List<Integer> clientIDs) throws Exception { List<Client> clients = new ArrayList<Client>(); st = con.createStatement(); String inString = "("; for (Integer s : clientIDs) { inString += s+","; } inString = removeLastChar(inString); inString += ")"; String query = "select * from Clients WHERE client_id IN"+inString+" LIMIT "+clientIDs.size(); System.out.println("query is "+query); rs = st.executeQuery(query); System.out.println("Records from DB"); while(rs.next()) { int id = rs.getInt("client_id"); String ip = rs.getString("client_ip"); int port = rs.getInt("client_port"); System.out.println("ip = "+ip+" "+"port= "+port); clients.add(new Client(id,ip,port)); } Client[] clientArray = clients.toArray(new Client[clients.size()]); return clientArray; } public Client[] getClientInfo() { checkConnection(); List<Client> clients = new ArrayList<Client>(); try{ st = con.createStatement(); String query = "select * from Clients"; rs = st.executeQuery(query); System.out.println("Records from DB"); while(rs.next()){ int id = rs.getInt("client_id"); String ip = rs.getString("client_ip"); int port = rs.getInt("client_port"); System.out.println("ip = "+ip+" "+"port= "+port); clients.add(new Client(id,ip,port)); } } catch(Exception ex){ System.out.println("Error: "+ex); } Client[] clientArray = clients.toArray(new Client[clients.size()]); return clientArray; } //method to get the remaining jobs for a task (waiting/working/error status jobs) public ArrayList<Job> getJobsForTask(int taskID) throws Exception{ checkConnection(); ArrayList<Job> jobs = new ArrayList<Job>(); //create statement object st = con.createStatement(); //query to retrieve job information for task String query = "SELECT j.job_id, j.input_file, prog.program_name, pre.pre_processor_name, j.job_parameters, post.post_processor_name, j.job_status" + " FROM Jobs AS j" + " INNER JOIN Programs AS prog ON j.program = prog.program_id" + " INNER JOIN PreProcessors AS pre ON j.pre_processor = pre.pre_processor_id" + " INNER JOIN PostProcessors AS post ON prog.post_processor = post.post_processor_id" + " WHERE j.task_id = '"+taskID+"' AND j.job_status != 'completed' AND j.job_status != 'timeout' AND j.job_status != 'failed' AND j.job_status != 'killed'" + " ORDER BY j.job_id"; //execute query and store results in resultset object rs = st.executeQuery(query); //load result set fields while(rs.next()) { int jid = rs.getInt(1); String input = rs.getString(2); String prog = rs.getString(3); String pre = rs.getString(4); String param = rs.getString(5); String post = rs.getString(6); String status = rs.getString(7); //add new job to queue jobs.add(new Job(jid,input,prog,pre,param,post,status)); } return jobs; } /* if(param.equals("")) { param = "none"; } */ //System.out.println("loaded a job with id: "+jid); public TaskInfo getTaskInfo(int taskID) throws Exception { checkConnection(); st = con.createStatement(); String query = "select * from Tasks where task_id = '"+taskID+"' LIMIT 1"; rs = st.executeQuery(query); System.out.println("Records from DB:"); if(!rs.next()) { System.err.println("no task found"); throw new Exception(); } else { int id = rs.getInt("task_id"); double load = rs.getDouble("max_load"); int memory = rs.getInt("max_memory"); int timeout = rs.getInt("timeout"); System.out.println("task_id = "+id+" "+"max_load= "+load+" max_memory= "+memory+" +timeout= "+timeout); return new TaskInfo(id,load,memory,timeout); } } public void saveCompletedJob(int taskID, int jobID, String startTime, String finishTime, String status, String logName, int clientID) { checkConnection(); try{ st = con.createStatement(); String updateJobQuery = "UPDATE Jobs SET start_time='"+startTime+"', end_time='"+finishTime+"', job_status='"+status+"', log_name='"+logName+"', client_id='"+clientID+"' WHERE job_id='"+jobID+"' LIMIT 1"; String updateTaskQuery = "UPDATE Tasks SET jobs_completed=jobs_completed+1 WHERE task_id='"+taskID+"' LIMIT 1"; st.executeUpdate(updateJobQuery); st.executeUpdate(updateTaskQuery); System.out.println("Updated completed job "+jobID); } catch(Exception ex){ System.out.println("Error: "+ex); } } public void saveCompletedTask(int taskID, int code, String finishTime) { checkConnection(); try{ st = con.createStatement(); String query = "UPDATE Tasks SET task_finished='"+code+"', finish_time='"+finishTime+"' WHERE task_id='"+taskID+"' LIMIT 1"; int numUpdated = st.executeUpdate(query); System.out.println("Task "+taskID+" has completed"); } catch(Exception ex){ System.out.println("Error: "+ex); } } //method to update a jobs start time, status and client public void saveWorkingJob(int taskID, int jobID, String status, int clientID) { checkConnection(); try { //create statement object st = con.createStatement(); //query to update a single jobs start time, status and client String query = "UPDATE Jobs SET start_time='"+getCurrentTimeStamp()+"', job_status='"+status+"', client_id='"+clientID+"' WHERE job_id='"+jobID+"' LIMIT 1"; //execute query and store results in resultset object st.executeUpdate(query); //System.out.println("Updated working job: "+jobID); } catch(Exception ex) { System.out.println("Error updating working job: "+ex); } } public void saveCancelledJobs(int taskID) { checkConnection(); try{ st = con.createStatement(); String query = "UPDATE Jobs SET job_status='cancelled' WHERE (task_id='"+taskID+"') AND (job_status='waiting' OR job_status='working')"; int numUpdated = st.executeUpdate(query); System.out.println("Updated cancelled jobs for task "+taskID); } catch(Exception ex){ System.out.println("Error: "+ex); } } public void updateErrorJobs(int taskID) { checkConnection(); try{ st = con.createStatement(); String query = "UPDATE Jobs SET job_status='error', client_id=null, end_time=null WHERE task_id='"+taskID+"' AND job_status='working'"; int numUpdated = st.executeUpdate(query); System.err.println("Updated "+numUpdated+" rows with errors"); } catch(Exception ex){ System.out.println("Error: "+ex); } } public void disconnectFromDB(){ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }<file_sep>function login(){ var theEmail = document.getElementById('name').value var thePassword = document.getElementById("password").value; //ajax request to login to the website $.ajax({ type: "POST", url: "login.php", data: {username : theEmail, password: <PASSWORD>}, dataType: "text", success: function (data) { if (data=="success") { window.location='distribution.php'; } else { document.getElementById('errors').innerHTML = data; console.log(data); } } }); } <file_sep>import java.util.*; public class Task { //task info protected final int taskID; protected final double taskLoad; protected final int taskMemory; protected final int timeout; protected final int userID; protected final int totalJobs; protected final DBConnect connect; protected volatile int numJobsCompleted = 0; //holds all of the jobs for this task private ArrayList<Job> jobQueue; public Task(int uid, int tid, double load, int memory, int time, ArrayList<Job> jobs, int numJobs, DBConnect con) { userID = uid; taskID = tid; taskLoad = load; taskMemory = memory; timeout = time; jobQueue = jobs; totalJobs = numJobs; connect = con; } //method to get the number of jobs in the job queue protected int getQueueSize() { return jobQueue.size(); } //method to get the next job in the jobqueue and remove it protected synchronized Job getNextJob() throws IndexOutOfBoundsException { if(jobQueue.size() == 0) { throw new IndexOutOfBoundsException("No jobs left"); } else { Job nextJob = jobQueue.remove(0); return nextJob; } } //method to add a job back to the job queue protected synchronized void addJobBackToQueue(Job aJob) { jobQueue.add(aJob); } } <file_sep><?php include('../dbinfo.php'); session_start(); $mysql_conn = mysqli_connect(HOST, USER, PASS, DB) or die("Cannot connect to DB" . mysqli_error($mysql_conn)); //select all of the tasks with the users id $query = mysqli_query($mysql_conn, "SELECT task_id, task_name, start_time, finish_time, max_load, max_memory, timeout, task_finished, total_jobs, jobs_completed FROM Tasks WHERE user_id= '".$_SESSION['userid']."'"); //load the tasks into array $tasks = array(); while(($row = mysqli_fetch_assoc($query))) { $tasks[] = $row; } echo json_encode($tasks); ?><file_sep><?php $dirPath = dir('problems'); $directoryArray = array(); //search problems directory for folders $results = scandir('problems'); //loop through the problems folder and add folder names to array foreach ($results as $result) { //check a real folder exists if ($result === '.' or $result === '..'){} else { $directoryArray[ ] = basename($result); } } $dirPath->close(); //sort folder names asort($directoryArray); //loop through the array creating options to be displayed on the HTML page $c = count($directoryArray); for($i=0; $i<$c; $i++) { echo "<option value=\"" . $directoryArray[$i] . "\">" . $directoryArray[$i] . "\n"; } ?><file_sep><?php exec('cd ../;./kill-clients.sh', $out, $status); if (0 === $status) { echo("Clients Stopped"); } else { echo "Command failed with status: $status"; } ?><file_sep><?php include('functions/Authenticate.php'); ?> <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Distribute tasks to remote machines</title> <script src="js/jquery-3.1.1.min.js"></script> <link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.13/b-1.2.4/b-html5-1.2.4/r-2.1.1/datatables.min.css"/> <script type="text/javascript" src="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.13/b-1.2.4/b-html5-1.2.4/r-2.1.1/datatables.min.js"></script> <link rel="stylesheet" href="css/material.min.css"/> <link rel="stylesheet" href="css/mystyle.css"/> <script src="js/material.min.js"></script> <script src="js/jobs.js"></script> </head> <body> <!-- get id of the task --> <?php session_start(); $_SESSION['task_id'] = $_GET['id']; ?> <div class="header-area"> <?php include_once 'navigation.php'; ?> </div> <div class="wrapper"> <!---------------------- Modals ----------------------> <div id="jobsModal" class="modal"> <div class="modal-content"> <a class="close">&times;</a> <p> The table will classify job Status using the following criteria: </p> <ol> <li> <span style="color: #4CAF50;" >completed:</span> The problem file was executed without problems</li> <li> <span style="color: #FFB300;" >waiting:</span> The problem file is waiting to be solved</li> <li> <span style="color: #9C27B0;" >timeout:</span> The program timed out</li> <li> <span style="color: #0277BD;" >error:</span> The client pc disconnected whilst solving the problem. This job will retry once the other jobs have finished</li> <li> <span style="color: #FF5722;" >working:</span> The job is currently being processed by a client</li> <li> <span style="color: #F44336;" >failed:</span> The job encountered an execution error. This could be due to incorrect parameters or missing files. Check the log for more information</li> <li> <span style="color: #F44336;" >killed:</span> The job process was killed multiple times</li> <li> <span style="color: #F44336;" >cancelled:</span> The job was cancelled by the user</li> </ol> <p> When a problem file has stopped executing (due to completing or being halted) the finish time, client pc and log (if available) will be displayed in the table.</p> <p> You can <b>export</b> the results to csv by clicking the csv button.</p> </div> </div> <!---------------------- viewing jobs ----------------------> <div class="card-wide mdl-card mdl-shadow--2dp" id = "tableCard"> <!-- title --> <div class="mdl-card__title"> <h2 class="mdl-card__title-text mdl-color-text--primary">Jobs for Task <?php echo $_GET['id']; ?></h2> <button id="jobsModalBtn" class="mdl-button mdl-js-button mdl-button--icon show-dialog"><i class="fa fa-info-circle" ></i> </div> <!-- jobs table --> <div class="mdl-card mdl-shadow--2dp" id="jobsTableArea"> <table id="jobsTable" class=" table table-striped table-bordered" cellspacing="0" width="100%"> <thead> <tr> <th class="mdl-data-table__cell--non-numeric">Job ID</th> <th class="mdl-data-table__cell--non-numeric">Start Time</th> <th class="mdl-data-table__cell--non-numeric">Finish Time</th> <th class="mdl-data-table__cell--non-numeric">Pre-Processor</th> <th class="mdl-data-table__cell--non-numeric">Program</th> <th class="mdl-data-table__cell--non-numeric">Input File</th> <th class="mdl-data-table__cell--non-numeric">Parameters</th> <th class="mdl-data-table__cell--non-numeric">Status</th> <th class="mdl-data-table__cell--non-numeric">Client PC</th> <th class="mdl-data-table__cell--non-numeric no-sort">Log</th> </tr> </thead> <tbody></tbody> </table> </div> </div> </div> </body> </html><file_sep>import java.io.*; import java.util.*; import java.net.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.sql.Timestamp; public class ServerSession implements Runnable { private static final int MAX_RECONNECT_ATTEMPTS = 1000; private static final int RECONNECT_WAIT_MILLIS = 10000; private static final int MAX_TIMES_KILLED = 2; private BufferedReader serverIn; private PrintWriter serverOut; private Socket serverSocket; private boolean validConnection; private int workerNum = 0; private Load loadObject; private Task task; private Client client; public ServerSession(Load l, int wNum, Client c, Task t){ loadObject = l; workerNum = wNum; client = c; task = t; } private void stopSession(){ try { if(serverSocket!=null){ System.out.println("Closing connection to client "+client.getClientID()); serverOut.println("2"); serverOut.flush(); serverIn.close(); serverOut.close(); serverSocket.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //method to connect to the client PC private void connectToClient() { int reconnectAttempts = 0; validConnection = false; //loop to retry connection until limit is reached while(reconnectAttempts < MAX_RECONNECT_ATTEMPTS) { //check if jobs remain if(task.numJobsCompleted < task.totalJobs) { try { //open socket and input/output streams to client PC serverSocket = new Socket(client.getIP(), client.getPORT()); serverIn = new BufferedReader( new InputStreamReader(serverSocket.getInputStream())); serverOut = new PrintWriter( new OutputStreamWriter(serverSocket.getOutputStream())); validConnection = true; break; } catch (IOException e) //could not connect { reconnectAttempts++; System.err.println("Error: could not connect to client "+client.getIP()+" using port "+client.getPORT()+". Retrying in "+RECONNECT_WAIT_MILLIS+"ms"); try { Thread.sleep(RECONNECT_WAIT_MILLIS); //wait 10seconds } catch (InterruptedException ie) { ie.printStackTrace(); } } } else { stopSession(); break; } } } public void run() { connectToClient(); if(validConnection == false) { return; //kill thread } Job nextJob = null; int jobID; boolean jobCompleted; double clientLoad; int clientMemory; while(task.numJobsCompleted<task.totalJobs) { try { //set load and memory to impossible values to handle disconnect clientLoad = -100.0; clientMemory = -1; jobCompleted = false; //request memory+load serverOut.println("1"); serverOut.flush(); //request memory and load from client String fromClient = null; while((fromClient = serverIn.readLine()) != null){ String[] memoryAndLoad = fromClient.split("@"); clientLoad = Double.parseDouble(memoryAndLoad[0]); clientMemory = Integer.parseInt(memoryAndLoad[1]); break; } System.out.println("clientMemory "+clientMemory+" task memory "+task.taskMemory+" client load "+clientLoad); //check memory and load requirements if(loadObject.checkRequirements(clientMemory, clientLoad, task.taskMemory, task.taskLoad, workerNum)) { //get next job in queue nextJob = task.getNextJob(); jobID = nextJob.getJobID(); //form job string to be sent to client String jobString = "0@"; jobString = jobString+task.userID+"@"; jobString = jobString+task.taskID+"@"; jobString = jobString+jobID+"@"; jobString = jobString+nextJob.getInputFile()+"@"; jobString = jobString+nextJob.getProgram()+"@"; jobString = jobString+nextJob.getPreProcessor()+"@"; jobString = jobString+nextJob.getParameters()+"@"; jobString = jobString+nextJob.getPostProcessor()+"@"; jobString = jobString+task.timeout; System.out.println("sent "+jobString+" to client "+client.getClientID()); //update working job task.connect.saveWorkingJob(task.taskID, jobID, "working", client.getClientID()); //get current time Timestamp timestamp = new Timestamp(System.currentTimeMillis()); long jobSentTime = timestamp.getTime(); //send job to client serverOut.println(jobString); serverOut.flush(); //wait for client response fromClient = null; while((fromClient = serverIn.readLine()) != null) { //client finished working on job so update its midprogress jobs loadObject.midProgressJobs[workerNum] = 0; timestamp = new Timestamp(System.currentTimeMillis()); //get current time long jobFinishedTime = timestamp.getTime(); //add new start time and finisht ime to finishedJobs list loadObject.finishedJobs.add(new times(jobSentTime, jobFinishedTime)); //load response from client into variables String[] jobResponse = fromClient.split("@"); String jobStatus = jobResponse[0]; String startTime = jobResponse[1]; String finishTime = jobResponse[2]; String logName = jobResponse[3]; System.out.println(jobStatus+" "+startTime+" "+finishTime+" "+logName); if(jobStatus.equals("killed")) //job did not complete { nextJob.updateTimesKilled(); if(nextJob.getTimesKilled()>MAX_TIMES_KILLED) //check if job killed too many times { //save job as killed System.out.println("job "+jobID+" was killed too many times"); task.connect.saveCompletedJob(task.taskID, jobID, startTime, finishTime, jobStatus, logName, client.getClientID()); task.numJobsCompleted++; jobCompleted = true; } } else //job completed { //save job as completed/timeout System.out.println("client "+client.getClientID()+" completed job "+jobID+" for task "+task.taskID+" with status: " +jobStatus); task.connect.saveCompletedJob(task.taskID, jobID, startTime, finishTime, jobStatus, logName, client.getClientID()); task.numJobsCompleted++; jobCompleted = true; } break; } //check if job completed or client disconnected if(jobCompleted == false) { task.connect.saveWorkingJob(task.taskID, jobID, "error", client.getClientID()); System.err.println("adding job back to queue"); task.addJobBackToQueue(nextJob); } } else { //check if client disconnected before it was sent a job if(clientLoad==-100.0) { System.err.println("client "+client.getClientID()+" has disconnected!"); connectToClient(); } else //client does not have enough memory/sufficient load. wait 10 seconds { System.out.println("client "+client.getClientID()+" does not have enough memory "+clientMemory+"/"+task.taskMemory+" or load "+clientLoad+"/"+task.taskLoad); Thread.sleep(10000); } } } catch(IndexOutOfBoundsException iob) //no jobs left in queue. enter wait loop { while(task.getQueueSize() == 0 && task.numJobsCompleted<task.totalJobs) { System.err.println("No jobs left but task incomplete. Waiting "+RECONNECT_WAIT_MILLIS+"ms"); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } catch(InterruptedException ie) { ie.printStackTrace(); } catch(IOException e) { task.addJobBackToQueue(nextJob); System.err.println("Could not reach client"); e.printStackTrace(); connectToClient(); } } stopSession(); } }<file_sep><?php include('../dbinfo.php'); session_start(); $mysql_conn = mysqli_connect(HOST, USER, PASS, DB) or die("Cannot connect to DB" . mysqli_error($mysql_conn)); $program = mysqli_real_escape_string($mysql_conn, $_GET['program']); $preProcessor = mysqli_real_escape_string($mysql_conn, $_GET['preProcessor']); $server = mysqli_real_escape_string($mysql_conn, $_GET['server']); $jobStatus = mysqli_real_escape_string($mysql_conn, $_GET['jobStatus']); $taskID = mysqli_real_escape_string($mysql_conn, $_GET['taskID']); $problemFile = mysqli_real_escape_string($mysql_conn, $_GET['problemFile']); $userid = $_SESSION['userid']; $conditions = ""; //conditions within where clause $andString = ""; //holds " AND " if one or more conditions set $conditionsExist = " AND "; //used to combine two where conditions if needed //check if conditions have been set and form condition string if($program !== "none") { $conditions = $conditions.$andString." j.program = '".$program."' "; $andString = " AND "; } if($preProcessor !== "none") { $conditions = $conditions.$andString." j.pre_processor = '".$preProcessor."' "; $andString = " AND "; } if($server !== "none") { $conditions = $conditions.$andString." j.client_id = '".$server."' "; $andString = " AND "; } if($jobStatus !== "none") { $conditions = $conditions.$andString." j.job_status = '".$jobStatus."' "; $andString = " AND "; } if($taskID !== "") { $conditions = $conditions.$andString." j.task_id = '".$taskID."' "; $andString = " AND "; } if($problemFile !== "") { $conditions = $conditions.$andString." j.input_file like '%".$problemFile."%' "; $andString = " AND "; } //no conditions specified so " AND " is not required to connect the conditions and userid if($conditions == '') { $conditionsExist = ''; } $query = mysqli_query($mysql_conn, "SELECT j.job_id, j.task_id, tasks.task_name, prog.program_name, j.input_file, j.start_time, j.end_time, j.job_parameters, j.job_status, c.client_name, j.log_name, pre.pre_processor_name FROM Jobs AS j INNER JOIN Programs AS prog ON j.program = prog.program_id INNER JOIN PreProcessors AS pre ON j.pre_processor = pre.pre_processor_id INNER JOIN Tasks As tasks ON j.task_id = tasks.task_id LEFT JOIN Clients AS c ON j.client_id = c.client_id WHERE ".$conditions." ".$conditionsExist." tasks.user_id = ".$userid." LIMIT 10000"); //load query results into array $jobs = array(); while(($row = mysqli_fetch_assoc($query))) { $jobs[] = $row; } mysqli_close($mysql_conn); echo json_encode($jobs); ?><file_sep><?php exec('cd ../;./shutdown-server.sh', $out, $status); if (0 === $status) { echo("Server shutdown"); } else { echo "Command failed with status: $status"; } ?> <file_sep><?php include('functions/Authenticate.php'); ?> <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Distribute tasks to remote machines</title> <script src="js/jquery-3.1.1.min.js"></script> <link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.13/b-1.2.4/b-html5-1.2.4/r-2.1.1/datatables.min.css"/> <script type="text/javascript" src="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.13/b-1.2.4/b-html5-1.2.4/r-2.1.1/datatables.min.js"></script> <link rel="stylesheet" href="css/material.min.css"/> <link rel="stylesheet" href="css/mystyle.css"/> <script src="js/material.min.js"></script> <script src="js/tasks.js"></script> <script src="js/notification.js"></script> </head> <body> <div class="header-area"> <?php include_once 'navigation.php'; ?> </div> <div class="wrapper"> <!---------------------- Modals ----------------------> <div id="tasksModal" class="modal"> <div class="modal-content"> <a class="close">&times;</a> <p> All of the tasks you have created will be displayed in the table. </p> <p> You can sort the table by clicking on one of the table headers. </p> <p> To view the jobs for the task, click on the <span style="color: #3F51B5;" >"View"</span> hyperlink for the task. </p> <p> <span style="color: #0277BD;" >To cancel a tasks execution you can click on the <i class="fa fa-times" ></i> button.</span> </p> <p> <span style="color: #0277BD;" >To delete a task and all of its log files you can click on the <i class="fa fa-trash" ></i> button.</span> </p> <p> <span style="color: #F44336;" >Cancelled tasks will have the jobs displayed in red.</span> </p> </div> </div> <!---------------------- viewing tasks ----------------------> <div class="card-wide mdl-card mdl-shadow--2dp" id = "tableCard"> <!-- title --> <div class="mdl-card__title"> <h2 class="mdl-card__title-text mdl-color-text--primary">Tasks</h2> <button id="tasksModalBtn" class="mdl-button mdl-js-button mdl-button--icon show-dialog"><i class="fa fa-info-circle" ></i> </div> <!-- options --> <div id="taskOptionsArea"> <label class="mdl-radio mdl-js-radio" for="allTasksOption"> <input type="radio" id="allTasksOption" name="taskFilters" class="mdl-radio__button" checked> <span class="mdl-radio__label">All Tasks</span> </label> <label class="mdl-radio mdl-js-radio" for="completedTasksOption"> <input type="radio" id="completedTasksOption" name="taskFilters" class="mdl-radio__button" > <span class="mdl-radio__label">Completed Tasks</span> </label> <label class="mdl-radio mdl-js-radio" for="incompleteTasksOption"> <input type="radio" id="incompleteTasksOption" name="taskFilters" class="mdl-radio__button" > <span class="mdl-radio__label">Incomplete Tasks</span> </label> </div> <!-- tasks table --> <div class="mdl-card mdl-shadow--2dp" id = "tasksTableArea"> <table id="tasksTable" class="table table-striped table-bordered" cellspacing="0" width="100%"> <thead> <tr> <th class="mdl-data-table__cell--non-numeric">Task ID</th> <th class="mdl-data-table__cell--non-numeric">Task Name</th> <th class="mdl-data-table__cell--non-numeric">Start Time</th> <th class="mdl-data-table__cell--non-numeric">Finish Time</th> <th class="mdl-data-table__cell--non-numeric">Load</th> <th class="mdl-data-table__cell--non-numeric">Memory (Mb)</th> <th class="mdl-data-table__cell--non-numeric">Timeout (s)</th> <th class="mdl-data-table__cell--non-numeric">Progress</th> <th class="mdl-data-table__cell--non-numeric no-sort">Jobs</th> <th class="mdl-data-table__cell--non-numeric no-sort">View Jobs</th> <th class="mdl-data-table__cell--non-numeric no-sort">Actions</th> </tr> </thead> <tbody></tbody> </table> </div> </div> </div> <!-- snackbar for notifications --> <div id="toastBar" class="mdl-js-snackbar mdl-snackbar"> <div class="mdl-snackbar__text"></div> <button class="mdl-snackbar__action" type="button"></button> </div> </body> </html><file_sep>#!/bin/sh FILE=${@: -1} LENGTH=$(($#-1)) ARRAY=${@:1:$LENGTH} DIR=$( dirname "$(readlink -f "$0")" ) echo "PROVER : BDDTab" echo "OPTIONS:" $ARRAY echo "FILE :" $FILE /usr/bin/time sh -c "cat $FILE | $DIR/bddtab $ARRAY | grep -v Garbage"<file_sep>$(document).ready(function() { $.fn.dataTable.ext.errMode = 'none'; setupModals(); loadTasks(); }); //data for the tasks table var loadedTasks; //position of page scroll var pageScrollPos=0; function setupModals() { //when help button clicked $(".show-dialog").click(function(){ //display modal modal = document.getElementById('tasksModal'); modal.style.display = "block"; //close modal when user clicks anywhere on the page window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } //close modal when close button is clicked $(".close").click(function(){ modal.style.display = "none"; }); }); } //function to load the users tasks and setup the jquery datatable function loadTasks() { //request task data from database $.ajax({ type: "GET", url: "functions/LoadTasks.php", dataType: "json", success: function (data) { loadedTasks = data; var tempPercent = 0; var taskStatus = 0; //jquery datatable var table = $('#tasksTable').DataTable( { dom: 'Blfrtip', buttons: [ ], "iDisplayLength": 50, //set to 50 results per page by default "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]], //results per page values "pagingType": "full_numbers", //setup scroll height remembering on table redraw "preDrawCallback": function (settings) { pageScrollPos = $('div.dataTables_scrollBody').scrollTop(); }, "drawCallback": function (settings) { $('div.dataTables_scrollBody').scrollTop(pageScrollPos); }, //set loadedTasks as array for datatable "aaData": loadedTasks, "aoColumns": [ //column row data {"mDataProp": "task_id"}, {"mDataProp": "task_name"}, {"mDataProp": "start_time"}, {"mDataProp": "finish_time"}, {"mDataProp": "max_load"}, {"mDataProp": "max_memory"}, {"mDataProp": "timeout"}, { //calculate cell mRender: function(data, type, row){ //load status of task, to be used in next cell taskStatus = row.task_finished; //calculate the tasks completion percentage tempPercent = Math.floor((row.jobs_completed / row.total_jobs) * 100); return tempPercent; }, //display cell data "fnCreatedCell": function(nTd, sData, oData, iRow, iCol){ if(tempPercent==100) //task full progress { $(nTd).html("<progress class='green' value='"+oData.jobs_completed+"' max='"+oData.total_jobs+"' ></progress> "); } else if(tempPercent<=30) //task low progress { $(nTd).html("<progress class='red' value='"+oData.jobs_completed+"' max='"+oData.total_jobs+"' ></progress> "); } else //task mid progress { $(nTd).html("<progress class='amber' value='"+oData.jobs_completed+"' max='"+oData.total_jobs+"' ></progress> "); } } }, { //cell for total jobs completed out of total jobs for the task "fnCreatedCell": function(nTd, sData, oData, iRow, iCol){ if(taskStatus==2) //task is cancelled, display jobs completed in red { $(nTd).html("<span style='color:#F44336'>"+oData.jobs_completed+"/"+oData.total_jobs+"</span>"); } else //display jobs completed { $(nTd).html(oData.jobs_completed+"/"+oData.total_jobs); } } }, { //cell for jobs hyperlink "fnCreatedCell": function(nTd, sData, oData, iRow, iCol){ $(nTd).html("<a href='jobs.php?id="+oData.task_id+"'>View</a>"); } }, { //cell for actions (cancel/delete) mRender: function (o) { if(taskStatus==0) //show cancel button if task in progress { return '<a class="btn-cancel mdl-button mdl-button--icon"><i class="fa fa-times" style="color:red" ></i></a>'; } else //show delete button { return '<a class="btn-delete mdl-button mdl-button--icon"><i class="fa fa-trash-o" ></i></a>'; } } } ], scrollY: '65vh', scrollX: true, scrollCollapse: true, paging: true, }); //handle click on "Delete" button $('#tasksTable tbody').on('click', '.btn-delete', function (e) { //get selected row data var data = table.row( $(this).parents('tr') ).data(); //ask user to confirm delete var response = confirm("Are you sure you want to delete task "+data.task_id+" ?"); if(response == true) { //delete task and the task directory deleteTask(data.task_id); //console.log("deleted task "+ data.task_id); //remove task from table and redraw table.row( $(this).parents('tr') ).remove(); table.draw(); } }); //handle click on "Cancel" button $('#tasksTable tbody').on('click', '.btn-cancel', function (e) { //get selected row data var data = table.row( $(this).parents('tr') ).data(); //ask user to confirm cancellation var response = confirm("Are you sure you want to cancel task "+data.task_id+" ?"); if(response == true) { //console.log("cancelling task "+ data.task_id); //cancel task cancelTask(data.task_id); } }); //custom filtering to filter table according to the radio buttons selected $.fn.dataTable.ext.search.push( function( settings, data, dataIndex ) { if($('#allTasksOption').is(':checked'))//display whole table { return true; } else if($('#completedTasksOption').is(':checked')) //display completed tasks only { var progress = parseFloat( data[7] ) || 0; //use data for the progress column if(progress==100) { return true; } return false; } else if($('#incompleteTasksOption').is(':checked')) //display incomplete jobs only { var progress = parseFloat( data[7] ) || 0; //use data for the progress column if(progress<100) { return true; } return false; } } ); //listener to redraw table when a radio button option is selected $(document).ready(function() { var table = $('#tasksTable').DataTable(); // Event listener to the two range filtering inputs to redraw on input $('#allTasksOption, #completedTasksOption, #incompleteTasksOption').change( function() { table.draw(); }); }); $('.dataTables_filter').addClass('auto-margin'); } }); } //function to cancel a working task function cancelTask(taskID) { //request to cancel the task on the distribution server $.ajax({ type: "POST", url: "functions/CancelTask.php", cache: false, data: {task_id : taskID}, dataType: "text", success: function (data) { displayNotification(data); } }); } //function to delete a task function deleteTask(theID){ //request to delete task in database $.ajax({ type: "POST", url: "functions/DeleteTask.php", data: {taskid: theID}, dataType: "text", success: function (data) { displayNotification(data); } }); }
b223ec8bba6942649ce13393b8e45c7536133bab
[ "JavaScript", "INI", "Java", "PHP", "Shell" ]
51
INI
liamc360/JobDistribution
5b600648779e89cecbe4bbe301b506383b1de89b
da9adf19730d066f464a4ad781255e01bee200e0
refs/heads/master
<file_sep>package com.example.ligabaloncesto.repository; import com.example.ligabaloncesto.domain.Estadisticas_jugador_partido; import org.springframework.data.jpa.repository.*; import java.util.List; /** * Spring Data JPA repository for the Estadisticas_jugador_partido entity. */ public interface Estadisticas_jugador_partidoRepository extends JpaRepository<Estadisticas_jugador_partido,Long> { } <file_sep>'use strict'; angular.module('ligabaloncestoApp') .controller('Estadisticas_jugador_partidoController', function ($scope, Estadisticas_jugador_partido, ParseLinks) { $scope.estadisticas_jugador_partidos = []; $scope.page = 1; $scope.loadAll = function() { Estadisticas_jugador_partido.query({page: $scope.page, per_page: 20}, function(result, headers) { $scope.links = ParseLinks.parse(headers('link')); $scope.estadisticas_jugador_partidos = result; }); }; $scope.loadPage = function(page) { $scope.page = page; $scope.loadAll(); }; $scope.loadAll(); $scope.delete = function (id) { Estadisticas_jugador_partido.get({id: id}, function(result) { $scope.estadisticas_jugador_partido = result; $('#deleteEstadisticas_jugador_partidoConfirmation').modal('show'); }); }; $scope.confirmDelete = function (id) { Estadisticas_jugador_partido.delete({id: id}, function () { $scope.loadAll(); $('#deleteEstadisticas_jugador_partidoConfirmation').modal('hide'); $scope.clear(); }); }; $scope.refresh = function () { $scope.loadAll(); $scope.clear(); }; $scope.clear = function () { $scope.estadisticas_jugador_partido = {asistencias: null, canastas: null, faltas: null, id: null}; }; }); <file_sep>package com.example.ligabaloncesto.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.example.ligabaloncesto.domain.util.CustomLocalDateSerializer; import com.example.ligabaloncesto.domain.util.ISO8601LocalDateDeserializer; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Type; import org.joda.time.LocalDate; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.Objects; /** * A Jugador. */ @Entity @Table(name = "JUGADOR") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class Jugador implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "nombre") private String nombre; @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate") @JsonSerialize(using = CustomLocalDateSerializer.class) @JsonDeserialize(using = ISO8601LocalDateDeserializer.class) @Column(name = "fecha") private LocalDate fecha; @Min(value = 0) @Column(name = "total_canastas") private Integer totalCanastas; @Min(value = 0) @Column(name = "total_asistencias") private Integer totalAsistencias; @Min(value = 0) @Column(name = "total_rebotes") private Integer totalRebotes; @Column(name = "posicion") private String posicion; @OneToMany(mappedBy = "jugador") @JsonIgnore @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private Set<Estadisticas_jugador_partido> estadisticas_jugador_partidos = new HashSet<>(); @ManyToOne private Equipo equipo; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public LocalDate getFecha() { return fecha; } public void setFecha(LocalDate fecha) { this.fecha = fecha; } public Integer getTotalCanastas() { return totalCanastas; } public void setTotalCanastas(Integer totalCanastas) { this.totalCanastas = totalCanastas; } public Integer getTotalAsistencias() { return totalAsistencias; } public void setTotalAsistencias(Integer totalAsistencias) { this.totalAsistencias = totalAsistencias; } public Integer getTotalRebotes() { return totalRebotes; } public void setTotalRebotes(Integer totalRebotes) { this.totalRebotes = totalRebotes; } public String getPosicion() { return posicion; } public void setPosicion(String posicion) { this.posicion = posicion; } public Set<Estadisticas_jugador_partido> getEstadisticas_jugador_partidos() { return estadisticas_jugador_partidos; } public void setEstadisticas_jugador_partidos(Set<Estadisticas_jugador_partido> estadisticas_jugador_partidos) { this.estadisticas_jugador_partidos = estadisticas_jugador_partidos; } public Equipo getEquipo() { return equipo; } public void setEquipo(Equipo equipo) { this.equipo = equipo; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Jugador jugador = (Jugador) o; if ( ! Objects.equals(id, jugador.id)) return false; return true; } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "Jugador{" + "id=" + id + ", nombre='" + nombre + "'" + ", fecha='" + fecha + "'" + ", totalCanastas='" + totalCanastas + "'" + ", totalAsistencias='" + totalAsistencias + "'" + ", totalRebotes='" + totalRebotes + "'" + ", posicion='" + posicion + "'" + '}'; } } <file_sep>package com.example.ligabaloncesto.web.rest; import com.example.ligabaloncesto.Application; import com.example.ligabaloncesto.domain.Estadisticas_jugador_partido; import com.example.ligabaloncesto.repository.Estadisticas_jugador_partidoRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.hamcrest.Matchers.hasItem; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; import javax.inject.Inject; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the Estadisticas_jugador_partidoResource REST controller. * * @see Estadisticas_jugador_partidoResource */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @IntegrationTest public class Estadisticas_jugador_partidoResourceTest { private static final Integer DEFAULT_ASISTENCIAS = 0; private static final Integer UPDATED_ASISTENCIAS = 1; private static final Integer DEFAULT_CANASTAS = 0; private static final Integer UPDATED_CANASTAS = 1; private static final Integer DEFAULT_FALTAS = 0; private static final Integer UPDATED_FALTAS = 1; @Inject private Estadisticas_jugador_partidoRepository estadisticas_jugador_partidoRepository; @Inject private MappingJackson2HttpMessageConverter jacksonMessageConverter; private MockMvc restEstadisticas_jugador_partidoMockMvc; private Estadisticas_jugador_partido estadisticas_jugador_partido; @PostConstruct public void setup() { MockitoAnnotations.initMocks(this); Estadisticas_jugador_partidoResource estadisticas_jugador_partidoResource = new Estadisticas_jugador_partidoResource(); ReflectionTestUtils.setField(estadisticas_jugador_partidoResource, "estadisticas_jugador_partidoRepository", estadisticas_jugador_partidoRepository); this.restEstadisticas_jugador_partidoMockMvc = MockMvcBuilders.standaloneSetup(estadisticas_jugador_partidoResource).setMessageConverters(jacksonMessageConverter).build(); } @Before public void initTest() { estadisticas_jugador_partido = new Estadisticas_jugador_partido(); estadisticas_jugador_partido.setAsistencias(DEFAULT_ASISTENCIAS); estadisticas_jugador_partido.setCanastas(DEFAULT_CANASTAS); estadisticas_jugador_partido.setFaltas(DEFAULT_FALTAS); } @Test @Transactional public void createEstadisticas_jugador_partido() throws Exception { int databaseSizeBeforeCreate = estadisticas_jugador_partidoRepository.findAll().size(); // Create the Estadisticas_jugador_partido restEstadisticas_jugador_partidoMockMvc.perform(post("/api/estadisticas_jugador_partidos") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(estadisticas_jugador_partido))) .andExpect(status().isCreated()); // Validate the Estadisticas_jugador_partido in the database List<Estadisticas_jugador_partido> estadisticas_jugador_partidos = estadisticas_jugador_partidoRepository.findAll(); assertThat(estadisticas_jugador_partidos).hasSize(databaseSizeBeforeCreate + 1); Estadisticas_jugador_partido testEstadisticas_jugador_partido = estadisticas_jugador_partidos.get(estadisticas_jugador_partidos.size() - 1); assertThat(testEstadisticas_jugador_partido.getAsistencias()).isEqualTo(DEFAULT_ASISTENCIAS); assertThat(testEstadisticas_jugador_partido.getCanastas()).isEqualTo(DEFAULT_CANASTAS); assertThat(testEstadisticas_jugador_partido.getFaltas()).isEqualTo(DEFAULT_FALTAS); } @Test @Transactional public void getAllEstadisticas_jugador_partidos() throws Exception { // Initialize the database estadisticas_jugador_partidoRepository.saveAndFlush(estadisticas_jugador_partido); // Get all the estadisticas_jugador_partidos restEstadisticas_jugador_partidoMockMvc.perform(get("/api/estadisticas_jugador_partidos")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.[*].id").value(hasItem(estadisticas_jugador_partido.getId().intValue()))) .andExpect(jsonPath("$.[*].asistencias").value(hasItem(DEFAULT_ASISTENCIAS))) .andExpect(jsonPath("$.[*].canastas").value(hasItem(DEFAULT_CANASTAS))) .andExpect(jsonPath("$.[*].faltas").value(hasItem(DEFAULT_FALTAS))); } @Test @Transactional public void getEstadisticas_jugador_partido() throws Exception { // Initialize the database estadisticas_jugador_partidoRepository.saveAndFlush(estadisticas_jugador_partido); // Get the estadisticas_jugador_partido restEstadisticas_jugador_partidoMockMvc.perform(get("/api/estadisticas_jugador_partidos/{id}", estadisticas_jugador_partido.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(estadisticas_jugador_partido.getId().intValue())) .andExpect(jsonPath("$.asistencias").value(DEFAULT_ASISTENCIAS)) .andExpect(jsonPath("$.canastas").value(DEFAULT_CANASTAS)) .andExpect(jsonPath("$.faltas").value(DEFAULT_FALTAS)); } @Test @Transactional public void getNonExistingEstadisticas_jugador_partido() throws Exception { // Get the estadisticas_jugador_partido restEstadisticas_jugador_partidoMockMvc.perform(get("/api/estadisticas_jugador_partidos/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateEstadisticas_jugador_partido() throws Exception { // Initialize the database estadisticas_jugador_partidoRepository.saveAndFlush(estadisticas_jugador_partido); int databaseSizeBeforeUpdate = estadisticas_jugador_partidoRepository.findAll().size(); // Update the estadisticas_jugador_partido estadisticas_jugador_partido.setAsistencias(UPDATED_ASISTENCIAS); estadisticas_jugador_partido.setCanastas(UPDATED_CANASTAS); estadisticas_jugador_partido.setFaltas(UPDATED_FALTAS); restEstadisticas_jugador_partidoMockMvc.perform(put("/api/estadisticas_jugador_partidos") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(estadisticas_jugador_partido))) .andExpect(status().isOk()); // Validate the Estadisticas_jugador_partido in the database List<Estadisticas_jugador_partido> estadisticas_jugador_partidos = estadisticas_jugador_partidoRepository.findAll(); assertThat(estadisticas_jugador_partidos).hasSize(databaseSizeBeforeUpdate); Estadisticas_jugador_partido testEstadisticas_jugador_partido = estadisticas_jugador_partidos.get(estadisticas_jugador_partidos.size() - 1); assertThat(testEstadisticas_jugador_partido.getAsistencias()).isEqualTo(UPDATED_ASISTENCIAS); assertThat(testEstadisticas_jugador_partido.getCanastas()).isEqualTo(UPDATED_CANASTAS); assertThat(testEstadisticas_jugador_partido.getFaltas()).isEqualTo(UPDATED_FALTAS); } @Test @Transactional public void deleteEstadisticas_jugador_partido() throws Exception { // Initialize the database estadisticas_jugador_partidoRepository.saveAndFlush(estadisticas_jugador_partido); int databaseSizeBeforeDelete = estadisticas_jugador_partidoRepository.findAll().size(); // Get the estadisticas_jugador_partido restEstadisticas_jugador_partidoMockMvc.perform(delete("/api/estadisticas_jugador_partidos/{id}", estadisticas_jugador_partido.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<Estadisticas_jugador_partido> estadisticas_jugador_partidos = estadisticas_jugador_partidoRepository.findAll(); assertThat(estadisticas_jugador_partidos).hasSize(databaseSizeBeforeDelete - 1); } }
966ca96c2a3692bf0a402f734085e3d839ab318b
[ "JavaScript", "Java" ]
4
Java
victorcv/BaloncestoJH
2308bf9381168d16f88ce4456b3b421a4b9a2cec
999db9c1f22952e0175d5b95a328c30bf31e1bbd
refs/heads/main
<repo_name>SDC-Willow/SDC-Willow<file_sep>/README.md # System Design Capstone - Hack Reactor - RPP29 - Team Willow *Project Owners: <NAME>, <NAME> and <NAME>* ## Project Overview Create FEC's API ### Table of Contents - [Description](#description) - [Installation](#installation) ## Description TBA ## Installation - Clone to local machine - Create .env file from example.env - Run NPM install to install all necessary dependencies - Run NPM start to transpile code into bundle.js file - Run NPM run server to run express server locally - To view in the browser, go to localhost:4000 in your broswer of choice <file_sep>/server/routes/reviews.js const router = require('express').Router(); const { getReviews, getMeta, putHelp, postReview, putReport } = require('../helpers/reviews_helpers.js'); router.get('/reviews', (req, res) => { getReviews(req.query.productId, req.query.sort).then((results) => { res.send(results); }).catch((err) => { res.send([]); }); }); router.put('/reviews/helpful', (req, res) => { console.log('🦜', req.query.review_id) putHelp(req.query.review_id).then((response) => { res.end(); }).catch((err) => console.log(err)); }); router.get('/reviews/meta', (req, res) => { getMeta(req.query.product_id).then((results) => { res.send(results); }).catch((err) => res.send([])); }); router.put('/reviews/report', (req, res) => { putReport(req.query.review_id).then((results) => res.end()); }); router.post('/reviews', (req, res) => { postReview(req.body).then((response) => res.send('Success')).catch((err) => console.log(err)); }); module.exports = router;
d514a2f253cf3753216724ab95c781a2fc1833d5
[ "Markdown", "JavaScript" ]
2
Markdown
SDC-Willow/SDC-Willow
ccfa79476bfd330c9b50b11c8987dde20c0aa85a
64d4f4c15e4ed4bbc7275007599a61e82aaffccf
refs/heads/master
<file_sep>[![Build Status](https://travis-ci.org/systelab/identity-service.svg?branch=master)](https://travis-ci.org/systelab/identity-service) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/7ce4e563c45b4d09a975d61bed7d5d50)](https://www.codacy.com/app/systelab/identity-service?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=systelab/identity-service&amp;utm_campaign=Badge_Grade) [![Known Vulnerabilities](https://snyk.io/test/github/systelab/identity-service/badge.svg?targetFile=pom.xml)](https://snyk.io/test/github/systelab/identity-service?targetFile=pom.xml) # Identity Service This project is simple microservice. ## Getting Started To get you started you can simply clone the `identity-service` repository and install the dependencies: ### Prerequisites You need [git][git] to clone the `identity-service` repository. You will need [Java™ SE Development Kit 8][jdk-download] and [Maven][maven]. ### Clone `identity-service` Clone the `identity-service` repository using git: ```bash git clone https://github.com/systelab/identity-service.git cd identity-service ``` ### Install Dependencies In order to install the dependencies and generate the Uber jar you must run: ```bash mvn clean install ``` ### Run To launch the server, simply run with java -jar the generated jar file. ```bash cd target java -jar identity-service-1.0.jar ``` ## API You will find the swagger UI at http://localhost:9090/swagger-ui.html ## Docker ### Build docker image There is an Automated Build Task in Docker Cloud in order to build the Docker Image. This task, triggers a new build with every git push to your source code repository to create a 'latest' image. There is another build rule to trigger a new tag and create a 'version-x.y.z' image You can always manually create the image with the following command: ```bash docker build -t systelab/identity-service . ``` ### Run the container ```bash docker run -p 9090:9090 systelab/identity-service ``` The app will be available at http://localhost:9090/swagger-ui.html [git]: https://git-scm.com/ [sboot]: https://projects.spring.io/spring-boot/ [maven]: https://maven.apache.org/download.cgi [jdk-download]: http://www.oracle.com/technetwork/java/javase/downloads [JEE]: http://www.oracle.com/technetwork/java/javaee/tech/index.html <file_sep>package com.systelab.identity.util; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MedicalRecordNumberValidator { /* Format xxx-xx-xxxx, xxxxxxxxx, xxx-xxxxxx; xxxxx-xxxx: ^\\d{3}: Starts with three numeric digits. [- ]?: Followed by an optional "-" \\d{2}: Two numeric digits after the optional "-" [- ]?: May contain an optional second "-" character. \\d{4}: ends with four numeric digits. Examples: 879-89-8989; 869878789 etc. */ public static boolean isValid(String number) { String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$"; CharSequence inputStr = number; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(inputStr); return matcher.matches(); } // Non real algorithm. Just for generate a compliant number public static String generateRandormNumber() { return generateRandormNumber(100,999)+"-"+generateRandormNumber(10,99)+"-"+generateRandormNumber(1000,9999); } private static int generateRandormNumber(int min, int max) { Random r = new Random(); return r.nextInt((max - min) + 1) + min; } } <file_sep>package com.systelab.identity.controller; import com.systelab.identity.util.InvalidNumberException; import com.systelab.identity.util.MedicalRecordNumberValidator; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @Api(value = "Medical Record Number", description = "API for Medical Record Number", tags = {"Medical Record Number"}) @RestController() @CrossOrigin(origins = "*", allowedHeaders = "*", exposedHeaders = "Authorization", allowCredentials = "true") @RequestMapping(value = "/identity/v1", produces = MediaType.APPLICATION_JSON_VALUE) public class MedicalRecordNumberController { @ApiOperation(value = "Check a Medical Record Number") @GetMapping("medical-record-number/{number}") public ResponseEntity checkRecordNumber(@PathVariable("number") String number) { if (MedicalRecordNumberValidator.isValid(number)) return ResponseEntity.ok().build(); else throw new InvalidNumberException(number); } @ApiOperation(value = "Check a New Medical Record Number") @GetMapping("medical-record-number") public ResponseEntity<String> getRecordNumber() { return ResponseEntity.ok(MedicalRecordNumberValidator.generateRandormNumber()); } }<file_sep>package com.systelab.identity.util; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class InvalidNumberException extends RuntimeException { private final String id; public InvalidNumberException(String id) { super("invalid-number-" + id); this.id = id; } public String getNumber() { return id; } }
16476973892a376fa8e4746093edc360559b6d95
[ "Markdown", "Java" ]
4
Markdown
systelab/identity-service
0aba98c6635f1810e419b2068cd84d7749118d0f
764bfdcdc9e20f1f6b768b33aff37d162c01b12f
refs/heads/master
<repo_name>rebeccaorgan/photoshop<file_sep>/image.h #pragma once #include "EasyBMP.h" class image { public: // constructor, copy constructor and assignment operator image(); image(const image& other); image& operator=(const image& other); // destructor ~image(); private: }; <file_sep>/Makefile CPP_FILES := $(wildcard *.cpp) OBJ_FILES := $(addprefix obj/,$(notdir $(CPP_FILES:.cpp=.o))) CC = g++ CC_FLAGS := -c -g -Wall -Wformat-nonliteral -ggdb -funsigned-char -fno-exceptions -std=c++1y -MMD LD_FLAGS := -g -pthread -pg -std=c++1y -rdynamic .PHONY: clean # create required directories then compile all .cpp files into .o files all: compile_dirs $(OBJ_FILES) main # generates all required directories if they don't yet exist compile_dirs: mkdir -p obj # compile all .cpp files into their respective obj files in obj obj/%.o: %.cpp $(CC) $(CC_FLAGS) -c -o $@ $< main: $(OBJ_FILES) $(CC) -o $@ $(LD_FLAGS) $^ # cleanup clean: rm -rf obj main gmon.out # not sure how this works, but this inspects the dependency graph and rebuilds # everything that depended on the change -include $(OBJ_FILES:.o=.d) <file_sep>/image.cpp // an implementation of the image class #include "image.h" // constructor image::image() { } // copy constructor image::image(const image& other) { } // assignment operator image& image::operator=(const image& other) { if (&other == this) return *this; // prevent self assignment return *this; } // destructor image::~image() { } <file_sep>/main.cpp #include "image.h" #include <string> #include <stdlib.h> // malloc #include <stdio.h> // fprintf // Triple index array. The respective indices are for the specific RGBA channel, // row and column. These bitmaps are all 32 bit RGBA, and will thus have 4 // channels. The canvas size of the image will dictate the exact size of the // other two dimensions int rgba_vals = 4; // TODO: Okay to have global? int rgb_vals = 3; // Header struct HeaderStruct{ uint16_t identifier; // Magic identifier for BMP and DIB file uint32_t data_size; // Int containing size of data uint16_t reserved1; // Value depends on app creating image uint16_t reserved2; // Value depends on app creating image uint32_t data_offset; // In bytes; Where image data starts }; typedef HeaderStruct Header; // Info Header struct InfoHeaderStruct{ uint32_t header_size; // In bytes int32_t width; // Int for image width int32_t height; // Int for image height uint16_t planes; // Number of color planes uint16_t datum_size; // bits per pixel uint32_t compression; // Compression type uint32_t image_size; // In bytes int32_t x_res; int32_t y_res; uint32_t n_colors; // Number of colors uint32_t important_colors; }; typedef InfoHeaderStruct InfoHeader; class Bitmap{ public: Bitmap(uint32_t w, uint32_t h, Header head, InfoHeader i_head); Bitmap(const Bitmap& other); Bitmap& operator=(const Bitmap& other); ~Bitmap(); uint8_t*** data; uint32_t width; uint32_t height; Header header; InfoHeader info_header; private: }; // (1) default constructor, creates a 1x1 image which is completely black and // opaque. Note that black and opaque implies an RGBA value of (0,0,0,0) Bitmap::Bitmap(uint32_t w, uint32_t h, Header my_header, InfoHeader my_info_header) { printf("Inside default constructor.\n"); // Saving dimensions as data members in the class // Copy over other variables besides data width = w; height = h; header = my_header; // TODO: Overload constructor to be able to assign these info_header = my_info_header; // Malloc each of the nested channels and save as rgba for xy data = (uint8_t***) malloc(sizeof(uint8_t***) * 4); for(int rgba = 0; rgba < rgba_vals; rgba++) { data[rgba] = (uint8_t**) malloc(sizeof(uint8_t**) * width ); // TODO: Draw and confirm for(int x = 0; x < width; x++) { data[rgba][x] = (uint8_t*) malloc(sizeof(uint8_t*) * height); for(int y = 0; y < height; y++) { //data[rgba][x][y] = (uint8_t) malloc(sizeof(uint8_t)); data[rgba][x][y] = 0; // Assign RGBA values to zero } } } } // (2) copy constructor. // Deep copy. // Want "this" to be identical to other Bitmap::Bitmap(const Bitmap& other) { // No dimensions because other is already created printf("Inside copy constructor\n"); width = other.width; height = other.height; header = other.header; info_header = other.info_header; // Malloc each of the nested channels and save as rgba for xy data = (uint8_t***) malloc(sizeof(uint8_t***) * 4); for(int rgba = 0; rgba < rgba_vals; rgba++) { data[rgba] = (uint8_t**) malloc(sizeof(uint8_t**) * width ); // TODO: Draw and confirm for(int x = 0; x < width; x++) { data[rgba][x] = (uint8_t*) malloc(sizeof(uint8_t*) * height); for(int y = 0; y < height; y++) { //data[rgba][x][y] = (uint8_t) malloc(sizeof(uint8_t)); data[rgba][x][y] = other.data[rgba][x][y]; // Assign RGBA values to zero } } } } // (3) assignment operator Bitmap& Bitmap::operator=(const Bitmap& other) { printf("Inside assignment operator\n"); //TODO: Check if is same size. Implement destructor and copy constructor? // Copy over other variables besides data width = other.width; height = other.height; header = other.header; info_header = other.info_header; for(int rgba = 0; rgba < rgba_vals; rgba++) { for(int x = 0; x < width; x++) { for(int y = 0; y < height; y++) { data[rgba][x][y] = other.data[rgba][x][y]; } } } } // (4) destructor Bitmap::~Bitmap() { printf("Inside destructor\n"); for(int rgba = 0; rgba < rgba_vals; rgba++) { for(int x = 0; x < width; x++) { free(data[rgba][x]); } free(data[rgba]); } //TODO free(data); //free(width); //free(height); } // (5) creates an empty (ie, completely black and opaque) image. Note that black //and opaque implies an RGBA value of (0,0,0,0). Returns true if the Bitmap was //created and false if the creation fails (eg, due to memory allocation failure). Bitmap create(uint32_t width, uint32_t height, Header header, InfoHeader info_header) { printf("Inside create\n"); Bitmap bmp(width, height, header, info_header); // Call constructor // TODO: Bool based on memory allocation failure and stuff return bmp; } // (6) Lodad bmp Bitmap load_bmp(const std::string& filename) { printf("Inside load_bmp\n"); // Instantiate an object of types both Header and InfoHeader Header header; InfoHeader info_header; // Open the file FILE *fp; fp = fopen(filename.c_str(), "r"); // .c_str() turns std::str into c style char* // Read in all header values fread(&header.identifier, sizeof(header.identifier), 1, fp); fread(&header.data_size, sizeof(header.data_size), 1, fp); fread(&header.reserved1, sizeof(header.reserved1), 1, fp); fread(&header.reserved2, sizeof(header.reserved2), 1, fp); fread(&header.data_offset, sizeof(header.data_offset), 1, fp); fread(&info_header.header_size, sizeof(info_header.header_size), 1, fp); fread(&info_header.width,sizeof(info_header.width), 1, fp); fread(&info_header.height, sizeof(info_header.height), 1, fp); fread(&info_header.planes, sizeof(info_header.planes), 1, fp); fread(&info_header.datum_size, sizeof(info_header.datum_size), 1, fp); fread(&info_header.compression, sizeof(info_header.compression), 1, fp); fread(&info_header.image_size, sizeof(info_header.image_size), 1, fp); fread(&info_header.x_res, sizeof(info_header.x_res), 1, fp); fread(&info_header.y_res, sizeof(info_header.y_res), 1, fp); fread(&info_header.n_colors, sizeof(info_header.n_colors), 1, fp); fread(&info_header.important_colors, sizeof(info_header.important_colors), 1, fp); // TODO: Why are width and height so big when I loaded the picture, saved it, then loaded my saved picture? printf("Data_size: %u, Data_offset: %u\n", header.data_size, header.data_offset); printf("Width: %u, Height: %u\n", info_header.width, info_header.height); // Make Bitmap image based on these dimensions Bitmap new_bmp = create(info_header.width, info_header.height, header, info_header); // Assign Header and InfoHeader // TODO: Switch statement. Get error for redefining datum. // Now you know bits per pixel, can create individual pixel value (datum) to // be extracted from image and fed into matrix piecemeal. According to // wikipedia. Typical values are 1, 4, 8, 16, 24, and 32. Also, // rgba_cap determines how many channels to look for based on size of pixel // datum (how many bits per pixel) int rgba_cap; if(info_header.datum_size == 8) { // Assuming 8 bit indexed color, not grayscale // 3 bits for red, 3 for green, 2 for blue uint8_t datum; rgba_cap = 1; } else if(info_header.datum_size == 24) { uint32_t datum; rgba_cap = 3; } else if(info_header.datum_size == 32) { uint32_t datum; rgba_cap = 4; } // TODO: Is this redundant from above? // Single data piece to be fed into matrix piecewise uint8_t datum; // Go to start of data and one by one store to matrix fseek(fp, header.data_offset, SEEK_SET); // fseek returns the current offset int row_count = new_bmp.height; int col_count = new_bmp.width; // Scanning left to right, top to bottom (raster scanning) for(int y = 0; y < row_count; y++) { for(int x = 0; x < col_count; x++) { for(int rgba = 0; rgba < rgba_cap; rgba++) { // alpha value is 0 here // printf("Location within pointer: %ld\n", ftell(fp)); fread(&datum, 1, 1, fp); // div by 8 to convert to bytes, by 4 for rgba component // printf("%d\n", datum); new_bmp.data[rgba][x][y] = (float) datum; } } } // Print some relevant stats printf("----Bits per pixel (datum_size): %d\n", info_header.datum_size); printf("----Measured data size: %d\n", ftell(fp)-header.data_offset); printf("----Width: %d\n", info_header.width); printf("----Height: %d\n", info_header.height); fclose(fp); return new_bmp; } // (7) saves the Bitmap into a bitmap file. Returns true if the bitmap was // successfully written to disk and false otherwise. bool save_bmp(Bitmap &bmp, const std::string& filename) { // TODO: Why signature like this? printf("Inside save_bmp\n"); // Change data_offset to 54 because we're going to store data after headers bmp.header.data_offset = 54; Header header = bmp.header; InfoHeader info_header = bmp.info_header; FILE *fp; fp = fopen(filename.c_str(), "w+"); // .c_str() turns std::str into c style char* // Write Header fwrite(&header.identifier, sizeof(header.identifier), 1, fp); fwrite(&header.data_size, sizeof(header.data_size), 1, fp); fwrite(&header.reserved1, sizeof(header.reserved1), 1, fp); fwrite(&header.reserved2, sizeof(header.reserved2), 1, fp); fwrite(&header.data_offset, sizeof(header.data_offset), 1, fp); // Write HeaderInfo fwrite(&info_header.header_size, sizeof(info_header.header_size), 1, fp); fwrite(&info_header.width, sizeof(info_header.width), 1, fp); fwrite(&info_header.height, sizeof(info_header.height), 1, fp); fwrite(&info_header.planes, sizeof(info_header.planes), 1, fp); fwrite(&info_header.datum_size, sizeof(info_header.datum_size), 1, fp); fwrite(&info_header.compression, sizeof(info_header.compression), 1, fp); fwrite(&info_header.image_size, sizeof(info_header.image_size), 1, fp); fwrite(&info_header.x_res, sizeof(info_header.x_res), 1, fp); fwrite(&info_header.y_res, sizeof(info_header.y_res), 1, fp); fwrite(&info_header.n_colors, sizeof(info_header.n_colors), 1, fp); fwrite(&info_header.important_colors, sizeof(info_header.important_colors), 1, fp); // TODO: Switch statement. Get error for redefining datum. // Now you know bits per pixel, can create individual pixel value (datum) to // be extracted from image and fed into matrix piecemeal. According to // wikipedia. Typical values are 1, 4, 8, 16, 24, and 32. Also, // rgba_cap determines how many channels to look for based on size of pixel // datum (how many bits per pixel) int rgba_cap; if(info_header.datum_size == 8) { // Assuming 8 bit indexed color, not grayscale uint8_t datum; rgba_cap = 3; } else if(info_header.datum_size == 24) { uint32_t datum; rgba_cap = 3; } else if(info_header.datum_size == 32) { uint32_t datum; rgba_cap = 4; } // TODO: Is this redundant from above? // Single data piece to be fed into matrix piecewise uint8_t datum; // Go to start of data and one by one store from matrix fseek(fp, header.data_offset, SEEK_SET); // Should already be here int row_count = info_header.height; int col_count = info_header.width; // Order is raster scan, left to right, top to bottom for(int y = 0; y < row_count; y++) { for(int x = 0; x < col_count; x++) { for(int rgba = 0; rgba < rgba_cap; rgba++) { // alpha value is 0 here fwrite(&bmp.data[rgba][x][y], sizeof(bmp.data[rgba][x][y]), 1, fp); // fprintf(fp, "%d", bmp.data[rgba][x][y]); } } } fclose(fp); } // (8) clears every pixel in the Bitmap image to the given color. Bitmap clear(Bitmap &bmp, uint8_t r , uint8_t g, uint8_t b, uint8_t a) { printf("Inside clear\n"); // Store the rgba parameters in an array in same order as that in Bitmap data // Note: blue and red order is inverted to match bitmap file type uint8_t rgba_array[4]; rgba_array[0] = b; rgba_array[1] = g; rgba_array[2] = r; rgba_array[3] = a; // Assign all values for(int y = 0; y < bmp.height; y++) { for(int x = 0; x < bmp.width; x++) { for(int rgba = 0; rgba < rgba_vals; rgba++) { bmp.data[rgba][x][y] = rgba_array[rgba]; } } } return bmp; } // (9) flips the image horizontally, identical to the corresponding Photoshop // operation. Bitmap horizontal_flip(Bitmap &bmp) { printf("Inside horizontal_flip()\n"); uint8_t temp; // rgba value uint32_t w = bmp.width; uint32_t h = bmp.height; int x_mid; if(w % 2) { // height is odd x_mid = (w + 1) / 2; } else { // height is even x_mid = w / 2; } // Assign all values for(int y = 0; y < h; y++) { for(int x = 0; x <= x_mid; x++) { for(int rgba = 0; rgba < rgba_vals; rgba++) { temp = bmp.data[rgba][x][y]; bmp.data[rgba][x][y] = bmp.data[rgba][w-1-x][y]; bmp.data[rgba][w-1-x][y] = temp; // printf("Temp: %d, x: %d, oppoxite x: %d, y: %d\n", temp, x, w-1-x, y); } } } return bmp; } // (10) flips the image vertically, identical to the corresponding Photoshop // operation. Bitmap vertical_flip(Bitmap &bmp) { printf("Inside vertical_flip()\n"); uint8_t temp; // rgba value uint32_t w = bmp.width; uint32_t h = bmp.height; int y_mid; // halfway mark; stopping point for why in inner for loop if(h % 2) { // height is odd y_mid = (h + 1) / 2; } else { // height is even y_mid = h / 2; } // Assign all values for(int y = 0; y <= y_mid; y++) { for(int x = 0; x < w; x++) { for(int rgba = 0; rgba < rgba_vals; rgba++) { temp = bmp.data[rgba][x][y]; bmp.data[rgba][x][y] = bmp.data[rgba][x][h-1-y]; bmp.data[rgba][x][h-1-y] = temp; } } } return bmp; } // (11) performs a blur on the image. For each pixel p in the original image, // its new RGBA value should be the average of the 9 pixels centered on p (ie, // average of the top left, top middle, top right, center left, p, center right, // bottom left, bottom middle and bottom right). You probably cannot operate //in-situ on the current image and you'll need to create a new temporary image //to write to. Bitmap blur(Bitmap &bmp) { printf("Inside blur\n"); Bitmap temp_bmp = bmp; uint32_t h = bmp.height; uint32_t w = bmp.width; uint32_t neighbor_pixel_sum; //TODO: Just have temp_bmp and have new values go over to that one. Deep copy // it over at end to bmp that gets returned // TODO: Borders // All but borders for(int y = 1; y < h - 1; y++) { for(int x = 1; x < w - 1; x++) { // TODO: confirm -1 for(int rgba = 0; rgba < rgba_vals; rgba++) { neighbor_pixel_sum = bmp.data[rgba][x-1][y+1] + bmp.data[rgba][x][y+1] + bmp.data[rgba][x+1][y+1] + bmp.data[rgba][x-1][y] + bmp.data[rgba][x][y] + bmp.data[rgba][x][y+1] + bmp.data[rgba][x-1][y-1] + bmp.data[rgba][x][y-1] + bmp.data[rgba][x+1][y-1]; temp_bmp.data[rgba][x][y] = neighbor_pixel_sum / 9; } } } printf("Marker\n"); bmp = temp_bmp; // Deep copy using copy constructor return bmp; } // (12; bonus) blends a given image with the current image at the specified // transparency level. For simplicity, you can assume the two input images will // have the same height and width. You'll need to perform some calculations to // determine the final color at each pixel position. Bitmap blend(const Bitmap &orig_bmp, const Bitmap& other_bmp, uint8_t transparency) { printf("Inside blend\n"); //TODO: Check the two are same dimensions uint32_t h = orig_bmp.height; uint32_t w = orig_bmp.width; Header header = orig_bmp.header; InfoHeader info_header = orig_bmp.info_header; float percentage = transparency / (float) 256; Bitmap blend_bmp = create(w, h, header, info_header); for(int rgba = 0; rgba < rgba_vals; rgba++) { for(int x = 0; x < w; x++) { for(int y = 0; y < h; y++) { blend_bmp.data[rgba][x][y] = (int) (orig_bmp.data[rgba][x][y]*(1-percentage)) + (other_bmp.data[rgba][x][y]*percentage); } } } return blend_bmp; } Bitmap scale(const Bitmap &bmp, float magnitude) { Bitmap new_bmp = create(bmp.width * magnitude, (bmp.height * magnitude), bmp.header, bmp.info_header); uint32_t h = bmp.height * magnitude; uint32_t w = bmp.width * magnitude; // Update header file new_bmp.height = h; new_bmp.width = w; new_bmp.info_header.height = h; new_bmp.info_header.width = w; for(int rgba = 0; rgba < rgba_vals; rgba++) { for(int x = 0; x < w; x++) { for(int y = 0; y < h; y++) { new_bmp.data[rgba][x][y] = bmp.data[rgba][int(x/magnitude)][int(y/magnitude)]; } } } return new_bmp; } // (13) prints out the matrix values of an image void print_data(Bitmap &bmp) { printf("Inside print data\n"); uint32_t h = bmp.height; uint32_t w = bmp.width; printf("\n"); for(int rgba = 0; rgba < rgba_vals; rgba++) { for(int x = 0; x < w; x++) { for(int y = 0; y < h; y++) { printf("%d ", bmp.data[rgba][x][y]); } printf("\n"); // Print new line at end of row } printf("\n"); // Print extra space between matrices } } // (14) prints out the header values of an image void print_header(Bitmap &bmp) { printf("Inside print header\n"); Header header = bmp.header; InfoHeader info_header = bmp.info_header; // Header printf("identifier: %u\n" "data_size: %u\n" "reserved1: %u\n" "reserved2: %u\n" "data_offset: %u\n", header.identifier, header.data_size, header.reserved1, header.reserved2, header.data_offset); // InfoHeader printf("header_size: %u\n" "width: %d\n" "height: %d\n" "planes: %u\n" "datum_size: %u\n" "compression: %u\n" "image_size: %u\n" "x_res: %d\n" "y_res: %d\n" "n_colors: %u\n" "important_colors: %u\n", info_header.header_size, info_header.width, info_header.height, info_header.planes, info_header.datum_size, info_header.compression, info_header.image_size, info_header.x_res, info_header.y_res, info_header.n_colors, info_header.important_colors); } // executive entrypoint int main(int argc, char** argv) { // instantiate a copy of the image object type //image img; // Bitmap zeros_bmp = create(5, 6); // Bitmap ones_bmp = clear(zeros_bmp, 1, 1, 1, 1); // Bitmap deciles_bmp = clear(zeros_bmp, 10, 20, 30, 40); // Bitmap edge_deciles_bmp = load("edges.txt"); //my_bmp = vertical_flip(loaded_bmp); //my_bmp = horizontal_flip(loaded_bmp); Bitmap loaded_bmp = load_bmp("picture3.bmp"); // Bitmap loaded_bmp = load_bmp("picture3.bmp"); // Bitmap loaded_bmp2 = load_bmp("picture.bmp"); // print_header(loaded_bmp); // loaded_bmp = clear(loaded_bmp, 128, 0, 0, 0); // loaded_bmp = vertical_flip(loaded_bmp); // loaded_bmp = horizontal_flip(loaded_bmp); // loaded_bmp = blur(loaded_bmp); // loaded_bmp = blend(loaded_bmp1, loaded_bmp2, 128); Bitmap scaled_bmp = scale(loaded_bmp, 10); save_bmp(scaled_bmp, "saved_picture.bmp"); //Bitmap blur_bmp = blur(edge_deciles_bmp); // Bitmap blended_bmp = blend(ones_bmp, deciles_bmp, 128); // print_data(blended_bmp); //save(deciles_bmp, "deciles.txt"); return 0; } // TODO: all todos // TODO: What other functions? set_opacity_percentage() // TODO: Have blend function blend the boundaries / edges // TODO: histogram // TODO: edge detection // TODO: Have a GUI? // TODO: Load picture2.bmp and work with other bitsperpixel
a243a48c8d6b09b6764d9b4c73f3c68c76991ab7
[ "Makefile", "C++" ]
4
C++
rebeccaorgan/photoshop
c5eea91d0640563339dd4b15f4865594b25091e2
24a12f8f730b9a210f59d9b8b44bd05cca83914c
refs/heads/master
<file_sep>#ifndef DEFINITIONS_H #define DEFINITIONS_H const float _version=0.93; const float _time_step=0.01; const float _unit_move_anim_speed=10.0; const float _game_start_time=10.0; const float _move_delay_min=20.0; const float _resend_delay_min=5.0; #endif <file_sep>#include "clientCom.h" clientCom::clientCom() { m_ready=false; } bool clientCom::init(void) { WSADATA w; int error = WSAStartup (0x0202, &w); if (error) { // there was an error return false; } if (w.wVersion != 0x0202) { // wrong WinSock version! WSACleanup (); // unload ws2_32.dll return false; } m_SocServer = socket (AF_INET, SOCK_STREAM, 0); // Create socket (TCP: SOCK_STREAM UDP:SOCK_DGRAM) m_ready=true; m_broadcast_ready=false; m_found_server=false; return true; } bool clientCom::set_IP_and_connect(string sIP,int port) { sockaddr_in target; target.sin_family = AF_INET; // address family Internet target.sin_port = htons (port); // set serverís port number target.sin_addr.s_addr = inet_addr ((const char *)sIP.c_str()); // set serverís IP int err=connect(m_SocServer, (SOCKADDR*) &target, sizeof(target));//will always give error if non-blocking /*if(err!=0) { cout<<err<<endl; cout<<WSAGetLastError()<<endl; }*/ cout<<"Connecting to "<<sIP<<":"<<port<<endl; return true; } bool clientCom::test_connection(void) { fd_set sockets; sockets.fd_count=1; sockets.fd_array[0]=m_SocServer; //set waiting time ell timeval waiting_time; waiting_time.tv_sec=2; waiting_time.tv_usec=2000; //int val=select( 0, &sockets, NULL, NULL, &waiting_time ); int val=select( 0, NULL, &sockets, NULL, &waiting_time ); //cout<<"Connected val: "<<val<<endl; //cout<<WSAGetLastError()<<endl; if(val==1) return true;//connected to one SOCKET, the server return false;//not connected } bool clientCom::broadcast_my_ip(void) { //init socket if(!m_broadcast_ready) { if(!init_broadcast_socket()) return false; else m_broadcast_ready=true; } sockaddr_in addr; int len; addr.sin_addr.s_addr = inet_addr( (const char *)m_broadcast_net.c_str() );//where to send, for broadcasting addr.sin_family = AF_INET; addr.sin_port = htons(m_broadcast_port); len = sizeof(addr); sendto(m_SocUDP_for_broadcasting, (const char*)m_my_IP.c_str(), sizeof(char)*(m_my_IP.length()+1), 0, (struct sockaddr *) &addr, len); cout<<"Broadcasted my IP: "<<m_my_IP<<endl; return true; } bool clientCom::check_for_broadcast_reply(void) { if(!m_broadcast_ready) { cout<<"ERROR: Can not listen to broadcast reply if sockets are not initiated\n"; return false; //sockets not ready } cout<<"Listening for broadcast response...\n"; //listen for broadcast reply char buff[256]={0}; int retVal=recvfrom(m_SocUDP_for_broadcast_reply, buff, sizeof(buff), NULL, NULL, NULL); if(retVal!=-1)//incoming data { cout<<"Received message: "<<buff<<endl; //separate IP and port string sIP; int port; for(int i=0;i<256;i++) //256 is size of buff { if(buff[i]!=':') { sIP.append(1,buff[i]); } else //now comes the port value { string sPort; for(int j=0;j<10;j++) //10 is maximum port value length { if(buff[i+1+j]!='\0') { sPort.append( 1, buff[i+1+j] ); } else //have port value { port=atoi(sPort.c_str());//convert string to int break; } } break; } } //test if buffer contains a valid IP char cIP[30]={0}; strcpy( cIP,sIP.c_str() );//non constant char* needed if( ip_is_valid(cIP) ) { cout<<"Got Server IP: "<<sIP<<", and port: "<<port<<endl; //store values m_found_server=true; m_server_IP=sIP; m_server_port=port; return true; } else //ip not valid { cout<<"Received a bad IP from broadcast reply\n"; } } return false; //no server found } bool clientCom::set_broadcast_net_and_port(string net,int port_sending,int port_replying) { m_broadcast_net=net; //net for broadcasting m_broadcast_port=port_sending; //port for broadcasting m_broadcast_port=port_replying; //port for broadcast reply listening close_broadcast_socket(); m_broadcast_ready=false; return true; } bool clientCom::get_server_IP_and_port(string& IP_and_port) { if(m_found_server) { IP_and_port=m_server_IP; IP_and_port.append(1,':'); //convert int to string //char buff[10]; //itoa(m_server_port, buff, 10); stringstream ss; ss<<m_server_port; IP_and_port.append(ss.str()); return true; } return false; } bool clientCom::send_data(string data_string) { int val=send(m_SocServer,(const char*)data_string.c_str(),sizeof(char)*(data_string.length()+1),0); if(val!=(int)data_string.length()+1) return false;//sent wrong amount return true; } bool clientCom::send_data(float* data_array) { int val=send(m_SocServer,(char*)data_array,sizeof(float)*data_array[0],0); if(val!=int(data_array[0]*sizeof(float))) return false;//sent wrong amount return true; } bool clientCom::send_data(int* data_array) { int val=send(m_SocServer,(char*)data_array,sizeof(int)*data_array[0],0); if(val!=int(data_array[0]*sizeof(int))) return false;//sent wrong amount return true; } bool clientCom::recv_data(string& data_string) { char buffer[256]; int val=recv(m_SocServer,(char*)buffer,sizeof(float)*256,0); data_string=string(buffer); if(val!=(int)data_string.length()+1) return false;//received wrong amount return true; } bool clientCom::recv_data(float* data_array) { int val=recv(m_SocServer,(char*)data_array,sizeof(float)*256,0); if(val!=int(data_array[0]*sizeof(float))) return false;//received wrong amount return true; } bool clientCom::recv_data(int* data_array) { int val=recv(m_SocServer,(char*)data_array,sizeof(int)*256,0); if(val!=int(data_array[0]*sizeof(int))) return false;//received wrong amount return true; } SOCKET clientCom::get_server_socket(void) { return m_SocServer; } bool clientCom::init_broadcast_socket(void) { // Create a datagram socket m_SocUDP_for_broadcasting = socket(AF_INET, SOCK_DGRAM, 0); if(m_broadcast_net.length()<1)//use default net and port { m_broadcast_net="255.255.255.255"; //net for broadcasting m_broadcast_port=5002; //port for broadcasting m_broadcast_port_reply=5003; //port for broadcast listening } //Turn on broadcasting const int broadcast_on = 1; setsockopt(m_SocUDP_for_broadcasting, SOL_SOCKET, SO_BROADCAST,(const char *) &broadcast_on, sizeof(broadcast_on)); //get clients computer name and IP char hostName[80]; if (gethostname(hostName, sizeof(hostName)) == SOCKET_ERROR) { cerr << "ERROR: " << WSAGetLastError() << " when getting local host name." << endl; m_ready=false; return false; } m_my_name=string(hostName); struct hostent* hostInfo = gethostbyname(hostName); if (hostInfo == 0) { cerr << "ERROR: No host name" << endl; m_ready=false; return false; } for (int i = 0; hostInfo->h_addr_list[i] != 0; ++i) { struct in_addr addr; memcpy(&addr, hostInfo->h_addr_list[i], sizeof(struct in_addr)); m_my_IP=string( inet_ntoa(addr) ); break; } //Create socket for listening for broadcast reply m_SocUDP_for_broadcast_reply = socket(AF_INET, SOCK_DGRAM, 0); SOCKADDR_IN addr; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = AF_INET; addr.sin_port = htons(m_broadcast_port_reply); bind(m_SocUDP_for_broadcast_reply,(SOCKADDR*)&addr,sizeof(addr)); u_long nonblocking_on = 1; ioctlsocket(m_SocUDP_for_broadcast_reply, FIONBIO, &nonblocking_on);//now non-blocking return true; } bool clientCom::close_broadcast_socket(void) { if(closesocket(m_SocUDP_for_broadcasting)==0 || closesocket(m_SocUDP_for_broadcast_reply==0)) { cerr << "ERROR: Could not close socket" << endl; m_broadcast_ready=false; return false; } else { m_broadcast_ready=false; } return true; } bool clientCom::ip_is_valid(char *str) { int segs = 0; //Segment count int chcnt = 0; // Character count within segment int accum = 0; // Accumulator for segment //Catch NULL pointer if (str == NULL) return 0; //Process every character in string while(*str != '\0') { //Segment changeover if (*str == '.') { //Must have some digits in segment if (chcnt == 0) return false; //Limit number of segments if (++segs == 4) return false; //Reset segment values and restart loop chcnt = accum = 0; str++; continue; } //Check numeric if ((*str < '0') || (*str > '9')) return false; //Accumulate and check segment if ((accum = accum * 10 + *str - '0') > 255) return false; //Advance other segment specific stuff and continue loop chcnt++; str++; } //Check enough segments and enough characters in last segment if (segs != 3) return false; if (chcnt == 0) return false; //Address okay return true; } <file_sep>#include "key_reroute.h" key_reroute::key_reroute() { report_status=true; } bool key_reroute::init(bool* pKeys_real,bool* pKeys_translated) { m_pKeys_real=pKeys_real; m_pKeys_translated=pKeys_translated; if(report_status) { cout<<"KEY REROUTE: Initialized\n"; } return true; } bool key_reroute::update(void) { //copy key state from the real keys for(int key_i=0;key_i<_key_count;key_i++) { m_pKeys_translated[key_i]=m_pKeys_real[key_i]; } //translate keys bassed of the rules list for(unsigned int rule_i=0;rule_i<m_vec_key_rules.size();rule_i++) { //translate key if(m_pKeys_real[ m_vec_key_rules[rule_i].input ]) { m_pKeys_translated[ m_vec_key_rules[rule_i].output ]=true; //real input key be false if no other rules are involved bool turn_off_real_input_key=true; for(unsigned int rule_b=0;rule_b<m_vec_key_rules.size();rule_b++) { if(m_vec_key_rules[rule_b].output==m_vec_key_rules[rule_i].input && m_pKeys_real[ m_vec_key_rules[rule_b].input ] ) { turn_off_real_input_key=false; break; } } if(turn_off_real_input_key) m_pKeys_translated[ m_vec_key_rules[rule_i].input ]=false; } } return true; } bool key_reroute::set_key_translation(int input_key,int output_key) { m_vec_key_rules.push_back( st_key_rule(input_key,output_key) ); if(report_status) { cout<<"KEY REROUTE: New key rule added: "<<input_key<<", to "<<output_key<<endl; } return true; } bool key_reroute::load_key_translation_from_file(string file_name) { //test if file exists ifstream file(file_name.c_str()); if(file==0) { cout<<"KEY REROUTE: Could not load key rules from file: "<<file_name<<endl; return false; } string line,word; getline(file,line);//skip first line //[key input] [key output] while(getline(file,line)) { stringstream ss(line); ss>>word; int input=(int)atof(word.c_str()); ss>>word; int output=(int)atof(word.c_str()); if(input>-1 && input<_key_count && output>-1 && output<_key_count) { //search for copies bool old_rule=false; for(unsigned int rule_i=0;rule_i<m_vec_key_rules.size();rule_i++) { if(m_vec_key_rules[rule_i].input==input && m_vec_key_rules[rule_i].output==output) { old_rule=true; break; } } //save rule if(!old_rule) m_vec_key_rules.push_back( st_key_rule(input,output) ); } } return true; } bool key_reroute::save_key_translation_to_file(string file_name) { if(m_vec_key_rules.empty()) return true; ofstream file(file_name.c_str()); if(file==0) { cout<<"KEY REROUTE: Could not load key rules from file: "<<file_name<<endl; return false; } file<<"Key configuration: Input_id Output_id\n"; for(unsigned int rule_i=0;rule_i<m_vec_key_rules.size();rule_i++) { file<<m_vec_key_rules[rule_i].input<<" "<<m_vec_key_rules[rule_i].output<<endl; } return true; } bool key_reroute::reset_key_translation(void) { m_vec_key_rules.clear(); if(report_status) { cout<<"KEY REROUTE: Key translation reset\n"; } return true; } <file_sep>#include "serverCom.h" serverCom::serverCom() { m_ready=false; } bool serverCom::init(void) { WSADATA w; int error = WSAStartup (0x0202, &w); if (error) { // there was an error return false; } if (w.wVersion != 0x0202) { // wrong WinSock version! WSACleanup (); // unload ws2_32.dll return false; } m_SocServer = socket (AF_INET, SOCK_STREAM, 0); // Create socket (TCP: SOCK_STREAM UDP:SOCK_DGRAM) m_ready=true; m_broadcast_ready=false; m_broadcast_port=0; return true; } bool serverCom::set_port_and_bind(int port) { m_host_port=port; sockaddr_in addr; // The address structure for a TCP socket addr.sin_family = AF_INET; // Address family Internet addr.sin_port = htons (port); // Assign port to this socket addr.sin_addr.s_addr = htonl (INADDR_ANY); // No destination //Show IP char hostName[80]; if (gethostname(hostName, sizeof(hostName)) == SOCKET_ERROR) { cerr << "ERROR: " << WSAGetLastError() << " when getting local host name." << endl; m_ready=false; return false; } m_host_name=string(hostName); struct hostent* hostInfo = gethostbyname(hostName); if (hostInfo == 0) { cerr << "ERROR: No host name" << endl; m_ready=false; return false; } for (int i = 0; hostInfo->h_addr_list[i] != 0; ++i) { struct in_addr addr; memcpy(&addr, hostInfo->h_addr_list[i], sizeof(struct in_addr)); m_host_IP=string( inet_ntoa(addr) ); break; } //Bind socket if (bind(m_SocServer, (LPSOCKADDR) &addr, sizeof(addr)) == SOCKET_ERROR) { // error WSACleanup (); // unload WinSock m_ready=false; return false; } cout<<"bind()\n"; return true; } bool serverCom::start_to_listen(int backLog) { if(backLog<1 || backLog>10) return false; if (listen(m_SocServer,10)==SOCKET_ERROR) { // error! unable to listen WSACleanup (); return false; } cout<<"listen()\n"; return true; } bool serverCom::known_socket(SOCKET new_socket) { for(int i=0;i<(int)m_vSocClients.size();i++) { if(m_vSocClients[i]==new_socket) return true; } return false; } bool serverCom::check_for_broadcast(void) { if(!m_broadcast_ready) { if(!init_broadcast_socket()) return false; else m_broadcast_ready=true; } cout<<"Listening for client broadcast...\n"; //listen for broadcast char buff[256]={0}; int retVal=recvfrom(m_SocUDP_for_broadcast_recv, buff, sizeof(buff), NULL, NULL, NULL); if(retVal!=-1)//incoming data { cout<<"Received message: "<<buff<<endl; //test if buffer contains a valid IP if( ip_is_valid(buff) ) { cout<<"Received valid IP: "<<buff<<endl; string sIP(buff); reply_to_broadcaster(sIP); } else //ip not valid { cout<<"Received a bad IP from broadcast\n"; } } return true; } bool serverCom::set_broadcast_port(int port_sending,int port_replying) { m_broadcast_port=port_sending; m_broadcast_port_reply=port_replying; close_broadcast_socket(); m_broadcast_ready=false; return true; } bool serverCom::send_data(string data_string)//send to all clients { bool error_flag=false; for(int i=0;i<(int)m_vSocClients.size();i++) { int val=send(m_vSocClients[i],(char*)data_string.c_str(),sizeof(char)*(data_string.length()+1),0); if(val!=(int)data_string.length()+1) error_flag=true;//received wrong amount } if(error_flag) return false;//error return true; } bool serverCom::send_data(float* data_array)//send to all clients { bool error_flag=false; for(int i=0;i<(int)m_vSocClients.size();i++) { int val=send(m_vSocClients[i],(char*)data_array,sizeof(float)*data_array[0],0); if(val!=int(data_array[0]*sizeof(float))) error_flag=true;//received wrong amount } if(error_flag) return false;//error return true; } bool serverCom::send_data(int* data_array)//send to all clients { bool error_flag=false; for(int i=0;i<(int)m_vSocClients.size();i++) { int val=send(m_vSocClients[i],(char*)data_array,sizeof(int)*data_array[0],0); if(val!=int(data_array[0]*sizeof(int))) error_flag=true;//received wrong amount } if(error_flag) return false;//error return true; } bool serverCom::send_data(string data_string,SOCKET SocReceiver)//send to specific socket { int val=send(SocReceiver,(char*)data_string.c_str(),sizeof(char)*(data_string.length()+1),0); if(val!=(int)data_string.length()+1) return false;//sent wrong amount return true; } bool serverCom::send_data(float* data_array,SOCKET SocReceiver)//send to specific socket { int val=send(SocReceiver,(char*)data_array,sizeof(float)*data_array[0],0); if(val!=int(data_array[0]*sizeof(float))) return false;//sent wrong amount return true; } bool serverCom::recv_data(string& data_string,SOCKET SocSender) { char buffer[256]; int val=recv(SocSender,(char*)buffer,sizeof(float)*256,0); data_string=string(buffer); if(val!=(int)data_string.length()+1) return false;//received wrong amount return true; } bool serverCom::recv_data(float* data_array,SOCKET SocSender) { int val=recv(SocSender,(char*)data_array,sizeof(float)*256,0); if(val!=int(data_array[0]*sizeof(float))) return false;//received wrong amount return true; } bool serverCom::recv_data(int* data_array) { //assume only one client if(m_vSocClients.size()>1) { cout<<"ERROR: NETCOM: More Clients than expected\n"; return false; } else if(m_vSocClients.size()==0) { cout<<"ERROR: NETCOM: Too few Clients than expected\n"; return false; } int val=recv(m_vSocClients[0],(char*)data_array,sizeof(int)*256,0); if(val!=int(data_array[0]*sizeof(int))) return false;//received wrong amount return true; } bool serverCom::add_client(SOCKET new_client) { SOCKET accepted_client=accept(new_client, NULL, NULL); if(accepted_client==INVALID_SOCKET) return false; //bad socket m_vSocClients.push_back(accepted_client); //good socket return true; } bool serverCom::remove_client(SOCKET client_to_remove) { for(int i=0;i<(int)m_vSocClients.size();i++) { if(m_vSocClients[i]==client_to_remove) { m_vSocClients.erase( m_vSocClients.begin()+i ); return true; } } return false;//client not found } SOCKET serverCom::get_server_socket(void) { return m_SocServer; } bool serverCom::init_broadcast_socket(void) { m_SocUDP_for_broadcast_recv = socket(AF_INET, SOCK_DGRAM, 0); if(m_broadcast_port==0) { m_broadcast_port=5002; //default value m_broadcast_port_reply=5003; //default value } SOCKADDR_IN addr; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = AF_INET; addr.sin_port = htons(m_broadcast_port); bind(m_SocUDP_for_broadcast_recv,(SOCKADDR*)&addr,sizeof(addr)); u_long on = 1; ioctlsocket(m_SocUDP_for_broadcast_recv, FIONBIO, &on);//now non-blocking return true; } bool serverCom::reply_to_broadcaster(string sIP) { //create UDP socket SOCKET broadcasterSocket = socket(AF_INET, SOCK_DGRAM, 0); sockaddr_in addr; int len; addr.sin_addr.s_addr = inet_addr( (const char *)sIP.c_str() ); addr.sin_family = AF_INET; addr.sin_port = htons(m_broadcast_port_reply); len = sizeof(addr); string IP_and_port; IP_and_port.append(m_host_IP); IP_and_port.append(1,':'); stringstream ss; ss<<m_host_port; //char buff[10]; //itoa(m_host_port, buff, 10); IP_and_port.append(ss.str()); //send Server IP sendto(broadcasterSocket, (const char*)IP_and_port.c_str(), sizeof(char)*(IP_and_port.length()+1), 0, (struct sockaddr *) &addr, len); cout<<"Replyed Server IP to Client IP: "<<IP_and_port<<endl; return true; } bool serverCom::close_broadcast_socket(void) { if(closesocket(m_SocUDP_for_broadcast_recv)==0) { cerr << "ERROR: Could not close socket" << endl; m_broadcast_ready=false; return false; } else { m_broadcast_ready=false; } return true; } bool serverCom::ip_is_valid(char *str) { int segs = 0; //Segment count int chcnt = 0; // Character count within segment int accum = 0; // Accumulator for segment //Catch NULL pointer if (str == NULL) return 0; //Process every character in string while(*str != '\0') { //Segment changeover if (*str == '.') { //Must have some digits in segment if (chcnt == 0) return false; //Limit number of segments if (++segs == 4) return false; //Reset segment values and restart loop chcnt = accum = 0; str++; continue; } //Check numeric if ((*str < '0') || (*str > '9')) return false; //Accumulate and check segment if ((accum = accum * 10 + *str - '0') > 255) return false; //Advance other segment specific stuff and continue loop chcnt++; str++; } //Check enough segments and enough characters in last segment if (segs != 3) return false; if (chcnt == 0) return false; //Address okay return true; } <file_sep>#ifndef SOUND_LIST_H #define SOUND_LIST_H //List of all in game sounds enum sounds { wav_beep1=0 }; #endif <file_sep>#ifndef CLIENTCOM_H #define CLIENTCOM_H #include <iostream> //For Debug #include <sstream> #include <stdlib.h> //For itoa() #include <string> #include <vector> #include <winsock2.h> using namespace std; class clientCom { public: clientCom(); //Variables bool m_ready; //Functions bool init(void); bool set_IP_and_connect(string sIP,int port); bool test_connection(void); bool broadcast_my_ip(void); bool check_for_broadcast_reply(void); bool set_broadcast_net_and_port(string net,int port_sending,int port_replying); bool get_server_IP_and_port(string& IP_and_port); bool send_data(string data_string); bool send_data(float* data_array); bool send_data(int* data_array); bool recv_data(string& data_string); bool recv_data(float* data_array); bool recv_data(int* data_array); SOCKET get_server_socket(void); private: //Variables bool m_broadcast_ready,m_found_server; string m_server_IP,m_my_IP,m_my_name,m_broadcast_net; int m_broadcast_port,m_broadcast_port_reply,m_server_port; SOCKET m_SocServer; SOCKET m_SocUDP_for_broadcasting,m_SocUDP_for_broadcast_reply; //Functions bool init_broadcast_socket(void); bool close_broadcast_socket(void); bool ip_is_valid(char *str); }; #endif // CLIENTCOM_H <file_sep>#include "game.h" game::game() { m_game_state=gs_init; } bool game::init(int* window_size,bool* pKeys_real,bool* pKeys_translated, int* pMouse_pos,bool* pMouse_but,bool reinit) { cout<<"Game: Initialization\n"; m_vec_units.clear(); m_vec_events.clear(); m_vec_pings.clear(); m_vec_rollbacks_to_ignore.clear(); m_vec_history_move.clear(); m_rollback_unconfirmed=false; m_window_size[0]=window_size[0]; m_window_size[1]=window_size[1]; m_pKeys_real=pKeys_real; m_pKeys_translated=pKeys_translated; m_pMouse_pos=pMouse_pos; m_pMouse_but=pMouse_but; m_LMB_trig=false; m_tick_counter=0; m_game_started=m_game_over=m_pause_game=false; m_game_start_countdown_timer=0.0; m_game_start_countdown=(int)_game_start_time; //default val m_static_event_delay=100; m_event_resend_delay=30; m_automove_timer=m_automove_delay=0.1; m_automove_on=false; m_pix_per_unit=(float)m_window_size[0]/8.0; m_player_id=0; m_print_log=false; //load textures and sound if(!reinit) { //texture if(!load_textures()) { return false; } //sound if(!load_sounds()) { return false; } } /*//init gamepads and players for(int i=0;i<4;i++) { m_gamepad[i]=gamepad(i); if( m_gamepad[i].IsConnected() ) m_gamepad_connected[i]=true; else m_gamepad_connected[i]=false; }*/ //m_key_rerouter.init(m_pKeys_real,m_pKeys_translated); //resent board movement for(int x=0;x<8;x++) for(int y=0;y<8;y++) { m_arr_board_movements[x][y]=0; } //place pieces { m_vec_units.push_back(new unit(0,0,ut_tower,2,m_tex_figures)); m_vec_units.push_back(new unit(1,0,ut_horse,2,m_tex_figures)); m_vec_units.push_back(new unit(2,0,ut_runner,2,m_tex_figures)); m_vec_units.push_back(new unit(3,0,ut_king,2,m_tex_figures)); m_vec_units.push_back(new unit(4,0,ut_queen,2,m_tex_figures)); m_vec_units.push_back(new unit(5,0,ut_runner,2,m_tex_figures)); m_vec_units.push_back(new unit(6,0,ut_horse,2,m_tex_figures)); m_vec_units.push_back(new unit(7,0,ut_tower,2,m_tex_figures)); m_vec_units.push_back(new unit(0,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(1,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(2,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(3,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(4,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(5,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(6,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(7,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(0,7,ut_tower,1,m_tex_figures)); m_vec_units.push_back(new unit(1,7,ut_horse,1,m_tex_figures)); m_vec_units.push_back(new unit(2,7,ut_runner,1,m_tex_figures)); m_vec_units.push_back(new unit(3,7,ut_queen,1,m_tex_figures)); m_vec_units.push_back(new unit(4,7,ut_king,1,m_tex_figures)); m_vec_units.push_back(new unit(5,7,ut_runner,1,m_tex_figures)); m_vec_units.push_back(new unit(6,7,ut_horse,1,m_tex_figures)); m_vec_units.push_back(new unit(7,7,ut_tower,1,m_tex_figures)); m_vec_units.push_back(new unit(0,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(1,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(2,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(3,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(4,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(5,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(6,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(7,6,ut_pawn,1,m_tex_figures)); } m_game_state=gs_menu; cout<<"Game: Initialization complete\n"; //online setup m_mp_status=0;//1-Host, 2-Join //text file read ifstream settings_file("Multiplayer_Settings.txt"); if(settings_file==0) { settings_file.close(); //create new file ofstream print_file("Multiplayer_Settings.txt"); if(print_file==0) { cout<<"ERROR: Could not create file Multiplayer_Settings.txt\n"; return false; } print_file<<"Rapid Chess Multiplayer Settings\n"; print_file<<"Enter Host/Join status below:\n"; print_file<<"HOST\n"; print_file<<"\n"; print_file<<"\n"; print_file<<"\n"; print_file<<"\n"; print_file<<"\n"; print_file<<"\n"; print_file<<"How to HOST a game\n"; print_file<<"********************************\n"; print_file<<"Rapid Chess Multiplayer Settings\n"; print_file<<"Enter Host/Join status below:\n"; print_file<<"HOST\n"; print_file<<"********************************\n"; print_file<<"\n"; print_file<<"\n"; print_file<<"\n"; print_file<<"\n"; print_file<<"How to JOIN a game\n"; print_file<<"********************************\n"; print_file<<"Rapid Chess Multiplayer Settings\n"; print_file<<"Enter Host/Join status below:\n"; print_file<<"JOIN\n"; print_file<<"192.168.1.1\n"; print_file<<"********************************\n"; print_file<<"\n"; print_file<<"\n"; print_file.close(); } else//read file { string line; getline(settings_file,line); getline(settings_file,line); getline(settings_file,line); //enable automove if(line=="AUTOMOVE ON") { cout<<"AUTOMOVE is ON\n"; m_automove_on=true; } //host/join getline(settings_file,line); if(line=="HOST") { m_mp_status=ps_hoster; } else if(line=="JOIN") { m_mp_status=ps_joiner; //get IP //default port is 5001 getline(settings_file,line); m_host_ip=line; } else if(line=="NONE") { m_mp_status=ps_none; } else { cout<<"ERROR: Bad Multiplayer_Settings.txt file\n"; return false; } settings_file.close(); } /*//console read cout<<"\n[H]ost or [J]oin game: "; string line; getline(cin,line); while(getline(cin,line)) { if(line=="H" || line=="h" || line=="Host" || line=="host") mp_status=1; if(line=="J" || line=="j" || line=="Join" || line=="join") mp_status=2; if(mp_status==0) { cout<<"\nInvalid option, please type Host or Join: "; } else break; } switch(mp_status) { case 0: cout<<"ERROR: Bad selection\n"; return false; case 1: cout<<"\nYou will HOST a game\n"; break; case 2: cout<<"You will JOIN a game\n"; break; }*/ m_game_state=gs_in_game; //create log file if(true) { m_print_log=true; time_t t = time(0);// get time now struct tm * now = localtime( & t ); string time_now("LOG_"); stringstream ss; if((now->tm_year-100)<10) ss<<"0"; ss<<(now->tm_year-100); if((now->tm_mon+1)<10) ss<<"0"; ss<<(now->tm_mon+1); if((now->tm_mday)<10) ss<<"0"; ss<<now->tm_mday; ss<<"_"; if((now->tm_hour)<10) ss<<"0"; ss<<now->tm_hour; if((now->tm_min)<10) ss<<"0"; ss<<now->tm_min; if((now->tm_sec)<10) ss<<"0"; ss<<now->tm_sec; time_now.append(ss.str()); time_now.append(".txt"); cout<<"Log data will be printed in: "<<time_now<<endl;; m_log.open(time_now.c_str()); if(m_log==0) { cout<<"ERROR: Could not create logfile\n"; m_print_log=false; } } return true; } bool game::update(bool& quit_flag) { /*//get gamepad data st_gamepad_data gamepad_data[4]; for(int gamepad_i=0;gamepad_i<4;gamepad_i++) { if( m_gamepad[gamepad_i].IsConnected() ) { //test if new connection if(!m_gamepad_connected[gamepad_i]) { cout<<"Gamepad: New controller conencted: "<<gamepad_i+1<<endl; } m_gamepad_connected[gamepad_i]=true; } else//lost controller { if( m_gamepad_connected[gamepad_i] )//had connection and lost it { m_gamepad_connected[gamepad_i]=false; cout<<"Gamepad: Lost connection to controller: "<<gamepad_i+1<<endl; } } } //update key rerouter m_key_rerouter.update();*/ switch(m_game_state) { case gs_init: { //nothing }break; case gs_menu: { //nothing }break; case gs_in_game: { if(m_pause_game) break; //update tick m_tick_counter++; //start timer if(!m_game_started && m_game_start_countdown_timer>0.0) { m_game_start_countdown_timer-=_time_step; //start if(m_game_start_countdown_timer<=0) { m_game_started=true; m_game_start_countdown_timer=0; cout<<"Match has started!\n"; //calc ping if(m_player_id==ps_hoster) { float ping_avg=0; float ping_max=0; for(int i=0;i<(int)m_vec_pings.size();i++) { ping_avg+=m_vec_pings[i]; if(m_vec_pings[i]>ping_max) ping_max=m_vec_pings[i]; cout<<m_vec_pings[i]<<endl; } ping_avg/=(float)m_vec_pings.size(); m_ping_avg=ping_avg; if(m_vec_pings.empty() || ping_max>1000.0) { cout<<"WARNING: Bad connection, abort game\n"; return false; } cout<<"Average ping: "<<m_ping_avg<<"\tMax ping: "<<ping_max<<endl; //set send settings m_static_event_delay=(ping_max+1)*2; if(m_static_event_delay<2) m_static_event_delay=2; m_event_resend_delay=int((float)m_static_event_delay/4.0); if(m_event_resend_delay<1) m_event_resend_delay=1; //set min values if(m_static_event_delay<_move_delay_min) m_static_event_delay=_move_delay_min; if(m_event_resend_delay<_resend_delay_min) m_event_resend_delay=_resend_delay_min; //m_event_resend_delay=m_static_event_delay;//TEMP if(m_print_log) { m_log<<"Event delay: "<<m_static_event_delay<<"\tResend delay: "<<m_event_resend_delay<<endl; } cout<<"Event delay: "<<m_static_event_delay<<"\tResend delay: "<<m_event_resend_delay<<endl; //send to client m_vec_events.push_back(st_event(m_static_event_delay,m_event_resend_delay)); } } else { //print progress if((int)m_game_start_countdown_timer<m_game_start_countdown) { for(int i=0;i<m_game_start_countdown-1;i++) cout<<"-"; cout<<m_game_start_countdown<<endl; m_game_start_countdown--; //ping if(m_player_id==ps_hoster) m_vec_events.push_back( st_event(m_tick_counter) ); } } } //check for active events for(int event_i=0;event_i<(int)m_vec_events.size();event_i++) { //ping if(m_vec_events[event_i].type==et_ping) { send_data(m_vec_events[event_i]); m_vec_events.erase(m_vec_events.begin()+event_i); event_i--; continue; } //settings if(m_vec_events[event_i].type==et_settings) { send_data(m_vec_events[event_i]); m_vec_events.erase(m_vec_events.begin()+event_i); event_i--; continue; } //rollback request/resend if(m_vec_events[event_i].type==et_rollback) { //if player is owner, resend if(m_vec_events[event_i].owner==m_player_id) { m_vec_events[event_i].resend_counter--; if(m_vec_events[event_i].resend_counter<=0) { m_vec_events[event_i].resend_counter=m_event_resend_delay; //resend if(!send_data(m_vec_events[event_i])) { cout<<"ERROR: Could not resend data\n"; } } } else//if player is not owner, do rollback { rollback(m_vec_events[event_i].tick_target); //reset tick m_tick_counter=m_rollback_tick_target; } continue; } //rollback confirmation if(m_vec_events[event_i].type==et_rollback_confirmation) { //should rollback be ignored, check list bool ignore_rollback=false; for(int i=0;i<(int)m_vec_rollbacks_to_ignore.size();i++) { if(m_vec_rollbacks_to_ignore[i]==m_vec_events[event_i].tick_target) { ignore_rollback=true; break; } } //m_vec_rollbacks_to_ignore if(ignore_rollback) { //delete this event m_vec_events.erase(m_vec_events.begin()+event_i); } else//do not ignore { //store rollback in ignore list m_vec_rollbacks_to_ignore.push_back(m_vec_events[event_i].tick_target); //allow game input, game resumed m_rollback_unconfirmed=false; //reset tick m_tick_counter=m_rollback_tick_target; //remove other events (to remove resend event) m_vec_events.clear(); return true; } } //movement //check if event is ready and confirmed if((m_vec_events[event_i].tick_target==m_tick_counter && m_vec_events[event_i].confirmed) || m_player_id==ps_none)//SP, run directly { //TEMP check for duplicates for(int event_i2=0;event_i2<(int)m_vec_events.size();event_i2++) { if(event_i==event_i2) continue; if(m_vec_events[event_i]==m_vec_events[event_i2]) { cout<<"ERROR: Event duplication found\n"; if(m_print_log) m_log<<"ERROR: Event duplication found\n"; } } //add event switch(m_vec_events[event_i].type) { case et_unit_move: { //check if other unit taken for(int unit_i=0;unit_i<(int)m_vec_units.size();unit_i++) { if(m_vec_units[unit_i]->m_pos[0]==m_vec_events[event_i].x_to && m_vec_units[unit_i]->m_pos[1]==m_vec_events[event_i].y_to) { m_vec_units[unit_i]->m_remove=true; //king test if(!m_game_over) { if(m_vec_units[unit_i]->m_type==ut_king) { m_game_over=true; cout<<"***************\n** GAME OVER **\n***************\n"; if(m_vec_units[unit_i]->m_owner==ps_joiner) cout<<"-- HOST WON --\n"; if(m_vec_units[unit_i]->m_owner==ps_hoster) cout<<"--CLIENT WON--\n"; } } } } //find unit bool unit_found=false; for(int unit_i=0;unit_i<(int)m_vec_units.size();unit_i++) { if(m_vec_units[unit_i]->m_pos[0]==m_vec_events[event_i].x_from && m_vec_units[unit_i]->m_pos[1]==m_vec_events[event_i].y_from) { unit_found=true; //move unit m_vec_units[unit_i]->m_pos[0]=m_vec_events[event_i].x_to; m_vec_units[unit_i]->m_pos[1]=m_vec_events[event_i].y_to; m_vec_units[unit_i]->m_has_moved=true; m_vec_units[unit_i]->m_move_timer=1.0; break; } } if(!unit_found) { cout<<"ERROR: Event unit move could not find unit\n"; //XXXX this happens! cout<<"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"; if(m_print_log) { m_log<<"ERROR: Invalid move from/to: "<<m_vec_events[event_i].x_from<<", "<<m_vec_events[event_i].y_from<<"\t"; m_log<<m_vec_events[event_i].x_to<<", "<<m_vec_events[event_i].y_to<<"\n"; } //XXXX } }break; } m_vec_events.erase(m_vec_events.begin()+event_i); event_i--; continue; } //too old? if(m_vec_events[event_i].tick_target<m_tick_counter) { //out of sync cout<<"ERROR: Event out of sync\n"; m_rollback_unconfirmed=true; //send rollback status to other player st_event event(m_vec_events[event_i].tick_target); event.type=et_rollback; event.owner=m_player_id; send_data(event);//quick send //rollback rollback(m_vec_events[event_i].tick_target); //store for resending event.resend_counter=m_event_resend_delay; m_vec_events.push_back(event); return true; } //check if unconfirmed package should be sent (again) if(!m_vec_events[event_i].confirmed) { //init first pass if(m_vec_events[event_i].resend_counter<=-100) m_vec_events[event_i].resend_counter=m_event_resend_delay; m_vec_events[event_i].resend_counter--; if(m_vec_events[event_i].resend_counter<=0) { m_vec_events[event_i].resend_counter=m_event_resend_delay; //resend if(!send_data(m_vec_events[event_i])) { cout<<"ERROR: Could not send data\n"; } } } } //no input if a rollback is not confirmed if(m_rollback_unconfirmed) break; for(int i=0;i<(int)m_vec_units.size();i++) { m_vec_units[i]->update(); } //unit marked test bool unit_selected=false; for(int i=0;i<(int)m_vec_units.size();i++) { if(m_pSelected_unit==m_vec_units[i]) { unit_selected=true; m_pSelected_unit->m_marked=true; break; } } //clear movement board for(int x=0;x<8;x++) for(int y=0;y<8;y++) { m_arr_board_movements[x][y]=0; } //mark possible movements if(unit_selected) { for(int x=0;x<8;x++) for(int y=0;y<8;y++) { if(move_test(m_pSelected_unit,x,y)) { //end pos block test for allied units bool unit_block=false; for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==x && m_vec_units[i]->m_pos[1]==y && m_vec_units[i]->m_owner==m_pSelected_unit->m_owner) { unit_block=true; break; } } if(!unit_block) m_arr_board_movements[x][y]=1; } } } //click test (inactive if game not started) bool LMB_click=false; if(m_pMouse_but[0] && m_game_started) { if(!m_LMB_trig) { m_LMB_trig=true; LMB_click=true; } } else { m_LMB_trig=false; } //selection and movement test if(LMB_click) { if(unit_selected) { //test possible movement int mouse_pos_tile_x=int((float)m_pMouse_pos[0]/m_pix_per_unit); int mouse_pos_tile_y=int((float)m_pMouse_pos[1]/m_pix_per_unit); bool move_ok=false; if(move_test(m_pSelected_unit,mouse_pos_tile_x,mouse_pos_tile_y)) { //test if other unit at target pos bool allied_unit_col=false; for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==mouse_pos_tile_x && m_vec_units[i]->m_pos[1]==mouse_pos_tile_y) { if(m_vec_units[i]->m_owner!=m_pSelected_unit->m_owner) { //take unit (occurs at package interpretation) //m_vec_units[i]->m_remove=true; } else allied_unit_col=true; break; } } if(!allied_unit_col) { move_ok=true; /*m_pSelected_unit->m_pos[0]=mouse_pos_tile_x; m_pSelected_unit->m_pos[1]=mouse_pos_tile_y; m_pSelected_unit->m_has_moved=true; m_pSelected_unit->m_move_timer=1.0; //pawn to queen test if(m_pSelected_unit->m_type==ut_pawn && m_pSelected_unit->m_pos[1]==0) { m_pSelected_unit->m_type=ut_queen; }*/ //test if unit already requested to move bool abort_send=false; for(int i=0;i<(int)m_vec_events.size();i++) { if(m_vec_events[i].x_from==mouse_pos_tile_x && m_vec_events[i].y_from==mouse_pos_tile_y) { abort_send=true; break; } } if(!abort_send) { //send event m_vec_events.push_back(st_event(m_tick_counter+m_static_event_delay,m_player_id, m_pSelected_unit->m_pos[0],mouse_pos_tile_x, m_pSelected_unit->m_pos[1],mouse_pos_tile_y)); m_vec_events.back().resend_counter=0;//sent directly } } //unselect m_pSelected_unit=NULL; } if(!move_ok) { unit_selected=false; m_pSelected_unit=NULL; } } if(!unit_selected) { //select unit int mouse_pos_tile_x=int((float)m_pMouse_pos[0]/m_pix_per_unit); int mouse_pos_tile_y=int((float)m_pMouse_pos[1]/m_pix_per_unit); //cout<<"mouse pos: "<<mouse_pos_tile_x<<", "<<mouse_pos_tile_y<<endl; //find unit for(int i=0;i<(int)m_vec_units.size();i++) { //test pos if(m_vec_units[i]->m_pos[0]==mouse_pos_tile_x && m_vec_units[i]->m_pos[1]==mouse_pos_tile_y ) { //test owner if(m_vec_units[i]->m_owner==m_player_id || m_player_id==ps_none) { //test if unit already has a move order bool abort_select=false; for(int i2=0;i2<(int)m_vec_events.size();i2++) { if(m_vec_events[i2].x_from==mouse_pos_tile_x && m_vec_events[i2].y_from==mouse_pos_tile_y) { abort_select=true; break; } } if(!abort_select) { m_pSelected_unit=m_vec_units[i]; m_pSelected_unit->m_marked=true; //cout<<"marked unit\n"; } } break; } } } } //automove if(m_automove_on && m_game_started && !m_vec_units.empty()) { m_automove_timer-=_time_step; if(m_automove_timer<=0) { m_automove_timer=m_automove_delay; //move random unit unit* unit_to_move; int try_counter=0; int max_tries=1000; bool move_ok=false; int unit_ind=rand()%(int)m_vec_units.size(); while(m_vec_units[unit_ind]->m_owner!=m_player_id && try_counter<max_tries) { try_counter++; unit_ind=rand()%(int)m_vec_units.size(); } unit_to_move=m_vec_units[unit_ind]; //fint acceptable target pos int target_pos_x=rand()%8; int target_pos_y=rand()%8; while(!move_test(unit_to_move,target_pos_x,target_pos_y) && try_counter<max_tries) { try_counter++; target_pos_x=rand()%8; target_pos_y=rand()%8; } if(move_test(unit_to_move,target_pos_x,target_pos_y)) { //test if other unit at target pos bool allied_unit_col=false; for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==target_pos_x && m_vec_units[i]->m_pos[1]==target_pos_y) { if(m_vec_units[i]->m_owner!=unit_to_move->m_owner) { //take unit (occurs at package interpretation) //m_vec_units[i]->m_remove=true; } else allied_unit_col=true; break; } } if(!allied_unit_col) { move_ok=true; //test if unit already requested to move bool abort_send=false; for(int i=0;i<(int)m_vec_events.size();i++) { if(m_vec_events[i].x_from==target_pos_x && m_vec_events[i].y_from==target_pos_y) { abort_send=true; break; } } if(!abort_send) { //send event m_vec_events.push_back(st_event(m_tick_counter+m_static_event_delay,m_player_id, unit_to_move->m_pos[0],target_pos_x, unit_to_move->m_pos[1],target_pos_y)); m_vec_events.back().resend_counter=0;//sent directly } } } if(move_ok) cout<<"Automove Successful\n"; else cout<<"Automove failed\n"; } } //remove units for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_remove) { if(m_vec_units[i]==m_pSelected_unit) { //unselect m_pSelected_unit=NULL; } delete m_vec_units[i]; m_vec_units.erase(m_vec_units.begin()+i); i--; } } }break; } return true; } bool game::draw(void) { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); //glLoadIdentity(); switch(m_game_state) { case gs_init: { //nothing }break; case gs_menu: { //nothing }break; case gs_in_game: { //rotate glPushMatrix(); /*glTranslatef(m_window_size[0],m_window_size[1],0); glRotatef(180,0,0,1);*/ //board glColor3f(1,1,1); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindTexture(GL_TEXTURE_2D,m_tex_board); glBegin(GL_QUADS); glTexCoord2f(0,0); glVertex2f(0,0); glTexCoord2f(0,1); glVertex2f(0,m_window_size[1]); glTexCoord2f(1,1); glVertex2f(m_window_size[0],m_window_size[1]); glTexCoord2f(1,0); glVertex2f(m_window_size[0],0); glEnd(); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); //allowed movement tiles glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(0.2,0.8,0.2,0.5); glBegin(GL_QUADS); for(int x=0;x<8;x++) for(int y=0;y<8;y++) { if(m_arr_board_movements[x][y]==1) { glVertex2f(x*m_pix_per_unit,y*m_pix_per_unit); glVertex2f(x*m_pix_per_unit,y*m_pix_per_unit+m_pix_per_unit); glVertex2f(x*m_pix_per_unit+m_pix_per_unit,y*m_pix_per_unit+m_pix_per_unit); glVertex2f(x*m_pix_per_unit+m_pix_per_unit,y*m_pix_per_unit); } } glEnd(); glDisable(GL_BLEND); /*//lines glBegin(GL_LINES); for(int x=0;x<=m_window_size[0];x+=int((float)m_window_size[0]/8.0)) { glVertex2f(x,0); glVertex2f(x,m_window_size[1]); } for(int y=0;y<=m_window_size[1];y+=int((float)m_window_size[1]/8.0)) { glVertex2f(0,y); glVertex2f(m_window_size[0],y); } glEnd();*/ //units for(int unit_i=0;unit_i<(int)m_vec_units.size();unit_i++) { m_vec_units[unit_i]->draw(m_pix_per_unit); } glPopMatrix(); }break; } return true; } int game::get_MP_settings(string& ip) { if(m_mp_status==2) ip=m_host_ip; return m_mp_status; } bool game::start_game(void) { m_tick_counter=0; m_game_start_countdown_timer=_game_start_time; cout<<"Match will start in..."<<endl; return true; } //Private bool game::load_textures(void) { cout<<"Game: Loading texture\n"; m_tex_figures=SOIL_load_OGL_texture ( "data\\texture\\figures.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, /*SOIL_FLAG_INVERT_Y | */SOIL_FLAG_COMPRESS_TO_DXT ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_tex_board=SOIL_load_OGL_texture ( "data\\texture\\board.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, /*SOIL_FLAG_INVERT_Y | */SOIL_FLAG_COMPRESS_TO_DXT ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); if(m_tex_figures==0 || m_tex_board==0) { cout<<"ERROR: Could not load texture\n"; return false; } return true; } bool game::load_sounds(void) { cout<<"Game: Loading sound\n"; m_pSound=new sound(); bool error_flag=false; if( !m_pSound->load_WAVE_from_file( wav_beep1,"data\\sound\\beep1.wav" ) ) error_flag=true; if(error_flag) { cout<<"ERROR: Could not load sound\n"; return false; } return true; } bool game::move_test(unit* pUnit,int target_x,int target_y) { int unit_pos_x=pUnit->m_pos[0]; int unit_pos_y=pUnit->m_pos[1]; //no movement during move anim if(pUnit->m_move_timer>0) return false; bool allow_move=false; switch(pUnit->m_type) { case ut_pawn: { int direction=0; switch(pUnit->m_owner) { case 0: direction=0; break; case 1: direction=-1; break; case 2: direction=1; break; } //normal if(unit_pos_x==target_x && target_y==unit_pos_y+direction) allow_move=true; //first step if(unit_pos_x==target_x && target_y==unit_pos_y+direction*2 && !pUnit->m_has_moved) allow_move=true; //diagonal attack if(!allow_move) { for(int i=0;i<(int)m_vec_units.size();i++) { if( m_vec_units[i]->m_pos[1]==unit_pos_y+direction && ( (m_vec_units[i]->m_pos[0]==unit_pos_x+1) || (m_vec_units[i]->m_pos[0]==unit_pos_x-1) ) ) { //target and unit pos should be same if(m_vec_units[i]->m_pos[0]!=target_x || m_vec_units[i]->m_pos[1]!=target_y) continue; if(m_vec_units[i]->m_owner!=m_player_id) allow_move=true; break; } } } }break; case ut_tower: { if(unit_pos_x==target_x || unit_pos_y==target_y) { //test path, end pos not tested bool x_move=false;//move along x-axis bool pos_move=false; if(unit_pos_x==target_x) x_move=true; if(target_x>unit_pos_x || target_y>unit_pos_y) pos_move=true; bool col_made=false; if(x_move) { if(pos_move) { for(int y=unit_pos_y+1;y<target_y;y++) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==unit_pos_x && m_vec_units[i]->m_pos[1]==y) { col_made=true; break; } } if(col_made) break; } } else { for(int y=unit_pos_y-1;y>target_y;y--) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==unit_pos_x && m_vec_units[i]->m_pos[1]==y) { col_made=true; break; } } if(col_made) break; } } } else//y move { if(pos_move) { for(int x=unit_pos_x+1;x<target_x;x++) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==x && m_vec_units[i]->m_pos[1]==unit_pos_y) { col_made=true; break; } } if(col_made) break; } } else { for(int x=unit_pos_x-1;x>target_x;x--) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==x && m_vec_units[i]->m_pos[1]==unit_pos_y) { col_made=true; break; } } if(col_made) break; } } } if(!col_made) allow_move=true; } }break; case ut_runner: { int x_dif=target_x-unit_pos_x; int y_dif=target_y-unit_pos_y; bool x_pos=false; bool y_pos=false; if(x_dif>0) x_pos=true; if(y_dif>0) y_pos=true; int steps=fabs(x_dif); if(fabs(x_dif)==fabs(y_dif) && x_dif!=0) { //test path, end pos not tested bool col_made=false; if(x_pos && y_pos) { for(int dif=1;dif<steps;dif++) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==unit_pos_x+dif && m_vec_units[i]->m_pos[1]==unit_pos_y+dif) { col_made=true; break; } } if(col_made) break; } } if(x_pos && !y_pos) { for(int dif=1;dif<steps;dif++) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==unit_pos_x+dif && m_vec_units[i]->m_pos[1]==unit_pos_y-dif) { col_made=true; break; } } if(col_made) break; } } if(!x_pos && y_pos) { for(int dif=1;dif<steps;dif++) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==unit_pos_x-dif && m_vec_units[i]->m_pos[1]==unit_pos_y+dif) { col_made=true; break; } } if(col_made) break; } } if(!x_pos && !y_pos) { for(int dif=1;dif<steps;dif++) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==unit_pos_x-dif && m_vec_units[i]->m_pos[1]==unit_pos_y-dif) { col_made=true; break; } } if(col_made) break; } } if(!col_made) allow_move=true; } }break; case ut_queen: { //runner int x_dif=target_x-unit_pos_x; int y_dif=target_y-unit_pos_y; bool x_pos=false; bool y_pos=false; if(x_dif>0) x_pos=true; if(y_dif>0) y_pos=true; int steps=fabs(x_dif); if(fabs(x_dif)==fabs(y_dif) && x_dif!=0) { //test path, end pos not tested bool col_made=false; if(x_pos && y_pos) { for(int dif=1;dif<steps;dif++) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==unit_pos_x+dif && m_vec_units[i]->m_pos[1]==unit_pos_y+dif) { col_made=true; break; } } if(col_made) break; } } if(x_pos && !y_pos) { for(int dif=1;dif<steps;dif++) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==unit_pos_x+dif && m_vec_units[i]->m_pos[1]==unit_pos_y-dif) { col_made=true; break; } } if(col_made) break; } } if(!x_pos && y_pos) { for(int dif=1;dif<steps;dif++) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==unit_pos_x-dif && m_vec_units[i]->m_pos[1]==unit_pos_y+dif) { col_made=true; break; } } if(col_made) break; } } if(!x_pos && !y_pos) { for(int dif=1;dif<steps;dif++) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==unit_pos_x-dif && m_vec_units[i]->m_pos[1]==unit_pos_y-dif) { col_made=true; break; } } if(col_made) break; } } if(!col_made) allow_move=true; } //tower if(unit_pos_x==target_x || unit_pos_y==target_y) { //test path, end pos not tested bool x_move=false;//move along x-axis bool pos_move=false; if(unit_pos_x==target_x) x_move=true; if(target_x>unit_pos_x || target_y>unit_pos_y) pos_move=true; bool col_made=false; if(x_move) { if(pos_move) { for(int y=unit_pos_y+1;y<target_y;y++) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==unit_pos_x && m_vec_units[i]->m_pos[1]==y) { col_made=true; break; } } if(col_made) break; } } else { for(int y=unit_pos_y-1;y>target_y;y--) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==unit_pos_x && m_vec_units[i]->m_pos[1]==y) { col_made=true; break; } } if(col_made) break; } } } else//y move { if(pos_move) { for(int x=unit_pos_x+1;x<target_x;x++) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==x && m_vec_units[i]->m_pos[1]==unit_pos_y) { col_made=true; break; } } if(col_made) break; } } else { for(int x=unit_pos_x-1;x>target_x;x--) { for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_pos[0]==x && m_vec_units[i]->m_pos[1]==unit_pos_y) { col_made=true; break; } } if(col_made) break; } } } if(!col_made) allow_move=true; } }break; case ut_king: { if( fabs(target_x-unit_pos_x)<=1 && fabs(target_y-unit_pos_y)<=1 ) { allow_move=true; } }break; case ut_horse: { int x_dif=target_x-unit_pos_x; int y_dif=target_y-unit_pos_y; if( (x_dif==-1 && y_dif==-2) || (x_dif==-1 && y_dif==2) || (x_dif==1 && y_dif==-2) || (x_dif==1 && y_dif==2) || (x_dif==-2 && y_dif==-1) || (x_dif==-2 && y_dif==1) || (x_dif==2 && y_dif==-1) || (x_dif==2 && y_dif==1) ) { allow_move=true; } }break; } //collision test if(allow_move) { //cout<<"Move OK\n"; return true; } return false; } bool game::send_data(st_event event) { //convert to int array int data[8]={8*sizeof(int), event.type, event.tick_target, event.owner, event.x_from, event.x_to, event.y_from, event.y_to}; return m_pNetCom->send_data(data); } bool game::send_data(int* data_array) { return m_pNetCom->send_data(data_array); } bool game::recv_data(SOCKET soc_sender) { //int data_array[8]={0,0,0,0,0,0,0,0}; for(int i=0;i<256;i++) m_data_array[i]=0;//requires 256 places to not interfere with others bool retval=m_pNetCom->recv_data(m_data_array); if(!retval) return false; //interpret package switch(m_data_array[1])//type { case et_error: { cout<<"ERROR: Received bad package\n"; retval=false; }break; case et_unit_move: { //place event in confirmed events vector st_event event(m_data_array[2], m_data_array[3], m_data_array[4], m_data_array[5], m_data_array[6], m_data_array[7]); event.confirmed=true; //test if package already received (reveresed order) bool move_order_already_in_history=false; for(int i=(int)m_vec_history_move.size()-1;i>=0;i--) { if(m_vec_history_move[i]==event) { move_order_already_in_history=true; cout<<"Received move order already received\n"; break; } } if(!move_order_already_in_history) { m_vec_events.push_back(event); //add to history m_vec_history_move.push_back(event); } //send confirmation package back m_data_array[1]=et_unit_move_confirmation; retval=send_data(m_data_array); }break; case et_unit_move_confirmation: { //translate to event st_event event(m_data_array[2], m_data_array[3], m_data_array[4], m_data_array[5], m_data_array[6], m_data_array[7]); //locate event in not confirmed packages bool event_found=false; for(int i=0;i<(int)m_vec_events.size();i++) { if(m_vec_events[i]==event) { event_found=true; //check if already confirmed if(m_vec_events[i].confirmed) { cout<<"Received package was already confirmed\n"; } else { //confirm event m_vec_events[i].confirmed=true; //check history bool move_order_already_in_history=false; for(int i2=(int)m_vec_history_move.size()-1;i2>=0;i2--) { if(m_vec_history_move[i2]==m_vec_events[i]) { move_order_already_in_history=true; cout<<"Received move order confirmation already received\n"; break; } } //add to history if(!move_order_already_in_history) { m_vec_history_move.push_back(m_vec_events[i]); } } break; } } if(!event_found) { cout<<"ERROR: Received event confirmation was not present in vector\n"; if(m_print_log) m_log<<"ERROR: Received event confirmation was not present in vector\n"; retval=false; } }break; case et_ping: { //server calc ping if(m_player_id==ps_hoster) { m_vec_pings.push_back(m_tick_counter-m_data_array[2]); } //client replies if(m_player_id==ps_joiner) { st_event event(m_data_array[2]); m_vec_events.push_back(event); } }break; case et_settings: { m_static_event_delay=m_data_array[2]; m_event_resend_delay=m_data_array[3]; cout<<"Received new send settings: "<<m_static_event_delay<<", "<<m_event_resend_delay<<endl; if(m_print_log) { m_log<<"Event delay: "<<m_static_event_delay<<"\tResend delay: "<<m_event_resend_delay<<endl; } }break; case et_rollback: { //rollback requested by the other player, place in event vector st_event event(m_data_array[2], m_data_array[3], m_data_array[4], m_data_array[5], m_data_array[6], m_data_array[7]); //event.confirmed=true; m_vec_events.push_back(event); //send confirmation now event.type=et_rollback_confirmation; send_data(event); }break; case et_rollback_confirmation: { //the requested rollback is now confirmed by the other player, place in event vector st_event event(m_data_array[2], m_data_array[3], m_data_array[4], m_data_array[5], m_data_array[6], m_data_array[7]); //event.confirmed=true; m_vec_events.push_back(event); }break; } //if print data to console if(true) { for(int i=0;i<8;i++) { cout<<m_data_array[i]<<"\t"; } cout<<endl; } //print data to file if(m_print_log) { time_t t = time(0);// get time now struct tm * now = localtime( & t ); stringstream ss; if((now->tm_hour)<10) ss<<"0"; ss<<now->tm_hour; if((now->tm_min)<10) ss<<"0"; ss<<now->tm_min; if((now->tm_sec)<10) ss<<"0"; ss<<now->tm_sec; string time_now=ss.str(); m_log<<time_now<<"_"; for(int i=0;i<8;i++) { m_log<<m_data_array[i]<<"\t"; } m_log<<endl; } return retval; } bool game::rollback(int end_tick) { cout<<"Game rollback in progress\n"; m_rollback_tick_target=end_tick; //reset units m_pSelected_unit=NULL; for(int i=0;i<(int)m_vec_units.size();i++) { delete m_vec_units[i]; } m_vec_units.clear(); m_vec_events.clear(); //place new units { m_vec_units.push_back(new unit(0,0,ut_tower,2,m_tex_figures)); m_vec_units.push_back(new unit(1,0,ut_horse,2,m_tex_figures)); m_vec_units.push_back(new unit(2,0,ut_runner,2,m_tex_figures)); m_vec_units.push_back(new unit(3,0,ut_king,2,m_tex_figures)); m_vec_units.push_back(new unit(4,0,ut_queen,2,m_tex_figures)); m_vec_units.push_back(new unit(5,0,ut_runner,2,m_tex_figures)); m_vec_units.push_back(new unit(6,0,ut_horse,2,m_tex_figures)); m_vec_units.push_back(new unit(7,0,ut_tower,2,m_tex_figures)); m_vec_units.push_back(new unit(0,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(1,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(2,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(3,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(4,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(5,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(6,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(7,1,ut_pawn,2,m_tex_figures)); m_vec_units.push_back(new unit(0,7,ut_tower,1,m_tex_figures)); m_vec_units.push_back(new unit(1,7,ut_horse,1,m_tex_figures)); m_vec_units.push_back(new unit(2,7,ut_runner,1,m_tex_figures)); m_vec_units.push_back(new unit(3,7,ut_queen,1,m_tex_figures)); m_vec_units.push_back(new unit(4,7,ut_king,1,m_tex_figures)); m_vec_units.push_back(new unit(5,7,ut_runner,1,m_tex_figures)); m_vec_units.push_back(new unit(6,7,ut_horse,1,m_tex_figures)); m_vec_units.push_back(new unit(7,7,ut_tower,1,m_tex_figures)); m_vec_units.push_back(new unit(0,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(1,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(2,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(3,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(4,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(5,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(6,6,ut_pawn,1,m_tex_figures)); m_vec_units.push_back(new unit(7,6,ut_pawn,1,m_tex_figures)); } //sort history while(true) { bool updated=false; for(int i=0;i<(int)m_vec_history_move.size()-1;i++) { if(m_vec_history_move[i].tick_target > m_vec_history_move[i+1].tick_target) { updated=true; //swap st_event temp(m_vec_history_move[i]); m_vec_history_move[i]=m_vec_history_move[i+1]; m_vec_history_move[i+1]=temp; } } if(!updated) break; } //remove history at target tick or later for(int i=0;i<(int)m_vec_history_move.size();i++) { if(m_vec_history_move[i].tick_target>=end_tick) { m_vec_history_move.erase(m_vec_history_move.begin()+i,m_vec_history_move.end()-1); break; } } //repeat history for(int i=0;i<(int)m_vec_history_move.size();i++) { switch(m_vec_history_move[i].type) { case et_unit_move: { //check if other unit taken for(int unit_i=0;unit_i<(int)m_vec_units.size();unit_i++) { if(m_vec_units[unit_i]->m_pos[0]==m_vec_history_move[i].x_to && m_vec_units[unit_i]->m_pos[1]==m_vec_history_move[i].y_to) { m_vec_units[unit_i]->m_remove=true; //king test if(!m_game_over) { if(m_vec_units[unit_i]->m_type==ut_king) { m_game_over=true; cout<<"***************\n** GAME OVER **\n***************\n"; if(m_vec_units[unit_i]->m_owner==ps_joiner) cout<<"-- HOST WON --\n"; if(m_vec_units[unit_i]->m_owner==ps_hoster) cout<<"--CLIENT WON--\n"; } } } } //find unit bool unit_found=false; for(int unit_i=0;unit_i<(int)m_vec_units.size();unit_i++) { if(m_vec_units[unit_i]->m_pos[0]==m_vec_history_move[i].x_from && m_vec_units[unit_i]->m_pos[1]==m_vec_history_move[i].y_from) { unit_found=true; //move unit directly m_vec_units[unit_i]->m_pos_prev[0]=m_vec_units[unit_i]->m_pos[0]=m_vec_history_move[i].x_to; m_vec_units[unit_i]->m_pos_prev[1]=m_vec_units[unit_i]->m_pos[1]=m_vec_history_move[i].y_to; //m_vec_units[unit_i]->m_has_moved=true; //m_vec_units[unit_i]->m_move_timer=1.0; break; } } if(!unit_found) { cout<<"ERROR: Rollback: Event unit move could not find unit\n"; } }break; } //remove inits for(int i=0;i<(int)m_vec_units.size();i++) { if(m_vec_units[i]->m_remove) { delete m_vec_units[i]; m_vec_units.erase(m_vec_units.begin()+i); i--; } } } return true; } <file_sep>#ifndef UNIT_H #define UNIT_H #include <gl/gl.h> #include "definitions.h" enum unit_types { ut_pawn=0, ut_horse, ut_runner, ut_tower, ut_queen, ut_king }; class unit { public: unit(int x_pos,int y_pos,int type,int owner,int tex); int m_type,m_owner; int m_pos[2]; int m_pos_prev[2]; int m_texture; bool m_marked,m_remove,m_has_moved; float m_move_timer; bool init(void); bool update(void); bool draw(float pos2pix); private: }; #endif // UNIT_H <file_sep>#ifndef KEY_REROUTE_H #define KEY_REROUTE_H #define _key_count 256 #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> #include <stdlib.h> using namespace std; enum key_table { key_ctrl=17, key_shift=16, key_caps=20, key_tab=9, key_tilde=220, key_enter=13, key_space=32, key_backspace=8, key_esc=27, key_np_0=96, key_np_1, key_np_2, key_np_3, key_np_4, key_np_5, key_np_6, key_np_7, key_np_8, key_np_9, key_np_mult=106, key_np_add=107, key_np_subs=109, key_np_dev=111, key_np_dot=110, key_pgup=33, key_pgdown, key_end, key_home, key_ins=45, key_del=46, key_left=37, key_up, key_right, key_down, key_0=48, key_1, key_2, key_3, key_4, key_5, key_6, key_7, key_8, key_9, key_a=65, key_b, key_c, key_d, key_e, key_f, key_g, key_h, key_i, key_j, key_k, key_l, key_m, key_n, key_o, key_p, key_q, key_r, key_s, key_t, key_u, key_v, key_w, key_x, key_y, key_z, }; struct st_key_rule { st_key_rule() { input=0; output=0; } st_key_rule(int _input,int _output) { input=_input; output=_output; } int input; int output; }; class key_reroute { public: key_reroute(); //initialize with sending the pointer to the array that keeps the key state information bool init(bool* pKeys_real,bool* pKeys_translated); bool update(void); bool set_key_translation(int input_key,int output_key); bool load_key_translation_from_file(string file_name="key_config.dat"); bool save_key_translation_to_file(string file_name="key_config.dat"); bool reset_key_translation(void); bool report_status; private: bool* m_pKeys_real; bool* m_pKeys_translated; vector<st_key_rule> m_vec_key_rules; }; #endif // KEY_REROUTE_H <file_sep>#ifndef SERVERCOM_H #define SERVERCOM_H #include <iostream> //For Debug #include <sstream> #include <stdlib.h> //For itoa() #include <winsock2.h> #include <string> #include <vector> using namespace std; class serverCom { public: //Constructors serverCom(); //Variables bool m_ready; //Functions bool init(void); bool start_to_listen(int backLog); bool set_port_and_bind(int port); bool known_socket(SOCKET new_socket); bool check_for_broadcast(void); bool set_broadcast_port(int port_sending,int port_replying); bool send_data(string data_string); bool send_data(float* data_array); bool send_data(int* data_array); bool send_data(string data_string,SOCKET SocReceiver); bool send_data(float* data_array,SOCKET SocReceiver); bool recv_data(string& data_string,SOCKET SocSender); bool recv_data(float* data_array,SOCKET SocSender); bool recv_data(int* data_array);//assume only client bool add_client(SOCKET new_client); bool remove_client(SOCKET client_to_remove); SOCKET get_server_socket(void); private: //Variables bool m_broadcast_ready; string m_host_name,m_host_IP; int m_host_port,m_broadcast_port,m_broadcast_port_reply; SOCKET m_SocServer; SOCKET m_SocUDP_for_broadcast_recv; vector<SOCKET> m_vSocClients; //Functions bool init_broadcast_socket(void); bool reply_to_broadcaster(string sIP); bool close_broadcast_socket(void); bool ip_is_valid(char *str); }; #endif // SERVERCOM_H <file_sep>#include "unit.h" unit::unit(int x_pos,int y_pos,int type,int owner,int tex) { m_type=type; m_owner=owner; m_texture=tex; m_pos_prev[0]=m_pos[0]=x_pos; m_pos_prev[1]=m_pos[1]=y_pos; m_marked=false; m_remove=false; m_has_moved=false; m_move_timer=0; } bool unit::init(void) { return true; } bool unit::update(void) { m_marked=false; if(m_move_timer>0) { m_move_timer-=_time_step*_unit_move_anim_speed; if(m_move_timer<=0.0) { //done m_move_timer=0; m_pos_prev[0]=m_pos[0]; m_pos_prev[1]=m_pos[1]; } } return true; } bool unit::draw(float pos2pix) { float tex_off_x=(float)m_type/6.0; float tex_off_y=(float)(m_owner-1)/2.0; float draw_pos_x=m_pos[0]*pos2pix; float draw_pos_y=m_pos[1]*pos2pix; //move anim if(m_move_timer>0) { draw_pos_x+=(m_pos_prev[0]*pos2pix-m_pos[0]*pos2pix)*m_move_timer; draw_pos_y+=(m_pos_prev[1]*pos2pix-m_pos[1]*pos2pix)*m_move_timer; } //rotate view glPushMatrix(); //glTranslatef(pos2pix,pos2pix,0); //glRotatef(180,0,0,1); //glTranslatef(pos2pix,pos2pix,0); glColor3f(1,1,1); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindTexture(GL_TEXTURE_2D,m_texture); glBegin(GL_QUADS); glTexCoord2f(tex_off_x,tex_off_y); glVertex2f(draw_pos_x,draw_pos_y); glTexCoord2f(tex_off_x,tex_off_y+0.5); glVertex2f(draw_pos_x,draw_pos_y+pos2pix); glTexCoord2f(tex_off_x+1.0/6.0,tex_off_y+0.5); glVertex2f(draw_pos_x+pos2pix,draw_pos_y+pos2pix); glTexCoord2f(tex_off_x+1.0/6.0,tex_off_y); glVertex2f(draw_pos_x+pos2pix,draw_pos_y); glEnd(); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); //marked if(m_marked) { glColor3f(1,0,0); glLineWidth(3); glBegin(GL_LINE_STRIP); glVertex2f(m_pos[0]*pos2pix,m_pos[1]*pos2pix); glVertex2f(m_pos[0]*pos2pix,m_pos[1]*pos2pix+pos2pix); glVertex2f(m_pos[0]*pos2pix+pos2pix,m_pos[1]*pos2pix+pos2pix); glVertex2f(m_pos[0]*pos2pix+pos2pix,m_pos[1]*pos2pix); glVertex2f(m_pos[0]*pos2pix,m_pos[1]*pos2pix); glEnd(); glLineWidth(1); } glPopMatrix(); return true; } <file_sep>#ifndef GAME_H #define GAME_H #include <iostream> #include <fstream> #include <SOIL/SOIL.h> #include <gl/gl.h> #include <string> #include <vector> #include <math.h> #include <ctime> #include "sound.h" #include "gamepad.h" #include "key_reroute.h" #include "unit.h" #include "networkCom.h" enum game_states { gs_init=0, gs_menu, gs_in_game }; enum player_status_types { ps_none=0, ps_hoster, ps_joiner }; enum event_types { et_error=0, et_unit_move, et_unit_move_confirmation, et_game_over, et_ping, et_settings, et_rollback,//request et_rollback_confirmation//sent back to rollback requester when confirmed }; struct st_event { st_event(const st_event& _event) { tick_target=_event.tick_target; owner=_event.owner; x_from=_event.x_from; x_to=_event.x_to; y_from=_event.y_from; y_to=_event.y_to; type=_event.type; confirmed=_event.confirmed; resend_counter=_event.resend_counter; } st_event(int tick) { type=et_ping; tick_target=tick; confirmed=false; x_from=x_to=y_from=y_to=0; resend_counter=0; owner=0; } st_event(int static_event_delay,int event_resend_delay) { type=et_settings; tick_target=static_event_delay; owner=event_resend_delay; confirmed=false; x_from=x_to=y_from=y_to=0; resend_counter=0; } st_event(int tick,int _owner,int xfrom,int xto,int yfrom,int yto) { tick_target=tick; owner=_owner; x_from=xfrom; x_to=xto; y_from=yfrom; y_to=yto; type=et_unit_move; confirmed=false; resend_counter=-100; } bool operator==(st_event& _event) { return (_event.tick_target==tick_target && _event.owner==owner && _event.x_from==x_from && _event.x_to==x_to && _event.y_from==y_from && _event.y_to==y_to ); } st_event operator=(const st_event& _event) { tick_target=_event.tick_target; owner=_event.owner; x_from=_event.x_from; x_to=_event.x_to; y_from=_event.y_from; y_to=_event.y_to; type=_event.type; confirmed=_event.confirmed; resend_counter=_event.resend_counter; return *this; } int tick_target; int owner; int x_from,x_to,y_from,y_to; int type; bool confirmed; int resend_counter; }; class game { public: game(); networkCom* m_pNetCom; int m_tick_counter; int m_player_id; bool m_game_started,m_game_over,m_pause_game; bool init(int* pWindow_size,bool* pKeys_real,bool* pKeys_translated, int* pMouse_pos,bool* pMouse_but,bool reinit=false); bool update(bool& quit_flag); bool draw(void); int get_MP_settings(string& ip_and_port); bool recv_data(SOCKET soc_sender); bool start_game(void); private: float m_pix_per_unit; float m_ping_avg; int m_mp_status; string m_host_ip; int m_static_event_delay=100; int m_event_resend_delay=30; int m_game_state; int m_window_size[2]; bool* m_pKeys_real; bool* m_pKeys_translated; int* m_pMouse_pos; bool* m_pMouse_but; bool m_gamepad_connected[4]; bool m_LMB_trig; int m_game_start_countdown; float m_game_start_countdown_timer; float m_automove_timer,m_automove_delay; bool m_automove_on; vector<unit*> m_vec_units; vector<st_event> m_vec_events; vector<int> m_vec_pings; vector<st_event> m_vec_history_move; vector<int> m_vec_rollbacks_to_ignore; bool m_rollback_unconfirmed; int m_rollback_tick_target; unit* m_pSelected_unit; int m_arr_board_movements[8][8]; int m_data_array[256]; //texture int m_tex_figures,m_tex_board; //object key_reroute m_key_rerouter; sound* m_pSound; gamepad m_gamepad[4]; ofstream m_log; bool m_print_log; bool load_textures(void); bool load_sounds(void); bool move_test(unit* pUnit,int target_x,int target_y); bool send_data(st_event event); bool send_data(int* data_array); bool rollback(int end_tick); }; #endif // GAME_H <file_sep> /* INSTRUCTIONS: #include <winsock2.h> must be included and libws2_32.a must be linked #define WM_WSAASYNC (WM_USER +5) for Async windows messages FOR SERVER: 1. Construct an networkCom object. networkCom g_NetCom; 2. Initialize by calling init(string server_or_client). g_NetCom.init("server"); 3. Set which network port to use with set_port_and_bind(int port). g_NetCom.set_port_and_bind(5001); 4. Make sockets Async by calling WSAAsyncSelect(SOCKET mySocket,HWND window_handle,windows_messages...). WSAAsyncSelect( g_NetCom.get_server_socket() , hwnd, WM_WSAASYNC, FD_READ | FD_WRITE | FD_ACCEPT | FD_CLOSE); 5. Allow clients to join by calling start_to_listen(). g_NetCom.start_to_listen(); Inside message handler: case WM_WSAASYNC: { // what word? switch(WSAGETSELECTEVENT(lParam)) { case FD_READ: //incomming data from SOCKET wParam { cout<<"FD_READ\n"; } break; case FD_WRITE: //only used if sending large files { cout<<"FD_WRITE\n"; } break; case FD_ACCEPT: // client wants to join { cout<<"FD_ACCEPT\n"; if(g_NetCom.add_client(wParam)) cout<<"New Client Joined\n"; else cout<<"Bad Client tried to join\n"; return(0); } break; case FD_CLOSE: // lost client { cout<<"FD_CLOSE\n"; if(g_NetCom.remove_client(wParam)) { cout<<"Client Removed\n"; } } break; } } FOR CLIENT: 1. Construct an networkCom object. networkCom g_NetCom; 2. Initialize by calling init(string server_or_client). g_NetCom.init("client"); 3. Make sockets Async by calling WSAAsyncSelect(SOCKET mySocket,HWND window_handle,windows_messages...). WSAAsyncSelect( g_NetCom.get_server_socket() , hwnd, WM_WSAASYNC, FD_WRITE | FD_CONNECT | FD_READ | FD_CLOSE); 4. Try to connect to server by calling connect_to_server(string IP_number,int port). g_NetCom.connect_to_server("192.168.0.1",5001); Inside message handler: case WM_WSAASYNC: { // what word? switch(WSAGETSELECTEVENT(lParam)) { case FD_READ: //incomming data from SOCKET wParam { cout<<"FD_READ\n"; } break; case FD_WRITE: //only used if sending large files { cout<<"FD_WRITE\n"; } break; case FD_CONNECT: //Client is now connected to server { cout<<"FD_CONNECT\n"; //Test Connection if(g_NetCom.test_connection()) { cout<<"You are now connected to the server\n"; } else//not connected { cout<<"Could not connect to server\n"; break; } } break; case FD_CLOSE: //lost connection to server { cout<<"FD_CLOSE\n"; g_NetCom.lost_connection(); } break; } } FOR BOTH: SENDING data is done by calling send_data() Data format is either a string or a float* string data_string("test"); g_NetCom.send_data(data_string); or float* data_array = new float[size]; data_array[0] = size; //First element must indicate size of array (number of elements) g_NetCom.send_data(data_array); delete[] data_array; The Client always sends to the Server The Server sends to all Clients or to specific client by specifying a SOCKET send_data(data,client_socket) RECEIVING data is handled inside the message handler (FD_READ) Either a string or a float* is received string data_string; g_NetCom.recv_data(data_string); or float data_array[256]; //maximum size is 256 elements g_NetCom.recv_data(data_array); For the Server the senders SOCKET must be provided recv_data(data,client_socket), (in message handler the socket is wParam) For the Client the sender is assumed to be the servers socket Both the sending and receiving functions will return false if an error occured BROADCASTING: The Client will broadcast it's IP adress to all IPs within the local "net" (default 255.255.255.255). The Server will periodically check if any broadcasted IP was intercepted. If the Server receives a broadcasted, valid IP, the Server will reply to that IP and send the IP and port to the Server. The Client will periodically check if any reply to the broadcasted message has been received. If the Client receives a reply to the broadcasted message, that contains a valid IP, this IP and port will be stored. Usage: The Client broadcasts it's IP by calling broadcast_my_ip(). g_NetCom.broadcast_my_ip(); The Server listens for broadcasts by calling check_for_broadcast(), reply will be sent automatically. g_NetCom.check_for_broadcast(); The Client listens for broadcast reply by calling check_for_broadcast_reply(), returns true if received reply. g_NetCom.check_for_broadcast_reply(); The Servers IP and port will be stored in the clientCom object and can is obtained by calling get_server_IP_and_port(string IP_and_port_container). g_NetCom.get_server_IP_and_port(IP_and_port_container); To change the broadcast listen and reply port for the Server use set_broadcast_port(int port_sending, int port_replying). To change the broadcast net, listen and reply port for the Client use set_broadcast_port(string net, int port_sending, int port_replying). */ #ifndef NETWORKCOM_H #define NETWORKCOM_H #include <iostream> //For Debug #include <string> #include <vector> #include <winsock2.h> #include "serverCom.h" #include "clientCom.h" enum net_statuses{net_server,net_client}; using namespace std; class networkCom { public: networkCom(); //Variables bool m_ready; int m_net_status; //Functions bool init(string status); bool connect_to_server(string sIP,int port); //only for CLIENT bool set_port_and_bind(int port); //only for SERVER bool start_to_listen(int backLog); //only for SERVER bool test_connection(void); //only for CLIENT bool set_broadcast_port(int port_sending, int port_replying); //only for SERVER bool set_broadcast_port(string net, int port_sending, int port_replying); //only for CLIENT bool known_socket(SOCKET new_socket); //only for SERVER bool broadcast_my_ip(void); //only for CLIENT bool check_for_broadcast(void); //only for SERVER bool check_for_broadcast_reply(void); //only for CLIENT bool get_server_IP_and_port(string& IP_and_port); //only for CLIENT bool send_data(string data_string); bool send_data(float* data_array); bool send_data(int* data_array); bool send_data(string data_string,SOCKET SocReceiver); //only for SERVER bool send_data(float* data_array,SOCKET SocReceiver); //only for SERVER bool recv_data(string& data_string); //only for CLIENT bool recv_data(float* data_array); //only for CLIENT bool recv_data(int* data_array); //only for CLIENT and SERVER if only one Client bool recv_data(string& data_string,SOCKET SocSender); //only for SERVER bool recv_data(float* data_array,SOCKET SocSender); //only for SERVER bool add_client(SOCKET new_client); //only for SERVER bool remove_client(SOCKET client_to_remove); //only for SERVER SOCKET get_server_socket(void); void lost_connection(void); private: //Variables bool m_connected_to_server; //only for CLIENT int m_clients_counter; //only for SERVER serverCom m_ServerCom; //only for SERVER clientCom m_ClientCom; //only for CLIENT //Functions }; #endif // NETWORKCOM_H <file_sep>#include "networkCom.h" networkCom::networkCom() { m_ready=false; } bool networkCom::init(string status) { //Init m_ready=false; m_connected_to_server=false; m_clients_counter=0; if(status=="server") { m_net_status=net_server; m_ServerCom=serverCom(); if(!m_ServerCom.init()) { cout<<"ERROR: Could not init Server\n"; } else m_ready=true; } if(status=="client") { m_net_status=net_client; m_ClientCom=clientCom(); if(!m_ClientCom.init()) { cout<<"ERROR: Could not init Client\n"; } else m_ready=true; } return m_ready; } bool networkCom::connect_to_server(string sIP,int port) { if(m_net_status==net_client) { if(m_ClientCom.set_IP_and_connect(sIP,port)) return true; } return false; } bool networkCom::set_port_and_bind(int port) { if(m_net_status==net_server) { if(m_ServerCom.set_port_and_bind(port)) return true; } return false; } bool networkCom::start_to_listen(int backLog) { if(m_net_status==net_server) { if(m_ServerCom.start_to_listen(backLog)) return true; } return false; } bool networkCom::set_broadcast_port(int port_sending,int port_replying) { if(m_net_status==net_server) { if(m_ServerCom.set_broadcast_port(port_sending, port_replying)) return true; } return false; } bool networkCom::set_broadcast_port(string net, int port_sending,int port_replying) { if(m_net_status==net_client) { if(m_ClientCom.set_broadcast_net_and_port(net, port_sending, port_replying)) return true; } return false; } bool networkCom::test_connection(void) { if(m_net_status==net_client) { if(m_ClientCom.test_connection()) { m_connected_to_server=true; return true; } else return false; } return false; } bool networkCom::known_socket(SOCKET new_socket) { if(m_net_status==net_server) { if(m_ServerCom.known_socket(new_socket)) return true; } return false; } bool networkCom::broadcast_my_ip(void) { if(m_net_status==net_client) { if(m_ClientCom.broadcast_my_ip()) return true; } return false; } bool networkCom::check_for_broadcast(void) { if(m_net_status==net_server) { if(m_ServerCom.check_for_broadcast()) return true; } return false; } bool networkCom::check_for_broadcast_reply(void) { if(m_net_status==net_client) { if(m_ClientCom.check_for_broadcast_reply()) return true; } return false; } bool networkCom::get_server_IP_and_port(string& IP_and_port) { if(m_net_status==net_client) { if(m_ClientCom.get_server_IP_and_port(IP_and_port)) return true; } return false; } bool networkCom::send_data(string data_string) { if(m_net_status==net_server) { m_ServerCom.send_data(data_string); return true; } if(m_net_status==net_client) { m_ClientCom.send_data(data_string); return true; } return false; } bool networkCom::send_data(float* data_array) { if(m_net_status==net_server) { m_ServerCom.send_data(data_array); return true; } if(m_net_status==net_client) { m_ClientCom.send_data(data_array); return true; } return false; } bool networkCom::send_data(int* data_array) { if(m_net_status==net_server) { m_ServerCom.send_data(data_array); return true; } if(m_net_status==net_client) { m_ClientCom.send_data(data_array); return true; } return false; } bool networkCom::send_data(string data_string,SOCKET SocReceiver) { if(m_net_status==net_server) { if(!m_ServerCom.send_data(data_string)) return false; return true; } return false; } bool networkCom::send_data(float* data_array,SOCKET SocReceiver) { if(m_net_status==net_server) { if(!m_ServerCom.send_data(data_array)) return false; return true; } return false; } bool networkCom::recv_data(string& data_string) { if(m_net_status==net_client) { if(m_ClientCom.recv_data(data_string)) return true; } return false; } bool networkCom::recv_data(float* data_array) { if(m_net_status==net_client) { if(m_ClientCom.recv_data(data_array)) return true; } return false; } bool networkCom::recv_data(string& data_string,SOCKET SocSender) { if(m_net_status==net_server) { m_ServerCom.recv_data(data_string,SocSender); return true; } return false; } bool networkCom::recv_data(float* data_array,SOCKET SocSender) { if(m_net_status==net_server) { m_ServerCom.recv_data(data_array,SocSender); return true; } return false; } bool networkCom::recv_data(int* data_array) { if(m_net_status==net_server) { m_ServerCom.recv_data(data_array); return true; } if(m_net_status==net_client) { m_ClientCom.recv_data(data_array); return true; } return false; } bool networkCom::add_client(SOCKET new_client) { if(m_net_status==net_server) { if(m_ServerCom.add_client(new_client)) { m_clients_counter++; return true; } } return false; } bool networkCom::remove_client(SOCKET client_to_remove) { if(m_net_status==net_server) { if(m_ServerCom.remove_client(client_to_remove)) { m_clients_counter--; return true; } } return false; } SOCKET networkCom::get_server_socket(void) { if(m_net_status==net_server) { return m_ServerCom.get_server_socket(); } if(m_net_status==net_client) { return m_ClientCom.get_server_socket(); } return SOCKET(); } void networkCom::lost_connection(void) { m_connected_to_server=false; } <file_sep>#define _WIN32_WINNT 0x0502 //Needed for GetConsoleWindow() #define WM_WSAASYNC (WM_USER +5) //for Async windows messages #include <iostream> #include <windows.h> #include <gl/gl.h> #include <fcntl.h> //for console #include <stdio.h> #include <cstdio> #include <ctime> #include <winsock2.h> #include "definitions.h" #include "game.h" #include "networkCom.h" /*Include following libraries lobSOIL.a OpenAL32.lib XInput32.lib XInput64.lib opengl32 glu32 gdi32 ogg.lib vorbis.lib vorbisfile.lib */ int* g_pWindow_size; bool* g_pKeys_real; bool* g_pKeys_translated; int* g_pMouse_pos; bool* g_pMouse_but; int g_window_border_size=28; game g_game; networkCom g_NetCom; using namespace std; LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM); void EnableOpenGL(HWND hwnd, HDC*, HGLRC*); void DisableOpenGL(HWND, HDC, HGLRC); bool MP_setup(HWND hwnd); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { string command_line=lpCmdLine; bool debug_mode=true; if(command_line=="debug") debug_mode=true; //init and reset keys g_pWindow_size=new int[2]; g_pWindow_size[0]=800; g_pWindow_size[1]=800; g_pKeys_real=new bool[256]; g_pKeys_translated=new bool[256]; for(int i=0;i<256;i++) { g_pKeys_real[i]=false; g_pKeys_translated[i]=false; } g_pMouse_pos=new int[2]; g_pMouse_pos[0]=0; g_pMouse_pos[1]=0; g_pMouse_but=new bool[4]; g_pMouse_but[0]=g_pMouse_but[1]=g_pMouse_but[2]=g_pMouse_but[3]=false; WNDCLASSEX wcex; HWND hwnd; HDC hDC; HGLRC hRC; MSG msg; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_OWNDC; wcex.lpfnWndProc = WindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wcex.lpszMenuName = NULL; wcex.lpszClassName = "Rapid Chess"; wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);; if (!RegisterClassEx(&wcex)) return 0; if(!debug_mode && false) { //Detect screen resolution RECT desktop; // Get a handle to the desktop window const HWND hDesktop = GetDesktopWindow(); // Get the size of screen to the variable desktop GetWindowRect(hDesktop, &desktop); // The top left corner will have coordinates (0,0) // and the bottom right corner will have coordinates // (horizontal, vertical) g_pWindow_size[0] = desktop.right; g_pWindow_size[1] = desktop.bottom; } //if debug mode start console HWND hwnd_console; if(debug_mode) { //Only output console AllocConsole() ; AttachConsole( GetCurrentProcessId() ) ; freopen( "CON", "w", stdout ) ; //Set console title SetConsoleTitle("Debug Console"); hwnd_console=GetConsoleWindow(); MoveWindow(hwnd_console,g_pWindow_size[0],0,680,510,TRUE); cout<<"*-------------*\n*-Rapid-Chess-*\n*-------------*\n\n"; cout<<"Version: "<<_version<<endl<<endl; } else { //ShowCursor(FALSE);//hide cursor //ShowWindow(GetConsoleWindow(),SW_HIDE);//hide console } hwnd = CreateWindowEx(0, "Rapid Chess", "Rapid Chess", //WS_VISIBLE | WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, //WS_OVERLAPPEDWINDOW for window WS_POPUP | (WS_OVERLAPPEDWINDOW ^ WS_THICKFRAME), CW_USEDEFAULT, CW_USEDEFAULT, g_pWindow_size[0], g_pWindow_size[1]+g_window_border_size, NULL, NULL, hInstance, NULL); ShowWindow(hwnd, nCmdShow); EnableOpenGL(hwnd, &hDC, &hRC); //CloseWindow(hwnd_console); //start the game if( !g_game.init(&g_pWindow_size[0],&g_pKeys_real[0],&g_pKeys_translated[0], &g_pMouse_pos[0],&g_pMouse_but[0]) ) { cout<<"ERROR: Could not initaialize the game\n"; if(debug_mode) system("PAUSE"); return 1; } //MP status MP_setup(hwnd); clock_t time_now=clock(); clock_t time_last=time_now; //clock_t time_sum=0; clock_t time_step=_time_step*1000.0;//10.0;//0.010 ms -> 100 updates per sec bool update_screen=true; bool quit=false; while(!quit) { if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if(msg.message==WM_QUIT) { quit=true; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } else { //quick quit test if(g_pKeys_real[VK_ESCAPE]) quit=true; time_now=clock(); while( time_last+time_step <= time_now ) { time_last+=time_step; bool quit_game=false; if( !g_game.update(quit_game) )//static update { //require reset of game if( !g_game.init(&g_pWindow_size[0],&g_pKeys_real[0],&g_pKeys_translated[0], &g_pMouse_pos[0],&g_pMouse_but[0],false) ) { cout<<"ERROR: Game could not reinitialize\n"; if(debug_mode) system("PAUSE"); return 1; } //MP reset WSACleanup(); MP_setup(hwnd); } if(quit_game) quit=true; update_screen=true; } //draw, if anything updated if(update_screen) { update_screen=false; g_game.draw(); SwapBuffers(hDC); } } } //clean up WSACleanup(); delete[] g_pWindow_size; delete[] g_pKeys_real; delete[] g_pKeys_translated; delete[] g_pMouse_pos; delete[] g_pMouse_but; DisableOpenGL(hwnd, hDC, hRC); DestroyWindow(hwnd); return msg.wParam; } LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CLOSE: { PostQuitMessage(0); } break; case WM_DESTROY: { return 0; } break; case WM_MOUSEMOVE: { g_pMouse_pos[0]=LOWORD(lParam); g_pMouse_pos[1]=HIWORD(lParam);//+g_window_border_size; } break; case WM_LBUTTONDOWN: { g_pMouse_but[0]=true; } break; case WM_LBUTTONUP: { g_pMouse_but[0]=false; } break; case WM_RBUTTONDOWN: { g_pMouse_but[1]=true; cout<<"x: "<<g_pMouse_pos[0]<<", y: "<<g_pMouse_pos[1]<<endl; //temp } break; case WM_RBUTTONUP: { g_pMouse_but[1]=false; } break; case WM_MOUSEWHEEL: { if(HIWORD(wParam)>5000) {g_pMouse_but[2]=true;} if(HIWORD(wParam)>100&&HIWORD(wParam)<5000) {g_pMouse_but[3]=true;} } break; case WM_KEYDOWN: { g_pKeys_real[wParam]=true; cout<<"Pressed: "<<wParam<<endl; } break; case WM_KEYUP: { g_pKeys_real[wParam]=false; } break; case WM_WSAASYNC: { // what word? switch(WSAGETSELECTEVENT(lParam)) { case FD_READ: //incomming data from SOCKET wParam { cout<<"FD_READ\n"; g_game.recv_data(wParam); } break; case FD_WRITE: //only used if sending large files { cout<<"FD_WRITE\n"; } break; case FD_ACCEPT: // client wants to join { cout<<"FD_ACCEPT\n"; if(g_NetCom.add_client(wParam)) { //start game counter g_game.start_game(); cout<<"New Client Joined\n"; } else { cout<<"Bad Client tried to join\n"; } return(0); } break; case FD_CONNECT: //Client is now connected to server { cout<<"FD_CONNECT\n"; //Test Connection if(g_NetCom.test_connection()) { //start game counter g_game.start_game(); cout<<"You are now connected to the server\n"; } else//not connected { cout<<"Could not connect to server\n"; break; } } break; case FD_CLOSE: //lost connection to server { cout<<"FD_CLOSE\n"; if(g_NetCom.m_net_status==net_client) g_NetCom.lost_connection(); if(g_NetCom.m_net_status==net_server) { if(g_NetCom.remove_client(wParam)) cout<<"Client Removed\n"; } g_game.m_pause_game=true; } break; } } default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0; } void EnableOpenGL(HWND hwnd, HDC* hDC, HGLRC* hRC) { PIXELFORMATDESCRIPTOR pfd; int iFormat; /* get the device context (DC) */ *hDC = GetDC(hwnd); /* set the pixel format for the DC */ ZeroMemory(&pfd, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; pfd.cDepthBits = 16; pfd.cStencilBits = 8; pfd.iLayerType = PFD_MAIN_PLANE; iFormat = ChoosePixelFormat(*hDC, &pfd); SetPixelFormat(*hDC, iFormat, &pfd); /* create and enable the render context (RC) */ *hRC = wglCreateContext(*hDC); wglMakeCurrent(*hDC, *hRC); //set 2D mode glClearColor(0.0,0.0,0.0,0.0); //Set the cleared screen colour to black glViewport(0,0,g_pWindow_size[0],g_pWindow_size[1]); //This sets up the viewport so that the coordinates (0, 0) are at the top left of the window //Set up the orthographic projection so that coordinates (0, 0) are in the top left //and the minimum and maximum depth is -10 and 10. To enable depth just put in //glEnable(GL_DEPTH_TEST) glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,g_pWindow_size[0],g_pWindow_size[1],0,-1,1); //Back to the modelview so we can draw stuff glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //Enable antialiasing glEnable(GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glHint(GL_LINE_SMOOTH_HINT,GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT,GL_NICEST); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearStencil( 0 ); } void DisableOpenGL (HWND hwnd, HDC hDC, HGLRC hRC) { wglMakeCurrent(NULL, NULL); wglDeleteContext(hRC); ReleaseDC(hwnd, hDC); } bool MP_setup(HWND hwnd) { string ip; switch(g_game.get_MP_settings(ip)) { case 0://SP { g_game.m_player_id=ps_none; g_game.start_game(); }break; case 1://host { cout<<"SERVER\n"; if(!g_NetCom.init("server")) cout<<"ERROR: Init\n"; if(!g_NetCom.set_port_and_bind(5001)) cout<<"ERROR: Set port and bind\n"; WSAAsyncSelect( g_NetCom.get_server_socket() , hwnd, WM_WSAASYNC, FD_READ | FD_WRITE | FD_ACCEPT | FD_CLOSE); int err=WSAGetLastError(); if(err!=0) cout<<"WSAAsync err: "<<err<<endl; if(!g_NetCom.start_to_listen(10)) cout<<"ERROR: Listen\n"; g_game.m_pNetCom=&g_NetCom; g_game.m_player_id=ps_hoster; }break; case 2://join { cout<<"CLIENT\n"; cout<<"IP: "<<ip<<endl; if(!g_NetCom.init("client")) cout<<"ERROR: Init\n"; WSAAsyncSelect( g_NetCom.get_server_socket() , hwnd, WM_WSAASYNC, FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE); int err=WSAGetLastError(); if(err!=0) cout<<"WSAAsync err: "<<err<<endl; if(!g_NetCom.connect_to_server(ip,5001)) cout<<"ERROR: Connect to server\n"; g_game.m_pNetCom=&g_NetCom; g_game.m_player_id=ps_joiner; }break; } return true; }
6fe72958bb68d17c9d493ab1b997e78e48218894
[ "C", "C++" ]
15
C
erikhallin/RTS_Chess
885c0dbc6cc58b99a52eb86b8826fac718f81e93
4d13d3145b43fa1bda815917c3822d7b1944e9b3
refs/heads/master
<file_sep>package notification type NotificationOptions struct { Endpoint string } func NewNotificationOptions() *NotificationOptions { return &NotificationOptions{ Endpoint: "", } } func (s *NotificationOptions) ApplyTo(options *NotificationOptions) { if s.Endpoint != "" { options.Endpoint = s.Endpoint } }
b81f7d60c9ef18e5462f1978d2477dedd84522de
[ "Go" ]
1
Go
gottaBoy/kubesphere
1361106bdd135ec294ac9a50409f0b2fbb2716da
4c6f6ab52371aed924efc37e0a3672ece31bc34a
refs/heads/main
<repo_name>Ali-Rakib-Bhuiyan1/helth-care<file_sep>/README.md live-Link:https://health-care-hospital.web.app/ #Features -Online appointment making -Prescribe medicine for each patient # Thechnology : -React.js -Bootstrap4 -CSS3 -React Router -Firebase <file_sep>/src/compoments/Doctors/Doctors.js import React from 'react'; import Doctor from './../Doctor/Doctor'; import { useState, useEffect } from 'react'; const Doctors = () => { const [doctors, setDoctors] = useState([]) useEffect(()=>{ fetch('doctor.json') .then(res =>res.json()) .then(data =>setDoctors(data)); },[]) return ( <div className = "doctors"> <h2 className ="text-primary text-center mt"> Our Doctors</h2> <div className ="doctors-continers"> { doctors.map(service =><Doctor key ={service.id} service={service} ></Doctor>) } </div> </div> ); }; export default Doctors;<file_sep>/src/compoments/AboutCare/AboutCare.js import React from 'react'; import { Card, CardGroup } from 'react-bootstrap'; import './AboutCare.css' const AboutCare = () => { return ( <div> <h1 className ="text-danger"> Welcome to HEALTHCARE</h1> <h3>Our medical specialists care about you & your family’s health</h3> <CardGroup> <Card> <Card.Img className="img-card" variant="top" src="https://image.shutterstock.com/image-vector/caduceus-hermes-healthcare-flat-vector-600w-272462960.jpg" /> <Card.Body> <Card.Title className ="text-danger">HealthCare Professionals</Card.Title> <Card.Text> Sed posuere nunc libero pellentesque vitae ultrices posuere. Praesent justo laoreet dignissim lectus etiam ipsum habitant tristique </Card.Text> </Card.Body> </Card> <Card> <Card.Img className="img-card" variant="top" src="https://image.shutterstock.com/image-vector/doctor-approval-check-mark-isolated-600w-607774457.jpg" /> <Card.Body> <Card.Title className ="text-danger">Medical Excellence</Card.Title> <Card.Text> Sed posuere nunc libero pellentesque vitae ultrices posuere. Praesent justo laoreet dignissim lectus etiam ipsum habitant tristique </Card.Text> </Card.Body> </Card> <Card> <Card.Img className="img-card" variant="top" src="https://www.greenlightmedical.com/wp-content/uploads/2020/01/breast_robotic_surgery-1080x675.jpg" /> <Card.Body> <Card.Title className ="text-danger">Latest Technologies</Card.Title> <Card.Text> Sed posuere nunc libero pellentesque vitae ultrices posuere. Praesent justo laoreet dignissim lectus etiam ipsum habitant tristique </Card.Text> </Card.Body> </Card> </CardGroup> </div> ); }; export default AboutCare; <file_sep>/src/compoments/Banner/Banner.js import React from 'react'; import { Carousel } from 'react-bootstrap'; import './Banner.css' const Banner = () => { return ( <> <Carousel> <Carousel.Item> <div> <img className="d-block banner-img" src="https://thumbs.dreamstime.com/b/doctor-banner-young-handsome-holding-white-blank-place-your-text-48602276.jpg/800x400?text=Best Treat" alt="First slide" /> <div className = "centered"> <h1 className ="text-danger">The best Hospital & doctors</h1> <p className ="text-dark">Nulla vitae elit libero, a pharetra augue mollis interdum.</p> </div> </div> </Carousel.Item> <Carousel.Item> <div> <img className="d-block banner-img" src="https://thumbs.dreamstime.com/b/nurse-doctor-training-young-woman-as-140360423.jpg" alt="Second slide" /> <div className="centered"> <h1 className ="text-danger ">Best Treatment & happy life</h1> <p className ="text-dark "> Lorem ipsum dolor sit amet consectetur adipisicing elit. At, beatae. </p> </div> </div> </Carousel.Item> <Carousel.Item> <div> <img className="d-block banner-img" src="https://i.pinimg.com/736x/6b/49/59/6b495988df108235cfd31bac305d8cf1.jpg" alt="Third slide" /> <div className ="centered"> <h1 className ="text-danger">Healthy tablets and medicine</h1> <p className ="text-dark">Praesent commodo cursus magna, vel scelerisque nisl consectetur.</p> </div> </div> </Carousel.Item> </Carousel> </> ); }; export default Banner;<file_sep>/src/compoments/Doctor/Doctor.js import React from 'react'; import { Image } from 'react-bootstrap'; import './doctor.css' const Doctor = ({service}) => { const {name, img, mobile} = service; return ( <div className ="doctor"> <div className="text-center"> <Image className="mb-3" src={img} alt="" fluid /> <h5>{name}</h5> <h6>{mobile}</h6> </div> </div> ); }; export default Doctor;<file_sep>/src/compoments/Allservices/Allservice.js import React, { useEffect, useState } from 'react'; import { useParams } from 'react-router'; const Allservice = () => { let {id} = useParams() const [servicesDetails, setServiceDetails] = useState([]) const [singleService, setSingleService] = useState({}) useEffect(()=>{ fetch('/allservice.json') .then(res =>res.json()) .then(data =>setServiceDetails(data)) },[]) useEffect(()=>{ const foundService = servicesDetails.find(service =>service.id== id) setSingleService(foundService) },[servicesDetails]) return ( <div> <img src={singleService?.img} alt="" /> <h1 className ="text-danger fw-bold"> WellCome {singleService?.name}</h1> <br /> <p className="fs-5" >{singleService?.description}</p> </div> ); }; export default Allservice;<file_sep>/src/compoments/Header/Navber/Naver.js import React from 'react'; import { Button, Container, Nav, Navbar } from "react-bootstrap"; import { Link } from "react-router-dom"; import useAuth from './../../../hoocks/useAuth'; const Naver = () => { const {user, logOut} = useAuth() return ( <Container> <Navbar fixed="top" collapseOnSelect expand="lg" bg="dark" variant="dark"> <div className="container mb-2"> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse id="responsive-navbar-nav"> <Nav className="m-auto"> <Nav.Link as={Link} to="/home">Home</Nav.Link> <Nav.Link as={Link} to="/services">services</Nav.Link> <Nav.Link as={Link} to="/contact">Contact</Nav.Link> <Nav.Link as={Link} to="/About">About us</Nav.Link> {user?.email? <Button onClick ={logOut} variant="light">Logout</Button>: <Nav.Link as={Link} to="/login">Login</Nav.Link> } <Navbar.Text> Signed in as: <a href="#login">{user?.displayName}</a> </Navbar.Text>H </Nav> </Navbar.Collapse> </div> </Navbar> </Container> ); }; export default Naver;<file_sep>/src/compoments/Login/firebase/firebase.js const firebaseConfig = { apiKey: "<KEY>", authDomain: "health-care-hospital.firebaseapp.com", projectId: "health-care-hospital", storageBucket: "health-care-hospital.appspot.com", messagingSenderId: "739857504279", appId: "1:739857504279:web:1eb108c800258f23196452" }; export default firebaseConfig <file_sep>/src/compoments/Home/Home.js import React from 'react'; import Banner from './../Banner/Banner'; import Naver from './../Header/Navber/Naver'; import AboutCare from './../AboutCare/AboutCare'; import Services from '../Services/Services'; import Contrac from '../contrac/Contrac'; import Doctors from './../Doctors/Doctors'; import Footer from '../Footer/Footer'; const Home = () => { return ( <div> <Naver></Naver> <Banner></Banner> <AboutCare></AboutCare> <Services></Services> <br /><br /> <Contrac></Contrac> <Doctors></Doctors> <br /> <br />\ <Footer></Footer> </div> ); }; export default Home;<file_sep>/src/compoments/contrac/Contrac.js import React from 'react'; const Contrac = () => { return ( <div className="text-center bg-dark text-white"> <br /> <br /><br /> <h3 className="p-3">Contact With Us</h3> <input className="p-2 rounded w-50" type="text" name="name" placeholder="Your Name" /> <br/> <br/> <input className="p-2 rounded w-50" type="email" name="email" placeholder="Your Email" /> <br/> <br/> <input className="p-2 rounded w-50" type="text" name="subject" placeholder="subject" /> <br/> <br/> <textarea className="p-2 mb-4 rounded w-50" name="message" id="message" cols="40" rows="7" placeholder="Your Message"></textarea> <br/> <input className="btn btn-primary" type="submit" value="SEND" /> <br /> </div> ); }; export default Contrac;
037f07b2f7f866686c75b8135d85191cb04e703e
[ "Markdown", "JavaScript" ]
10
Markdown
Ali-Rakib-Bhuiyan1/helth-care
9ea7172a78ac97594ddfbffcfdcc088bad92beb7
5792af7ea2a756fbd55b032166e0bb7d01183b0e
refs/heads/main
<repo_name>jonaMclaurin/jqgrid_example<file_sep>/script.js let myBttn = document.getElementById("add"); let dataBttn = document.getElementById("data"); let textarea = document.getElementById("text"); let idx = 1; myBttn.addEventListener("click", (e) => { //event.preventDefault(); idx++; $("#grid").jqGrid("addRow", { rowID: idx, position: "first", initdata: { id: idx.toString(), FirstName: "sda", LastName: "asda" }, }); lastSel = idx; }); dataBttn.addEventListener("click", (e) => { let ids = $("#grid").jqGrid("getDataIDs"); let objData = []; for (var i = 0; i < ids.length; i++) { var rowId = ids[i]; var rowData = $("#grid").jqGrid("getRowData", rowId); objData.push(rowData); } textarea.value = JSON.stringify(objData); }); var lastSel; $(function () { $("#grid").jqGrid({ datatype: "local", caption: "My Grid", height: "auto", data: [{ id: 1, FirstName: "Angela", LastName: "Mekel" }], colNames: ["id", "First Name", "Last Name"], colModel: [ { name: "id", editable: false }, { name: "FirstName", label: "FirstName", editable: true }, { name: "LastName", label: "LastName", editable: true }, ], pager: "#pager", afterInsertRow: function (id, rowdata, rowel) { if (lastSel !== undefined) { $("#grid").jqGrid("editRow", id, true); } }, onSelectRow: function (id, status, e) { if (id && id !== lastSel) { $("#grid").jqGrid("saveRow", lastSel); //$("#grid").jqGrid("restoreRow", lastSel); $("#grid").jqGrid("editRow", id, true); console.log(id, lastSel); } else if (id === lastSel) { $("#grid").jqGrid("editRow", id, true); lastSel = id; } lastSel = id; }, }); $("#grid").jqGrid("navGrid", "#pager", { add: true, edit: true, del: true, view: false, search: false, refresh: false, }); }); document.addEventListener("click", function (e) { let id = e.target.id; console.log(id, e.target.nodeName); if (!isDescendant(event.target, "gbox_grid")) { console.log(lastSel); $("#grid").jqGrid("saveRow", lastSel); $("#grid").jqGrid("resetSelection"); } }); const isDescendant = (el, parentId) => { let isChild = false; let i = 0; if (el.id === parentId) { isChild = true; } while ((el = el.parentNode)) { i++; console.log(i); if (el.id === parentId) { isChild = true; } } console.log(isChild); return isChild; }; <file_sep>/script2.js let myBttn = document.getElementById("add"); //let dataBttn = document.getElementById("data"); let textarea = document.getElementById("text"); let delBttn = document.getElementById("del"); let idx1 = 1; let idx2 = 1; myBttn.addEventListener("click", (e) => { //event.preventDefault(); let selrow = $("#grid").jqGrid("getGridParam", "selrow"); if (selrow == null) { alert("Please select a row"); } else { let data = $("#grid").jqGrid("getRowData", selrow); //onsole.log(data); $("#grid2").jqGrid("addRow", { rowId: data.id, initdata: { id: data.id, FirstName: data.FirstName, LastName: data.LastName, IP: data.IP, "IP set": data.IP !== "" ? "yes" : "no", }, position: "last", }); } }); del.addEventListener("click", (e) => { let selrow = $("#grid2").jqGrid("getGridParam", "selrow"); if (selrow == null) { alert("Please select a row"); } else { //console.log(selrow); $("#grid2").jqGrid("delGridRow", selrow); lastSel2 = undefined; } }); /* dataBttn.addEventListener("click", (e) => { let ids = $("#grid").jqGrid("getDataIDs"); let objData = []; for (var i = 0; i < ids.length; i++) { var rowId = ids[i]; var rowData = $("#grid").jqGrid("getRowData", rowId); objData.push(rowData); } textarea.value = JSON.stringify(objData); }); */ var lastSel; var lastSel2; var first = 0; $(function () { $("#grid") .jqGrid({ datatype: "local", caption: "My Grid", height: "auto", data: dummy /* [ { id: 1, FirstName: "Angela", LastName: "Mekel", IP: "123" }, { id: 2, FirstName: "JONA", LastName: "RM", IP: "" }, ] */, colNames: ["id", "First Name", "Last Name", "IP"], colModel: [ { name: "id", editable: false }, { name: "FirstName", label: "FirstName", editable: false }, { name: "LastName", label: "LastName", editable: false }, { name: "IP", label: "IP", editable: false }, ], pager: true, afterInsertRow: function (id, rowdata, rowel) {}, onSelectRow: function (id, status, e) { if (id === lastSel) { $("#grid").jqGrid("setSelection", id); } }, }) .jqGrid("filterToolbar"); $("#grid2").jqGrid({ datatype: "local", caption: "My Grid", height: "auto", data: [ { id: 1, FirstName: "Angela", LastName: "Mekel", IP: "192.168.23.23", Occupation: "OptionA", "IP set": "yes", }, ], colNames: ["id", "First Name", "Last Name", "IP", "Occupation", "IP set"], colModel: [ { name: "id", editable: false }, { name: "FirstName", label: "FirstName", editable: false }, { name: "LastName", label: "LastName", editable: false }, { name: "IP", index: "IP", label: "IP", editable: true, edittype: "custom", editoptions: { custom_element: function (value, options) { console.log(value); let data = $("#grid2").jqGrid("getRowData", options.rowId); console.log(data["IP set"]); if (data["IP set"] === "yes") { return $("<input disabled>").attr("type", "text").val(value); } else { return $("<input>").attr("type", "text").val(value); } }, custom_value: function (elem, operation, value) { //console.log(elem, operation, value); if (operation == "get") { return elem.val(); } else { elem.val(value); } }, }, }, { name: "Occupation", index: "Occupation", label: "Occupation", editable: true, edittype: "select", editoptions: { value: { OptionA: "OptionA", OptionB: "OptionB", }, }, }, { name: "IP set", editable: false, hidden: true }, ], pager: "#pager2", afterInsertRow: function (id, rowdata, rowel) {}, onSelectRow: function (id, status, e) { if (id && id !== lastSel2) { $("#grid2").jqGrid("saveRow", lastSel2); //$("#grid").jqGrid("restoreRow", lastSel); $("#grid2").jqGrid("editRow", id, true); //console.log(id, lastSel2); } else if (id === lastSel2) { $("#grid2").jqGrid("editRow", id, true); lastSel2 = id; } lastSel2 = id; }, }); }); document.addEventListener("click", function (e) { let selrow1 = $("#grid").jqGrid("getGridParam", "selrow"); let selrow2 = $("#grid2").jqGrid("getGridParam", "selrow"); //console.log(selrow1, selrow2); if (!isDescendant(e.target, "gbox_grid") && selrow1) { //console.log(lastSel); $("#grid").jqGrid("resetSelection"); lastSel = undefined; } if (!isDescendant(e.target, "gbox_grid2") && selrow2) { $("#grid2").jqGrid("saveRow", selrow2); $("#grid2").jqGrid("resetSelection"); lastSel2 = undefined; } }); const isDescendant = (el, parentId) => { let isChild = false; let i = 0; if (el.id === parentId) { isChild = true; } while ((el = el.parentNode)) { i++; //console.log(i); if (el.id === parentId) { isChild = true; } } //console.log(isChild); return isChild; }; var dummy = [ { id: 19, FirstName: "NOOEQz", LastName: "LiyUip", IP: "172.16.58.3", }, { id: 143, FirstName: "JoKXCb", LastName: "pBuubi", IP: "192.168.3.11", }, { id: 168, FirstName: "GrDLXH", LastName: "lgzGsF", IP: "192.168.3.11", }, { id: 23, FirstName: "IHTvkF", LastName: "VoMmAC", IP: "172.16.31.10", }, { id: 115, FirstName: "QiqTtI", LastName: "xciMld", IP: "172.16.17.32", }, { id: 30, FirstName: "uHdxng", LastName: "SaeQUW", IP: "172.16.31.10", }, { id: 173, FirstName: "fEbpRk", LastName: "sTaBQH", IP: "172.16.17.32", }, { id: 118, FirstName: "zyfinN", LastName: "BAxNlk", IP: "192.168.3.11", }, { id: 34, FirstName: "uqMQDq", LastName: "bOTqwP", IP: "172.16.17.32", }, { id: 130, FirstName: "EPvAaQ", LastName: "WevECm", IP: "172.16.58.3", }, { id: 193, FirstName: "LisYXM", LastName: "YyXVSf", IP: "172.16.17.32", }, { id: 55, FirstName: "ScSaYq", LastName: "nTKXup", IP: "10.130.251.53", }, { id: 185, FirstName: "onlLXQ", LastName: "rudgFm", IP: "192.168.127.12", }, { id: 68, FirstName: "sxxgwm", LastName: "febgtD", IP: "172.16.58.3", }, { id: 48, FirstName: "pljVQl", LastName: "UXVVVC", IP: "172.16.17.32", }, { id: 27, FirstName: "TtCFYu", LastName: "hEKDGz", IP: "192.168.3.11", }, { id: 79, FirstName: "mbjzfe", LastName: "YDVezA", IP: "172.16.17.32", }, { id: 129, FirstName: "rkiHRc", LastName: "rbGCni", IP: "172.16.31.10", }, { id: 145, FirstName: "KXUixg", LastName: "oAbfzS", IP: "172.16.17.32", }, { id: 23, FirstName: "AhsDoQ", LastName: "fiCWHR", IP: "172.16.17.32", }, ];
e08957097a05936ce3946a02be2f5cfb5cd122b8
[ "JavaScript" ]
2
JavaScript
jonaMclaurin/jqgrid_example
cd56e426b27b3312b91cb0b6278624088fd75d3d
7379e0d6a868522551604404766cfa73942eb5f2
refs/heads/master
<repo_name>superbiche/sentry-laravel<file_sep>/test/Sentry/ExpectsException.php <?php namespace Sentry\Laravel\Tests; use RuntimeException; trait ExpectsException { protected function safeExpectException(string $class): void { if (method_exists($this, 'expectException')) { $this->expectException($class); return; } if (method_exists($this, 'setExpectedException')) { $this->setExpectedException($class); return; } throw new RuntimeException('Could not expect an exception.'); } } <file_sep>/src/Sentry/Laravel/Tracing/Middleware.php <?php namespace Sentry\Laravel\Tracing; use Closure; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Routing\Route; use Sentry\Laravel\Integration; use Sentry\SentrySdk; use Sentry\State\HubInterface; use Sentry\Tracing\Span; use Sentry\Tracing\SpanContext; use Sentry\Tracing\TransactionContext; class Middleware { /** * The current active transaction. * * @var \Sentry\Tracing\Transaction|null */ protected $transaction; /** * The span for the `app.handle` part of the application. * * @var \Sentry\Tracing\Span|null */ protected $appSpan; /** * The timestamp of application bootstrap completion. * * @var float|null */ private $bootedTimestamp; /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * * @return mixed */ public function handle($request, Closure $next) { if (app()->bound(HubInterface::class)) { $this->startTransaction($request, app(HubInterface::class)); } return $next($request); } /** * Handle the application termination. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Response $response * * @return void */ public function terminate($request, $response): void { if ($this->transaction !== null && app()->bound(HubInterface::class)) { if ($this->appSpan !== null) { $this->appSpan->finish(); } // Make sure we set the transaction and not have a child span in the Sentry SDK // If the transaction is not on the scope during finish, the trace.context is wrong SentrySdk::getCurrentHub()->setSpan($this->transaction); if ($request instanceof Request) { $this->hydrateRequestData($request); } if ($response instanceof Response) { $this->hydrateResponseData($response); } $this->transaction->finish(); } } /** * Set the timestamp of application bootstrap completion. * * @param float|null $timestamp The unix timestamp of the booted event, default to `microtime(true)` if not `null`. * * @return void * @internal This method should only be invoked right after the application has finished "booting": * For Laravel this is from the application `booted` callback. * For Lumen this is right before returning from the `bootstrap/app.php` file. */ public function setBootedTimestamp(?float $timestamp = null): void { $this->bootedTimestamp = $timestamp ?? microtime(true); } private function startTransaction(Request $request, HubInterface $sentry): void { $requestStartTime = $request->server('REQUEST_TIME_FLOAT', microtime(true)); $sentryTraceHeader = $request->header('sentry-trace'); $context = $sentryTraceHeader ? TransactionContext::fromSentryTrace($sentryTraceHeader) : new TransactionContext; $context->setOp('http.server'); $context->setData([ 'url' => '/' . ltrim($request->path(), '/'), 'method' => strtoupper($request->method()), ]); $context->setStartTimestamp($requestStartTime); $this->transaction = $sentry->startTransaction($context); // Setting the Transaction on the Hub SentrySdk::getCurrentHub()->setSpan($this->transaction); $bootstrapSpan = $this->addAppBootstrapSpan($request); $appContextStart = new SpanContext(); $appContextStart->setOp('app.handle'); $appContextStart->setStartTimestamp($bootstrapSpan ? $bootstrapSpan->getEndTimestamp() : microtime(true)); $this->appSpan = $this->transaction->startChild($appContextStart); SentrySdk::getCurrentHub()->setSpan($this->appSpan); } private function addAppBootstrapSpan(Request $request): ?Span { if ($this->bootedTimestamp === null) { return null; } $laravelStartTime = defined('LARAVEL_START') ? LARAVEL_START : $request->server('REQUEST_TIME_FLOAT'); if ($laravelStartTime === null) { return null; } $spanContextStart = new SpanContext(); $spanContextStart->setOp('app.bootstrap'); $spanContextStart->setStartTimestamp($laravelStartTime); $spanContextStart->setEndTimestamp($this->bootedTimestamp); $span = $this->transaction->startChild($spanContextStart); // Consume the booted timestamp, because we don't want to report the bootstrap span more than once $this->bootedTimestamp = null; // Add more information about the bootstrap section if possible $this->addBootDetailTimeSpans($span); return $span; } private function addBootDetailTimeSpans(Span $bootstrap): void { // This constant should be defined right after the composer `autoload.php` require statement in `public/index.php` // define('SENTRY_AUTOLOAD', microtime(true)); if (!defined('SENTRY_AUTOLOAD') || !SENTRY_AUTOLOAD) { return; } $autoload = new SpanContext(); $autoload->setOp('autoload'); $autoload->setStartTimestamp($bootstrap->getStartTimestamp()); $autoload->setEndTimestamp(SENTRY_AUTOLOAD); $bootstrap->startChild($autoload); } private function hydrateRequestData(Request $request): void { $route = $request->route(); if ($route instanceof Route) { $this->updateTransactionNameIfDefault(Integration::extractNameForRoute($route)); $this->transaction->setData([ 'name' => $route->getName(), 'action' => $route->getActionName(), 'method' => $request->getMethod(), ]); } $this->updateTransactionNameIfDefault('/' . ltrim($request->path(), '/')); } private function hydrateResponseData(Response $response): void { $this->transaction->setHttpStatus($response->status()); } private function updateTransactionNameIfDefault(?string $name): void { // Ignore empty names (and `null`) for caller convenience if (empty($name)) { return; } // If the transaction already has a name other than the default // ignore the new name, this will most occur if the user has set a // transaction name themself before the application reaches this point if ($this->transaction->getName() !== TransactionContext::DEFAULT_NAME) { return; } $this->transaction->setName($name); } } <file_sep>/src/Sentry/Laravel/Tracing/EventHandler.php <?php namespace Sentry\Laravel\Tracing; use Exception; use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Contracts\Container\Container; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Database\Events as DatabaseEvents; use Illuminate\Queue\Events as QueueEvents; use Illuminate\Queue\Queue; use Illuminate\Queue\QueueManager; use RuntimeException; use Sentry\Laravel\Integration; use Sentry\SentrySdk; use Sentry\Tracing\SpanContext; use Sentry\Tracing\SpanStatus; use Sentry\Tracing\TransactionContext; class EventHandler { public const QUEUE_PAYLOAD_TRACE_PARENT_DATA = 'sentry_trace_parent_data'; /** * Map event handlers to events. * * @var array */ protected static $eventHandlerMap = [ 'illuminate.query' => 'query', // Until Laravel 5.1 DatabaseEvents\QueryExecuted::class => 'queryExecuted', // Since Laravel 5.2 ]; /** * Map queue event handlers to events. * * @var array */ protected static $queueEventHandlerMap = [ QueueEvents\JobProcessing::class => 'queueJobProcessing', // Since Laravel 5.2 QueueEvents\JobProcessed::class => 'queueJobProcessed', // Since Laravel 5.2 QueueEvents\JobExceptionOccurred::class => 'queueJobExceptionOccurred', // Since Laravel 5.2 ]; /** * The Laravel container. * * @var \Illuminate\Contracts\Container\Container */ private $container; /** * Indicates if we should we add SQL queries as spans. * * @var bool */ private $traceSqlQueries; /** * Indicates if we should we add SQL query origin data to query spans. * * @var bool */ private $traceSqlQueryOrigins; /** * Indicates if we should trace queue job spans. * * @var bool */ private $traceQueueJobs; /** * Indicates if we should trace queue jobs as separate transactions. * * @var bool */ private $traceQueueJobsAsTransactions; /** * Holds a reference to the parent queue job span. * * @var \Sentry\Tracing\Span|null */ private $parentQueueJobSpan; /** * Holds a reference to the current queue job span or transaction. * * @var \Sentry\Tracing\Transaction|\Sentry\Tracing\Span|null */ private $currentQueueJobSpan; /** * The backtrace helper. * * @var \Sentry\Laravel\Tracing\BacktraceHelper */ private $backtraceHelper; /** * EventHandler constructor. * * @param \Illuminate\Contracts\Container\Container $container * @param \Sentry\Laravel\Tracing\BacktraceHelper $backtraceHelper * @param array $config */ public function __construct(Container $container, BacktraceHelper $backtraceHelper, array $config) { $this->container = $container; $this->backtraceHelper = $backtraceHelper; $this->traceSqlQueries = ($config['sql_queries'] ?? true) === true; $this->traceSqlQueryOrigins = ($config['sql_origin'] ?? true) === true; $this->traceQueueJobs = ($config['queue_jobs'] ?? false) === true; $this->traceQueueJobsAsTransactions = ($config['queue_job_transactions'] ?? false) === true; } /** * Attach all event handlers. */ public function subscribe(): void { try { /** @var \Illuminate\Contracts\Events\Dispatcher $dispatcher */ $dispatcher = $this->container->make(Dispatcher::class); foreach (static::$eventHandlerMap as $eventName => $handler) { $dispatcher->listen($eventName, [$this, $handler]); } } catch (BindingResolutionException $e) { // If we cannot resolve the event dispatcher we also cannot listen to events } } /** * Attach all queue event handlers. * * @param \Illuminate\Queue\QueueManager $queue */ public function subscribeQueueEvents(QueueManager $queue): void { // If both types of queue job tracing is disabled also do not register the events if (!$this->traceQueueJobs && !$this->traceQueueJobsAsTransactions) { return; } // The payload create callback was introduced in Laravel 5.7 so we need to guard against older versions if (method_exists(Queue::class, 'createPayloadUsing')) { Queue::createPayloadUsing(static function (?string $connection, ?string $queue, ?array $payload): ?array { $currentSpan = Integration::currentTracingSpan(); if ($currentSpan !== null && $payload !== null) { $payload[self::QUEUE_PAYLOAD_TRACE_PARENT_DATA] = $currentSpan->toTraceparent(); } return $payload; }); } $queue->looping(function () { $this->afterQueuedJob(); }); try { /** @var \Illuminate\Contracts\Events\Dispatcher $dispatcher */ $dispatcher = $this->container->make(Dispatcher::class); foreach (static::$queueEventHandlerMap as $eventName => $handler) { $dispatcher->listen($eventName, [$this, $handler]); } } catch (BindingResolutionException $e) { // If we cannot resolve the event dispatcher we also cannot listen to events } } /** * Pass through the event and capture any errors. * * @param string $method * @param array $arguments */ public function __call($method, $arguments) { $handlerMethod = "{$method}Handler"; if (!method_exists($this, $handlerMethod)) { throw new RuntimeException("Missing tracing event handler: {$handlerMethod}"); } try { call_user_func_array([$this, $handlerMethod], $arguments); } catch (Exception $exception) { // Ignore } } /** * Until Laravel 5.1 * * @param string $query * @param array $bindings * @param int $time * @param string $connectionName */ protected function queryHandler($query, $bindings, $time, $connectionName): void { $this->recordQuerySpan($query, $time); } /** * Since Laravel 5.2 * * @param \Illuminate\Database\Events\QueryExecuted $query */ protected function queryExecutedHandler(DatabaseEvents\QueryExecuted $query): void { $this->recordQuerySpan($query->sql, $query->time); } /** * Helper to add an query breadcrumb. * * @param string $query * @param float|null $time */ private function recordQuerySpan($query, $time): void { if (!$this->traceSqlQueries) { return; } $parentSpan = Integration::currentTracingSpan(); // If there is no tracing span active there is no need to handle the event if ($parentSpan === null) { return; } $context = new SpanContext(); $context->setOp('sql.query'); $context->setDescription($query); $context->setStartTimestamp(microtime(true) - $time / 1000); $context->setEndTimestamp($context->getStartTimestamp() + $time / 1000); if ($this->traceSqlQueryOrigins) { $queryOrigin = $this->resolveQueryOriginFromBacktrace($context); if ($queryOrigin !== null) { $context->setData(['sql.origin' => $queryOrigin]); } } $parentSpan->startChild($context); } /** * Try to find the origin of the SQL query that was just executed. * * @return string|null */ private function resolveQueryOriginFromBacktrace(): ?string { $firstAppFrame = $this->backtraceHelper->findFirstInAppFrameForBacktrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)); if ($firstAppFrame === null) { return null; } $filePath = $this->backtraceHelper->getOriginalViewPathForFrameOfCompiledViewPath($firstAppFrame) ?? $firstAppFrame->getFile(); return "{$filePath}:{$firstAppFrame->getLine()}"; } /* * Since Laravel 5.2 * * @param \Illuminate\Queue\Events\JobProcessing $event */ protected function queueJobProcessingHandler(QueueEvents\JobProcessing $event) { $parentSpan = Integration::currentTracingSpan(); // If there is no tracing span active and we don't trace jobs as transactions there is no need to handle the event if ($parentSpan === null && !$this->traceQueueJobsAsTransactions) { return; } // If there is a parent span we can record that job as a child unless configured to not do so if ($parentSpan !== null && !$this->traceQueueJobs) { return; } if ($parentSpan === null) { $traceParent = $event->job->payload()[self::QUEUE_PAYLOAD_TRACE_PARENT_DATA] ?? null; $context = $traceParent === null ? new TransactionContext : TransactionContext::fromSentryTrace($traceParent); // If the parent transaction was not sampled we also stop the queue job from being recorded if ($context->getParentSampled() === false) { return; } } else { $context = new SpanContext; } $job = [ 'job' => $event->job->getName(), 'queue' => $event->job->getQueue(), 'attempts' => $event->job->attempts(), 'connection' => $event->connectionName, ]; // Resolve name exists only from Laravel 5.3+ $resolvedJobName = method_exists($event->job, 'resolveName') ? $event->job->resolveName() : null; if ($resolvedJobName !== null) { $job['resolved'] = $resolvedJobName; } if ($context instanceof TransactionContext) { $context->setName($resolvedJobName ?? $event->job->getName()); } $context->setOp('queue.job'); $context->setData($job); $context->setStartTimestamp(microtime(true)); // When the parent span is null we start a new transaction otherwise we start a child of the current span if ($parentSpan === null) { $this->currentQueueJobSpan = SentrySdk::getCurrentHub()->startTransaction($context); } else { $this->currentQueueJobSpan = $parentSpan->startChild($context); } $this->parentQueueJobSpan = $parentSpan; SentrySdk::getCurrentHub()->setSpan($this->currentQueueJobSpan); } /** * Since Laravel 5.2 * * @param \Illuminate\Queue\Events\JobExceptionOccurred $event */ protected function queueJobExceptionOccurredHandler(QueueEvents\JobExceptionOccurred $event) { $this->afterQueuedJob(SpanStatus::internalError()); } /** * Since Laravel 5.2 * * @param \Illuminate\Queue\Events\JobProcessed $event */ protected function queueJobProcessedHandler(QueueEvents\JobProcessed $event) { $this->afterQueuedJob(SpanStatus::ok()); } private function afterQueuedJob(?SpanStatus $status = null): void { if ($this->currentQueueJobSpan === null) { return; } $this->currentQueueJobSpan->setStatus($status); $this->currentQueueJobSpan->finish(); $this->currentQueueJobSpan = null; SentrySdk::getCurrentHub()->setSpan($this->parentQueueJobSpan); $this->parentQueueJobSpan = null; } } <file_sep>/test/Sentry/IntegrationTest.php <?php namespace Sentry\Laravel\Tests; use Illuminate\Http\Request; use Illuminate\Routing\Events\RouteMatched; use Illuminate\Routing\Route; use Mockery; use Sentry\Event; use Sentry\Laravel\Integration; use Sentry\State\Scope; use function Sentry\withScope; class IntegrationTest extends SentryLaravelTestCase { public function testIntegrationIsRegistered(): void { $integration = $this->getHubFromContainer()->getIntegration(Integration::class); $this->assertInstanceOf(Integration::class, $integration); } public function testTransactionIsSetWhenRouteMatchedEventIsFired(): void { if (!class_exists(RouteMatched::class)) { $this->markTestSkipped('RouteMatched event class does not exist on this version of Laravel.'); } Integration::setTransaction(null); $event = new RouteMatched( new Route('GET', $routeUrl = '/sentry-route-matched-event', static function () { // do nothing... }), Mockery::mock(Request::class)->makePartial() ); $this->dispatchLaravelEvent($event); $this->assertSame($routeUrl, Integration::getTransaction()); } public function testTransactionIsSetWhenRouterMatchedEventIsFired(): void { Integration::setTransaction(null); $this->dispatchLaravelEvent('router.matched', [ new Route('GET', $routeUrl = '/sentry-router-matched-event', static function () { // do nothing... }), ]); $this->assertSame($routeUrl, Integration::getTransaction()); } public function testTransactionIsAppliedToEventWithoutTransaction(): void { Integration::setTransaction($transaction = 'some-transaction-name'); withScope(function (Scope $scope) use ($transaction): void { $event = Event::createEvent(); $this->assertNull($event->getTransaction()); $event = $scope->applyToEvent($event); $this->assertNotNull($event); $this->assertSame($transaction, $event->getTransaction()); }); } public function testTransactionIsAppliedToEventWithEmptyTransaction(): void { Integration::setTransaction($transaction = 'some-transaction-name'); withScope(function (Scope $scope) use ($transaction): void { $event = Event::createEvent(); $event->setTransaction($emptyTransaction = ''); $this->assertSame($emptyTransaction, $event->getTransaction()); $event = $scope->applyToEvent($event); $this->assertNotNull($event); $this->assertSame($transaction, $event->getTransaction()); }); } public function testTransactionIsNotAppliedToEventWhenTransactionIsAlreadySet(): void { Integration::setTransaction('some-transaction-name'); withScope(function (Scope $scope): void { $event = Event::createEvent(); $event->setTransaction($eventTransaction = 'some-other-transaction-name'); $this->assertSame($eventTransaction, $event->getTransaction()); $event = $scope->applyToEvent($event); $this->assertNotNull($event); $this->assertSame($eventTransaction, $event->getTransaction()); }); } } <file_sep>/test/Sentry/Tracing/EventHandlerTest.php <?php namespace Sentry\Laravel\Tests\Tracing; use ReflectionClass; use Sentry\Laravel\Tests\SentryLaravelTestCase; use Sentry\Laravel\Tracing\BacktraceHelper; use RuntimeException; use Sentry\Laravel\Tests\ExpectsException; use Sentry\Laravel\Tracing\EventHandler; class EventHandlerTest extends SentryLaravelTestCase { use ExpectsException; public function test_missing_event_handler_throws_exception() { $this->safeExpectException(RuntimeException::class); $handler = new EventHandler($this->app, $this->app->make(BacktraceHelper::class), []); $handler->thisIsNotAHandlerAndShouldThrowAnException(); } public function test_all_mapped_event_handlers_exist() { $this->tryAllEventHandlerMethods( $this->getStaticPropertyValueFromClass(EventHandler::class, 'eventHandlerMap') ); } private function tryAllEventHandlerMethods(array $methods): void { $handler = new EventHandler($this->app, $this->app->make(BacktraceHelper::class), []); $methods = array_map(static function ($method) { return "{$method}Handler"; }, array_unique(array_values($methods))); foreach ($methods as $handlerMethod) { $this->assertTrue(method_exists($handler, $handlerMethod)); } } private function getStaticPropertyValueFromClass($className, $attributeName) { $class = new ReflectionClass($className); $attributes = $class->getStaticProperties(); return $attributes[$attributeName]; } }
978d8dc16fbbbf1d83bb95bed21fd0de8b88c6fc
[ "PHP" ]
5
PHP
superbiche/sentry-laravel
3abf5c48f2b2c5825290bcbdb639f7763d15fba1
801c7600d09955adfbf62b81edebde6aeddbd5ad
refs/heads/master
<file_sep>let superChimpOne = { name: "Chad", species: "Chimpanzee", mass: 9, age: 6, astronautID: 10, move: function(){ return Math.floor(Math.random() * 11); } }; let salamander = { name: "Lacey", species: "Axolotl Salamander", mass: 0.1, age: 5, astronautID: 9, move: function(){ return Math.floor(Math.random() * 11); } }; let superChimpTwo = { name: "Brad", species: "Chimpanzee", mass: 11, age: 6, astronautID: 6, move: function(){ return Math.floor(Math.random() * 11); } }; let superCat = { name: "Leroy", species: "Beagle", mass: 14, age: 5, astronautID: 3, move: function(){ return Math.floor(Math.random() * 11); } }; let superMicrobe = { name: "Almina", species: "Tardigrade", mass: 0.0000000001, age: 1, astronautID: 1, move: function(){ return Math.floor(Math.random() * 11); } }; // After you have created the other object literals, add the astronautID property to each one. let animalAstronauts = [superChimpOne, superChimpTwo, salamander, superCat, superMicrobe] // Create an array to hold the animal objects. function crewReports(animalAstronauts){ return console.log(`${animalAstronauts.name} is a ${animalAstronauts.species}. They are ${animalAstronauts.age} years old and ${animalAstronauts.mass} kilograms. Their ID is ${animalAstronauts.astronautID}.`); } crewReports(superCat); // Print out the relevant information about each animal. // Start an animal race! console.log(superMicrobe.move()); //console.log(speedRun) function fitnessTest(animalAstronautsArr){ let results = []; let numOfSteps; let turns; for(let i = 0; i < animalAstronauts.length; i++){ numOfSteps = 0 turns = 0 while(numOfSteps < 20){ numOfSteps += animalAstronautsArr[i].move(); turns++; } //push the string to the results array results.push(`${animalAstronautsArr[i].name} took ${turns} turns to take 20 steps. `); } return results; } fitnessTest(animalAstronauts);
c5563fc2c2d00c5d2cf21fcc0ffd356cca839a59
[ "JavaScript" ]
1
JavaScript
randomcase/ObjectsExercises-3
556e0d6fa5ee4da6450ea0513ed1ad2ffb85eb2d
50cb3de31c603ff09bc5e8d3aff6e33149f60812
refs/heads/master
<repo_name>FlexPress/component-menu<file_sep>/src/FlexPress/Components/Menu/MenuInterface.php <?php namespace FlexPress\Components\Menu; interface MenuInterface { public function output(array $args = array()); } <file_sep>/src/FlexPress/Components/Menu/PostTypeMenu.php <?php namespace FlexPress\Components\Menu; class PostTypeMenu implements MenuInterface { /** * @var array */ protected $defaultArgs; public function __construct() { $this->defaultArgs = array( 'starting_level' => 1, 'post_type' => 'page', 'post_id' => 0, 'sudo_items' => array(), 'force_current' => null, "recurse" => true ); } /** * * Outputs the menu with the given args * * @param array $args * @throws \RuntimeException * @author <NAME> */ public function output(array $args = array()) { if (get_the_ID()) { $this->defaultArgs['post_id'] = get_the_ID(); } $args = array_merge($this->defaultArgs, $args); if (!empty($args['sudo_items'])) { $args['sudo_items'] = $this->getSudoObjects($args['sudo_items']); } // zero index $args['starting_level'] -= 1; $args['level'] = $args['starting_level']; $args['ancestors'] = $this->getAncestors($args); if ($this->validateArgs($args)) { $this->recurse($args); } } /** * * Recurses with the given args * * @author <NAME> * */ protected function recurse(array $args) { $pages = $this->getPagesWithSudoItems($args); if (empty($pages)) { return; } $nextParentID = $this->getNextParentID($args); $this->outputMenu($pages, $args, $nextParentID); } /** * * Loops through the given pages and delegates their output * to various methods(override as necessary) * * @param $pages * @param $args * @param $nextParentID * @author <NAME> */ protected function outputMenu($pages, $args, $nextParentID) { $this->outputOpeningUl($args['level']); foreach ($pages as $page) { $this->outputOpeningLi($page, $args['level']); $this->outputPageLink($page, $args['level'], $args); if ($args["recurse"] && ($page->ID == $nextParentID) ) { $nextLevelArgs = $args; $nextLevelArgs['level']++; $nextLevelArgs['parent_id'] = $page->ID; $this->recurse($nextLevelArgs); } $this->outputClosingLi($page, $args['level']); } $this->outputClosingUl($args['level']); } /** * * Outputs the opening ul for a given level * * @author <NAME> * */ protected function outputOpeningUl($level) { echo '<ul class="level-', $level + 1, '">'; } /** * * Outputs the closing ul for a given level * * @param $level * @author <NAME> * */ protected function outputClosingUl($level) { echo "</ul>"; } /** * * Outputs the opening li for a given level and page * * @param $page * @param $level * @author <NAME> * */ protected function outputOpeningLi($page, $level) { echo "<li>"; } /** * * Outputs the closing ul for a given level and page * * @param $page * @param $level * @author <NAME> * */ protected function outputClosingLi($page, $level) { echo "</li>"; } /** * * Outputs the page link for a given level, page and args * * @param $page * @param $level * @param $args * @author <NAME> */ protected function outputPageLink($page, $level, $args) { $classes = ''; if (in_array($page->ID, $args['ancestors']) || $page->ID == $args['force_current'] ) { $classes = ' class="is-current"'; } $permalink = (property_exists($page, 'permalink')) ? $page->permalink : get_permalink($page->ID); echo '<a href="', $permalink, '"', $classes, '>', $page->post_title, '</a>'; } /** * * Validates the arguments passed to the output menu function * * @param $args * @throws \RuntimeException * @return bool * @author <NAME> */ protected function validateArgs($args) { $totalAncestors = count($args['ancestors']); if ($args['starting_level'] >= $totalAncestors) { $message = __CLASS__ . ': Invalid starting level of '; $message .= $args['starting_level'] . ' exceed the total ' . $totalAncestors; throw new \RuntimeException($message); } return true; } /** * * For the array of given sudo items, * returns the object * * @param array $sudoItems * @return array * @author <NAME> */ protected function getSudoObjects(array $sudoItems) { $item_objects = array(); if (!empty($sudoItems)) { foreach ($sudoItems as $parentID => $items) { $item_objects[$parentID] = array(); foreach ($items as $item) { $item_object = new \stdClass(); $item_object->ID = $item['id']; $item_object->post_title = $item['title']; $item_object->permalink = $item['link']; $item_objects[$parentID][] = $item_object; } } } return $item_objects; } /** * * Gets the pages for the given args * and combines then with sudo items also given * in the args * * @param $args * @return array * @author <NAME> */ protected function getPagesWithSudoItems($args) { /** * if a parent id is set use that, if not grab a parent id from the ancestors, i.e. on top level grab which * one should be used as simply using 0 would mean we get the top level of the site, which is typically * not what we want, so by using the ancestors along with the level, which should be the starting level * then we can ensure that we get the correct parent id. **/ $parentID = 0; if ((isset($args['parent_id']))) { $parentID = $args['parent_id']; } elseif (isset($args['ancestors'][$args['level']])) { $parentID = $args['ancestors'][$args['level']]; } $getPostsArgs = array( 'child_of' => $parentID, 'post_parent' => $parentID, 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => '-1', 'post_type' => $args['post_type'], 'post_status' => 'publish', 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'fp_page_type', 'value' => 'nonmenu', 'compare' => '!=' ), array( 'key' => 'fp_page_type', 'value' => 'nonmenu', 'compare' => 'NOT EXISTS' ) ) ); $pages = get_posts($getPostsArgs); if ($args['sudo_items'] && array_key_exists($parentID, $args['sudo_items'])) { $pages = array_merge($pages, $args['sudo_items'][$parentID]); } return $pages; } /** * * Returns the next parent ID for the given args * * @param $args * @return bool * @author <NAME> * */ protected function getNextParentID($args) { if (array_key_exists($args['level'] + 1, $args['ancestors'])) { return $args['ancestors'][$args['level'] + 1]; } return false; } /** * * Builds the array of ancestors * * @param $args * @return array * @author <NAME> */ protected function getAncestors($args) { if (!isset($args['post_id']) || $args['post_id'] == 0 ) { return array(); } $ancestors = get_post_ancestors($args['post_id']); $ancestors = array_reverse($ancestors); $ancestors[] = $args['post_id']; return $ancestors; } } <file_sep>/README.md # FlexPress menu helpers component ## Install via Pimple ``` $pimple["menu"] = function() { return new PostTypeMenu(); }; ``` ## Usage ``` $defaults = array( 'starting_level' => 1, 'post_type' => 'page', 'post_id' => $GLOBALS['post']->ID, 'sudo_items' => array(), 'force_current' => null, "recurse" => true ); $pimple["menu"]->output($defaults); ``` ## Options #### starting_level This is what level the meny should start displaying on, for example if you have Careers > Vacancies > Vacancy listings and you set the level as 1(default) then it would display Vacancies and skip the Careers level. #### post_type This option allows you to specify what post type you want to use, defaults to page #### post_id This option lets you change the post_id that is used to get the ancestors and is also used to set the current page in the menu. #### sudo_items This option allows you to create sudo menu items, an example config would look like this: ``` $args['sudo_items'] = array( 123 => array( "id" => -1, "title" => "Some random link", "link" => "/some/random/link", ) ); ``` This would add a page with the title Some random link, which links to /some/random/link under the item in the menu that has the id 123. #### force_current You can use this option to speficy what the current link is, this is a post_id #### recurse You can turn off recurse to make the menu not recurse and just output the current level.
fd8cacadf7a18a487463f796f88920b10db0b3e6
[ "Markdown", "PHP" ]
3
PHP
FlexPress/component-menu
6935a505513651c347ca76b12f5de4eef187d5fc
82158fb275c5ae355fc1fdd002c5231e20bd3ac8
refs/heads/master
<repo_name>sura1214/Group-one<file_sep>/README.md # Group-one <file_sep>/user/routes/api.php <?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\http\controllers\StudController; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); //add user Route::post('add',[StudController::class,'addUser']); //Get specfic user Route::get('user/{id}',[StudController::class,'searchUserById']); //update user Route::put('update/{id}',[StudController::class,'updateUser']); //delete user Route::delete('delete/{id}',[StudController::class,'deleteUser']);<file_sep>/user/app/Http/Controllers/StudController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Stud; class StudController extends Controller { // public function addUser(Request $request){ $user=Stud::create($request->all()); return response($user,201); } public function searchUserById($id){ $user=Stud::find($id); if(is_null($user)){ return response()->json(['message' => 'User Not Found'],404); } return response()->json($user::find($id)); } public function updateUser(Request $request,$id){ $user=Stud::find($id); if(is_null($user)){ return response()->json(['message' => 'User Not Found'],404); } $user->update($request->all()); return response($user,200); } public function deleteUser(Request $request,$id){ $user=Stud::find($id); if(is_null($user)){ return response()->json(['message' => 'User Not Found'],404); } $user->delete(); return response()->json(null,204); } }
400382d3e76eb926ca6e90e00176c1e8a9de4a1d
[ "Markdown", "PHP" ]
3
Markdown
sura1214/Group-one
7e0070bd71ae178d5b4d38edef35588219e60fe1
2f3012fe5fc3ad33bb35a6e142281fffcfa216c9
refs/heads/master
<file_sep>import React, {useState, useEffect, useRef} from 'react'; import './App.css'; import FlashcardList from './FlashcardList'; import axios from 'axios' function App() { const [flashcards, setFlashcards] = useState([]); const [categories, setCategories] = useState([]) const categoryEl = useRef() const amountEl = useRef() useEffect(() => { axios.get('https://opentdb.com/api_category.php').then((response) => { console.log(response); setCategories(response.data.trivia_categories); }) }, []) function decodeString(str){ const textArea = document.createElement('textarea') textArea.innerHTML = str return textArea.value } function handleSubmit(e){ e.preventDefault(); axios.get('https://opentdb.com/api.php',{ params:{ amount:amountEl.current.value, category:categoryEl.current.value } }) .then((response) => { setFlashcards(response.data.results.map((item, index) =>{ const answer = decodeString(item.correct_answer); const options = [...item.incorrect_answers.map(opt => decodeString(opt)), answer] return { id : `${index}-${Date.now()}`, question: decodeString(item.question), answer : answer, options : options.sort(() => Math.random() -.5) } })); }) } return ( <> <form className="header" onSubmit={handleSubmit}> <div className="form-group"> <label htmlFor="category"> Category </label> <select id="category" ref={categoryEl}> {categories.map(category =>{ return <option value = {category.id} key={category.id}>{category.name}</option> })} </select> </div> <div className="form-group"> <label htmlFor="amount"> Number of Questions </label> <input ref = {amountEl} type="number" name="amount" id="amount" defaultValue={10} min="1" max="50" step="1"/> </div> <div className="btn"> <button className="btn"> Generate </button> </div> </form> <div className="container"> <FlashcardList flashcards={flashcards}/> </div> </> ); } export default App;
b6b002ec0aae229c42d228d998f260941329f6e6
[ "JavaScript" ]
1
JavaScript
paulkg4u/react-flashcard-tutorial
5531c5210ecc09e787498c962bb9ed84be0faace
0bab0acd1dc6cf29d4461437f16314ea41497a2c
refs/heads/master
<file_sep>## Overview The Enigma Machine is an encryption device used by the Nazis during WW2. This code replicates the substitution cipher and allows the user to encrypt their plain text. The main class is Enigma, its parents are the classes Rotors and Plugboard which must be configured in order for Enigma to be used. ### Rotors This object is simply an array of the 26 letters of the alphabet in lower case in the order you decide. These rotors are how letters will be encrypted. ### Plugboard This is simply a list of 2-tuples of letters. If the letter that comes out of rotor encryption is paired in the plugboard object, it is swapped with the letter it's paired with. ### Enigma This object is a child of both Rotors and Plugboard. As an input, it takes three rotor configurations and one plugboard setting. It has the following methods: <code>increment(self, rotor)</code> This takes a specific rotor as an inputs and increments it by one then does mod 26 on its new index position. So, letter 0 becomes letter 1, letter 1 becomes letter 2... letter 25 becomes letter 0. <code>encrypt(self,i)</code> This takes a specific letter as an input and encrypts it. The first rotor is then incremented by 1 position. <code>decrypt(self,i)</code> This take a specific letter as an input and decrypts it. The first rotor is then incremented by 1 position. <code>swap(self,n)</code> This take a specific letter as an input and checks to see if it has been connected with another letter on the pluboard. If it has, the input letter becomes the letter it has been paired with after decryption. <code>encrypt_input(self, s)</code> This method takes the message as a string for the input _s_. It encrypts each letter. Every time the first rotor is incremented 26 times, the second rotor is incremented once. Every time the second rotor is incremented 26 times, the third rotor is incremented once. <code>decrypt_input(self, old_swaps, old_settings, old_settings2, old_settings3, e_input)</code> This method takes original plugboard configuration _old_swaps_, the three original rotor positions (in the correct order) and the encrypted input _e_input_, as inputs. It will then decrypt the message and return the original message. Note, there are no spaces in a message. ### Instructions Give the enigma object 4 arguments: a plugboard setting (swaps) and three rotor settings. Make sure that both the sender and the receiver know these settings. In order to encrypt the message, use _encrypt_input._ The receiver must then use _decryt_input_ with the correct swap settings, and rotor settings (in the correct order) on the encrypted message in order to get the original message. <file_sep>import random import string #encryption must be in lower case #this is the Plugboard class. This takes a list of 2-tuples. Each tuple is the two letters you want to swap together. class Plugboard: def __init__(self, swaps): self.swaps = swaps #this is the Rotors class. This must be a list of letters (strings). Each letter in the alphabet must be there. class Rotors: def __init__(self, settings): self.settings = settings #error checking, there cannot be any duplicates, nonalpha characters or less than 26 letters if len(settings) != 26: raise Exception("Rotor must have 26 unique letters") if len(settings) != len(set(settings)): raise Exception("Rotor must have 26 unique letters") for i in settings: if i.isalpha() != True: raise Exception("Rotor must have 26 unique letters") #this is the main machine, where the encryption happens class Enigma(Rotors, Plugboard): def __init__(self, swaps, settings, settings2, settings3): Plugboard.__init__(self, swaps) self.settings = settings self.settings2 = settings2 self.settings3 = settings3 #this function increments the rotor provided. def increment(self, rotor): for i in range(0, len(rotor)-1): if rotor[(i%len(rotor))-1] == 0: break else: temp = rotor[(i%len(rotor))-1] rotor[(i%len(rotor))-1] = rotor[i] rotor[i] = temp return rotor #this function encrypts a single letter and increments the first rotor. def encrypt(self,i): alphabet = list(map(chr, range(97, 123))) index = alphabet.index(i) i = self.settings[index] index = alphabet.index(i) i = self.settings2[index] index = alphabet.index(i) i = self.swap(self.settings3[index]) self.settings = self.increment(self.settings) return i #this function decrypts a single letter and increments the first rotor. def decrypt(self,i): alphabet = list(map(chr, range(97, 123))) i = self.swap(i) index = self.settings3.index(i) i = alphabet[index] index = self.settings2.index(i) i = alphabet[index] index = self.settings.index(i) i = alphabet[index] self.settings = self.increment(self.settings) return i #this function checks to see if the encrypted letter has been swapped on the plugboard. If so, it is swapped. def swap(self,n): for x in self.swaps: if n in x: for j in x: if j != n: n = j break return n #this function encrypts an entire message. Every 26 times the first rotor is incremented, it increments the next rotor and so on. def encrypt_input(self, s): message = "" fst_rotation = 0 snd_rotation = 0 trd_rotation = 0 for i in s: if i != " ": message = message + self.encrypt(i) fst_rotation+=1 if fst_rotation % 26 == 0: self.settings2 = self.increment(self.settings2) snd_rotation+=1 if snd_rotation % 26 == 0: self.settings3 = self.increment(self.settings3) trd_rotation+=1 return message #this function decrypts the entire message. The plugboard position, original 3 rotor positions in addition to the decrypted message must be provided. Every 26 times the first rotor is incremented, it increments the next rotor and so on. def decrypt_input(self, old_swaps, old_settings, old_settings2, old_settings3, e_input): message = "" fst_rotation = 0 snd_rotation = 0 trd_rotation = 0 self.reset(old_swaps, old_settings, old_settings2, old_settings3) for i in e_input: message = message + self.decrypt(i) fst_rotation+=1 if fst_rotation % 26 == 0: self.settings2 = self.increment(self.settings2) snd_rotation+=1 if snd_rotation % 26 == 0: self.settings3 = self.increment(self.settings3) trd_rotation+=1 return message #this function resets the rotor and swap settings for decryption. If the rotor and swap settings are correct, the message will be successfully decrypted. def reset(self, old_swaps, old_settings, old_settings2, old_settings3): self.swaps = old_swaps self.settings = old_settings self.settings2 = old_settings2 self.settings3 = old_settings3
82e6ea5bd1847b5014a4fb77abe031528c0cfa33
[ "Markdown", "Python" ]
2
Markdown
kudz7/enigma-machine
30a887b512017c384cd0132c0f9253682f1af90f
40db39eddcf73ed9cfa5d89c86972debf596a504
refs/heads/master
<file_sep>package org.jyu.itks545; /** * Callback interface for asynchronous network ASyncTask. * For example: Show all markers when they retrieved from server. * */ public interface AsyncCallback { public void callback(String json); } <file_sep>AndroidClient ============= Add google_play_servicer.jar as dependancy. /sdk/extras/google/google_play_services/libproject/google-play-services_lib/libs/ <file_sep>package org.jyu.itks545; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.jyu.itks545.MyOAuth.AddMessage; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.View; import android.widget.EditText; public class WriteMessageActivity extends FragmentActivity { @SuppressWarnings("unused") private static final String TAG = WriteMessageActivity.class.getSimpleName(); private Double latitude, longitude; private int userID; private String consumerKey, consumerSecret, accessToken, accessTokenSecret; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_writemessage); Bundle extras = getIntent().getExtras(); if (extras != null) { latitude = extras.getDouble("latitude"); longitude = extras.getDouble("longitude"); userID = extras.getInt("userID"); consumerKey = extras.getString("consumerKey"); consumerSecret = extras.getString("consumerSecret"); accessToken = extras.getString("accessToken"); accessTokenSecret = extras.getString("accessTokenSecret"); } } public void onClick(View v) { int buttonID = v.getId(); switch (buttonID) { case R.id.buttonSend: new AddMessageASync().execute((Void) null); break; case R.id.buttonCancel: break; default: break; } // We go back to Map in every case. Intent intent1 = new Intent(this, MyMapActivity.class); startActivity(intent1); } /** * This sends message to the server on the background. * @author tonsal * */ private class AddMessageASync extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { EditText editText = (EditText) findViewById(R.id.editTextMessage); try { String message = URLEncoder.encode(editText.getText().toString(), "UTF-8"); AddMessage addMessage = new AddMessage( userID, latitude, longitude, message, consumerKey, consumerSecret, accessToken, accessTokenSecret); addMessage.sendRequest(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } } } <file_sep>package org.jyu.itks545; /** * Base for Twitter OAuth http-messages * * @author <NAME> <<EMAIL> at <EMAIL>> * @version 14.2.2013 */ public class MyOAuth { @SuppressWarnings("unused") private static final String TAG = MyOAuth.class.getSimpleName(); private static final String API_URL = "http://itks545.it.jyu.fi/toarjusa/itks545/index.php"; // private static final String API_URL = "http://192.168.100.41/itks545/index.php"; private static final String REQUEST_TOKEN_PATH = API_URL + "/request_token"; private static final String ACCESS_TOKEN_PATH = API_URL + "/access_token"; private static final String ADD_MESSAGE_PATH = API_URL + "/messages/add"; private static final String DELETE_MESSAGE_PATH = API_URL + "/messages/delete"; public static class RequestToken extends OAuthGetRequest { public RequestToken(String consumerKey, String consumerSecret) { super(consumerKey, consumerSecret, REQUEST_TOKEN_PATH); } } public static class AccessToken extends OAuthGetRequest { public AccessToken(String consumerKey, String consumerSecret, String pin, RequestToken requestToken) { super(consumerKey, consumerSecret, ACCESS_TOKEN_PATH); super.putValue(ParameterKey.oauth_verifier, pin); super.putValue(ParameterKey.oauth_token, requestToken.response_oauth_token()); super.putValue(ParameterKey.oauth_token_secret, requestToken.getResponseString(ParameterKey.oauth_token_secret.toString())); } } public static class AddMessage extends OAuthGetRequest { public AddMessage(int userID, double latitude, double longitude, String message, String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret) { super(consumerKey, consumerSecret, ADD_MESSAGE_PATH + "/" + userID + "/" + latitude + "/" + longitude + "/" + message); super.putValue(ParameterKey.oauth_token, accessToken); super.putValue(ParameterKey.oauth_token_secret, accessTokenSecret); } } public static class DeleteMessage extends OAuthGetRequest { public DeleteMessage(int messageID, String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret) { super(consumerKey, consumerSecret, DELETE_MESSAGE_PATH + "/" + messageID); super.putValue(ParameterKey.oauth_token, accessToken); super.putValue(ParameterKey.oauth_token_secret, accessTokenSecret); } } } <file_sep>package org.jyu.itks545; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import android.net.http.AndroidHttpClient; import android.os.AsyncTask; import android.util.Log; /** * Get the response string from the server. * */ class GetJsonASync extends AsyncTask<Void, Void, HttpResponse> { private static final String TAG = GetJsonASync.class.getSimpleName(); private final AsyncCallback asyncCallback; private final String url; private final List<NameValuePair> data; public GetJsonASync(AsyncCallback asyncCallback, String url, List<NameValuePair> data) { this.asyncCallback = asyncCallback; this.url = url; this.data = data; } @Override protected HttpResponse doInBackground(Void... params) { Log.i(TAG, url); HttpPost httpPost = new HttpPost(url); AndroidHttpClient client = AndroidHttpClient.newInstance("Android"); StringEntity tmp = null; // httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); try { if (data != null) { tmp = new UrlEncodedFormEntity(data); httpPost.setEntity(tmp); } } catch (UnsupportedEncodingException e) { Log.e(TAG, "HttpUtils : UnsupportedEncodingException : " + e); } try { return client.execute(httpPost); } catch (IOException e) { e.printStackTrace(); return null; } finally { client.close(); } } @Override protected void onPostExecute(HttpResponse result) { if (result != null) { Log.i("Content lenght",Long.toString(result.getEntity().getContentLength())); try { InputStream is = result.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } reader.close(); is.close(); Log.i("Content", sb.toString()); if (asyncCallback != null) { asyncCallback.callback(sb.toString()); } } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } } <file_sep>package org.jyu.itks545; import java.io.UnsupportedEncodingException; import org.jyu.itks545.MyOAuth.DeleteMessage; import org.jyu.itks545.R.id; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; public class MyMapActivity extends FragmentActivity { private static final String TAG = MyMapActivity.class.getSimpleName(); private static final int LOGIN_REQUEST_CODE = 1234; private int mUserID; private String mAuthorizedAccessToken; private String mAuthorizedAccessTokenSecret; // private String mUsername; private String mConsumerKey; private String mConsumerSecret; private static final int UPDATE_LATLNG = 2; // Current location. private LatLng location; // Message handler. private Handler mHandler; private final LocationListener listener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { // A new location update is received. Do something useful with it. In this case, // we're sending the update to a handler which then updates the UI with the new // location. Message.obtain(mHandler, UPDATE_LATLNG, new LatLng(location.getLatitude(), location.getLongitude())).sendToTarget(); } }; private LocationManager mLocationManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_mymap); // Restore apps state (if exists) after rotation. if (savedInstanceState != null) { Double latitude = savedInstanceState.getDouble("latitude"); Double longitude = savedInstanceState.getDouble("longitude"); if (latitude != 0 || longitude != 0) { location = new LatLng(latitude, longitude); } } else { } // if we have userID and accessToken we are good to go. SharedPreferences preferences = getPreferences(MODE_PRIVATE); mUserID = preferences.getInt("userID", 0); mAuthorizedAccessToken = preferences.getString("authorizedAccessToken", null); mAuthorizedAccessTokenSecret = preferences.getString("authorizedAccessTokenSecret", null); mConsumerKey = preferences.getString("consumerKey", null); mConsumerSecret = preferences.getString("consumerSecret", null); // Check if location services are enabled. Nothing to do with LocationService. mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // We are using only network-based location. // boolean gpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); boolean gpsEnabled = true; boolean networkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); // boolean networkEnabled = true; // Check if enabled and if not send user to the GPS settings if (!gpsEnabled || !networkEnabled) { showLocationDisabledAlertToUser(); } mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, // mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2 * 60 * 1000, // 2 minutes 10, // 10 meters listener); mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_LATLNG: // When first location is received, we move the camera to that location. boolean firstFix = false; if (location == null) { firstFix = true; } location = (LatLng) msg.obj; if (firstFix) { MyMapFragment mapFrag = (MyMapFragment) getSupportFragmentManager().findFragmentByTag("MapFrag"); mapFrag.setPosition(location); } break; } } }; createMap(); } /* * We create a map if there is no map already. */ public void createMap() { FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.findFragmentByTag("MapFrag") == null) { Log.d(TAG, this + ": Existing fragment not found."); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, new MyMapFragment(), "MapFrag"); fragmentTransaction.commit(); } else { Log.d(TAG, this + ": Existing fragment found."); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case id.action_add_message: if(mUserID != 0 && mAuthorizedAccessToken != null && mConsumerKey != null && mConsumerSecret != null) { Intent intent = new Intent(this, WriteMessageActivity.class); intent.putExtra("latitude", location.latitude); intent.putExtra("longitude", location.longitude); intent.putExtra("userID", mUserID); intent.putExtra("consumerKey", mConsumerKey); intent.putExtra("consumerSecret", mConsumerSecret); intent.putExtra("accessToken", mAuthorizedAccessToken); intent.putExtra("accessTokenSecret", mAuthorizedAccessTokenSecret); startActivity(intent); } else { Intent intent = new Intent(this, LoginActivity.class); startActivityForResult(intent, LOGIN_REQUEST_CODE); } break; case id.action_delete_message: FragmentManager fragmentManager = getSupportFragmentManager(); MyMapFragment myMapFragment = (MyMapFragment) fragmentManager.findFragmentByTag("MapFrag"); if (myMapFragment != null) { Marker marker = myMapFragment.getCurrentMarker(); if (marker != null) { int messageID = Integer.parseInt(marker.getTitle()); new DeleteMessageASync().execute(messageID); } } break; case id.action_refresh_map: FragmentManager fragmentManager1 = getSupportFragmentManager(); MyMapFragment myMapFragment1 = (MyMapFragment) fragmentManager1.findFragmentByTag("MapFrag"); if (myMapFragment1 != null) { myMapFragment1.getAllMarkers(); } break; case id.action_about: Intent intent = new Intent(this, About.class); startActivity(intent); break; default: return super.onOptionsItemSelected(item); } return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Get the results from the login intent and put them to shared preferences. if (resultCode == RESULT_OK && requestCode == LOGIN_REQUEST_CODE) { Bundle returnedData = data.getExtras(); mUserID = returnedData.getInt(LoginActivity.USERID); mConsumerKey = returnedData.getString(LoginActivity.CONSUMERKEY); mConsumerSecret = returnedData.getString(LoginActivity.CONSUMERSECRET); mAuthorizedAccessToken = returnedData.getString(LoginActivity.AUTHORIZEDACCESSTOKEN); mAuthorizedAccessTokenSecret = returnedData.getString(LoginActivity.AUTHORIZEDACCESSTOKENSECRET); Log.d(TAG, "UserID: " + mUserID + ", ConsumerKey: " + mConsumerKey + ", ConsumerSecret: " + mConsumerSecret + ", mAuthorizedAccessToken: " + mAuthorizedAccessToken + ", mAuthorizedAccessTokenSecret: " + mAuthorizedAccessTokenSecret); SharedPreferences preferences = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("userID", mUserID); editor.putString("consumerKey", mConsumerKey); editor.putString("consumerSecret", mConsumerSecret); editor.putString("authorizedAccessToken", mAuthorizedAccessToken); editor.putString("authorizedAccessTokenSecret", mAuthorizedAccessTokenSecret); editor.commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (location != null) { outState.putDouble("latitude", location.latitude); outState.putDouble("longitude", location.longitude); } } @Override protected void onResume() { super.onResume(); } @Override protected void onStop() { super.onStop(); } /* * Show location settings. * * http://stackoverflow.com/questions/843675/how-do-i-find-out-if-the-gps-of- * an-android-device-is-enabled */ private void showLocationDisabledAlertToUser() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder .setMessage(R.string.enable_GPS) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent callGPSSettingIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(callGPSSettingIntent); } }); alertDialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); } /** * This deletes message from the server on the background. * @author tonsal * */ private class DeleteMessageASync extends AsyncTask<Integer, Void, Void> { @Override protected Void doInBackground(Integer... params) { try { int messageID = params[0]; DeleteMessage deleteMessage = new DeleteMessage( messageID, mConsumerKey, mConsumerSecret, mAuthorizedAccessToken, mAuthorizedAccessTokenSecret); deleteMessage.sendRequest(); FragmentManager fragmentManager = getSupportFragmentManager(); MyMapFragment myMapFragment = (MyMapFragment) fragmentManager.findFragmentByTag("MapFrag"); if (myMapFragment != null) { myMapFragment.getAllMarkers(); } } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } } } <file_sep>package org.jyu.itks545; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; public class MyMapFragment extends SupportMapFragment implements AsyncCallback, OnMarkerClickListener, OnMapClickListener{ private static final String TAG = MyMapFragment.class.getSimpleName(); /** * Note that this may be null if the Google Play services APK is not * available. */ private GoogleMap mMap; private Marker currentMarker; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); return view; } @Override public void onResume() { super.onResume(); mMap = getMap(); mMap.setOnMarkerClickListener(this); mMap.setOnMapClickListener(this); initMap(); getAllMarkers(); } private void initMap() { UiSettings settings = mMap.getUiSettings(); settings.setAllGesturesEnabled(true); settings.setMyLocationButtonEnabled(false); } /* * Set camera position on the map. */ public void setPosition(LatLng latLng) { mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.moveCamera(CameraUpdateFactory.zoomTo(16)); } /* * Get all the markers. */ public void getAllMarkers() { new GetJsonASync(this, getString(R.string.server) + getString(R.string.getallmessages), null).execute(); } /* * Clears map and then show markers on the map. * Its called from GetJsonASync() as a callback when acquiring the markers. */ private void showMarkers(String json) { Log.i(TAG, json); mMap.clear(); currentMarker = null; try { JSONObject jObj = new JSONObject(json); JSONArray jArray = new JSONArray(); jArray = jObj.getJSONArray("messages"); for(int i = 0; i < jArray.length(); i++) { JSONObject o = jArray.getJSONObject(i); mMap.addMarker(createMarker(o)); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * Parse json and put marker on the map. */ private MarkerOptions createMarker(JSONObject o) throws JSONException { int userID = o.getInt("userID"); double longitude = o.getDouble("longitude"); double latitude = o.getDouble("latitude"); String text = o.getString("text"); LatLng latLng = new LatLng(latitude, longitude); Log.i(TAG, latLng.toString()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title(Integer.toString(userID)); markerOptions.snippet(text); return markerOptions; } @Override public void callback(String json) { showMarkers(json); } @Override public boolean onMarkerClick(Marker marker) { Log.i(TAG, "Clicked: " + marker.getSnippet()); currentMarker = marker; return false; } @Override public void onMapClick(LatLng arg0) { Log.i(TAG, "Map clicked"); currentMarker = null; } public Marker getCurrentMarker() { return currentMarker; } }
ccd10e85d3ac848c2d542048c81e7f94a7f521b0
[ "Markdown", "Java" ]
7
Java
Hootee/AndroidClient
ed543c944f76eb3ba82c751cd6d640ec0efb442a
dec2e1b255b73b0053c4e98154f8746dcf9f81de
refs/heads/master
<file_sep>import React, { useState, useEffect } from "react"; import ListCategories from "../../../components/List/Categories"; import { getCategoryGroup, createCategory, deleteCategory, updateCategory, bulkDeleteCategory, } from "../../../network"; export default function ListCategoriesCtrl({ dataLabel, label, labelPlural }) { let isMounted = true; const [eCategories, setECategories] = useState([]); // categories_ is the mutable version of eCategories that we'll be using to filter const [categories_, setCategories_] = useState([]); const [searchQuery, setSearchQuery] = useState(""); const [hasPages, setHasPages] = useState(false); const [pages, setPages] = useState([]); const [page, setPage] = useState(1); const [selectedCategories, setSelectedCategories] = useState([]); const [newCat, setNewCat] = useState(""); const [editCat, setEditCat] = useState(""); const [pendingDelete, setPendingDelete] = useState({}); const [pendingEdit, setPendingEdit] = useState({}); const [modalActive, setModalActive] = useState(false); const [modalState, setModalState] = useState("delete"); const [loading, setLoading] = useState(false); const [bulkAction, setBulkAction] = useState(""); // Error Messaging const [directive, setDirective] = useState(null); useEffect(() => { // eslint-disable-next-line react-hooks/exhaustive-deps isMounted = true; queryCategories(); return () => { isMounted = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { if (isMounted) setCategories_(eCategories); // eslint-disable-next-line react-hooks/exhaustive-deps }, [eCategories]); useEffect(() => { setPage(1); formatPages(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [categories_]); useEffect(() => { if (isMounted) resetDirective(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [directive]); const resetDirective = async () => { await setTimeout(() => { if (!isMounted) return; setDirective(null); }, 4000); }; const formatPages = () => { const dataLength = categories_.length; if (dataLength < 5) return setHasPages(false); setHasPages(true); let itemsChunk = 5, categoriesData = categories_; // split the data into pages const pages = categoriesData.reduce((resultArray, item, index) => { const chunkIndex = Math.floor(index / itemsChunk); if (!resultArray[chunkIndex]) { resultArray[chunkIndex] = []; // start a new chunk } resultArray[chunkIndex].push(item); return resultArray; }, []); setPages(pages); }; const queryCategories = async () => { if (!isMounted) return; setLoading(true); const result = await getCategoryGroup(dataLabel); if (!isMounted) return; setLoading(false); if (result.error) return; setECategories(result); }; const handleQueryChange = (e) => { setSearchQuery(e.target.value); }; const applySearch = () => { const searchQ = searchQuery.toLowerCase(); if (!searchQ) return setCategories_(eCategories); let filteredData = eCategories.filter((category) => category.category_name.toLowerCase().startsWith(searchQ) ); setCategories_(filteredData); }; const clearSearch = () => { setSearchQuery(""); setCategories_(eCategories); }; const nextPage = () => { let currentPage = page; if (currentPage >= pages.length) return; currentPage = currentPage + 1; setPage(currentPage); }; const prevPage = () => { let currentPage = page; if (currentPage === 1) return; currentPage = currentPage - 1; setPage(currentPage); }; const handleSelected = (e) => { const id = e.target.value; let newSelected = [...selectedCategories]; if (selectedCategories.includes(id)) { newSelected = newSelected.filter((item) => item !== id); } else { newSelected = [...newSelected, id]; } setSelectedCategories(newSelected); }; const batchSelect = () => { const resourceIds = eCategories.map((category) => category._id); const selectedIds = selectedCategories; const allSelected = resourceIds.length === selectedIds.length && resourceIds.every(function (element, index) { return element === selectedIds[index]; }); if (!allSelected) { setSelectedCategories(resourceIds); } else { setSelectedCategories([]); } }; const submitNewCategory = async () => { if (!isMounted) return; if (!newCat) return setDirective({ header: "Error creating category", message: "Can't create a category with an empty category name", success: false, }); const category = { category_name: newCat, resource: `${dataLabel}`, }; const result = await createCategory(category); if (!isMounted) return; if (result.error) return setDirective({ header: "Error creating tag", message: result.error.data.error, success: false, }); queryCategories(); setNewCat(""); }; const closeModal = () => { setModalActive(false); }; const handleDelete = async (e) => { if (!isMounted) return; setModalState("delete"); const id = e.target.value; const foundCategory = eCategories.filter( (category) => category._id === id )[0]; if (!foundCategory) return setDirective({ header: "Error deleting category", message: "Could not locate category", success: false, }); await setPendingDelete(foundCategory); if (!isMounted) return; setModalActive(true); }; const applyDelete = async () => { if (!isMounted) return; const id = pendingDelete._id; if (!id) return setDirective({ header: "Error deleting category", message: "Could not locate category", success: false, }); const result = await deleteCategory(id); if (!isMounted) return; if (result.error) return setDirective({ header: "Error deleting category", message: result.error.data.error, success: false, }); closeModal(); setPendingDelete({}); queryCategories(); }; const handleEdit = async (e) => { if (!isMounted) return; setModalState("edit"); const id = e.target.value; const foundCategory = eCategories.filter( (category) => category._id === id )[0]; if (!foundCategory) return setDirective({ header: "Error updating category", message: "Could not locate category", success: false, }); await setPendingEdit(foundCategory); if (!isMounted) return; setEditCat(foundCategory.category_name); setModalActive(true); }; const applyEdit = async (e) => { if (!isMounted) return; const id = pendingEdit._id; if (!id) return setDirective({ header: "Error updating category", message: "Could not locate category", success: false, }); if (!editCat || !pendingEdit.resource) return setDirective({ header: "Error updating category", message: "Required fields are missing", success: false, }); const updatedCategory = { category_name: editCat, resource: pendingEdit.resource, }; const result = await updateCategory(id, updatedCategory); if (!isMounted) return; if (result.error) return setDirective({ header: "Error deleting category", message: result.error.data.error, success: false, }); closeModal(); setPendingEdit({}); queryCategories(); }; const handleBulkActionChange = (_, data) => { const value = data.value; setBulkAction(value); }; const handleBulkDelete = async () => { setModalState("bulk"); if (selectedCategories.length < 1) return setDirective({ header: "Error applying bulk actions", message: "No items selected", success: false, }); if (bulkAction === "default") return setDirective({ header: "Error applying bulk actions", message: "Invalid action", success: false, }); setModalActive(true); }; const applyBulkDelete = async () => { if (!isMounted) return; const result = await bulkDeleteCategory(selectedCategories); if (!isMounted) return; if (result.error) return setDirective({ header: "Error applying bulk action", message: result.error.data.error, success: false, }); closeModal(); setSelectedCategories([]); queryCategories(); }; return ( <ListCategories dataLabel={dataLabel} categories={categories_} label={label} labelPlural={labelPlural} searchQuery={searchQuery} handleQueryChange={handleQueryChange} applySearch={applySearch} clearSearch={clearSearch} page={page} pages={pages} hasPages={hasPages} nextPage={nextPage} prevPage={prevPage} handleSelected={handleSelected} batchSelect={batchSelect} newCategory={setNewCat} handleDelete={handleDelete} newCategoryValue={newCat} selectedCategories={selectedCategories} pendingDelete={pendingDelete} pendingEdit={pendingEdit} submitNewCategory={submitNewCategory} closeModal={closeModal} applyDelete={applyDelete} modalActive={modalActive} modalState={modalState} handleEdit={handleEdit} editCategory={setEditCat} editCategoryValue={editCat} applyEdit={applyEdit} loading={loading} directive={directive} handleBulkActionChange={handleBulkActionChange} handleBulkDelete={handleBulkDelete} applyBulkDelete={applyBulkDelete} /> ); } <file_sep>import React, { useState, useEffect } from "react"; import ContentPicker from "../../../components/Forms/ContentPicker"; export default function ContentPickerCtrl({ label, dataLabel, data, setter, selected, }) { // =============================================================== // STATE VARIABLES // =============================================================== /* @desc an array of Id's that of selected items @author <NAME> @type Array<id> */ const [activeSelection, setActiveSelection] = useState([]); /* @desc an array of formatted options to be parsed by semantic ui's dropdown. @author <NAME> @type Array<{formattedOption}> */ const [formattedOptions, setFormattedOptions] = useState([]); /* @desc a string value that holds the focused/selected item's id -- to be added in activeSelection @author <NAME> @type String (ObjectId) */ const [selectedOption, setSelectedOption] = useState(""); /* @desc An array of raw options, to be formatted and used in dropdowns. @author <NAME> @type Array<{option}> */ const [options, setOptions] = useState([]); // =============================================================== // USE EFFECTS // =============================================================== /* @desc once the data mounts, we set our options, then format them. @author <NAME> */ useEffect(() => { setOptions(data); formatOptions(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [data]); /* @desc once the selection data mounts, format it. @author <NAME> */ useEffect(() => { formatSelection(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [selected]); /* @desc everytime the selection changes, we want to sync up with the parent's data by calling the setter method. @author <NAME> */ useEffect(() => { setter(activeSelection); // eslint-disable-next-line react-hooks/exhaustive-deps }, [activeSelection]); /* @desc everytime the activeSelection, or options change, we want to format the options @author <NAME> */ useEffect(() => { formatOptions(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [options, activeSelection]); // =============================================================== // FUNCTIONS // =============================================================== /* @desc formats the existing data into an array that can be accepted by the picker. @author <NAME> @param none @return none */ const formatSelection = () => { if ((selected && selected.length < 1) || !selected) return; const formatted = selected.map((option) => { const obj = { _id: option._id, title: option[`${dataLabel}_name`], // Nullify isPublish to suppress react warning isPublish: null, }; if (obj.isPublish) delete obj.isPublish; return obj; }); setActiveSelection(formatted); }; /* @desc listens for drag events to reorder items within the picker. @author <NAME> @param result {Object} -- a custom response object from react drag-and-drop. @return null -- if there's no destination, we return null to exit the function. */ const handleOnDragEnd = (result) => { if (!result.destination) return; const items = Array.from(activeSelection); const [reorderedItem] = items.splice(result.source.index, 1); items.splice(result.destination.index, 0, reorderedItem); setActiveSelection(items); }; /* @desc formats the available option into an array that can be accepted by the dropdown. @author <NAME> @param none @return none */ const formatOptions = () => { const activeOptions = [...activeSelection].map((item) => item._id); const filtered = options.filter( (option) => !activeOptions.includes(option._id) ); const formatted = filtered.map((option) => { const obj = { ...option, key: option._id, value: option._id, // Nullify description, it looks like semantic UI drop downs look for this specific key, value which produces unwanted effects. description: null, // Nullify isPublish isPublish: null, text: option[`${dataLabel}_name`], }; if (obj.isPublish) delete obj.isPublish; return obj; }); setFormattedOptions(formatted); }; /* @desc watches for changes in drop-down selection, sets the selected option. @author <NAME> @param none @return none */ const handleSelectChange = (e, data) => { setSelectedOption(data.value); }; /* @desc formats, finds, and adds the selected content into the picker. @author <NAME> @param none @return none */ const confirmSelection = () => { let foundOption = options.filter( (option) => option._id === selectedOption )[0]; if (!foundOption || foundOption.length < 1) return; foundOption = { _id: foundOption._id, title: foundOption[`${dataLabel}_name`], }; const newActiveSelection = [...activeSelection, foundOption]; setActiveSelection(newActiveSelection); }; /* @desc removes the chosen content from the picker. @author <NAME> @param id {String} -- an ObjectId that is unique to the content being picked. @return none */ const handleRemove = (id) => { let selected = [...activeSelection]; selected = selected.filter((item) => item._id !== id); setActiveSelection(selected); }; return ( <ContentPicker // METHODS handleSelectChange={handleSelectChange} handleRemove={handleRemove} confirmSelection={confirmSelection} handleOnDragEnd={handleOnDragEnd} // ATTRIBUTES activeSelection={activeSelection} options={formattedOptions} label={label} /> ); } <file_sep>import React, { useState, useEffect } from "react"; import Profile from "../../components/Profile"; import { useAuth } from "../../context/AuthContext"; import { updateUser } from "../../network"; export default function ProfileCtrl() { const authContext = useAuth(); const { userData, queryUser } = authContext; const [changePassword, setChangePassword] = useState(false); const [username, setUsername] = useState(userData?.user.user_name); const [email, setEmail] = useState(userData?.user.email); const [role, setRole] = useState(userData?.user.role); const [newPassword, setNewPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); // Error Messaging const [directive, setDirective] = useState(null); // Preloader const [loading, setLoading] = useState(false); useEffect(() => { resetDirective(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [directive]); const resetDirective = async () => { if (directive) { switch (directive.success) { case true: break; case false: await setTimeout(() => { setDirective(null); }, 4000); break; default: break; } } }; const toggleChangePassword = () => { setChangePassword(true); }; const cancelChangePassword = () => { setChangePassword(false); setNewPassword(""); setConfirmPassword(""); }; const applyUpdate = async () => { const id = userData.user._id; if (!id) return setDirective({ header: "Error", message: "Cannot fetch user data", success: false, }); let userData_ = { email: email, user_name: username, role: role, }; if (changePassword) { if (!newPassword || !confirmPassword) return setDirective({ header: "Could not update user", message: "Password fields are empty.", success: false, }); if (newPassword !== confirmPassword) return setDirective({ header: "Could not update user", message: "Password fields don't match.", success: false, }); userData_ = { ...userData_, password: <PASSWORD>, }; } setLoading(true); const result = await updateUser(userData_, id); if (result.error) { setLoading(false); return setDirective({ header: "Error updating your profile", message: result.error.data.error, success: false, }); } setDirective({ header: "Update Successful", message: "Successfully updated your profile", success: true, }); queryUser(); setLoading(false); }; return ( <Profile toggleChangePassword={toggleChangePassword} cancelChangePassword={cancelChangePassword} changePassword={changePassword} username={username} changeUsername={setUsername} changeEmail={setEmail} changeRole={setRole} email={email} role={role} newPassword={<PASSWORD>} confirmPassword={<PASSWORD>} changeNewPassword={<PASSWORD>} changeConfirmPassword={<PASSWORD>} applyUpdate={applyUpdate} loading={loading} directive={directive} /> ); } <file_sep>import React from "react"; import EditUserCtrl from "../../controllers/Edit/User/EditUserCtrl"; export default function EditUser() { return ( <main> <EditUserCtrl /> </main> ); } <file_sep>import React from "react"; import { Link } from "react-router-dom"; import MenuItem from "./MenuItem"; /* @desc UI component that displays a sidebar navigation. @controller ~/src/controller/Sidebar/SidebarCtrl */ export default function Sidebar({ sidebarLinks, path, sidebarModel, userData, }) { return ( <aside className="sidebar"> <ul> {sidebarLinks.map((item, index) => ( <MenuItem sidebarModel={sidebarModel} path={path} key={index} label={item.label} formattedLabel={item.formattedLabel} navigationPath={item.navigationPath} subItems={item.subItems} /> ))} <li> <Link to="/profile"> <span className={ sidebarModel["profile"] ? "menu__item item__wrap parent active" : "menu__item item__wrap parent" } > <span style={style.initial}> {" "} {userData?.user?.user_name[0].toUpperCase()} </span> <span className="menu__item item__label"> {" "} {userData?.user?.user_name} </span> </span> </Link> </li> </ul> </aside> ); } const style = { initial: { height: "26px", width: "26px", backgroundColor: "var(--highlight)", border: "1px solid var(--highlightsecondary)", color: "var(--lightprimary)", borderRadius: "50%", lineHeight: "24px", textAlign: "center", fontFamily: "serif, Times", display: "block", cursor: "pointer", fontSize: 14, }, }; <file_sep>import React, { useState, useEffect } from "react"; import TextInput from "../../../components/Forms/TextInput"; export default function TextInputCtrl({ label, setter, eValue }) { const [value, setValue] = useState(" "); useEffect(() => { setter(value); // eslint-disable-next-line react-hooks/exhaustive-deps }, [value]); useEffect(() => { setValue(eValue); // eslint-disable-next-line react-hooks/exhaustive-deps }, [eValue]); return <TextInput label={label} setValue={setValue} value={value} />; } <file_sep>import axios from "axios"; const BASE_URL = process.env.REACT_APP_BASE_URL; /* ================================================= GET STORED TOKEN ==================================================*/ const getToken = () => { const userData = JSON.parse( localStorage.getItem("INDIGENOUSPLANTGOCMS-userData") ); if (userData && userData.accessToken) return userData.accessToken; // Else return nothing return null; }; /* ================================================= PING ==================================================*/ export const ping = async () => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.get(`${BASE_URL}/ping`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; /* ================================================= USERS ==================================================*/ export const login = async ({ username, password }) => { try { const response = await axios.post(`${BASE_URL}/users/login`, { user_name: username, password: <PASSWORD>, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const getUser = async (id) => { try { const response = await axios.get(`${BASE_URL}/users/${id}`); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const getAllUsers = async () => { try { const response = await axios.get(`${BASE_URL}/users`); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const updateUser = async (userData, id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.put(`${BASE_URL}/users/${id}`, userData, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const deleteUser = async (id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.delete(`${BASE_URL}/users/${id}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const createUser = async (user) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.post(`${BASE_URL}/users`, user, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const bulkDeleteUsers = async (array) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const deleteRequests = array.map((userId) => axios.delete(`${BASE_URL}/users/${userId}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }) ); const responses = await Promise.all(deleteRequests); return responses; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const resetPassword = async (email) => { try { const response = await axios.post( `${BASE_URL}/users/reset_password`, email ); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; /* ================================================= LOCATIONS ==================================================*/ export const createLocation = async (location) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.post(`${BASE_URL}/locations`, location, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const getLocations = async () => { try { const response = await axios.get(`${BASE_URL}/locations`); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const bulkDeleteLocations = async (array) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const deleteRequests = array.map((locationId) => axios.delete(`${BASE_URL}/locations/${locationId}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }) ); const responses = await Promise.all(deleteRequests); return responses; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const deleteLocation = async (id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.delete(`${BASE_URL}/locations/${id}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const updateLocation = async (id, location) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.put(`${BASE_URL}/locations/${id}`, location, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.message, }; } }; /* ================================================= IMAGES ==================================================*/ export const createImage = async (formData) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.post(`${BASE_URL}/images`, formData, { headers: { "Content-Type": "multipart/form-data", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const getImages = async () => { try { const response = await axios.get(`${BASE_URL}/images`); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const deleteImage = async (id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.delete(`${BASE_URL}/images/${id}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const updateImage = async (image, id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.put(`${BASE_URL}/images/${id}`, image, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const bulkDeleteImages = async (array) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const deleteRequests = array.map((imageId) => axios.delete(`${BASE_URL}/images/${imageId}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }) ); const responses = await Promise.all(deleteRequests); return responses; } catch (error) { console.log(error.response); return { error: error.response, }; } }; /* ================================================= AUDIOS ==================================================*/ export const createAudio = async (formData) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.post(`${BASE_URL}/audios`, formData, { headers: { "Content-Type": "multipart/form-data", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const getAudios = async () => { try { const response = await axios.get(`${BASE_URL}/audios`); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const deleteAudio = async (id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.delete(`${BASE_URL}/audios/${id}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const updateAudio = async (audio, id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.put(`${BASE_URL}/audios/${id}`, audio, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const bulkDeleteAudios = async (array) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const deleteRequests = array.map((audioId) => axios.delete(`${BASE_URL}/audios/${audioId}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }) ); const responses = await Promise.all(deleteRequests); return responses; } catch (error) { console.log(error.response); return { error: error.response, }; } }; /* ================================================= VIDEOS ==================================================*/ export const createVideo = async (video) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.post(`${BASE_URL}/videos`, video, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const getVideos = async () => { try { const response = await axios.get(`${BASE_URL}/videos`); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const deleteVideo = async (id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.delete(`${BASE_URL}/videos/${id}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const updateVideo = async (video, id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.put(`${BASE_URL}/videos/${id}`, video, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const bulkDeleteVideos = async (array) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const deleteRequests = array.map((videoId) => axios.delete(`${BASE_URL}/videos/${videoId}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }) ); const responses = await Promise.all(deleteRequests); return responses; } catch (error) { console.log(error.response); return { error: error.response, }; } }; /* ================================================= TAGS ==================================================*/ export const createTag = async (tag) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.post(`${BASE_URL}/tags`, tag, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const deleteTag = async (id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.delete(`${BASE_URL}/tags/${id}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const updateTag = async (id, tag) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.put(`${BASE_URL}/tags/${id}`, tag, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const getTags = async () => { try { const response = await axios.get(`${BASE_URL}/tags`); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const bulkDeleteTags = async (array) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const deleteRequests = array.map((tagId) => axios.delete(`${BASE_URL}/tags/${tagId}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }) ); const responses = await Promise.all(deleteRequests); return responses; } catch (error) { console.log(error.response); return { error: error.response, }; } }; /* ================================================= CATEGORIES ==================================================*/ export const getAllCategories = async () => { try { const response = await axios.get(`${BASE_URL}/categories`); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const getCategoryGroup = async (group) => { try { const response = await axios.get(`${BASE_URL}/categories/group/${group}`); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const createCategory = async (category) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.post(`${BASE_URL}/categories`, category, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const deleteCategory = async (id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.delete(`${BASE_URL}/categories/${id}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const bulkDeleteCategory = async (array) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const deleteRequests = array.map((categoryId) => axios.delete(`${BASE_URL}/categories/${categoryId}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }) ); const responses = await Promise.all(deleteRequests); return responses; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const updateCategory = async (id, category) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.put(`${BASE_URL}/categories/${id}`, category, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; /* ================================================= PLANTS ==================================================*/ export const getAllPlants = async () => { try { const response = await axios.get(`${BASE_URL}/plants/all`); return response.data; } catch (error) { console.log(error.reponse); return { error: error.response, }; } }; export const getPlant = async (id) => { try { const response = await axios.get(`${BASE_URL}/plants/${id}`); return response.data; } catch (error) { console.log(error.reponse); return { error: error.response, }; } }; export const updatePlant = async (id, plant) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.put(`${BASE_URL}/plants/${id}`, plant, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.message, }; } }; export const createPlant = async (plant) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.post(`${BASE_URL}/plants`, plant, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const deletePlant = async (id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.delete(`${BASE_URL}/plants/${id}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const bulkDeletePlants = async (array) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const deleteRequests = array.map((plantId) => axios.delete(`${BASE_URL}/plants/${plantId}`, { headers: { "Content-Type": "multipart/form-data", Authorization: `Bearer ${token}`, }, }) ); const responses = await Promise.all(deleteRequests); return responses; } catch (error) { console.log(error.response); return { error: error.response, }; } }; /* ================================================= WAYPOINTS ==================================================*/ export const getAllWaypoints = async () => { try { const response = await axios.get(`${BASE_URL}/waypoints/all`); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const deleteWaypoint = async (id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.delete(`${BASE_URL}/waypoints/${id}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const createWaypoint = async (waypoint) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.post(`${BASE_URL}/waypoints`, waypoint, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const getWaypoint = async (id) => { try { const response = await axios.get(`${BASE_URL}/waypoints/${id}`); return response.data; } catch (error) { console.log(error.reponse); return { error: error.response, }; } }; export const updateWaypoint = async (id, waypoint) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.put(`${BASE_URL}/waypoints/${id}`, waypoint, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.message, }; } }; export const bulkDeleteWaypoints = async (array) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const deleteRequests = array.map((waypointId) => axios.delete(`${BASE_URL}/waypoints/${waypointId}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }) ); const responses = await Promise.all(deleteRequests); return responses; } catch (error) { console.log(error.response); return { error: error.response, }; } }; /* ================================================= LEARN MORE ==================================================*/ export const getAllLearnMore = async () => { try { const response = await axios.get(`${BASE_URL}/learn_more`); return response.data; } catch (error) { console.log(error.reponse); return { error: error.response, }; } }; export const getLearnMore = async (id) => { try { const response = await axios.get(`${BASE_URL}/learn_more/${id}`); return response.data; } catch (error) { console.log(error.reponse); return { error: error.response, }; } }; export const deleteLearnMore = async (id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.delete(`${BASE_URL}/learn_more/${id}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const bulkDeleteLearnMore = async (array) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const deleteRequests = array.map((learnMoreId) => axios.delete(`${BASE_URL}/learn_more/${learnMoreId}`, { headers: { "Content-Type": "multipart/form-data", Authorization: `Bearer ${token}`, }, }) ); const responses = await Promise.all(deleteRequests); return responses; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const createLearnMore = async (learnMore) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.post(`${BASE_URL}/learn_more`, learnMore, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const updateLearnMore = async (id, learnMore) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.put(`${BASE_URL}/learn_more/${id}`, learnMore, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.message, }; } }; /* ================================================= TOURS ==================================================*/ export const getAllTours = async () => { try { const response = await axios.get(`${BASE_URL}/tours`); return response.data; } catch (error) { console.log(error.reponse); return { error: error.response, }; } }; export const getTour = async (id) => { try { const response = await axios.get(`${BASE_URL}/tours/${id}`); return response.data; } catch (error) { console.log(error.reponse); return { error: error.response, }; } }; export const deleteTour = async (id) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.delete(`${BASE_URL}/tours/${id}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const bulkDeleteTours = async (array) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const deleteRequests = array.map((tourId) => axios.delete(`${BASE_URL}/tours/${tourId}`, { headers: { "Content-Type": "multipart/form-data", Authorization: `Bearer ${token}`, }, }) ); const responses = await Promise.all(deleteRequests); return responses; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const createTour = async (tour) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.post(`${BASE_URL}/tours`, tour, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.response, }; } }; export const updateTour = async (id, learnMore) => { const token = getToken(); if (!token) return { error: "No token found. Could not authenticate request.", }; try { const response = await axios.put(`${BASE_URL}/tours/${id}`, learnMore, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.log(error.response); return { error: error.message, }; } };<file_sep>import Navigation from "./navigation"; import HeaderCtrl from "./controllers/Header/HeaderCtrl"; import SidebarCtrl from "./controllers/Sidebar/SidebarCtrl"; import { useAuth } from "./context/AuthContext"; function App() { const authContext = useAuth(); const { isAuthenticated } = authContext; return ( <> {isAuthenticated && ( <> <HeaderCtrl /> <SidebarCtrl /> </> )} <Navigation /> </> ); } export default App; <file_sep>import React from "react"; import Table from "./Table"; import DashHeader from "../../DashHeader"; import { Dropdown, Input, Icon } from "semantic-ui-react"; import Modal from "../../Modal"; import { Loader } from "semantic-ui-react"; import Message from "../../Message"; /* @desc UI component that Lists media and allows the list to be managed. @controller ~/src/controllers/List/Media/ListMediaCtrl.js */ export default function ListMedia({ // Data to List: Medias medias, // Labels label, dataLabel, // SEARCH -- Attributes searchQuery, // SEARCH -- METHODS handleQueryChange, applySearch, clearSearch, // PAGINATION -- Attributes hasPages, page, pages, // PAGINATION -- Methods nextPage, prevPage, // BATCH SELECT -- Attributes selectedMedias, // BATCH SELECT -- Methods handleSelected, batchSelect, // NEW MEDIA -- METHODS setFile, setCaption, handleUpload, // NEW MEDIA -- Attributes file, caption, // MODAL -- Methods closeModal, // MODAL -- Attributes modalState, modalActive, // DELETE -- Methods handleDelete, applyDelete, // DELETE -- Attributes pendingDelete, // EDIT -- Methods handleEdit, handleChangeFile, handleCaptionChange, applyEdit, // EDIT -- Attributes pendingEdit, editMedia, // BULK DELETE -- Methods handleBulkActionChange, handleBulkDelete, applyBulkDelete, // LOADING -- Attributes loading, directive, videoLink, setVideoLink, editVideoLink, setEditVideoLink, }) { const renderModal = () => { switch (modalState) { case "edit": return editModal(); case "delete": return deleteModal(); case "bulk": return bulkDeleteModal(); default: return <></>; } }; const deleteModal = () => ( <> {dataLabel === "image" && ( <> <p style={style.label}>Thumbnail</p> <div className="thumbnail__container"> <div className="thumbnail__image"> <img src={pendingDelete[`${dataLabel}_url`]} alt="thumbnail" /> </div> <div className="thumbnail__meta"> <a href={pendingDelete[`${dataLabel}_url`]} target="blank_"> View full {label.toLowerCase()} &nbsp; <Icon name="sign-out" /> </a> </div> </div> </> )} <p> Deleting this tag will remove all instances of &nbsp; <strong style={{ color: "var(--danger)" }}> {pendingDelete.caption} </strong> . Do you wish to proceed? </p> <button onClick={() => applyDelete("delete")} className="field__button"> Yes, I know what I am doing. </button> <button onClick={() => closeModal()} className="field__button secondary"> No, cancel my request. </button> </> ); const editModal = () => ( <> {dataLabel === "image" && ( <> <p style={style.label}>Thumbnail</p> <div className="thumbnail__container"> <div className="thumbnail__image"> <img src={editMedia.url} alt="thumbnail" /> </div> <div className="thumbnail__meta"> <a href={editMedia.url} target="blank_"> View full {label.toLowerCase()} &nbsp; <Icon name="sign-out" /> </a> </div> </div> </> )} {dataLabel === "audio_file" && ( <> <p style={style.label}>Audio Preview</p> <div className="thumbnail__container audio"> <div className="thumbnail__audio"> <audio controls src={editMedia.url}> Your browser does not support the <code>audio</code> element. </audio> </div> </div> </> )} <fieldset style={style.fieldset}> <p style={style.label}> Caption <span style={style.req}>*</span> </p> <Input value={editMedia.caption} onChange={(e) => handleCaptionChange(e)} style={style.input} placeholder="Enter caption" /> </fieldset> {dataLabel === "video" ? ( <> <fieldset style={style.fieldset}> <p style={style.label}> Youtube URL <span style={style.req}>*</span> </p> <Input value={editVideoLink} onChange={(e) => setEditVideoLink(e.target.value)} style={style.input} placeholder="Enter Youtube URL" /> <p style={{ fontSize: 12, marginTop: 7 }}> Valid Example: https://www.youtube.com/watch?v=lhqNduGgpC8 </p> </fieldset> <button className="field__button" onClick={() => applyEdit()}> Update {label[0].toUpperCase()} {label.substring(1)} </button> </> ) : ( <> <p style={style.label}> Upload file: <span style={style.req}>*</span> </p> <fieldset style={style.fieldset}> <div className="field__file"> <div style={{ padding: "10px 10px", minWidth: 100 }} className="file__meta" > <p> {editMedia.file !== null ? editMedia.file?.name : editMedia.url} </p> </div> <input filename={editMedia?.file !== null ? editMedia.file : null} onChange={(e) => { handleChangeFile(e); }} style={{ display: "none" }} id="file--update" type="file" accept={ dataLabel === "image" ? "image/*" : dataLabel === "audio_file" ? "audio/*" : "video/*" } /> <button className="field__button"> <label htmlFor="file--update">Choose File</label> </button> </div> <button className="field__button" onClick={() => applyEdit()}> Update {label[0].toUpperCase()} {label.substring(1)} </button> </fieldset> </> )} <button onClick={() => closeModal()} style={{ color: "var(--highlight)" }} > Cancel </button> </> ); const bulkDeleteModal = () => ( <> <p> Deleting&nbsp; <strong style={{ color: "var(--danger)" }}> {selectedMedias.length} </strong> &nbsp;{label}s will remove{" "} <strong style={{ color: "var(--danger)", fontWeight: "700", textTransform: "uppercase", }} > all </strong>{" "} instances of the deleted {label}s. Do you wish to proceed? </p> <button onClick={() => applyBulkDelete()} className="field__button"> Yes, I know what I am doing. </button> <button onClick={() => closeModal()} className="field__button secondary"> No, cancel my request. </button> </> ); return ( <div> {typeof directive === "object" && directive !== null && Object.keys(directive).length > 0 && ( <Message success={directive.success} header={directive.header} message={directive.message} /> )} <DashHeader title={`${label}s`} /> <div className="resource__container"> <div className="resource__col left"> <h3>Add New {label}</h3> <fieldset style={style.fieldset}> <p style={style.label}> Caption <span style={style.req}>*</span> </p> <Input value={caption} onChange={(e) => setCaption(e.target.value)} style={style.input} placeholder="Enter caption" /> </fieldset> {dataLabel === "video" ? ( <> <fieldset style={style.fieldset}> <form> <fieldset style={style.fieldset}> <p style={style.label}> Youtube URL <span style={style.req}>*</span> </p> <Input value={videoLink} onChange={(e) => setVideoLink(e.target.value)} style={style.input} placeholder="Enter Youtube URL" /> <p style={{ fontSize: 12, marginTop: 7 }}> Valid Example: https://www.youtube.com/watch?v=lhqNduGgpC8 </p> </fieldset> <button type="button" className="field__button" onClick={() => handleUpload()} > Upload {label[0].toUpperCase()} {label.substring(1)} </button> </form> </fieldset> </> ) : ( <> <p style={style.label}> Upload file: <span style={style.req}>*</span> </p> <fieldset style={style.fieldset}> <form> <div className="field__file"> <div style={{ padding: "10px 10px", minWidth: 100 }} className="file__meta" > <p>{file?.name}</p> </div> <input filename={file} onChange={(e) => { setFile(e.target.files[0]); }} key={file?.name || ""} style={{ display: "none" }} id="file--upload" type="file" accept={ dataLabel === "image" ? "image/*" : dataLabel === "audio_file" ? "audio/*" : "video/*" } /> <button type="button" className="field__button"> <label htmlFor="file--upload">Choose File</label> </button> </div> <button type="button" className="field__button" onClick={() => handleUpload()} > Upload {label[0].toUpperCase()} {label.substring(1)} </button> </form> </fieldset> </> )} </div> <div className="resource__col right"> <div style={{ marginBottom: 10, display: "flex" }}> <p> <strong>Results</strong> ({medias.length}){" "} </p> {loading && <Loader active inline size="tiny" />} </div> <div className="table__controls"> <div style={{ display: "flex" }}> <div className="table__action"> <Dropdown placeholder={"Bulk Actions"} onChange={(e, data) => handleBulkActionChange(e, data)} selection options={[ { key: "default", value: "default", text: "Bulk Actions" }, { key: "delete", value: "delete", text: "Delete" }, ]} /> <button onClick={() => handleBulkDelete()}>Apply</button> </div> </div> <div> <div className="table__action" style={{ marginRight: 0 }}> {searchQuery && ( <button onClick={() => clearSearch()} className="sub__action"> Clear search </button> )} <Input onChange={(e) => handleQueryChange(e)} value={searchQuery} style={{ ...style.input, minWidth: 250 }} placeholder={`Enter search query`} /> <button onClick={() => applySearch()}>Search</button> </div> </div> </div> <div className="table__heading table__row"> <div className="table__col head select"> <input type="checkbox" value={"select all"} onChange={(e) => batchSelect(e)} /> </div> <div className="table__col head title"> <h3>caption</h3> </div> <div className="table__col head url"> <h3>url</h3> </div> {dataLabel === "image" && ( <div className="table__col head thumbnail"> <h3>thumbnail</h3> </div> )} {dataLabel === "audio_file" && ( <div className="table__col head audio__preview"> <h3>Preview</h3> </div> )} </div> <Table medias={hasPages ? pages[page - 1] : medias} selectedMedias={selectedMedias} dataLabel={dataLabel} handleSelected={handleSelected} handleDelete={handleDelete} handleEdit={handleEdit} /> {hasPages && ( <div className="pagination__control"> <div> <p style={{ marginBottom: "7px" }}> Page {page} of {pages.length} </p> <div className="control"> <button onClick={() => prevPage()}> <Icon name="caret left" /> </button> <span>{page}</span> <button onClick={() => nextPage()}> <Icon name="caret right" /> </button> </div> </div> </div> )} <Modal isActive={modalActive} title={ modalState === "delete" ? `Delete ${pendingDelete.caption}?` : modalState === "edit" ? `Edit ${pendingEdit.caption}` : `Delete all ${selectedMedias.length} ${label}s?` } closeModal={closeModal} > {renderModal()} </Modal> </div> </div> </div> ); } const style = { input: { width: "100%", color: "var(--darksecondary)", }, textarea: { height: 200, border: "1px solid lightgrey", color: "var(--darkprimary)", padding: "7px 14px", background: "var(--lighttertiary)", }, label: { color: "var(--darksecondary)", margin: 0, fontSize: 11, marginBottom: "3px", }, fieldset: { marginBottom: "10px", padding: 0, }, req: { color: "red", fontSize: 14, }, }; <file_sep>import React from "react"; import { Input, Button, Loader, Icon } from "semantic-ui-react"; import Message from "../Message"; export default function ResetForm({ email, setEmail, navigateToLogin, submitReset, directive, loading, }) { return ( <div> {typeof directive === "object" && directive !== null && Object.keys(directive).length > 0 && ( <Message success={directive.success} header={directive.header} message={directive.message} /> )} <form style={style.form} onSubmit={(e) => e.preventDefault()}> <fieldset style={style.fieldset}> <p style={{ maxWidth: 300, lineHeight: "1.7em", fontSize: 13 }}> <Icon name="info circle" /> please enter the email associated with your account and click{" "} <span style={{ background: "var(--highlight)", color: "white", padding: "3px 6px", borderRadius: "3px", }} > Reset Password </span>{" "} to send a recovery email and code. </p> <p style={style.label}> Email<span style={style.req}>*</span> </p> <Input style={style.input} onChange={(e) => setEmail(e.target.value)} value={email} icon="user" iconPosition="left" placeholder="Email" /> </fieldset> <fieldset className="submit__fieldset" style={style.fieldset}> <Button onClick={() => submitReset()} primary style={{ ...style.submit, position: "relative" }} > Reset Password {loading && <Loader active inline inverted size="small" />} </Button> </fieldset> </form> <div style={style.formFooter}> <button onClick={() => navigateToLogin()} style={{ color: "grey" }}> ← Back to login </button> </div> </div> ); } const style = { form: { background: "var(--lightprimary)", border: "1px solid lightgrey", minWidth: "350px", margin: "auto", padding: 20, boxShadow: "var(--shadow)", }, formFooter: { padding: "20px 0", }, input: { width: "100%", color: "var(--darksecondary)", }, label: { color: "var(--darksecondary)", margin: 0, fontSize: 11, marginBottom: "3px", }, fieldset: { marginBottom: "3px", }, submit: { width: "100%", background: "var(--highlight)", borderRadius: "unset", }, req: { color: "red", fontSize: 14, }, }; <file_sep>import React from "react"; import ListMediaCtrl from "../../controllers/List/Media/ListMediaCtrl"; export default function AudioFiles() { return ( <main> <ListMediaCtrl dataLabel="audio_file" label="Audio File" /> </main> ); } <file_sep>import React from "react"; import EditWaypointCtrl from "../../controllers/Edit/Waypoint/EditWaypointCtrl"; export default function EditWaypoints() { return ( <main> <EditWaypointCtrl /> </main> ); } <file_sep>import React from "react"; import { Loader } from "semantic-ui-react"; /* @desc UI component for the Dashboard header. Displays A title, and a controlled button. @controller null */ export default function DashHeader({ title, subtitle, action, method, loading, }) { return ( <> <div className="dash__header"> <div className="dash__title"> <h2>{title}</h2> {action && method && ( <button onClick={() => method()}>{action}</button> )}{" "} &nbsp; &nbsp; {loading && <Loader active inline size="mini" />} </div> {subtitle && <p style={{ margin: 0 }}>{subtitle}</p>} </div> </> ); } <file_sep>import React from "react"; /* @desc UI component that renders a table of categories. @controller ../Categories/index.js */ export default function Table({ // Attributes categories, selectedCategories, // Methods handleSelected, handleDelete, handleEdit, }) { return ( <ul className="table__list"> {categories && categories.length > 0 && categories.map((category, index) => { return ( <li className={ selectedCategories.includes(category._id) ? "table__row selected" : "table__row" } key={index} > <div className="table__col select"> <input type="checkbox" value={category._id} checked={ selectedCategories.includes(category._id) ? true : false } onChange={(e) => handleSelected(e)} /> </div> <div className="table__col title"> <p>{category.category_name}</p> <span className="action"> <button type="button" value={category._id} onClick={(e) => handleEdit(e)} > Edit&nbsp; </button> <button type="button" value={category._id} onClick={(e) => handleDelete(e)} > &nbsp;Delete </button> </span> </div> </li> ); })} </ul> ); } <file_sep>import React, { useState, useEffect } from "react"; import TextPicker from "../../../components/Forms/TextPicker"; import { createTag, createCategory, createLocation } from "../../../network"; export default function TextPickerCtrl({ label, dataLabel, data, selected, setter, query, resource, }) { const fieldInputs = { location: { name: "", latitude: 0, longitude: 0, description: "", }, category: { name: "", }, tag: { name: "", }, }; // =============================================================== // STATE VARIABLES // =============================================================== /* @desc an array of Id's that of selected items @author <NAME> @type Array<id> */ const [activeSelection, setActiveSelection] = useState([]); /* @desc an array of formatted options to be parsed by semantic ui's dropdown. @author <NAME> @type Array<{formattedOption}> */ const [formattedOptions, setFormattedOptions] = useState([]); /* @desc a string value that holds the focused/selected item's id -- to be added in activeSelection @author <NAME> @type String (ObjectId) */ const [selectedOption, setSelectedOption] = useState(""); /* @desc An array of raw options, to be formatted and used in dropdowns. @author <NAME> @type Array<{option}> */ const [options, setOptions] = useState(data); /* @desc a variable that holds the active state of the modal @author <NAME> @type boolean */ const [modalActive, setModalActive] = useState(false); /* @desc a variable that holds different fields of a text picker's data @author <NAME> @type {Object<fieldInputs>} */ const [fields, setFields] = useState(fieldInputs); const [directive, setDirective] = useState(null); // =============================================================== // USE EFFECTS // =============================================================== useEffect(() => { resetDirective(); }, [directive]); /* @desc once the data mounts, we set our options, then format them. @author <NAME> */ useEffect(() => { setOptions(data); formatOptions(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [data]); /* @desc once the selection data mounts, format it. @author <NAME> */ useEffect(() => { formatSelection(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [selected]); /* @desc everytime the selection changes, we want to sync up with the parent's data by calling the setter method. @author <NAME> */ useEffect(() => { setter(activeSelection); // eslint-disable-next-line react-hooks/exhaustive-deps }, [activeSelection]); /* @desc everytime the activeSelection, or options change, we want to format the options @author <NAME> */ useEffect(() => { formatOptions(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [options, activeSelection]); // =============================================================== // FUNCTIONS // =============================================================== const resetDirective = async () => { await setTimeout(() => { setDirective(null); }, 4000); }; /* @desc formats the existing data into an array that can be accepted by the picker. @author <NAME> @param none @return none */ const formatSelection = () => { if (!selected) return; const formatted = selected.map((option) => { return { _id: option._id, title: option[`${dataLabel}_name`], }; }); setActiveSelection(formatted); }; /* @desc formats the available option into an array that can be accepted by the dropdown. @author <NAME> @param none @return none */ const formatOptions = () => { const activeOptions = [...activeSelection].map((item) => item._id); const filtered = data.filter( (option) => !activeOptions.includes(option._id) ); const formatted = filtered.map((option) => { return { ...option, description: null, key: option._id, value: option._id, text: option[`${dataLabel}_name`], }; }); setFormattedOptions(formatted); }; /* @desc listens for drag events to reorder items within the picker. @author <NAME> @param result {Object} -- a custom response object from react drag-and-drop. @return null -- if there's no destination, we return null to exit the function. */ const handleOnDragEnd = (result) => { if (!result.destination) return; const items = Array.from(activeSelection); const [reorderedItem] = items.splice(result.source.index, 1); items.splice(result.destination.index, 0, reorderedItem); setActiveSelection(items); }; /* @desc watches for changes in drop-down selection, sets the selected option. @author <NAME> @param none @return none */ const handleSelectChange = (e, data) => { setSelectedOption(data.value); }; /* @desc formats, finds, and adds the selected content into the picker. @author <NAME> @param none @return none */ const confirmSelection = () => { let foundOption = options.filter( (option) => option._id === selectedOption )[0]; if (!foundOption || foundOption.length < 1) return; foundOption = { _id: foundOption._id, title: foundOption[`${dataLabel}_name`], }; const newActiveSelection = [...activeSelection, foundOption]; setActiveSelection(newActiveSelection); }; /* @desc removes the chosen media from the picker. @author <NAME> @param id {String} -- an ObjectId that is unique to the content being picked. @return none */ const handleRemove = (id) => { let selected = [...activeSelection]; selected = selected.filter((item) => item._id !== id); setActiveSelection(selected); }; const openModal = () => { setModalActive(true); }; const closeModal = () => { setModalActive(false); }; /* @desc watches field updates, updates the field state variable @author <NAME> @param none @return none */ const handleFieldChange = (e, label_) => { let target = e.target.name, fieldLabel = label_, value = e.target.value; let currentFields = { ...fields }; currentFields[`${fieldLabel}`][`${target}`] = value; setFields(currentFields); }; /* @desc uploads a new text field, and adds the uploaded text field to the picker. @author <NAME> @param none @return none */ const handleFieldUpload = async (label_) => { let fieldLabel = label_; let result, currSelection, formatted; switch (fieldLabel) { case "tag": if (!fields.tag.name) return; const tag = { tag_name: fields.tag.name, }; result = await createTag(tag); break; case "category": if (!fields.category.name) return; const category = { category_name: fields.category.name, resource: resource, }; result = await createCategory(category); break; case "location": if ( !fields.location.name || !fields.location.longitude || !fields.location.latitude ) return; const location = { location_name: fields.location.name, latitude: +fields.location.latitude, longitude: +fields.location.longitude, description: fields.location.description, }; result = await createLocation(location); break; default: break; } if (result.error) return setDirective({ header: `Error creating ${dataLabel}`, message: result.error.data.error, success: false, }); formatted = { _id: result._id, title: result[`${dataLabel}_name`], }; currSelection = [...activeSelection, formatted]; closeModal(); setFields(fieldInputs); setActiveSelection(currSelection); query(); }; return ( <TextPicker handleSelectChange={handleSelectChange} handleRemove={handleRemove} confirmSelection={confirmSelection} handleOnDragEnd={handleOnDragEnd} activeSelection={activeSelection} options={formattedOptions} label={label} dataLabel={dataLabel} modalActive={modalActive} openModal={openModal} closeModal={closeModal} fields={fields} handleFieldChange={handleFieldChange} handleFieldUpload={handleFieldUpload} directive={directive} /> ); } <file_sep>import React from "react"; import ResetFormCtrl from "../../controllers/ResetForm/ResetFormCtrl"; export default function Login() { return ( <div className="page page__login" style={style.container}> <div style={{ paddingBottom: 100 }}> <div style={style.loginHead}> <div style={style.logo}> <img style={style.image} src="/assets/images/iip_logo.png" alt="Indigenous Initiatives and Partnerships Logo" /> </div> </div> <ResetFormCtrl /> </div> </div> ); } const style = { container: { background: "var(--lightsecondary)", height: "100vh", display: "flex", alignItems: "center", justifyContent: "center", }, logo: { maxWidth: 75, }, image: { width: "100%", height: "auto", }, loginHead: { display: "flex", justifyContent: "center", padding: "20px 0", }, }; <file_sep>import React from "react"; import AddWaypointsCtrl from "../../controllers/Add/Waypoints/AddWaypointsCtrl"; export default function AddWaypoint() { return ( <main> <AddWaypointsCtrl /> </main> ); } <file_sep>import React from "react"; import AddUserCtrl from "../../controllers/Add/Users/AddUserCtrl"; export default function AddUser() { return ( <main> <AddUserCtrl /> </main> ); } <file_sep>import React from "react"; import ListWaypointsCtrl from "../../controllers/List/Waypoints/ListWaypointsCtrl"; export default function AllWaypoints() { return ( <main> <ListWaypointsCtrl /> </main> ); } <file_sep>import React from "react"; import ListCategoriesCtrl from "../../controllers/List/Categories/ListCategoriesCtrl"; export default function PlantCategories() { return ( <main> <ListCategoriesCtrl dataLabel={"plant"} label={"Plant"} labelPlural={"Plants"} /> </main> ); } <file_sep>import React from "react"; import ListLocationsCtrl from "../../controllers/List/Locations/ListLocationsCtrl"; export default function Locations() { return ( <main> <ListLocationsCtrl /> </main> ); } <file_sep>import React from "react"; import ProfileCtrl from "../../controllers/Profile/ProfileCtrl"; export default function Profile() { return ( <main> <ProfileCtrl /> </main> ); } <file_sep>import React from "react"; import ListCategoriesCtrl from "../../controllers/List/Categories/ListCategoriesCtrl"; export default function TourCategories() { return ( <main> <ListCategoriesCtrl dataLabel={"tour"} label={"Tour"} labelPlural={"Tours"} /> </main> ); } <file_sep>import React, { useState, useEffect } from "react"; import ListUsers from "../../../components/List/Users"; import { getAllUsers, deleteUser, bulkDeleteUsers } from "../../../network"; import { useAuth } from "../../../context/AuthContext"; export default function ListUsersCtrl() { let isMounted = true; const authContext = useAuth(); const { userData } = authContext; const [userDatas, setUserDatas] = useState([]); const [userDatas_, setUserDatas_] = useState([]); const [roleSelection, setRoleSelection] = useState([]); const [bulkAction, setBulkAction] = useState(""); const [selectedUsers, setSelectedUsers] = useState([]); const [modalState, setModalState] = useState("single"); const [modalActive, setModalActive] = useState(false); const [roleFilter, setCategoryFilter] = useState("default"); const [searchQuery, setSearchQuery] = useState(""); const [hasPages, setHasPages] = useState(false); const [pages, setPages] = useState([]); const [page, setPage] = useState(1); const [pendingDelete, setPendingDelete] = useState({}); const [loading, setLoading] = useState(false); useEffect(() => { // eslint-disable-next-line react-hooks/exhaustive-deps isMounted = true; queryUsers(); return () => { isMounted = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { if (isMounted) { formatRoles(); setUserDatas_(userDatas); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [userDatas]); useEffect(() => { if (!searchQuery) applyFilter(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [searchQuery]); useEffect(() => { setPage(1); formatPages(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [userDatas_]); const formatPages = () => { const dataLength = userDatas_.length; if (dataLength < 5) return setHasPages(false); setHasPages(true); let itemsChunk = 5, userData__ = userDatas_; // split the data into pages const pages = userData__.reduce((resultArray, item, index) => { const chunkIndex = Math.floor(index / itemsChunk); if (!resultArray[chunkIndex]) { resultArray[chunkIndex] = []; // start a new chunk } resultArray[chunkIndex].push(item); return resultArray; }, []); setPages(pages); }; const formatRoles = () => { const rolesUnique = [ ...new Set([...userDatas].map((userData) => userData.role)), ]; let text; const formattedSelection = rolesUnique.map((role) => { if (role === "Admin") text = "Administrator"; if (role === "Manager") text = "Content Manager"; return { key: role, value: role, text: text, }; }); setRoleSelection(formattedSelection); }; const queryUsers = async () => { if (!isMounted) return; setLoading(true); let myUserId; if (userData && userData.user) myUserId = userData.user._id; const result = await getAllUsers(); if (!isMounted) return; setLoading(false); if (result.error) return; if (result.length < 1) setUserDatas([]); const filteredResults = result.filter((user) => user._id !== myUserId); setUserDatas(filteredResults); }; const resetFilters = () => { setSearchQuery(""); setUserDatas_(userDatas); setCategoryFilter("default"); }; const handleFilterChange = (e, data) => { setCategoryFilter(data.value); }; const applyFilter = () => { // APPLY A CATEGORY FILTER const roleF = roleFilter.toLowerCase(); let filteredData = [...userDatas].filter((userData) => { let userRole = userData.role.toLowerCase(); return userRole === roleF; }); if (roleF === "default") filteredData = [...userDatas]; // APPLY A SEARCH FILTER const searchQ = searchQuery.toLowerCase(); if (!searchQ) return setUserDatas_(filteredData); filteredData = filteredData.filter( (userData) => userData.user_name.toLowerCase().startsWith(searchQ) || userData.email.toLowerCase().startsWith(searchQ) ); setUserDatas_(filteredData); }; const clearSearch = () => { setSearchQuery(""); }; const handleQueryChange = (e) => { setSearchQuery(e.target.value); }; const batchSelect = () => { const resourceIds = userDatas.map((userData) => userData._id); const selectedIds = selectedUsers; const allSelected = resourceIds.length === selectedIds.length && resourceIds.every(function (element, index) { return element === selectedIds[index]; }); if (!allSelected) { setSelectedUsers(resourceIds); } else { setSelectedUsers([]); } }; const handleSelected = (e) => { const id = e.target.value; let newSelected = [...selectedUsers]; if (selectedUsers.includes(id)) { newSelected = newSelected.filter((item) => item !== id); } else { newSelected = [...newSelected, id]; } setSelectedUsers(newSelected); }; const nextPage = () => { let currentPage = page; if (currentPage >= pages.length) return; currentPage = currentPage + 1; setPage(currentPage); }; const prevPage = () => { let currentPage = page; if (currentPage === 1) return; currentPage = currentPage - 1; setPage(currentPage); }; const closeModal = () => { setModalActive(false); }; const handleDelete = async (e) => { setModalState("single"); const id = e.target.value; const foundUser = userDatas.filter((userData) => userData._id === id)[0]; if (!foundUser) return; await setPendingDelete(foundUser); setModalActive(true); }; const applyDelete = async () => { if (!isMounted) return; const id = pendingDelete._id; if (!id) return; const result = await deleteUser(id); if (!isMounted) return; if (result.error) return; closeModal(); setPendingDelete({}); queryUsers(); }; const handleBulkActionChange = (_, data) => { const value = data.value; setBulkAction(value); }; const handleBulkDelete = async () => { if (selectedUsers.length < 1) if (bulkAction === "default") return; setModalState("bulk"); setModalActive(true); }; const applyBulkDelete = async () => { if (!isMounted) return; const result = await bulkDeleteUsers(selectedUsers); if (!isMounted) return; if (result.error) return; closeModal(); setSelectedUsers([]); queryUsers(); }; return ( <ListUsers userDatas={userDatas_} roleSelection={roleSelection} handleBulkActionChange={handleBulkActionChange} bulkAction={bulkAction} handleBulkDelete={handleBulkDelete} roleFilter={roleFilter} resetFilters={resetFilters} searchQuery={searchQuery} handleFilterChange={handleFilterChange} applyFilters={applyFilter} clearSearch={clearSearch} handleQueryChange={handleQueryChange} batchSelect={batchSelect} handleSelected={handleSelected} selectedUsers={selectedUsers} page={page} hasPages={hasPages} pages={pages} nextPage={nextPage} prevPage={prevPage} closeModal={closeModal} handleDelete={handleDelete} pendingDelete={pendingDelete} applyDelete={applyDelete} modalActive={modalActive} modalState={modalState} applyBulkDelete={applyBulkDelete} loading={loading} /> ); } <file_sep>import React from "react"; import ListCategoriesCtrl from "../../controllers/List/Categories/ListCategoriesCtrl"; export default function WaypointCategories() { return ( <main> <ListCategoriesCtrl dataLabel={"waypoint"} label={"Waypoint"} labelPlural={"Waypoints"} /> </main> ); } <file_sep>import React from "react"; import ListUsersCtrl from "../../controllers/List/Users/ListUsersCtrl"; export default function AllUsers() { return ( <main> <ListUsersCtrl /> </main> ); } <file_sep>import React from "react"; import ListToursCtrl from "../../controllers/List/Tours/ListToursCtrl"; export default function AllTours() { return ( <main> <ListToursCtrl/> </main> ); } <file_sep>import React from "react"; /* @desc UI component that renders a table of media. @controller ../Media/index.js */ export default function Table({ medias, selectedMedias, dataLabel, handleSelected, handleDelete, handleEdit, }) { return ( <ul className="table__list"> {medias && medias.length > 0 && medias.map((media, index) => { return ( <li className={ selectedMedias.includes(media._id) ? "table__row selected" : "table__row" } key={index} > <div className="table__col select"> <input type="checkbox" value={media._id} checked={selectedMedias.includes(media._id) ? true : false} onChange={(e) => handleSelected(e)} /> </div> <div className="table__col title"> <p>{media.caption}</p> <span className="action"> <button type="button" value={media._id} onClick={(e) => handleEdit(e)} > Edit&nbsp; </button> <button type="button" value={media._id} onClick={(e) => handleDelete(e)} > &nbsp;Delete </button> </span> </div> <div className="table__col url"> <p>{media[`${dataLabel}_url`]}</p> </div> {dataLabel === "image" && ( <div className="table__col thumbnail"> <div> <img src={media[`${dataLabel}_url`]} alt="thumbnail" /> </div> </div> )} {dataLabel === "audio_file" && ( <div className="table__col head audio__preview"> <audio controls src={media[`${dataLabel}_url`]}> Your browser does not support the <code>audio</code>{" "} element. </audio> </div> )} </li> ); })} </ul> ); } <file_sep>import React from "react"; import { parseDate } from "../../../../utility"; import { Link } from "react-router-dom"; export default function Table({ toursData, selectedTour, handleSelected, handleDelete, }) { return( <ul className="table__list"> { toursData && toursData.length > 0 && toursData.map((tour, index) => { const lastRevision = { date: parseDate(tour.revision_history[0]?.date), user: tour.revision_history[0].user[0]?.user_name, }; return( <li className={ selectedTour.includes(tour._id) ? "table__row selected" : "table__row" } key={index} > <div className="table__col select"> <input type="checkbox" value={tour._id} checked={selectedTour.includes(tour._id) ? true : false} onChange={ e => handleSelected(e)} /> </div> <div className="table__col title"> <p>{tour.tour_name}</p> <span className="action"> <Link type="button" value={tour._id} to={`/tours/edit/${tour._id}`} > Edit&nbsp; </Link> <button type="button" value={tour._id} onClick={(e) => handleDelete(e)} > &nbsp;Delete </button> </span> </div> <div className="table__col author"> <p>{tour.isPublish === true ? "Visible" : "Hidden"}</p> </div> <div className="table__col categories"> <p> {tour.categories .map((category) => category.category_name) .join(', ') } </p> </div> <div className="table__col tags"> {tour.tags.map((tag) => tag.tag_name).join(", ")} </div> <div className="table__col updated"> <p> { tour && tour.revision_history.length > 0 && ( <> {typeof lastRevision.date === "string" && typeof lastRevision.user === "string" ? `${lastRevision.date} by ${lastRevision.user}` : "Sorry, could not fetch revision history."} </> ) } </p> </div> </li> ); })} </ul> ); }<file_sep>import React from "react"; import Header from "../../components/Header"; import { useAuth } from "../../context/AuthContext"; import { useHistory } from "react-router-dom"; export default function HeaderCtrl() { const authContext = useAuth(); const { setUserData, userData } = authContext; const history = useHistory(); // PROFILE const navigateToProfile = () => { history.push("/profile"); }; const handleSignout = () => { setUserData(null); }; return ( <Header handleSignout={handleSignout} navigateToProfile={navigateToProfile} userData={userData} /> ); } <file_sep>import React from "react"; import Table from "./Table"; import DashHeader from "../../DashHeader"; import { Dropdown, Input, Icon, TextArea } from "semantic-ui-react"; import Modal from "../../Modal"; import { Loader } from "semantic-ui-react"; import Message from "../../Message"; /* @desc UI component that Lists locations and allows the list to be managed. @controller ~/src/controllers/List/Locations/ListLocationsCtrl.js */ export default function ListLocations({ // Data to List: Locations locations, // SEARCH -- Attributes searchQuery, // SEARCH -- Methods handleQueryChange, applySearch, clearSearch, // PAGINATION -- Attributes hasPages, pages, page, // PAGINATION -- Methods nextPage, prevPage, // BATCH SELECT -- Attributes selectedLocations, // BATCH SELECT -- Methods handleSelected, batchSelect, // NEW LOCATION -- Methods submitNewLocation, handleNewLocation, // NEW LOCATION --Attributes newLocation, // MODAL -- Methods closeModal, // MODAL -- Attributes modalActive, modalState, // DELETE -- Methods handleDelete, applyDelete, // DELETE -- Attributes pendingDelete, // EDIT -- Methods applyEdit, handleEdit, handleChangeLocation, // EDIT -- Attributes editLocation, pendingEdit, // BULK DELETE -- Methods handleBulkActionChange, handleBulkDelete, applyBulkDelete, // LOADING -- Attributes loading, directive, }) { const renderModal = () => { switch (modalState) { case "edit": return editModal(); case "delete": return deleteModal(); case "bulk": return bulkDeleteModal(); default: return <></>; } }; const editModal = () => ( <> <fieldset style={style.fieldset}> <p style={style.label}> Location Name <span style={style.req}>*</span> </p> <Input onChange={(e) => handleChangeLocation(e)} style={style.input} value={editLocation.name} name="name" placeholder="Enter location name" /> </fieldset> <fieldset style={style.fieldset}> <p style={style.label}> Latitude <span style={style.req}>*</span> </p> <Input onChange={(e) => handleChangeLocation(e)} value={editLocation.latitude} name="latitude" type="number" style={style.input} placeholder="Enter latitude (number)" /> </fieldset> <fieldset style={style.fieldset}> <p style={style.label}> Longitude <span style={style.req}>*</span> </p> <Input onChange={(e) => handleChangeLocation(e)} value={editLocation.longitude} name="longitude" type="number" style={style.input} placeholder="Enter longitude (number)" /> </fieldset> <fieldset style={style.fieldset}> <p style={style.label}>Description</p> <TextArea onChange={(e) => handleChangeLocation(e)} value={editLocation.description} name="description" style={{ ...style.input, ...style.textarea, }} /> </fieldset> <button onClick={() => applyEdit()} className="field__button"> Update location </button> <button onClick={() => closeModal()} style={{ color: "var(--highlight)" }} > Cancel </button> </> ); const deleteModal = () => ( <> <p> Deleting this tag will remove all instances of the location&nbsp; <strong style={{ color: "var(--danger)" }}> {pendingDelete.location_name} </strong> . Do you wish to proceed? </p> <button onClick={() => applyDelete()} className="field__button"> Yes, I know what I am doing. </button> <button onClick={() => closeModal()} className="field__button secondary"> No, cancel my request. </button> </> ); const bulkDeleteModal = () => ( <> <p> Deleting&nbsp; <strong style={{ color: "var(--danger)" }}> {selectedLocations.length} </strong> &nbsp;locations will remove{" "} <strong style={{ color: "var(--danger)", fontWeight: "700", textTransform: "uppercase", }} > all </strong>{" "} instances of the deleted locations. Do you wish to proceed? </p> <button onClick={() => applyBulkDelete()} className="field__button"> Yes, I know what I am doing. </button> <button onClick={() => closeModal()} className="field__button secondary"> No, cancel my request. </button> </> ); return ( <div> {typeof directive === "object" && directive !== null && Object.keys(directive).length > 0 && ( <Message success={directive.success} header={directive.header} message={directive.message} /> )} <DashHeader title="Locations" /> <div className="resource__container"> <div className="resource__col left"> <h3>Add New location</h3> <fieldset style={style.fieldset}> <p style={style.label}> Location Name <span style={style.req}>*</span> </p> <Input onChange={(e) => handleNewLocation(e)} style={style.input} value={newLocation.name} name="name" placeholder="Enter location name" /> </fieldset> <fieldset style={style.fieldset}> <p style={style.label}> Latitude <span style={style.req}>*</span> </p> <Input onChange={(e) => handleNewLocation(e)} value={newLocation.latitude} name="latitude" type="number" style={style.input} placeholder="Enter latitude (number)" /> </fieldset> <fieldset style={style.fieldset}> <p style={style.label}> Longitude <span style={style.req}>*</span> </p> <Input onChange={(e) => handleNewLocation(e)} value={newLocation.longitude} name="longitude" type="number" style={style.input} placeholder="Enter longitude (number)" /> </fieldset> <fieldset style={style.fieldset}> <p style={style.label}>Description</p> <TextArea onChange={(e) => handleNewLocation(e)} value={newLocation.description} name="description" style={{ ...style.input, ...style.textarea, }} /> </fieldset> <button onClick={() => submitNewLocation()} className="field__button"> Create new location </button> </div> <div className="resource__col right"> <div style={{ marginBottom: 10, display: "flex" }}> <p> <strong>Results</strong> ({locations.length}){" "} </p> {loading && <Loader active inline size="tiny" />} </div> <div className="table__controls"> <div style={{ display: "flex" }}> <div className="table__action"> <Dropdown placeholder={"Bulk Actions"} onChange={(e, data) => handleBulkActionChange(e, data)} selection options={[ { key: "default", value: "default", text: "Bulk Actions" }, { key: "delete", value: "delete", text: "Delete" }, ]} /> <button onClick={() => handleBulkDelete()}>Apply</button> </div> </div> <div> <div className="table__action" style={{ marginRight: 0 }}> {searchQuery && ( <button onClick={() => clearSearch()} className="sub__action"> Clear search </button> )} <Input onChange={(e) => handleQueryChange(e)} value={searchQuery} style={{ ...style.input, minWidth: 250 }} placeholder={`Enter search query`} /> <button onClick={() => applySearch()}>Search</button> </div> </div> </div> <div className="table__heading table__row"> <div className="table__col head select"> <input type="checkbox" value={"select all"} onChange={(e) => batchSelect(e)} /> </div> <div className="table__col head title"> <h3>name</h3> </div> <div className="table__col head author"> <h3>latitude</h3> </div> <div className="table__col head categories"> <h3>longitude</h3> </div> </div> <Table locations={hasPages ? pages[page - 1] : locations} selectedLocations={selectedLocations} handleSelected={handleSelected} handleDelete={handleDelete} handleEdit={handleEdit} /> {hasPages && ( <div className="pagination__control"> <div> <p style={{ marginBottom: "7px" }}> Page {page} of {pages.length} </p> <div className="control"> <button onClick={() => prevPage()}> <Icon name="caret left" /> </button> <span>{page}</span> <button onClick={() => nextPage()}> <Icon name="caret right" /> </button> </div> </div> </div> )} <Modal isActive={modalActive} title={ modalState === "delete" ? `Delete ${pendingDelete.location_name}?` : modalState === "edit" ? `Edit ${pendingEdit?.location_name}` : `Delete all ${selectedLocations.length} tags?` } closeModal={closeModal} > {renderModal()} </Modal> </div> </div> </div> ); } const style = { input: { width: "100%", color: "var(--darksecondary)", }, textarea: { height: 200, border: "1px solid lightgrey", color: "var(--darkprimary)", padding: "7px 14px", background: "var(--lighttertiary)", }, label: { color: "var(--darksecondary)", margin: 0, fontSize: 11, marginBottom: "3px", }, fieldset: { marginBottom: "10px", padding: 0, }, req: { color: "red", fontSize: 14, }, }; <file_sep>import React from "react"; import { Input, Checkbox, Button } from "semantic-ui-react"; import Message from "../Message"; import { Loader } from "semantic-ui-react"; /* @desc UI component that displays a Login form. @controller ~/src/controllers/LoginForm/LoginFormCtrl.js */ export default function LoginForm({ //PROPERTIES username, password, rememberMe, directive, loading, // METHODS setPassword, setUsername, setRememberMe, attemptLogin, navigateToRecovery, }) { return ( <div> {typeof directive === "object" && directive !== null && Object.keys(directive).length > 0 && ( <Message success={directive.success} header={directive.header} message={directive.message} /> )} <form style={style.form} onSubmit={(e) => attemptLogin(e)}> <fieldset style={style.fieldset}> <p style={style.label}> Username or Email<span style={style.req}>*</span> </p> <Input style={style.input} onChange={(e) => setUsername(e.target.value)} value={username} icon="user" iconPosition="left" placeholder="Username or email" /> </fieldset> <fieldset style={style.fieldset}> <p style={style.label}> Password <span style={style.req}>*</span> </p> <Input style={style.input} onChange={(e) => setPassword(e.target.value)} value={password} type="password" icon="key" iconPosition="left" placeholder="<PASSWORD>" /> </fieldset> <fieldset style={style.fieldset}> <Checkbox checked={rememberMe} onChange={(_, data) => { setRememberMe(data.checked); }} toggle label={{ children: "Remember me" }} style={style.input} /> </fieldset> <fieldset className="submit__fieldset" style={style.fieldset}> <Button primary style={{ ...style.submit, position: "relative" }}> Log in {loading && <Loader active inline inverted size="small" />} </Button> </fieldset> </form> <div style={style.formFooter}> <button onClick={() => navigateToRecovery()} style={{ color: "grey" }}> ← Lost your password? </button> </div> </div> ); } const style = { form: { background: "var(--lightprimary)", border: "1px solid lightgrey", minWidth: "350px", margin: "auto", padding: 20, boxShadow: "var(--shadow)", }, formFooter: { padding: "20px 0", }, input: { width: "100%", color: "var(--darksecondary)", }, label: { color: "var(--darksecondary)", margin: 0, fontSize: 11, marginBottom: "3px", }, fieldset: { marginBottom: "3px", }, submit: { width: "100%", background: "var(--highlight)", borderRadius: "unset", }, req: { color: "red", fontSize: 14, }, }; <file_sep>import React from "react"; /* @desc UI component that renders a table of locations. @controller ../Locations/index.js */ export default function Table({ locations, handleSelected, selectedLocations, handleDelete, handleEdit, }) { return ( <ul className="table__list"> {locations && locations.length > 0 && locations.map((location, index) => { return ( <li className={ selectedLocations.includes(location._id) ? "table__row selected" : "table__row" } key={index} > <div className="table__col select"> <input type="checkbox" value={location._id} checked={ selectedLocations.includes(location._id) ? true : false } onChange={(e) => handleSelected(e)} /> </div> <div className="table__col title"> <p>{location.location_name}</p> <span className="action"> <button type="button" value={location._id} onClick={(e) => handleEdit(e)} > Edit&nbsp; </button> <button type="button" value={location._id} onClick={(e) => handleDelete(e)} > &nbsp;Delete </button> </span> </div> <div className="table__col author"> <p>{location.latitude}</p> </div> <div className="table__col author"> <p>{location.longitude}</p> </div> </li> ); })} </ul> ); } <file_sep>import React from "react"; import { ExitIcon } from "../../icons"; /* @desc UI component that displays a modal. @controller null */ export default function Modal({ children, title, subtitle, isActive, closeModal, }) { return ( <> {isActive && ( <div className="modal__container"> <div className="modal__body"> <div className="modal__head"> <button onClick={() => closeModal()}> <span>Cancel</span> <ExitIcon /> </button> </div> <div className="modal__title"> <h3>{title}</h3> <h4>{subtitle || " "}</h4> </div> {children} </div> </div> )} </> ); } <file_sep>import React from "react"; import { parseDate } from "../../../../utility"; import { Link } from "react-router-dom"; export default function Table({ learnMoreData, selectedLearnMore, handleSelected, handleDelete, }) { return( <ul className="table__list"> { learnMoreData && learnMoreData.length > 0 && learnMoreData.map((learnMore, index) => { const lastRevision = { date: parseDate(learnMore.revision_history[0]?.date), user: learnMore.revision_history[0].user[0]?.user_name, }; return( <li className={ selectedLearnMore.includes(learnMore._id) ? "table__row selected" : "table__row" } key={index} > <div className="table__col select"> <input type="checkbox" value={learnMore._id} checked={selectedLearnMore.includes(learnMore._id) ? true : false} onChange={ e => handleSelected(e)} /> </div> <div className="table__col title"> <p>{learnMore.learn_more_title}</p> <span className="action"> <Link type="button" value={learnMore._id} to={`/learnmore/edit/${learnMore._id}`} > Edit&nbsp; </Link> <button type="button" value={learnMore._id} onClick={(e) => handleDelete(e)} > &nbsp;Delete </button> </span> </div> <div className="table__col author"> <p>{learnMore.isPublish === true ? "Visible" : "Hidden"}</p> </div> <div className="table__col categories"> <p> {learnMore.categories .map((category) => category.category_name) .join(', ') } </p> </div> <div className="table__col tags"> {learnMore.tags.map((tag) => tag.tag_name).join(", ")} </div> <div className="table__col updated"> <p> { learnMore && learnMore.revision_history.length > 0 && ( <> {typeof lastRevision.date === "string" && typeof lastRevision.user === "string" ? `${lastRevision.date} by ${lastRevision.user}` : "Sorry, could not fetch revision history."} </> ) } </p> </div> </li> ); })} </ul> ); }<file_sep>import React from "react"; import { TrashIcon, ImageIcon, AudioIcon, VideoIcon } from "../../../icons"; import { Dropdown, Input } from "semantic-ui-react"; import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd"; import Modal from "../../Modal"; import Message from "../../Message"; /* @desc UI component for A media picker form control. Allows the user to select existing media, or upload their own to a given content type. @controller ~/src/controllers/Forms/MediaPicker/MediaPickerCtrl.js */ export default function MediaPicker({ options, activeSelection, handleSelectChange, handleRemove, confirmSelection, handleOnDragEnd, label, openModal, closeModal, modalActive, file, setFile, caption, setCaption, handleUpload, dataLabel, setVideoLink, videoLink, directive, }) { const renderModal = () => { switch (dataLabel) { case "video": return ( <> <form onSubmit={(e) => { e.preventDefault(); }} > <fieldset style={style.fieldset}> <p style={style.label}> Caption <span style={style.req}>*</span> </p> <Input value={caption} onChange={(e) => setCaption(e.target.value)} style={style.input} placeholder="Enter caption" /> </fieldset> <fieldset style={style.fieldset}> <p style={style.label}> Youtube URL <span style={style.req}>*</span> </p> <Input value={videoLink} onChange={(e) => setVideoLink(e.target.value)} style={style.input} placeholder="Enter Youtube URL" /> <p style={{ fontSize: 12, marginTop: 7 }}> Valid Example: https://www.youtube.com/watch?v=lhqNduGgpC8 </p> </fieldset> <button className="field__button" onClick={() => handleUpload()}> Upload {label[0].toUpperCase()} {label.substring(1)} </button> <button className="modal__cancel" onClick={() => closeModal()}> Cancel </button> </form> </> ); default: return ( <> <form onSubmit={(e) => { e.preventDefault(); }} > <fieldset style={style.fieldset}> <p style={style.label}> Caption <span style={style.req}>*</span> </p> <Input value={caption} onChange={(e) => setCaption(e.target.value)} style={style.input} placeholder="Enter caption" /> </fieldset> <p style={style.label}> Upload file: <span style={style.req}>*</span> </p> <fieldset style={style.fieldset}> <div className="field__file"> <div className="file__meta"> <p>{file?.name}</p> </div> <input filename={file} onChange={(e) => { setFile(e.target.files[0]); }} style={{ display: "none" }} id="file--upload" type="file" accept={ dataLabel === "image" ? "image/*" : dataLabel === "audio_file" ? "audio/*" : "video/*" } /> <button className="field__button"> <label htmlFor="file--upload">Choose File</label> </button> </div> <button className="field__button" onClick={() => handleUpload()} > Upload {label[0].toUpperCase()} {label.substring(1)} </button> <button className="modal__cancel" onClick={() => closeModal()}> Cancel </button> </fieldset> </form> </> ); } }; return ( <div className="textpicker"> {typeof directive === "object" && directive !== null && Object.keys(directive).length > 0 && ( <Message success={directive.success} header={directive.header} message={directive.message} /> )} <label> {label === "category" ? "Categories:" : `${label[0].toUpperCase()}${label.substring(1)}(s):`} </label> {activeSelection && activeSelection.length > 0 && ( <div className="textpicker__scroll"> <DragDropContext onDragEnd={(result) => handleOnDragEnd(result)}> <Droppable droppableId="textpicker"> {(provided) => ( <ul {...provided.droppableProps} ref={provided.innerRef}> {activeSelection.map((item, index) => ( <Draggable key={item._id} draggableId={item._id} index={index} > {(provided) => ( <li {...provided.draggableProps} ref={provided.innerRef} {...provided.dragHandleProps} className="textpicker__selected" > <span className="selected__title"> <span className="selected__icon"> {renderIcon(label)} </span> <div className="selected__media__meta"> <label className="caption"> <strong>Caption: </strong> {item.title} </label> <label className="url"> <strong>URL: </strong> {item.url} </label> </div> </span> <button onClick={() => handleRemove(item._id)}> <TrashIcon /> </button> </li> )} </Draggable> ))} {provided.placeholder} </ul> )} </Droppable> </DragDropContext> </div> )} <div className="textpicker__picker"> <Dropdown onChange={(e, data) => handleSelectChange(e, data)} placeholder={`Select an existing ${label[0].toUpperCase()}${label.substring( 1 )}`} search selection options={options} /> <button onClick={() => confirmSelection()}> Add Existing {`${label[0].toUpperCase()}${label.substring(1)}`} </button> </div> <div className="textpicker__footer"> <button onClick={() => openModal()}> + Upload A New {`${label[0].toUpperCase()}${label.substring(1)}`} </button> </div> <Modal title={`Upload a new ${label[0].toUpperCase()}${label.substring(1)}`} isActive={modalActive} closeModal={closeModal} > {renderModal()} </Modal> </div> ); } const renderIcon = (label) => { switch (label) { case "image": return <ImageIcon />; case "video": return <VideoIcon />; case "Audio File": return <AudioIcon />; default: return <ImageIcon />; } }; const style = { form: { background: "var(--lightprimary)", border: "1px solid lightgrey", minWidth: "350px", margin: "auto", padding: 20, boxShadow: "var(--shadow)", }, formFooter: { padding: "20px 0", }, input: { width: "100%", color: "var(--darksecondary)", }, textarea: { height: 200, border: "1px solid lightgrey", color: "var(--darkprimary)", padding: "7px 14px", background: "var(--lighttertiary)", }, label: { color: "var(--darksecondary)", margin: 0, fontSize: 11, marginBottom: "3px", }, fieldset: { marginBottom: "10px", padding: 0, }, submit: { width: "100%", background: "var(--highlight)", borderRadius: "unset", }, req: { color: "red", fontSize: 14, }, }; <file_sep>import React from "react"; import ListMediaCtrl from "../../controllers/List/Media/ListMediaCtrl"; export default function Videos() { return ( <main> <ListMediaCtrl dataLabel="video" label="Video" /> </main> ); } <file_sep>import React, { useState, useEffect } from "react"; import ListWaypoints from "../../../components/List/Waypoints"; import { getAllWaypoints, getCategoryGroup, deleteWaypoint, bulkDeleteWaypoints, } from "../../../network"; export default function ListWaypointsCtrl() { let isMounted = true; const [waypointData, setWaypointData] = useState([]); // waypointData_ is the mutable version of waypointData that we'll be using to filter const [waypointData_, setWaypointData_] = useState([]); const [bulkAction, setBulkAction] = useState(""); const [modalState, setModalState] = useState("single"); const [modalActive, setModalActive] = useState(false); const [pendingDelete, setPendingDelete] = useState({}); const [selectedWaypoints, setSelectedWaypoints] = useState([]); const [categoryFilter, setCategoryFilter] = useState("default"); const [searchQuery, setSearchQuery] = useState(""); const [formattedCategories, setFormattedCategories] = useState([]); const [eCategories, setECategories] = useState([]); const [hasPages, setHasPages] = useState(false); const [pages, setPages] = useState([]); const [page, setPage] = useState(1); const [loading, setLoading] = useState(false); useEffect(() => { // eslint-disable-next-line react-hooks/exhaustive-deps isMounted = true; queryWaypoints(); queryCategories(); formatPages(); return () => { isMounted = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { formatCategories(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [eCategories]); useEffect(() => { if (isMounted) setWaypointData_(waypointData); // eslint-disable-next-line react-hooks/exhaustive-deps }, [waypointData]); useEffect(() => { if (!searchQuery) applyFilter(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [searchQuery]); useEffect(() => { setPage(1); formatPages(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [waypointData_]); const formatPages = () => { const dataLength = waypointData_.length; if (dataLength < 5) return setHasPages(false); setHasPages(true); let itemsChunk = 5, waypointData = waypointData_; // split the data into pages const pages = waypointData.reduce((resultArray, item, index) => { const chunkIndex = Math.floor(index / itemsChunk); if (!resultArray[chunkIndex]) { resultArray[chunkIndex] = []; // start a new chunk } resultArray[chunkIndex].push(item); return resultArray; }, []); setPages(pages); }; const queryWaypoints = async () => { if (!isMounted) return; setLoading(true); const result = await getAllWaypoints(); if (!isMounted) return; setLoading(false); if (result.error) return; if (result.length < 1) setWaypointData([]); setWaypointData(result); }; const queryCategories = async () => { if (!isMounted) return; const result = await getCategoryGroup("waypoint"); if (!isMounted) return; if (result.error) return; setECategories(result); }; const formatCategories = () => { const formatted = eCategories.map((category) => { return { ...category, key: category._id, value: category.category_name, text: category.category_name, }; }); setFormattedCategories(formatted); }; const handleBulkActionChange = (_, data) => { const value = data.value; setBulkAction(value); }; const handleBulkDelete = async () => { if (selectedWaypoints.length < 1) return; if (bulkAction === "default") return; setModalState("bulk"); setModalActive(true); }; const resetFilters = () => { setSearchQuery(""); setWaypointData_(waypointData); setCategoryFilter("default"); }; const handleFilterChange = (e, data) => { setCategoryFilter(data.value); }; const clearSearch = () => { setSearchQuery(""); }; const applyFilter = () => { // APPLY A CATEGORY FILTER const categoryF = categoryFilter.toLowerCase(); let filteredData = [...waypointData].filter((waypoint) => { let waypointCategories = waypoint.categories.map((category) => category.category_name.toLowerCase() ); return waypointCategories.includes(categoryF); }); if (categoryF === "default") filteredData = [...waypointData]; // APPLY A SEARCH FILTER const searchQ = searchQuery.toLowerCase(); if (!searchQ) return setWaypointData_(filteredData); filteredData = filteredData.filter((waypoint) => waypoint.waypoint_name.toLowerCase().startsWith(searchQ) ); setWaypointData_(filteredData); }; const handleQueryChange = (e) => { setSearchQuery(e.target.value); }; const nextPage = () => { let currentPage = page; if (currentPage >= pages.length) return; currentPage = currentPage + 1; setPage(currentPage); }; const prevPage = () => { let currentPage = page; if (currentPage === 1) return; currentPage = currentPage - 1; setPage(currentPage); }; const batchSelect = () => { const resourceIds = waypointData.map((waypoint) => waypoint._id); const selectedIds = selectedWaypoints; const allSelected = resourceIds.length === selectedIds.length && resourceIds.every(function (element, index) { return element === selectedIds[index]; }); if (!allSelected) { setSelectedWaypoints(resourceIds); } else { setSelectedWaypoints([]); } }; const handleSelected = (e) => { const id = e.target.value; let newSelected = [...selectedWaypoints]; if (selectedWaypoints.includes(id)) { newSelected = newSelected.filter((item) => item !== id); } else { newSelected = [...newSelected, id]; } setSelectedWaypoints(newSelected); }; const handleDelete = async (e) => { if (!isMounted) return; setModalState("single"); const id = e.target.value; const foundWaypoint = waypointData.filter( (waypoint) => waypoint._id === id )[0]; if (!foundWaypoint) return; await setPendingDelete(foundWaypoint); setModalActive(true); }; const closeModal = () => { setModalActive(false); }; const applyDelete = async () => { if (!isMounted) return; const id = pendingDelete._id; if (!id) return; const result = await deleteWaypoint(id); if (result.error) return; if (!isMounted) return; closeModal(); setPendingDelete({}); queryWaypoints(); }; const applyBulkDelete = async () => { if (!isMounted) return; const result = await bulkDeleteWaypoints(selectedWaypoints); if (result.error) return; closeModal(); setSelectedWaypoints([]); queryWaypoints(); }; return ( <ListWaypoints categories={formattedCategories} handleBulkActionChange={handleBulkActionChange} waypointData={waypointData_} bulkAction={bulkAction} handleBulkDelete={handleBulkDelete} categoryFilter={categoryFilter} resetFilters={resetFilters} handleFilterChange={handleFilterChange} applyFilters={applyFilter} searchQuery={searchQuery} clearSearch={clearSearch} handleQueryChange={handleQueryChange} hasPages={hasPages} page={page} pages={pages} nextPage={nextPage} prevPage={prevPage} batchSelect={batchSelect} selectedWaypoints={selectedWaypoints} handleSelected={handleSelected} handleDelete={handleDelete} modalState={modalState} closeModal={closeModal} modalActive={modalActive} applyDelete={applyDelete} pendingDelete={pendingDelete} loading={loading} applyBulkDelete={applyBulkDelete} /> ); } <file_sep>import React, { useEffect, useState } from "react"; import Sidebar from "../../components/Sidebar"; import { useAuth } from "../../context/AuthContext"; import { useLocation } from "react-router-dom"; import { sidebarLinks } from "./SidebarLinks"; export default function SidebarCtrl() { const authContext = useAuth(); const { userData } = authContext; const location = useLocation(); const { pathname } = location; const [sidebarModel, setSidebarModel] = useState({ dashboard: true, plants: false, waypoints: false, learnmore: false, users: false, locations: false, media: false, tags: false, profile: false, }); const evaluatePath = () => { let currentPath = pathname.split("/").filter((string) => string)[0]; if (!currentPath || currentPath === undefined) currentPath = "dashboard"; const newSidebarModel = { dashboard: false, plants: false, waypoints: false, learnmore: false, users: false, locations: false, media: false, tags: false, profile: false, }; newSidebarModel[currentPath] = true; setSidebarModel(newSidebarModel); }; useEffect(() => { evaluatePath(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [location]); return ( <Sidebar userData={userData} sidebarModel={sidebarModel} sidebarLinks={sidebarLinks} path={pathname} /> ); } <file_sep>import React, { useState, useEffect } from "react"; import EditUser from "../../../components/Edit/User"; import { useParams } from "react-router-dom"; import { getUser, updateUser } from "../../../network"; import { useHistory } from "react-router-dom"; export default function EditUserCtrl() { let isMounted = true; const history = useHistory(); const { userId } = useParams(); // =============================================================== // FORM DATA // =============================================================== const [changePassword, setChangePassword] = useState(false); const [username, setUsername] = useState(""); const [email, setEmail] = useState(""); const [role, setRole] = useState(""); const [newPassword, setNewPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); // Error Messaging const [directive, setDirective] = useState(null); // Preloader const [loading, setLoading] = useState(false); useEffect(() => { if (isMounted) resetDirective(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [directive]); const resetDirective = async () => { await setTimeout(() => { if (!isMounted) return; setDirective(null); }, 4000); }; /* @desc invoke queryUser on mount @author <NAME> */ useEffect(() => { // eslint-disable-next-line react-hooks/exhaustive-deps isMounted = true; queryUser(); return () => { isMounted = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); /* @desc queries the user's data and delegates to state variables @author <NAME> */ const queryUser = async () => { if (!isMounted) return; if (!userId) return setDirective({ header: "Error", message: "Cannot fetch this user", success: false, }); setLoading(true); const result = await getUser(userId); if (!isMounted) return; setLoading(false); if (result.error) return setDirective({ header: "Error", message: "Cannot fetch this user", success: false, }); // delegate setEmail(result.email); setRole(result.role); setUsername(result.user_name); }; /* @desc toggles changePassword to true @author <NAME> */ const toggleChangePassword = () => { if (!isMounted) return; setChangePassword(true); }; /* @desc toggles changePassword to false and resets form controls related to passwords. @author <NAME> */ const cancelChangePassword = () => { if (!isMounted) return; setChangePassword(false); setNewPassword(""); setConfirmPassword(""); }; // =============================================================== // POST // @desc applies the updates to the given user. // =============================================================== const applyUpdate = async () => { if (!isMounted) return; const id = userId; if (!id) return setDirective({ header: "Error", message: "Cannot fetch this user", success: false, }); if (!email || !username || !role) return setDirective({ header: "Error could not update user", message: "Required fields are missing", success: false, }); let userData_ = { email: email, user_name: username, role: role, }; if (!isMounted) return; if (changePassword) { if (!newPassword || !confirmPassword) return setDirective({ header: "Could not update user", message: "Password fields are empty.", success: false, }); if (newPassword !== confirmPassword) return setDirective({ header: "Could not update user", message: "Password fields don't match.", success: false, }); userData_ = { ...userData_, password: <PASSWORD>, }; } setLoading(true); const result = await updateUser(userData_, id); if (!isMounted) return; setLoading(false); if (result.error) return setDirective({ header: "Error updating user", message: result.error.data.error, success: false, }); history.push("/users"); }; return ( <EditUser // METHODS toggleChangePassword={toggleChangePassword} cancelChangePassword={cancelChangePassword} changeUsername={setUsername} changeEmail={setEmail} changeRole={setRole} changeNewPassword={<PASSWORD>} changeConfirmPassword={<PASSWORD>} applyUpdate={applyUpdate} // ATTRIBUTES changePassword={<PASSWORD>} username={username} email={email} role={role} newPassword={<PASSWORD>} confirmPassword={<PASSWORD>} loading={loading} directive={directive} /> ); } <file_sep>import React from "react"; import AddPlantsCtrl from "../../controllers/Add/Plants/AddPlantsCtrl"; export default function AddPlant() { return ( <main> <AddPlantsCtrl /> </main> ); } <file_sep>import React, { useState, useEffect } from "react"; import AddUser from "../../../components/Add/Users"; import { createUser } from "../../../network"; import { useHistory } from "react-router-dom"; export default function AddUserCtrl() { let isMounted = true; const history = useHistory(); // =============================================================== // FORM DATA // =============================================================== const [username, setUsername] = useState(""); const [email, setEmail] = useState(""); const [role, setRole] = useState("Manager"); const [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); // Error Messaging const [directive, setDirective] = useState(null); // Preloader const [loading, setLoading] = useState(false); useEffect(() => { // eslint-disable-next-line react-hooks/exhaustive-deps isMounted = true; return () => { isMounted = false; }; }, []); useEffect(() => { if (isMounted) resetDirective(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [directive]); const resetDirective = async () => { await setTimeout(() => { setDirective(null); }, 4000); }; // =============================================================== // POST // =============================================================== const registerUser = async () => { if (!isMounted) return; if (!username || !email || !role || !password) return setDirective({ header: "Error creating user", message: "Required fields are missing", success: false, }); if (password !== <PASSWORD>Password) return setDirective({ header: "Error creating user", message: "Passwords do not match", success: false, }); const user = { email: email, user_name: username, password: <PASSWORD>, role: role, }; setLoading(true); const result = await createUser(user); if (!isMounted) return; setLoading(false); if (result.error) return setDirective({ header: "Error registering a user", message: result.error.data.error, success: false, }); history.push("/users"); }; return ( <AddUser // Attributes username={username} email={email} role={role} password={<PASSWORD>} confirmPassword={<PASSWORD>} directive={directive} loading={loading} // Methods changeUsername={setUsername} changeEmail={setEmail} changeRole={setRole} changePassword={set<PASSWORD>} changeConfirmPassword={setConfirm<PASSWORD>} registerUser={registerUser} /> ); } <file_sep>import React, { useState, useEffect } from "react"; import TextArea from "../../../components/Forms/TextArea"; export default function TextAreaCtrl({ label, setter, eValue }) { const [value, setValue] = useState(""); useEffect(() => { setter(value); // eslint-disable-next-line react-hooks/exhaustive-deps }, [value]); useEffect(() => { setValue(eValue); // eslint-disable-next-line react-hooks/exhaustive-deps }, [eValue]); return <TextArea label={label} setValue={setValue} value={value} />; } <file_sep># Getting Started with Create React App **Table Of Contents** 1. [Core Application Features](#core-application-features) 2. [Application Features](#application-features) 3. [Road-mapped Features](#road-mapped-features) 4. [Technology Stack](#technology-stack) 5. [Wireframes](#wireframes) 6. [Installation Documents](#installation) ### Content Management System (Client) This specific repository houses the client-side user interface of the mobile application's content management system (cms). #### Core Application Features * User authentication * Users can create, read, update, delete resources: * Plants * Waypoints * Locations * Media (Images, Video, Audio) * Categories + Tags * CMS Exposes a Restful API for the Mobile application to consume #### Application Features * Users can create, read, update, delete resources using a visual, tabular dashboard. * The tabular dashboard can be filtered, and searched. * Users can bulk-delete any resource * All DESTRUCTIVE requests will prompt the user for confirmation. * Users can upload images and audio files directly from the CMS. * A user can create other users. #### Road-mapped Features * Interface is mobile-responsive * Allow input for a QR code data for a plant and/or waypoint * Implement (2) more resource types: "tours", and "learn more" * Enhanced media previews allow the user to see the exact image/video/audio before upload. ### Technology Stack * Client: ReactJS, axios * Deployment: Netlify ### Wireframes #### Home ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/DASHBOARDHOME.png) #### Plant Content Type ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/PLANTS1.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/PLANTS2.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/PLANTS3.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/PLANTS4.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/PLANTS5.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/PLANTS6.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/PLANTS7.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/PLANTS8.png) #### Waypoint Content Type ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/WAYPOINTS1.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/WAYPOINTS2.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/WAYPOINTS3.png) #### Learn More Content Type ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/LEARNMORE1.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/LEARNMORE2.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/LEARNMORE3.png) #### Users ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/USERS1.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/USERS2.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/USERS3.png) #### Profile ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/PROFILE.png) #### Tags ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/TAGS.png) #### Locations ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/LOCATIONS.png) #### Media Uploads ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/MEDIA1.png) ![image](https://raw.githubusercontent.com/BCIT-SSD-2020-21/indigenous-plant-go-cms/main/planning/client/wireframes/MEDIA2.png) ### Installation #### Local Installment 1. Clone the repo with the following code: ``` git clone https://github.com/BCITConstruction/indigenousplantgo-cms-client.git ``` And navigate into the folder: ``` cd indigenousplantgo-cms-client ``` 2. Install all the node module with `npm install`. 3. Add a .env file with the base url of your server-side code. - If you run the server-side locally, the link will be `http://localhost:8080/api`. - If you run the server-side on heroku, the link will be where the the url provided by heroku followed by /api. ``` REACT_APP_BASE_URL="<Your link>/api" ``` 4. Running `npm start` now should run it at `http://localhost:3000`. #### Deploying client-side of cms to netlify 1. Proceed to https://www.netlify.com/ 2. Select New site from Git and connect to a Git provider 3. Select the repository for the client-side application 4. Click on Advanced settings and define the environment variable (refer to the .env file): ``` Key = "REACT_APP_BASE_URL" Value : <-Your-Heroku-URL-> ``` 5. Deploy the site <file_sep>import React, { useState, useEffect } from "react"; import LoginForm from "../../components/LoginForm"; import useLocalStorage from "../../hooks/useLocalStorage"; import { login } from "../../network"; import { useAuth } from "../../context/AuthContext"; import { useHistory } from "react-router-dom"; export default function LoginFormCtrl() { const authContext = useAuth(); const { setUserData } = authContext; const [username, setUsername] = useLocalStorage("username", ""); const [password, setPassword] = useState(""); const [rememberMe, setRememberMe] = useLocalStorage("rememberMe", true); const [directive, setDirective] = useState(null); const [loading, setLoading] = useState(false); const history = useHistory(); useEffect(() => { if (rememberMe === false) { setUsername(""); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { resetDirective(); }, [directive]); const resetDirective = async () => { await setTimeout(() => { setDirective(null); }, 4000); }; const attemptLogin = async (e) => { setLoading(true); e.preventDefault(); const result = await login({ username, password }); setLoading(false); if (result.error) return setDirective({ header: "Error signing in", message: result.error.data.error, success: false, }); setUserData(result); }; const navigateToRecovery = () => { history.push("/recovery"); }; return ( <LoginForm // PROPERTIES username={username} password={<PASSWORD>} rememberMe={rememberMe} directive={directive} loading={loading} // METHODS setPassword={setPassword} setUsername={setUsername} setRememberMe={setRememberMe} attemptLogin={attemptLogin} navigateToRecovery={navigateToRecovery} /> ); } <file_sep>import React, { useState, useEffect } from 'react'; import EditLearnMore from "../../../components/Edit/LearnMore"; import { getLearnMore, getImages, getAudios, getVideos, getCategoryGroup, getTags, updateLearnMore, } from "../../../network"; import { useParams } from "react-router-dom"; import { useHistory } from "react-router-dom"; export default function EditLearnMoreCtrl(){ let isMounted = true; const history = useHistory(); const [learnMoreData, setLearnMoreData] = useState({}); const { learnMoreId } = useParams(); // =============================================================== // FORM DATA // @desc form control data // =============================================================== const [images, setImages] = useState([]); const [audioFiles, setAudioFiles] = useState([]); const [videos, setVideos] = useState([]); const [categories, setCategories] = useState([]); const [tags, setTags] = useState([]); const [learnMoreTitle, setLearnMoreTitle] = useState(""); const [description, setDescription] = useState(""); const [customFields, setCustomFields] = useState([]); const [isVisible, setIsVisible] = useState(true); // =============================================================== // SELECTION DATA // @desc data that appears as options in select boxes. // =============================================================== const [eImages, setEImages] = useState([]); const [eAudios, setEAudios] = useState([]); const [eVideos, setEVideos] = useState([]); const [eCategories, setECategories] = useState([]); const [eTags, setETags] = useState([]); // Error handling const [directive, setDirective] = useState(null); // Preloader const [loading, setLoading] = useState(false); useEffect(() => { if (isMounted) resetDirective(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [directive]); const resetDirective = async () => { await setTimeout(() => { if (!isMounted) return; setDirective(null); }, 4000); }; useEffect(() => { // eslint-disable-next-line react-hooks/exhaustive-deps isMounted = true; if (isMounted) { (async () => { setLoading(true); await queryLearnMore(); await queryImages(); await queryAudios(); await queryVideos(); await queryCategories(); await queryTags(); setLoading(false); })(); } return () => { isMounted = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // =============================================================== // NETWORK QUERIES FOR EXISTING DATA // @desc queries for existing data in the database, and delegates to selection data // =============================================================== const queryLearnMore = async () => { if (!learnMoreId) return; const result = await getLearnMore(learnMoreId); if (result.error) return; if (!isMounted) return; setLearnMoreData(result); }; const queryImages = async () => { const result = await getImages(); if (result.error) return; if (!isMounted) return; setEImages(result); }; const queryAudios = async () => { const result = await getAudios(); if (result.error) return; if (!isMounted) return; setEAudios(result); }; const queryVideos = async () => { const result = await getVideos(); if (result.error) return; if (!isMounted) return; setEVideos(result); }; const queryCategories = async () => { const result = await getCategoryGroup("learn_more"); if (result.error) return; if (!isMounted) return; setECategories(result); }; const queryTags = async () => { const result = await getTags(); if (result.error) return; if (!isMounted) return; setETags(result); }; // =============================================================== // INPUT WATCHERS AND SETTERS // @desc functions that watch updates in children components, and sets them here. // =============================================================== const categoriesChanged = (data) => { const mappedData = data.map((d) => d._id); if (!isMounted) return; setCategories(mappedData); }; const tagsChanged = (data) => { const mappedData = data.map((d) => d._id); if (!isMounted) return; setTags(mappedData); }; const learnMoreTitleChanged = (data) => { if (!isMounted) return; setLearnMoreTitle(data); }; const descriptionChanged = (data) => { if (!isMounted) return; setDescription(data); }; const customFieldsChanged = (data) => { if (!isMounted) return; setCustomFields(data); }; const imagesChanged = (data) => { const mappedData = data.map((d) => d._id); if (!isMounted) return; setImages(mappedData); }; const audioFilesChanged = (data) => { const mappedData = data.map((d) => d._id); if (!isMounted) return; setAudioFiles(mappedData); }; const videosChanged = (data) => { const mappedData = data.map((d) => d._id); if (!isMounted) return; setVideos(mappedData); }; const isVisibleChanged = (data) => { if (!isMounted) return; setIsVisible(data); }; // =============================================================== // POST // @desc updates the Plant. // =============================================================== const handleUpdate = async () => { if (!isMounted) return; if (!learnMoreTitle || !description) return setDirective({ header: "Error updating item", message: "Missing required fields", success: false, }); setLoading(true); const learnMore = { learn_more_title: learnMoreTitle, description: description, images: images, audio_files: audioFiles, videos: videos, tags: tags, categories: categories, custom_fields: customFields, isPublish: isVisible, }; const result = await updateLearnMore(learnMoreId, learnMore); if (!isMounted) return; setLoading(false); if (result.error) return setDirective({ header: "Error updating item", message: result.error.data.error, success: false, }); history.push("/learnmore"); }; return ( <EditLearnMore learnMoreData = {learnMoreData} // METHODS categoriesChanged={categoriesChanged} tagsChanged={tagsChanged} learnMoreTitleChanged ={learnMoreTitleChanged} descriptionChanged={descriptionChanged} customFieldsChanged={customFieldsChanged} imagesChanged={imagesChanged} audioFilesChanged={audioFilesChanged} videosChanged={videosChanged} isVisibleChanged={isVisibleChanged} handleUpdate={handleUpdate} // SELECTION DATA eImages={eImages} eAudios={eAudios} eVideos={eVideos} eCategories={eCategories} eTags={eTags} // QUERIES queryLearnMore={queryLearnMore} queryImages={queryImages} queryAudios={queryAudios} queryVideos={queryVideos} queryCategories={queryCategories} queryTags={queryTags} loading={loading} directive={directive} /> ); }<file_sep>import React from "react"; import ListCategoriesCtrl from "../../controllers/List/Categories/ListCategoriesCtrl"; export default function LearnMoreCategories() { return ( <main> <ListCategoriesCtrl dataLabel={"learn_more"} label={"Learn More"} labelPlural={"Learn More"} /> </main> ); } <file_sep>import React from "react"; import { Link } from "react-router-dom"; /* @desc UI component that renders a table of users. @controller ../Users/index.js */ export default function Table({ userDatas, selectedUsers, handleSelected, handleDelete, }) { return ( <ul className="table__list"> {userDatas && userDatas.length > 0 && userDatas.map((user, index) => { return ( <li className={ selectedUsers.includes(user._id) ? "table__row selected" : "table__row" } key={index} > <div className="table__col select"> <input type="checkbox" value={user._id} checked={selectedUsers.includes(user._id) ? true : false} onChange={(e) => handleSelected(e)} /> </div> <div className="table__col title"> <p>{user.user_name}</p> <span className="action"> <Link to={`/users/edit/${user._id}`} type="button" value={user._id} > Edit&nbsp; </Link> <button type="button" onClick={(e) => handleDelete(e)} value={user._id} > &nbsp;Delete </button> </span> </div> <div className="table__col author"> <p>{user.role}</p> </div> <div className="table__col categories"> <p>{user.email}</p> </div> </li> ); })} </ul> ); } <file_sep>import React, { useState, useEffect } from "react"; import ListMedia from "../../../components/List/Media"; import { getImages, createImage, deleteImage, updateImage, getAudios, createAudio, deleteAudio, updateAudio, getVideos, deleteVideo, updateVideo, createVideo, bulkDeleteImages, bulkDeleteAudios, bulkDeleteVideos, } from "../../../network"; export default function ListMediaCtrl({ dataLabel, label }) { let isMounted = true; const mediaFields = { file: null, caption: "", url: "", }; const [file, setFile] = useState(null); const [caption, setCaption] = useState(""); const [eMedias, setEMedias] = useState([]); // medias_ is the mutable version of eMedias that we'll be using to filter const [medias_, setMedias_] = useState([]); const [searchQuery, setSearchQuery] = useState(""); const [selectedMedias, setSelectedMedias] = useState([]); const [hasPages, setHasPages] = useState(false); const [pages, setPages] = useState([]); const [page, setPage] = useState(1); const [pendingDelete, setPendingDelete] = useState({}); const [modalActive, setModalActive] = useState(false); const [modalState, setModalState] = useState("delete"); const [pendingEdit, setPendingEdit] = useState({}); const [editMedia, setEditMedia] = useState(mediaFields); const [bulkAction, setBulkAction] = useState(""); const [loading, setLoading] = useState(false); const [videoLink, setVideoLink] = useState(""); const [editVideoLink, setEditVideoLink] = useState(""); // Error Messaging const [directive, setDirective] = useState(null); useEffect(() => { // eslint-disable-next-line react-hooks/exhaustive-deps isMounted = true; queryMedia(); return () => { isMounted = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { if (isMounted) setMedias_(eMedias); // eslint-disable-next-line react-hooks/exhaustive-deps }, [eMedias]); useEffect(() => { setPage(1); formatPages(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [medias_]); useEffect(() => { resetDirective(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [directive]); const resetDirective = async () => { await setTimeout(() => { if (!isMounted) return; setDirective(null); }, 4000); }; const formatPages = () => { const dataLength = medias_.length; if (dataLength < 5) return setHasPages(false); setHasPages(true); let itemsChunk = 5, locationsData = medias_; // split the data into pages const pages = locationsData.reduce((resultArray, item, index) => { const chunkIndex = Math.floor(index / itemsChunk); if (!resultArray[chunkIndex]) { resultArray[chunkIndex] = []; // start a new chunk } resultArray[chunkIndex].push(item); return resultArray; }, []); setPages(pages); }; const nextPage = () => { let currentPage = page; if (currentPage >= pages.length) return; currentPage = currentPage + 1; setPage(currentPage); }; const prevPage = () => { let currentPage = page; if (currentPage === 1) return; currentPage = currentPage - 1; setPage(currentPage); }; const queryMedia = async () => { if (!isMounted) return; setLoading(true); let result; switch (dataLabel) { case "image": result = await getImages(); break; case "audio_file": result = await getAudios(); break; case "video": result = await getVideos(); break; default: break; } if (!isMounted) return; setLoading(false); if (result.error) return setDirective({ header: "Error fetching media", message: "A network error has occurred", success: false, }); setEMedias(result); }; const handleQueryChange = (e) => { setSearchQuery(e.target.value); }; const clearSearch = () => { setSearchQuery(""); setMedias_(eMedias); }; const applySearch = () => { const searchQ = searchQuery.toLowerCase(); if (!searchQ) return setMedias_(eMedias); let filteredData = eMedias.filter((media) => media[`caption`].toLowerCase().startsWith(searchQ) ); setMedias_(filteredData); }; const batchSelect = () => { const resourceIds = eMedias.map((media) => media._id); const selectedIds = selectedMedias; const allSelected = resourceIds.length === selectedIds.length && resourceIds.every(function (element, index) { return element === selectedIds[index]; }); if (!allSelected) { setSelectedMedias(resourceIds); } else { setSelectedMedias([]); } }; const handleSelected = (e) => { const id = e.target.value; let newSelected = [...selectedMedias]; if (selectedMedias.includes(id)) { newSelected = newSelected.filter((item) => item !== id); } else { newSelected = [...newSelected, id]; } setSelectedMedias(newSelected); }; const handleUpload = async () => { if (!isMounted) return; let result; if ((dataLabel !== "video" && !file) || !caption) return setDirective({ header: "Error uploading media", message: "Required fields are missing", success: false, }); if ((dataLabel === "video" && !videoLink) || !caption) return setDirective({ header: "Error uploading media", message: "Required fields are missing", success: false, }); const formData = new FormData(); setLoading(true); switch (dataLabel) { case "image": formData.append("image", file); formData.append("caption", caption); result = await createImage(formData); break; case "audio_file": formData.append("audio", file); formData.append("caption", caption); result = await createAudio(formData); break; case "video": const video_ = { caption: caption, video_url: videoLink, }; result = await createVideo(video_); break; default: break; } if (!isMounted) return; setLoading(false); if (result.error) return setDirective({ header: "Error uploading media", message: result.error.data.error, success: false, }); setFile(undefined); setVideoLink(""); setCaption(""); queryMedia(); }; const handleDelete = async (e) => { if (!isMounted) return; setModalState("delete"); const id = e.target.value; const foundMedia = eMedias.filter((tag) => tag._id === id)[0]; if (!foundMedia) return setDirective({ header: "Error deleting media", message: "Unable to locate media", success: false, }); await setPendingDelete(foundMedia); if (!isMounted) return; setModalActive(true); }; const applyDelete = async () => { if (!isMounted) return; let result; const id = pendingDelete._id; if (!id) return setDirective({ header: "Error deleting media", message: "Unable to locate media", success: false, }); switch (dataLabel) { case "image": result = await deleteImage(id); break; case "audio_file": result = await deleteAudio(id); break; case "video": result = await deleteVideo(id); break; default: break; } if (!isMounted) return; if (result.error) return setDirective({ header: "Error deleting media", message: result.error.data.error, success: false, }); closeModal(); setPendingDelete({}); queryMedia(); }; const handleEdit = async (e) => { if (!isMounted) return; setModalState("edit"); const id = e.target.value; const foundMedia = eMedias.filter((media) => media._id === id)[0]; if (!foundMedia) return setDirective({ header: "Error updating media", message: "Unable to locate media", success: false, }); await setPendingEdit(foundMedia); if (!isMounted) return; if (dataLabel === "video") setEditVideoLink(foundMedia.video_url); const m = { file: null, caption: foundMedia.caption, url: foundMedia[`${dataLabel}_url`], }; setEditMedia(m); setModalActive(true); }; const closeModal = () => { setModalActive(false); }; const handleChangeFile = (e) => { const file = e.target.files[0]; let currentMedia = { ...editMedia }; currentMedia.file = file; setEditMedia(currentMedia); }; const handleCaptionChange = (e) => { let currentMedia = { ...editMedia }; currentMedia.caption = e.target.value; setEditMedia(currentMedia); }; const applyEdit = async () => { if (!isMounted) return; const id = pendingEdit._id; if (!id) return setDirective({ header: "Error updating media", message: "Unable to locate media", success: false, }); let result; if (dataLabel !== "video" && !editMedia.file && !editMedia.caption) return setDirective({ header: "Error updating media", message: "Required fields are missing", success: false, }); if (dataLabel === "video" && !editVideoLink && !editMedia.caption) return setDirective({ header: "Error uploading media", message: "Required fields are missing", success: false, }); const formData = new FormData(); switch (dataLabel) { case "image": formData.append("image", editMedia.file); formData.append("caption", editMedia.caption); result = await updateImage(formData, id); break; case "audio_file": formData.append("audio", editMedia.file); formData.append("caption", editMedia.caption); result = await updateAudio(formData, id); break; case "video": const video_ = { caption: editMedia.caption, video_url: editVideoLink, }; result = await updateVideo(video_, id); break; default: break; } if (!isMounted) return; if (result.error) return setDirective({ header: "Error deleting media", message: result.error.data.error, success: false, }); setPendingEdit({}); setEditMedia(mediaFields); closeModal(); queryMedia(); }; const handleBulkActionChange = (_, data) => { const value = data.value; setBulkAction(value); }; const handleBulkDelete = async () => { if (selectedMedias.length < 1) return setDirective({ header: "Error applying bulk actions", message: "No items selected", success: false, }); if (bulkAction === "default") return setDirective({ header: "Error applying bulk actions", message: "Invalid action", success: false, }); setModalState("bulk"); setModalActive(true); }; const applyBulkDelete = async () => { if (!isMounted) return; let result; switch (dataLabel) { case "image": result = await bulkDeleteImages(selectedMedias); break; case "audio_file": result = await bulkDeleteAudios(selectedMedias); break; case "video": result = await bulkDeleteVideos(selectedMedias); break; default: break; } if (!isMounted) return; if (result.error) return setDirective({ header: "Error applying bulk action", message: result.error.data.error, success: false, }); closeModal(); setSelectedMedias([]); queryMedia(); }; return ( <ListMedia label={label} dataLabel={dataLabel} caption={caption} setCaption={setCaption} file={file} setFile={setFile} medias={medias_} searchQuery={searchQuery} handleQueryChange={handleQueryChange} clearSearch={clearSearch} applySearch={applySearch} batchSelect={batchSelect} selectedMedias={selectedMedias} handleSelected={handleSelected} handleUpload={handleUpload} hasPages={hasPages} page={page} pages={pages} nextPage={nextPage} prevPage={prevPage} closeModal={closeModal} handleDelete={handleDelete} pendingDelete={pendingDelete} modalState={modalState} modalActive={modalActive} applyDelete={applyDelete} handleEdit={handleEdit} pendingEdit={pendingEdit} editMedia={editMedia} handleChangeFile={handleChangeFile} handleCaptionChange={handleCaptionChange} applyEdit={applyEdit} handleBulkActionChange={handleBulkActionChange} handleBulkDelete={handleBulkDelete} applyBulkDelete={applyBulkDelete} loading={loading} directive={directive} videoLink={videoLink} setVideoLink={setVideoLink} editVideoLink={editVideoLink} setEditVideoLink={setEditVideoLink} /> ); } <file_sep>import React from "react"; import AddTourCtrl from "../../controllers/Add/Tours/AddTourCtrl"; export default function AddTour() { return ( <main> <AddTourCtrl/> </main> ); } <file_sep>import React from "react"; import EditLearnMoreCtrl from '../../controllers/Edit/LearnMore/EditLearnMoreCtrl'; export default function EditLearnMore() { return ( <main> <EditLearnMoreCtrl/> </main> ); } <file_sep>import { Switch, Route, Redirect } from "react-router-dom"; import { useAuth } from "../context/AuthContext"; /* ======================================================== IMPORTING PAGES ======================================================== */ // 1.0 HOME PAGE import Home from "../pages/home"; // 2.0 PLANTS import AllPlants from "../pages/plants/AllPlants"; import AddPlant from "../pages/plants/AddPlant"; import EditPlant from "../pages/plants/EditPlant"; import PlantCategories from "../pages/plants/PlantCategories"; // 3.0 WAYPOINTS import AllWaypoints from "../pages/waypoints/AllWaypoints"; import AddWaypoint from "../pages/waypoints/AddWaypoint"; import EditWaypoint from "../pages/waypoints/EditWaypoint"; import WaypointCategories from "../pages/waypoints/WaypointCategories"; // TOURS import AllTours from "../pages/tours/AllTours"; import AddTour from "../pages/tours/AddTour"; import EditTour from "../pages/tours/EditTour"; import ToursCategories from "../pages/tours/TourCategories"; // LEARN MORE import AllLearnMore from '../pages/learnmore/AllLearnMore'; import AddLearnMore from '../pages/learnmore/AddLearnMore'; import EditLearnMore from "../pages/learnmore/EditLearnMore"; import LearnMoreCategories from "../pages/learnmore/LearnMoreCategories"; // 4.0 USERS import AllUsers from "../pages/users/AllUsers"; import AddUser from "../pages/users/AddUser"; import EditUser from "../pages/users/EditUser"; // 5.0 LOCATIONS import Locations from "../pages/locations"; // 6.0 MEDIA import Images from "../pages/media/Images"; import AudioFiles from "../pages/media/AudioFiles"; import Videos from "../pages/media/Videos"; // 7.0 TAGS import Tags from "../pages/tags"; // 8.0 PROFILE import Profile from "../pages/profile"; // 9.0 LOGIN import Login from "../pages/login"; // 10.0 RECOVERY import ResetPassword from "../pages/resetpassword"; // Routes that should only be visible if authenticated. const PrivateRoute = ({ component: Component, ...rest }) => { const authContext = useAuth(); const { isAuthenticated } = authContext; return ( <Route {...rest} render={(props) => isAuthenticated === false ? ( <Redirect to="/login" /> ) : ( <Component {...props} /> ) } /> ); }; // Routes that should only be visible if NOT authenticated const AnonymousRoute = ({ component: Component, ...rest }) => { const authContext = useAuth(); const { isAuthenticated } = authContext; return ( <Route {...rest} render={(props) => isAuthenticated === false ? ( <Component {...props} /> ) : ( <Redirect to="/" /> ) } /> ); }; export default function Navigation() { return ( <> <Switch> {/* 1.0 HOME */} <PrivateRoute exact path="/" component={Home} /> {/* 2.0 PLANTS */} <PrivateRoute exact path="/plants" component={AllPlants} /> <PrivateRoute exact path="/plants/add" component={AddPlant} /> <PrivateRoute exact path="/plants/edit/:plantId" component={EditPlant} /> <PrivateRoute exact path="/plants/categories" component={PlantCategories} /> {/* 3.0 WAYPOINTS */} <PrivateRoute exact path="/waypoints" component={AllWaypoints} /> <PrivateRoute exact path="/waypoints/add" component={AddWaypoint} /> <PrivateRoute exact path="/waypoints/edit/:waypointId" component={EditWaypoint} /> <PrivateRoute exact path="/waypoints/categories" component={WaypointCategories} /> {/* TOURS */} <PrivateRoute exact path="/tours" component={AllTours}/> <PrivateRoute exact path="/tours/add" component={AddTour}/> <PrivateRoute exact path="/tours/edit/:tourId" component={EditTour}/> <PrivateRoute exact path="/tours/categories" component={ToursCategories} /> {/* LEARN MORE */} <PrivateRoute exact path="/learnmore" component={AllLearnMore}/> <PrivateRoute exact path="/learnmore/add" component={AddLearnMore} /> <PrivateRoute exact path="/learnmore/edit/:learnMoreId" component={EditLearnMore} /> <PrivateRoute exact path="/learnmore/categories" component={LearnMoreCategories} /> {/* 6.0 USERS */} <PrivateRoute exact path="/users" component={AllUsers} /> <PrivateRoute exact path="/users/add" component={AddUser} /> <PrivateRoute exact path="/users/edit/:userId" component={EditUser} /> {/* 7.0 LOCATIONS */} <PrivateRoute exact path="/locations" component={Locations} /> {/* 8.0 MEDIA */} <PrivateRoute exact path="/media/images" component={Images} /> <PrivateRoute exact path="/media/audiofiles" component={AudioFiles} /> <PrivateRoute exact path="/media/videos" component={Videos} /> {/* 9.0 TAGS */} <PrivateRoute exact path="/tags" component={Tags} /> {/* 10.0 PROFILE */} <PrivateRoute exact path="/profile" component={Profile} /> {/* 11.0 LOGIN */} <AnonymousRoute exact path="/login" component={Login} /> {/* 11.0 LOGIN */} <AnonymousRoute exact path="/recovery" component={ResetPassword} /> </Switch> </> ); } <file_sep>import React from "react"; import EditPlantCtrl from "../../controllers/Edit/Plant/EditPlantCtrl"; export default function EditPlant() { return ( <main> <EditPlantCtrl /> </main> ); } <file_sep>import React from "react"; import DashHeader from "../../DashHeader"; import Table from "./Table"; import Modal from "../../Modal"; import { Dropdown, Input, Icon, Loader } from "semantic-ui-react"; import Message from "../../Message"; /* @desc UI component that Lists tags and allows the list to be managed. @controller ~/src/controllers/List/Tags/ListTagsCtrl.js */ export default function ListTags({ // Datas to List: Tags tags, // SEARCH -- Attributes searchQuery, // SEARCH -- Methods handleQueryChange, applySearch, clearSearch, // PAGINATION -- Attributes hasPages, pages, page, // PAGINATION -- Methods nextPage, prevPage, // BATCH SELECT -- Attributes selectedTags, // BATCH SELECT -- Methods handleSelected, batchSelect, // NEW TAG -- Methods newTag, submitNewTag, // NEW TAG -- Attributes newTagValue, // MODAL -- Methods closeModal, // MODAL -- Attributes modalActive, modalState, // DELETE -- Methods handleDelete, applyDelete, // DELETE -- Attributes pendingDelete, // EDIT -- Methods applyEdit, handleEdit, editTag, // EDIT -- Attributes pendingEdit, editTagValue, // BULK DELETE handleBulkActionChange, handleBulkDelete, applyBulkDelete, // LOADING -- Attributes loading, directive, }) { const renderModal = () => { switch (modalState) { case "edit": return editModal(); case "delete": return deleteModal(); case "bulk": return bulkDeleteModal(); default: return <></>; } }; const editModal = () => ( <> <fieldset style={style.fieldset}> <p style={style.label}> Tag name <span style={style.req}>*</span> </p> <Input onChange={(e) => editTag(e.target.value)} value={editTagValue} style={style.input} placeholder="Enter category name" /> </fieldset> <button onClick={() => applyEdit()} className="field__button"> Update tag </button> <button onClick={() => closeModal()} style={{ color: "var(--highlight)" }} > Cancel </button> </> ); const deleteModal = () => ( <> <p> Deleting this tag will remove all instances of the tag&nbsp; <strong style={{ color: "var(--danger)" }}> {pendingDelete.tag_name} </strong> . Do you wish to proceed? </p> <button onClick={() => applyDelete("attempt delete")} className="field__button" > Yes, I know what I am doing. </button> <button onClick={() => closeModal()} className="field__button secondary"> No, cancel my request. </button> </> ); const bulkDeleteModal = () => ( <> <p> Deleting&nbsp; <strong style={{ color: "var(--danger)" }}> {selectedTags.length} </strong> &nbsp;tags will remove{" "} <strong style={{ color: "var(--danger)", fontWeight: "700", textTransform: "uppercase", }} > all </strong>{" "} instances of the deleted tags. Do you wish to proceed? </p> <button onClick={() => applyBulkDelete()} className="field__button"> Yes, I know what I am doing. </button> <button onClick={() => closeModal()} className="field__button secondary"> No, cancel my request. </button> </> ); return ( <div> {typeof directive === "object" && directive !== null && Object.keys(directive).length > 0 && ( <Message success={directive.success} header={directive.header} message={directive.message} /> )} <DashHeader title="Tags" /> <div className="resource__container"> <div className="resource__col left"> <h3>Add New Tag</h3> <fieldset style={style.fieldset}> <p style={style.label}> Tag name <span style={style.req}>*</span> </p> <Input onChange={(e) => newTag(e.target.value)} value={newTagValue} style={style.input} placeholder="Enter tag name" /> </fieldset> <button onClick={() => submitNewTag()} className="field__button"> Create new tag </button> </div> <div className="resource__col right"> <div style={{ marginBottom: 10, display: "flex" }}> <p> <strong>Results</strong> ({tags.length}){" "} </p> {loading && <Loader active inline size="tiny" />} </div> <div className="table__controls"> <div style={{ display: "flex" }}> <div className="table__action"> <Dropdown placeholder={"Bulk Actions"} onChange={(e, data) => handleBulkActionChange(e, data)} selection options={[ { key: "default", value: "default", text: "Bulk Actions" }, { key: "delete", value: "delete", text: "Delete" }, ]} /> <button onClick={() => handleBulkDelete()}>Apply</button> </div> </div> <div> <div className="table__action" style={{ marginRight: 0 }}> {searchQuery && ( <button onClick={() => clearSearch()} className="sub__action"> Clear search </button> )} <Input onChange={(e) => handleQueryChange(e)} value={searchQuery} style={{ ...style.input, minWidth: 250 }} placeholder={`Enter search query`} /> <button onClick={() => applySearch()}>Search</button> </div> </div> </div> <div className="table__heading table__row"> <div className="table__col head select"> <input type="checkbox" value={"select all"} onChange={(e) => batchSelect(e)} /> </div> <div className="table__col head title"> <h3>name</h3> </div> </div> <Table tags={hasPages ? pages[page - 1] : tags} selectedTags={selectedTags} handleSelected={handleSelected} handleDelete={handleDelete} handleEdit={handleEdit} /> {hasPages && ( <div className="pagination__control"> <div> <p style={{ marginBottom: "7px" }}> Page {page} of {pages.length} </p> <div className="control"> <button onClick={() => prevPage()}> <Icon name="caret left" /> </button> <span>{page}</span> <button onClick={() => nextPage()}> <Icon name="caret right" /> </button> </div> </div> </div> )} <Modal isActive={modalActive} title={ modalState === "delete" ? `Delete ${pendingDelete.tag_name}?` : modalState === "edit" ? `Edit ${pendingEdit?.tag_name}` : `Delete all ${selectedTags.length} tags?` } closeModal={closeModal} > {renderModal()} </Modal> </div> </div> </div> ); } const style = { input: { width: "100%", color: "var(--darksecondary)", }, label: { color: "var(--darksecondary)", margin: 0, fontSize: 11, marginBottom: "3px", }, fieldset: { marginBottom: "10px", padding: 0, }, req: { color: "red", fontSize: 14, }, }; <file_sep>import React from "react"; /* @desc UI component that renders a table of tags. @controller ../Tags/index.js */ export default function Table({ tags, handleSelected, selectedTags, handleDelete, handleEdit, }) { return ( <ul className="table__list"> {tags && tags.length > 0 && tags.map((tag, index) => { return ( <li className={ selectedTags.includes(tag._id) ? "table__row selected" : "table__row" } key={index} > <div className="table__col select"> <input type="checkbox" value={tag._id} checked={selectedTags.includes(tag._id) ? true : false} onChange={(e) => handleSelected(e)} /> </div> <div className="table__col title"> <p>{tag.tag_name}</p> <span className="action"> <button type="button" value={tag._id} onClick={(e) => handleEdit(e)} > Edit&nbsp; </button> <button type="button" value={tag._id} onClick={(e) => handleDelete(e)} > &nbsp;Delete </button> </span> </div> </li> ); })} </ul> ); } <file_sep>import React, { useState, useEffect } from "react"; import { useHistory } from "react-router-dom"; import { useAuth } from "../../context/AuthContext"; import { CompassIcon2, UsersIcon2, LocationIcon2, PlantIcon2, } from "../../icons"; export default function Home({ action, method }) { let isMounted = true; const history = useHistory(); const authContext = useAuth(); const { userData } = authContext; //Get Signed in User const [user, setUser] = useState(); useEffect(() => { // eslint-disable-next-line react-hooks/exhaustive-deps isMounted = true; if (isMounted && userData && userData.user && userData.user.user_name) setUser(userData.user.user_name); return () => { isMounted = false; }; }, []); //Get Date const dateToday = new Date(); const options = { year: "numeric", month: "short", day: "numeric" }; const displayDate = dateToday.toLocaleDateString("en-US", options); //Get Clock const [time, setTime] = useState(); const clock = () => { var time_; var date = new Date(); var minute = date.getMinutes(); var hour = date.getHours(); var formathour; if (hour > 12) { formathour = hour - 12; } if (hour === 0) { formathour = 12; } var amOrPm; if (hour >= 12) { amOrPm = "PM"; } else { amOrPm = "AM"; } if (hour > 12) { time_ = { hour: `${("0" + formathour).substr(-2)}`, minute: `${("0" + minute).substr(-2)}`, twelveHour: `${amOrPm}`, }; } else { time_ = { hour: `${("0" + hour).substr(-2)}`, minute: `${("0" + minute).substr(-2)}`, twelveHour: `${amOrPm}`, }; } if (isMounted) setTime(time_); }; if (isMounted) setInterval(clock, 1000); return ( <main className="homewrapper"> {/* HERO SECTION */} <div style={style.hero}> <img className="carousel" style={style.image} src="/assets/images/hero.jpg" alt="Indigenous Initiatives and Partnerships Logo Red" /> <span style={style.textDisplay}> <h1 style={style.time}> {time && typeof time === "object" && time !== null && Object.keys(time).length > 1 ? `${time.hour}` : `00`} <span className="time__colon">:</span> {time && typeof time === "object" && time !== null && Object.keys(time).length > 1 ? `${time.minute} ${time.twelveHour}` : `00 PM`} </h1> <h3 style={style.greeting}>Ey' Swayel, {user}!</h3> <div style={style.date}> {displayDate}</div> </span> </div> {/* QUICKLINK SECTION */} <div className="quick__links" style={style.quicklinks}> <div className="subhead" style={style.subhead}> <h3 style={{ fontSize: 21 }}>Quick Links</h3> </div> <div className="quick__grid" style={style.grid}> <button className="link__button" style={style.button} onClick={() => history.push("/plants/add")} > <div className="quickicons" style={style.icon}> <PlantIcon2 /> </div> <div> <label style={style.addnew}>Add New </label> <p style={style.resource}>Plant</p> </div> <div className="icon__accent"> <PlantIcon2 /> </div> </button> <button className="link__button" style={style.button} onClick={() => history.push("/users/add")} > <div style={style.icon}> <UsersIcon2 /> </div> <div> <label style={style.addnew}>Add New </label> <p style={style.resource}>User</p> </div> <div className="icon__accent"> <UsersIcon2 /> </div> </button> <button className="link__button" style={style.button} onClick={() => history.push("/waypoints/add")} > <div style={style.icon}> <CompassIcon2 /> </div> <div> <label style={style.addnew}>Add New </label> <p style={style.resource}>Waypoint</p> </div> <div className="icon__accent"> <CompassIcon2 /> </div> </button> <button className="link__button" style={style.button} onClick={() => history.push("/locations")} > <div style={style.icon}> <LocationIcon2 /> </div> <div> <label style={style.addnew}>Add New </label> <p style={style.resource}>Location</p> </div> <div className="icon__accent"> <LocationIcon2 /> </div> </button> </div> </div> </main> ); } const style = { hero: { position: "relative", height: "100%", textAlign: "center", overflow: "hidden", maxWidth: "1400px", }, image: { width: "100%", maxHeight: "550px", opacity: 0.75, verticalAlign: "bottom", }, quicklinks: { paddingLeft: "20px", }, subhead: { padding: "10px 0", }, textDisplay: { position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", color: "white", zIndex: "1", textShadow: "1px 1px 8px rgba(0, 0, 0, 0.5)", }, greeting: { textTransform: "capitalize", fontSize: "175%", marginTop: "10px", marginBottom: "5px", fontWeight: "normal", }, resource: { fontSize: 21, fontWeight: "normal", margin: 0, marginLeft: 1, marginTop: 3, }, time: { marginBottom: "0", fontSize: "40px", }, date: { fontSize: "17px", }, grid: { display: "flex", }, col: { display: "block", marginRight: "10px", width: "100%", }, button: { display: "flex", textAlign: "left", }, icon: { marginRight: "20px", color: "white", }, addnew: { textTransform: "uppercase", fontSize: 12, letterSpacing: "0.09em", background: "var(--highlightsecondary)", padding: "3px 7px", borderRadius: "2px", }, }; <file_sep>import React, { useState, useEffect } from "react"; import AddWaypoints from "../../../components/Add/Waypoints"; import { useHistory } from "react-router-dom"; import { getLocations, getImages, getAudios, getVideos, getTags, getCategoryGroup, getAllPlants, createWaypoint, } from "../../../network"; export default function AddWaypointsCtrl() { let isMounted = true; const history = useHistory(); // =============================================================== // FORM DATA // @desc state variables that map back to what the user has selected. // These variables are updated when the user changes any form // controls for a waypoint. // =============================================================== const [tags, setTags] = useState([]); const [categories, setCategories] = useState([]); const [locations, setLocations] = useState([]); const [images, setImages] = useState([]); const [audioFiles, setAudioFiles] = useState([]); const [videos, setVideos] = useState([]); const [customFields, setCustomFields] = useState([]); const [waypointName, setWaypointName] = useState(""); const [description, setDescription] = useState(""); const [plants, setPlants] = useState([]); const [isVisible, setIsVisible] = useState(true); // =============================================================== // SELECTION DATA // @desc state variables that hold EXISTING data. These variables // allow the user to see what is currently in the DB, and select // from that existing data. We immediately query for these on mount. // =============================================================== const [eLocations, setELocations] = useState([]); const [eImages, setEImages] = useState([]); const [eAudios, setEAudios] = useState([]); const [eVideos, setEVideos] = useState([]); const [eTags, setETags] = useState([]); const [eCategories, setECategories] = useState([]); const [ePlants, setEPlants] = useState([]); // Error handling const [directive, setDirective] = useState(null); // Preloader const [loading, setLoading] = useState(false); useEffect(() => { if (isMounted) resetDirective(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [directive]); const resetDirective = async () => { await setTimeout(() => { setDirective(null); }, 4000); }; useEffect(() => { // eslint-disable-next-line react-hooks/exhaustive-deps isMounted = true; if (isMounted) { (async () => { setLoading(true); await queryLocations(); await queryImages(); await queryAudios(); await queryVideos(); await queryTags(); await queryCategories(); await queryPlants(); setLoading(false); })(); } return () => { isMounted = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // =============================================================== // NETWORK QUERIES FOR EXISTING DATA // @desc queries locations, media, categories, and tags to display // available options when creating a plant. // =============================================================== const queryLocations = async () => { const result = await getLocations(); if (result.error) return; if (!isMounted) return; setELocations(result); }; const queryImages = async () => { const result = await getImages(); if (result.error) return; if (!isMounted) return; setEImages(result); }; const queryAudios = async () => { const result = await getAudios(); if (result.error) return; if (!isMounted) return; setEAudios(result); }; const queryVideos = async () => { const result = await getVideos(); if (result.error) return; if (!isMounted) return; setEVideos(result); }; const queryTags = async () => { const result = await getTags(); if (result.error) return; if (!isMounted) return; setETags(result); }; const queryCategories = async () => { const result = await getCategoryGroup("waypoint"); if (result.error) return; if (!isMounted) return; setECategories(result); }; const queryPlants = async () => { const result = await getAllPlants(); if (result.error) return; if (!isMounted) return; setEPlants(result); }; // =============================================================== // INPUT WATCHERS AND SETTERS // @desc functions that watch for state updates in child components. // These functions are used as setters, and when a form-control // is updated, these functions update this component's state to match. // =============================================================== const categoriesChanged = (data) => { const mappedData = data.map((d) => d._id); setCategories(mappedData); }; const tagsChanged = (data) => { const mappedData = data.map((d) => d._id); setTags(mappedData); }; const locationsChanged = (data) => { const mappedData = data.map((d) => d._id); setLocations(mappedData); }; const imagesChanged = (data) => { const mappedData = data.map((d) => d._id); setImages(mappedData); }; const audioFilesChanged = (data) => { const mappedData = data.map((d) => d._id); setAudioFiles(mappedData); }; const videosChanged = (data) => { const mappedData = data.map((d) => d._id); setVideos(mappedData); }; const customFieldsChanged = (data) => { setCustomFields(data); }; const waypointNameChanged = (data) => { setWaypointName(data); }; const descriptionChanged = (data) => { setDescription(data); }; const plantsChanged = (data) => { const mappedData = data.map((d) => d._id); setPlants(mappedData); }; const isVisibleChanged = (data) => { setIsVisible(data); }; const handlePublish = async () => { if (!isMounted) return; const waypoint = { waypoint_name: waypointName, description: description, images: images, audio_files: audioFiles, videos: videos, tags: tags, categories: categories, locations: locations, custom_fields: customFields, plants: plants, isPublish: isVisible, }; setLoading(true); const result = await createWaypoint(waypoint); if (!isMounted) return; setLoading(false); if (result.error) return setDirective({ header: "Error creating waypoint", message: result.error.data.error, success: false, }); history.push("/waypoints"); }; return ( <AddWaypoints // WATCHERS categoriesChanged={categoriesChanged} tagsChanged={tagsChanged} locationsChanged={locationsChanged} imagesChanged={imagesChanged} audioFilesChanged={audioFilesChanged} customFieldsChanged={customFieldsChanged} videosChanged={videosChanged} waypointNameChanged={waypointNameChanged} descriptionChanged={descriptionChanged} plantsChanged={plantsChanged} isVisibleChanged={isVisibleChanged} // SELECTION DATA eLocations={eLocations} eImages={eImages} eAudios={eAudios} eVideos={eVideos} eTags={eTags} eCategories={eCategories} ePlants={ePlants} // QUERIES queryLocations={queryLocations} queryImages={queryImages} queryAudios={queryAudios} queryVideos={queryVideos} queryTags={queryTags} queryCategories={queryCategories} // PUBLISH handlePublish={handlePublish} loading={loading} directive={directive} /> ); }
909ae74afb3b100ed46f8f97be1ccb312dc9b8c6
[ "JavaScript", "Markdown" ]
57
JavaScript
BCITConstruction/indigenousplantgo-cms-client-1
8caaea6f2f0acccd4ac54c8693d54b95503c090c
fe4b8a777c7c9abb9c3d4bba4ea055c2c67f30b8
refs/heads/main
<file_sep><?php public function excluir(){ if($this->id){ $sql = "DELETE FROM operacoes WHERE id_operacao = :id_operacao"; $stmt = DB::conexao()->prepare($sql); $stmt->bindParam(':id_operacao', $this->id); $stmt->execute(); } } ?> <?php if(isset($_GET['remove']) && $_GET['remove'] == true){ $listaPermissao = Operacao::listar($_GET['idgrupo'], $_GET['idmodulo'],$_GET['idpermissao']); foreach($listaPermissao as $itemPermissao){ $excluir= new Operacao($itemPermissao->getId()); $excluir->excluir(); } } ?><file_sep><?php public static function listar(){ $sql = "SELECT * FROM permissoes"; $stmt = DB::conexao()->prepare($sql); $stmt->execute(); $registros = $stmt->fetchAll(); if($registros){ $itens = array(); foreach($registros as $objeto){ $temporario = new Permissao(); $temporario->setId($objeto['id_permissao']); $temporario->setDescricao($objeto['descricao']); $temporario->setAcao($objeto['acao']); $itens[] = $temporario; } return $itens; }return false; } ?><file_sep> <?php include "classes/DB.class.php"; include "classes/Agentes.class.php"; ?> <?php if (isset($_GET['id']) and is_numeric($_GET['id'])) { $agentes = new Agentes($_GET['id']); $agentes->excluir(); ?> <?php }?><file_sep> <?php if (isset($_POST['botao']) && $_POST['botao'] == "Salvar") { include 'classes/Agentes.class.php'; $agentes = new Agentes(); $agentes->setSentinelas($_POST['sentinelas']); $agentes->setControladores($_POST['controladores']); $agentes->setDuelistas($_POST['duelistas']); $agentes->adicionar(); } ?> <form method='post' action=''> Sentinelas: <input type="text" name='sentinelas'></br> Controladores: <input type="text" name='controladores'></br> Duelistas: <input type="text" name='duelistas'></br> <input type='submit' name='botao' value='Salvar'> </form><file_sep><?php class Armas { private $id; private $sub; private $fuzis; private $pistolas; public function __construct($id = false) { if ($id) { $sql = "SELECT * FROM armas WHERE id_armas = :id"; $stmt = DB::Conexao()->prepare($sql); $stmt->bindParam(":id", $id, PDO::PARAM_INT); $stmt->execute(); foreach ($stmt as $registro) { $this->setId($registro['id_armas']); $this->setSub($registro['sub']); $this->setFuzis($registro['fuzis']); $this->setPistolas($registro['pistolas']); } } } public function setId($id) { $this->id = $id; } public function setSub($string) { $this->sub = $string; } public function setFuzis($fuzis) { $this->fuzis = $fuzis; } public function setPistolas($qnt) { $this->pistolas = $qnt; } public function setEscopetas($qnt) { $this->escopetas = $qnt; } public function setRifles($qnt) { $this->rifles = $qnt; } public function getId() { return $this->id; } public function getSub() { return $this->sub; } public function getFuzis() { return $this->fuzis; } public function getPistolas() { return $this->pistolas; public static function listar() { $sql = "SELECT * FROM armas"; $stmt = DB::conexao()->prepare($sql); $stmt->execute(); $registros = $stmt->fetchAll(PDO::FETCH_ASSOC); if ($registros) { $itens = array(); foreach ($registros as $registro) { $objTemporario = new Armas(); $objTemporario->setId($registro['id_armas']); $objTemporario->setSub($registro['sub']); $objTemporario->setFuzis($registro['fuzis']); $objTemporario->setPistolas($registro['pistolas']); $itens[] = $objTemporario; } return $itens; } return false; } public function adicionar() { try { $sql = "INSERT INTO armas (sub, fuzis, pistolas) VALUES (:sub, :fuzis, :pistolas)"; $conexao = DB::conexao(); $stmt = $conexao->prepare($sql); $stmt->bindParam(':sub', $this->sub); $stmt->bindParam(':fuzis', $this->fuzis); $stmt->bindParam(':pistolas', $this->pistolas); $stmt->execute(); return $conexao->lastInsertId(); } catch (PDOException $e) { echo "ERRO AO ADICIONAR: " . $e->getMessage(); } } public function atualizar() { if ($this->id) { try { $sql = "UPDATE armas SET sub = :sub, fuzis = :fuzis, pistolas = :pistolas, WHERE id_armas = :id"; $stmt = DB::conexao()->prepare($sql); $stmt->bindParam(':sub', $this->sub); $stmt->bindParam(':fuzis', $this->fuzis); $stmt->bindParam(':id', $this->id); $stmt->bindParam(':pistolas', $this->pistolas); $stmt->execute(); } catch (PDOExcetion $e) { echo "ERRO AO ATUALIZAR: " . $e->getMessage(); } } } public function excluir() { if ($this->id) { try { $sql = "DELETE FROM armas WHERE id_armas = :id"; $stmt = DB::Conexao()->prepare($sql); $stmt->bindParam(":id", $this->id); $stmt->execute(); } catch (PDOExcetion $e) { echo "ERRO AO EXCLUIR: " . $e->getMessage(); } } } } <file_sep><?php include "classes/DB.class.php"; include "classes/Agentes.class.php"; $agentes = Agentes::listar(); ?> <table> <tr> <th>ID</th> <th>SENTINELAS</th> <th>CONTROLADORES</th> <th>DUELISTAS</th> </tr> <?php public static function listar(){ $sql = "SELECT * FROM modulos"; $stmt = DB::conexao()->prepare($sql); $stmt->execute(); $registros = $stmt->fetchAll(); if ($agentes) { $itens = array(); foreach ($agentes as $agentes) { ?> <tr> <td><?php echo $agentes->setId(); ?></td> <td><?php echo $agentes->setSentinelas(); ?></td> <td><?php echo $agentes->setControladores(); ?></td> <td><?php echo $agentes->setDuelistas(); ?></td> <td><?php echo $itens[] = $agentes; ?></td> </tr> } } </table> ?><file_sep><?php include "classes/DB.class.php"; include "classes/Armas.class.php"; $armas = Armas::listar(); ?> <table> <tr> <th>ID</th> <th>SUB</th> <th>FUZIS</th> <th>PISTOLAS</th> </tr> <?php if ($armas) { foreach ($armas as $armas) { ?> <tr> <td><?php echo $armas->getId(); ?></td> <td><?php echo $armas->getSub(); ?></td> <td><?php echo $armas->getFuzis(); ?></td> <td><?php echo $armas->getPistolas(); ?></td> <td><a href="?modulo=armas&acao=editar&id=<?php echo $armas->getId(); ?>">Editar</a></td> <td><a href="?modulo=armas&acao=excluir&id=<?php echo $armas->getId(); ?>">Excluir</a></td> </tr> <?php } } else { echo "<tr><td colspan='4'> Nenhum Registro Encontrado.</td></tr>"; } ?> </table><file_sep> <?php include "classes/DB.class.php"; include "classes/Armas.class.php"; ?> <?php if (isset($_GET['id']) and is_numeric($_GET['id'])) { $armas = new Armas($_GET['id']); $armas->excluir(); ?> <?php }?><file_sep> <?php session_start(); if (isset($_SESSION['login']) && isset($_SESSION['id'])) { ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 2 | Blank Page</title> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <link rel="stylesheet" href="publico/css/bootstrap.min.css"> <link rel="stylesheet" href="publico/css/AdminLTE.min.css"> <link rel="stylesheet" href="publico/css/all-skins.min.css"> </head> <body class="hold-transition skin-blue sidebar-mini"> <!-- Site wrapper --> <div class="wrapper"> <header class="main-header"> <!-- Logo --> <a href="../../index2.html" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>A</b>LT</span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>ValConsulta</span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> </nav> </header> <!-- Left side column. contains the sidebar --> <aside class="main-sidebar"> <!-- sidebar: style can be found in sidebar.less --> <section class="sidebar"> <!-- Sidebar user panel --> <div class="user-panel"> <div class="pull-left image"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle"> </div> <div class="pull-left info"> <p><NAME></p> <a href="#"><i class="fa fa-circle text-success"></i> Online</a> </div> </div> <ul class="sidebar-menu" data-widget="tree"> <li class="header">MAIN NAVIGATION</li> <li> <a href="?modulo=armas&acao=listar"> <i class="fa fa-list"></i> <span>Armas Listar</span> </a> </li> <li> <a href="?modulo=armas&acao=adicionar"> <i class="fa fa-list"></i> <span>Armas Adicionar</span> </a> </li> <li> <a href="?modulo=agentes&acao=listar"> <i class="fa fa-list"></i> <span>Agentes Listar</span> </a> </li> <li> <a href="?modulo=agentes&acao=adicionar"> <i class="fa fa-list"></i> <span>Agentes Adicionar</span> </a> </li> </ul> </section> <!-- /.sidebar --> </aside> <!-- =============================================== --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <section class="content"> <?php if (isset($_GET['modulo'])) {$modulo = $_GET['modulo'];} else { $modulo = "false";} if (isset($_GET['acao'])) {$acao = $_GET['acao'];} else { $acao = 'listar';} ?> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <section class="content"> <?php if(isset($_GET[“modulo”])){ $modulo = $_GET[“modulo”]} else { $modulo = false;} if(isset($_GET[“acao”])){ $acao= $_GET[“acao”]} else { $acao= listar;} if($modulo){ if(file_exists(“modulos/”.$modulo.”/”.$acao.”.php”)){ $permissao = verificaPermissao($_SESSION[‘id_grupo’], $modulo, $acao); if($permissao ){ include(“modulos/”.$modulo.”/”.$acao.”.php”); }else{ echo “Página Solicitada não Existe”; } } ?> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div class="pull-right hidden-xs"> <b>Version</b> 2.4.13 </div> <strong>Copyright &copy; 2014-2021 <NAME></strong> Todos os Direitos Reservados. </footer> </div> </body> </html> <?php } else { echo "Você precisa efetuar o login. <a href='login.php'>VOLTAR</a>"; } ?> <file_sep><?php class Agentes { private $id; private $sentinelas; private $controladores; private $duelistas; public function __construct($id = false) { if ($id) { $sql = "SELECT * FROM agentes WHERE id_agentes = :id"; $stmt = DB::Conexao()->prepare($sql); $stmt->bindParam(":id", $id, PDO::PARAM_INT); $stmt->execute(); foreach ($stmt as $registro) { $this->setId($registro['id_agentes']); $this->setSentinelas($registro['sentinelas']); $this->setControladores($registro['controladores']); $this->setDuelistas($registro['duelistas']); } } public function setId($id) { $this->id = $id; } public function setSentinelas($string) { $this->sentinelas = $string; } public function setControladores($controladores) { $this->controladores = $controladores; } public function setDuelistas($qnt) { $this->duelistas = $qnt; } public function setIniciadores($qnt) { $this->iniciadores = $qnt; } public function setEspectadores($qnt) { $this->espectadores = $qnt; } public function getId() { return $this->id; } public function getSentinelas() { return $this->sentinelas; } public function getControladores() { return $this->controladores; } public function getDuelistas() { return $this->duelistas; public static function listar() { $sql = "SELECT * FROM agentes"; $stmt = DB::conexao()->prepare($sql); $stmt->execute(); $registros = $stmt->fetchAll(PDO::FETCH_ASSOC); if ($registros) { $itens = array(); foreach ($registros as $registro) { $objTemporario = new Agentes(); $objTemporario->setId($registro['id_agentes']); $objTemporario->setSentinelas($registro['sentinelas']); $objTemporario->setControladores($registro['controladores']); $objTemporario->setDuelistas($registro['duelistas']); $itens[] = $objTemporario; } return $itens; } return false; } public function adicionar() { try { $sql = "INSERT INTO agentes (sentinelas, controladores, duelistas) VALUES (:sentinelas, :controladores, :duelistas, )"; $conexao = DB::conexao(); $stmt = $conexao->prepare($sql); $stmt->bindParam(':sentinelas', $this->sentinelas); $stmt->bindParam(':controladores', $this->controladores); $stmt->bindParam(':duelistas', $this->duelistas); $stmt->execute(); return $conexao->lastInsertId(); } catch (PDOException $e) { echo "ERRO AO ADICIONAR: " . $e->getMessage(); } } public function atualizar() { if ($this->id) { try { $sql = "UPDATE agentes SET sentinelas = :sentinelas, controladores = :controladores, duelistas = :duelistas, WHERE id_agentes = :id"; $stmt = DB::conexao()->prepare($sql); $stmt->bindParam(':sentinelas', $this->sentinelas); $stmt->bindParam(':controladores', $this->controladores); $stmt->bindParam(':id', $this->id); $stmt->bindParam(':duelistas', $this->duelistas); $stmt->execute(); } catch (PDOExcetion $e) { echo "ERRO AO ATUALIZAR: " . $e->getMessage(); } } } public function excluir() { if ($this->id) { try { $sql = "DELETE FROM agentes WHERE id_agentes = :id"; $stmt = DB::Conexao()->prepare($sql); $stmt->bindParam(":id", $this->id); $stmt->execute(); } catch (PDOExcetion $e) { echo "ERRO AO EXCLUIR: " . $e->getMessage(); } } } } <file_sep><?php public function listar($idgrupo, $idmodulo, $idacao){ $sql = "SELECT * FROM operacoes WHERE fk_grupo = '$idgrupo' AND fk_modulo = '$idmodulo' AND fk_permissao = $idacao"; $stmt = DB::conexao()->prepare($sql); $stmt->execute(); $registros = $stmt->fetchAll(PDO::FETCH_ASSOC); } ?> <?php public function listar($idgrupo, $idmodulo, $idacao){ if($registros){ $itens = array(); foreach($registros as $objeto){ $temporario = new Operacao(); $temporario->setId($objeto['id_operacao']); $temporario->setFkGrupo($objeto['fk_grupo']); $temporario->setFkModulo($objeto['fk_modulo']); $temporario->setFkPermissao($objeto['fk_permissao']); $itens[] = $temporario; } return $itens; } return false; } ?><file_sep><?php public function adicionar(){ $sql = "INSERT INTO operacoes (fk_grupo, fk_modulo, fk_permissao) VALUES (:fk_grupo, :fk_modulo, :fk_permissao)"; $conexao = DB::conexao(); $stmt = $conexao->prepare($sql); $stmt->bindParam(':fk_grupo', $this->fkgrupo); $stmt->bindParam(':fk_modulo', $this->fkmodulo); $stmt->bindParam(':fk_permissao', $this->fkpermissao); $stmt->execute(); return $conexao->lastInsertid(); } if(isset($_POST['atualizarPermissao']) && $_POST['atualizarPermissao'] == 'Salvar'){ $listaPermissao = $_POST['listaPermissao']; foreach($listaPermissao as $itemPermissao){ $item = explode('-', $itemPermissao); $grupo = $item[0]; $modulo = $item[1]; $permissao = $item[2]; $add = new Operacao(); $add->setFkGrupo($grupo); $add->setFkModulo($modulo); $add->setFkPermissao($permissao); $add->adicionar(); } }<file_sep> <?php include "classes/DB.class.php"; include "classes/Agentes.class.php"; ?> <?php if (isset($_POST['botao']) && $_POST['botao'] == "Salvar") { $agentes = new Agentes($_POST['id']); $agentes->setSentinelas($_POST['sentinelas']); $agentes->setControladores($_POST['controladores']); $agentes->setDuelistas($_POST['duelistas']); $agentes->atualizar(); } ?> <?php if (isset($_GET['id']) and is_numeric($_GET['id'])) { $agentes = new Agentes($_GET['id']); ?> <form method='post' action=''> Sentinelas: <input type="text" name='sentinelas' value='<?php echo $agentes->getSentinelas(); ?>'></br> Controladores: <input type="text" name='controladores' value='<?php echo $agentes->getControladores(); ?>'></br> Duelistas: <input type="text" name='duelistas' value='<?php echo $agentes->getDuelistas(); ?>'></br> <input type="hidden" name='id' value='<?php echo $agentes->getId(); ?>'></br> <input type='submit' name='botao' value='Salvar'> </form> <?php }?><file_sep><?php public function verificaPermissao($idgrupo, $modulo, $acao){ $sql = "SELECT * FROM operacoes INNER JOIN modulos ON modulos.id_modulo = operacoes.fk_modulo INNER JOIN permissoes ON permissoes.id_permissao = operacao.fk_permissao WHERE modulos.diretorio = ‘$modulo’ AND permissoes.acao = ‘$acao’ AND operacoes.fk_grupo = $idgrupo"; $stmt = DB::conexao()->prepare($sql); $stmt->execute(); $rg = $stmt->fetchAll(PDO::FETCH_ASSOC); if($rg){ return true; } return false; } ?><file_sep> <?php if (isset($_POST['botao']) && $_POST['botao'] == "Salvar") { include 'classes/Armas.class.php'; $armas = new Armas(); $armas->setSub($_POST['sub']); $armas->setFuzis($_POST['fuzis']); $armas->setPistolas($_POST['pistolas']); $armas->adicionar(); } ?> <form method='post' action=''> Sub: <input type="text" name='sub'></br> Fuzis: <input type="text" name='fuzis'></br> Pistolas: <input type="text" name='pistolas'></br> <input type='submit' name='botao' value='Salvar'> </form><file_sep><?php foreach ($modulos as $modulo) { $permissoes = Permissao::listar(); if ($permissoes) { foreach ($permissoes as $permissao) { $verifica = Operacao::verificaPermissao($idgrupo, $modulo->getDiretorio(), $acao->getAcao()); ?> <input<?php if ($verifica) {echo 'checked disabled';}?> type="checkbox" name='listaPermissao[]‘ value='<?php echo $idgrupo; ?>-<?php echo $modulo->getId(); ?>-<?php echo $acao->getId(); ?>'> <?php echo $acao->getDescricao() ?> <?php if($verifica){ echo " <a href='?idgrupo=".$idgrupo.“ &idmodulo=".$modulo->getId().“ &idpermissao=".$acao->getId().“ &remove=true'>(x)</a> "; }?> ] } <form method='post'> <?php ?> <input type='submit' name='atualizarPermissao' value='Salvar'>"; <form><file_sep> <?php include "classes/DB.class.php"; include "classes/Armas.class.php"; ?> <?php if (isset($_POST['botao']) && $_POST['botao'] == "Salvar") { $armas = new Armas($_POST['id']); $armas->setSub($_POST['sub']); $armas->setFuzis($_POST['fuzis']); $armas->setPistolas($_POST['pistolas']); $armas->atualizar(); } ?> <?php if (isset($_GET['id']) and is_numeric($_GET['id'])) { $armas = new Armas($_GET['id']); ?> <form method='post' action=''> Sub: <input type="text" name='sub' value='<?php echo $armas->getSub(); ?>'></br> Fuzis: <input type="text" name='fuzis' value='<?php echo $armas->getFuzis(); ?>'></br> Pistolas: <input type="text" name='pistolas' value='<?php echo $armas->getPistolas(); ?>'></br> <input type='submit' name='botao' value='Salvar'> </form> <?php }?>
1750a935c603b21c580c844d824f1e5016fa05d3
[ "PHP" ]
17
PHP
Felkarto/Sistema-de-Permissao
c540d054e5df309614d8353b1ee35895d35bf35e
27bd50cd676927af408a1e2df21a70d424e3f71f
refs/heads/master
<file_sep>import { createStore, applyMiddleware, compose } from 'redux'; import createSagaMiddleware from 'redux-saga'; import { persistStore, persistReducer } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; import rootReducer from './module/rootReducer'; import rootSaga from './module/rootSaga'; // monitorando a integração SAGA x Reatotron const sagaMonitor = process.env.NODE_ENV === 'development' ? console.tron.createSagaMonitor() : null; const sagaMiddleware = createSagaMiddleware({ sagaMonitor, }); // Conectando com o Reactotron const enhancer = process.env.NODE_ENV === 'development' ? compose(console.tron.createEnhancer(), applyMiddleware(sagaMiddleware)) : applyMiddleware(sagaMiddleware); const persistConfig = { key: 'cart', storage, }; const persistedReducer = persistReducer(persistConfig, rootReducer); const store = createStore(persistedReducer, enhancer); const persistor = persistStore(store); // startando o root sagaMiddleware.run(rootSaga); export { store, persistor }; <file_sep>import styled from 'styled-components'; import { Link } from 'react-router-dom'; export const Container = styled.header` display: flex; justify-content: space-between; align-items: center; width: 100%; height: 55px; position: relative; .top-bar { width: 100%; position: absolute; top: 0; left: 0; height: 100%; .top-bar-fixed { background: #fff; width: 100%; height: 55px; padding-top: 27.5px; position: fixed; z-index: 999; top: 0; left: 0; box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.1); } #container { display: flex; justify-content: space-between; align-items: center; height: 100%; } } `; export const Logo = styled(Link)` text-decoration: none; color: #000; font-weight: bold; font-size: 25px; `; export const Cart = styled(Link)` display: flex; align-items: center; text-decoration: none; transition: opacity 0.2s; position: relative; &:hover { opacity: 0.7; } > div { text-align: center; margin-right: 10px; position: relative; span { position: absolute; left: -8px; border-radius: 10px; padding: 2px 7px; background: #4876ee; font-size: 12px; color: #fff; font-weight: bold; } } `; export const Search = styled.div` display: flex; width: 50%; > div { display: flex; align-items: center; width: 100%; input { text-align: center; width: 100%; border: 0; height: 55px; } } `; <file_sep>import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import api from '../../service/api'; import { ProductList, Header, Products, Filter } from './styles'; import indisponivel from '../../assets/images/imagemindisponivel.png'; import { ordenationASC, repeatDelete } from '../../util/format'; export default function Home() { const [products, setProducts] = useState([]); const [ordenationColor, setOrdenationColor] = useState([]); useEffect(() => { async function loadProducts() { const response = await api.get('products'); const data = response.data.map(product => ({ ...product, color: product.color, })); const temp = data.map(color => ({ cor: color.color })); const orderColor = ordenationASC(temp); const repeatColor = repeatDelete(orderColor); setProducts(data); setOrdenationColor(repeatColor); } loadProducts(); }, []); return ( <> <Header> <div id="container"> <div className="title-page"> <h1>All Products</h1> <span> Lorem ipsum dolor sit amet consectetur, adipisicing elit. </span> </div> </div> </Header> <Products id="container"> <div id="bar-top"> <div className="location"> <span>Home > Shop</span> </div> <div className="products-count"> <span> Mostrando 1 - {products.length} de {products.length} resultados </span> </div> </div> <div id="filters-and-products"> <Filter> <div> <input type="checkbox" className="checkbox" id="post-1" /> <label htmlFor="post-1" className="color-strong"> Colors </label> <ul> {ordenationColor.map(product => ( <li key={product.cor}> <Link to={`/products/filter/color/${encodeURIComponent( product.cor )}`} > {product.cor} </Link> </li> ))} </ul> </div> </Filter> <ProductList> {products.map(product => ( <li key={product.code_color}> <Link to={`/product/${encodeURIComponent(product.code_color)}`}> {product.image !== '' ? ( <img src={product.image} alt={product.name} /> ) : ( <img src={indisponivel} alt={product.name} /> )} <div> <strong>{product.name}</strong> </div> {product.actual_price !== product.regular_price ? ( <> <div className="discount_percentage"> <span>{product.discount_percentage}</span> </div> <div className="price"> <span className="regular_price"> {product.regular_price} </span> <span className="actual_price"> {product.actual_price} </span> </div> </> ) : ( <div className="price"> <span className="actual_price"> {product.actual_price} </span> </div> )} </Link> </li> ))} </ProductList> </div> </Products> </> ); } <file_sep>import styled from 'styled-components'; export const Container = styled.header` display: flex; justify-content: center; align-items: center; width: 100%; position: relative; background: #222; margin-top: 50px; text-align: center; div { display: block; margin: 35px 0; .logo { color: #fff; font-weight: bold; font-size: 30px; } .midias ul { display: flex; margin: 20px 0; li { display: flex; justify-content: center; align-items: center; list-style: none; width: 50px; height: 50px; border: 1px solid #fff; margin: 0 10px; border-radius: 50%; cursor: pointer; transition: background 0.2s; &:hover { background: #4876ee; color: #fff; border: 1px solid #4876ee; } i { color: #fff; font-size: 20px; } } } span { color: #fff; font-size: 15px; } } `; <file_sep>import React from 'react'; import { Switch, Route } from 'react-router-dom'; import Home from './pages/Home'; import Cart from './pages/Cart'; import Product from './pages/Product'; import Filters from './pages/Filters/Color'; import Search from './pages/Filters/Search'; export default function Routes() { return ( /* Switch - Obriga a utilização de apenas um rota por vez Route - Define a rota */ <Switch> <Route path="/" exact component={Home} /> <Route path="/cart" component={Cart} /> <Route path="/product/:product" component={Product} /> <Route path="/products/filter/color/:filter" component={Filters} /> <Route path="/search/:search" component={Search} /> </Switch> ); } <file_sep>import React from 'react'; import { Container } from './styles'; export default function Footer() { return ( <Container> <div> <div className="logo">Co.</div> <div className="midias"> <ul> <li className="midia"> <i className="fa fa-facebook" /> </li> <li className="midia"> <i className="fa fa-google-plus" /> </li> <li className="midia"> <i className="fa fa-instagram" /> </li> <li className="midia"> <i className="fa fa-twitter" /> </li> </ul> </div> <span>© 2020 Co.</span> </div> </Container> ); } <file_sep>import { call, select, put, all, takeLatest } from 'redux-saga/effects'; import api from '../../../service/api'; import history from '../../../service/history'; import { addToCartSuccess, updateAmountSuccess } from './actions'; function* addToCart({ id, skuID }) { // VERIFICANDO SE O PRODUTO ADICIONADO JÁ NÃO EXISTE NO CARRINHO const productExists = yield select(state => state.cart.find(p => p.code_color === id) ); const currentAmount = productExists ? productExists.amount : 0; const amount = currentAmount + 1; if (productExists) { const findSizes = yield select(state => state.cart.find(p => p.sizes.sku === skuID) ); if (findSizes) { yield put(updateAmountSuccess(skuID, amount)); history.push('/cart'); } else { const response = yield call(api.get, `/products`); const findProd = response.data.find(prod => prod.code_color === id); const skusMap = findProd.sizes.map(sizes => ({ ...sizes, })); const sizeSelection = skusMap.find(skuCode => skuCode.sku === skuID); const data = { ...findProd, sizes: sizeSelection, amount: 1, }; history.push('/cart'); yield put(addToCartSuccess(data)); } } else { const response = yield call(api.get, `/products`); const findProd = response.data.find(prod => prod.code_color === id); const skusMap = findProd.sizes.map(sizes => ({ ...sizes, })); const sizeSelection = skusMap.find(skuCode => skuCode.sku === skuID); const data = { ...findProd, sizes: sizeSelection, amount: 1, }; history.push('/cart'); yield put(addToCartSuccess(data)); } } function* updateAmount({ id, amount }) { if (amount <= 0) return; yield put(updateAmountSuccess(id, amount)); } export default all([ takeLatest('@cart/ADD_REQUEST', addToCart), takeLatest('@cart/UPDATE_AMOUNT_REQUEST', updateAmount), ]); <file_sep># Sobre Aplicação React desenvolvida com o objetivo de simular o funcionamento básico de uma loja virtual. A Aplicação conta com um catálogo de produtos, uma página de detalhes dos produtos, um carrinho de compras, além de alguns filtros de pesquisa. # Iniciando o Projeto ## Instalando Para inicializar o arquivo package.json e instalar todas as dependências digite o comando abaixo: ```yarn install``` ou ```yarn``` ## Inicializando o projeto Basta rodar o comando abaixo e uma nova aba com a aplicação irá abrir no seu navegador ```yarn start``` Para iniciar a API da aplicação e carregar os produtos digite o comando abaixo em uma nova aba do terminal: ```json-server server.json -p 3333``` A aplicação irá rodar na porta 3333. ## Ferramentas utilizadas - React Router Dom; - Styled Components; - React Icons; - Polished; - Axios; - Json Server; - Immer; - React Toastify; - History; - Proptypes; - Reactotron; - Redux; - Redux Saga; - Redux Persist. <file_sep>import styled from 'styled-components'; export const Header = styled.div` background-color: #f7ebf5; height: 180px; margin-bottom: 50px; #container { padding-bottom: 0 !important; } > div { height: 100%; display: flex; justify-content: center; align-items: center; .title-page { display: block; text-align: center; width: 100%; h1 { font-family: Poppins; font-size: 55.8px; font-weight: 700; line-height: 80px; margin-bottom: 8px; } span { font-family: 'Poppins', sans-serif; font-size: 16px; text-transform: capitalize; letter-spacing: 0; line-height: 30px; font-weight: 500; } } } @media screen and (max-width: 600px) { > div { .title-page { h1 { font-size: 45px; line-height: 70px; } span { font-size: 14px; } } } } `; export const Products = styled.div` display: block; #bar-top { display: flex; justify-content: space-between; align-items: center; padding: 15px 0; margin-bottom: 40px; border-bottom: 1px solid #eee; } .location, .products-count { font-size: 13px; color: #808080; } #filters-and-products { display: flex; justify-content: space-between; } @media screen and (max-width: 1023px) { #filters-and-products { display: block; } #bar-top { margin-bottom: 25px; } } @media screen and (max-width: 600px) { #filters-and-products { display: block; } } `; export const Filter = styled.div` display: flex; width: 25%; div { display: block; width: 100%; .checkbox { display: none; } .color-strong { cursor: auto; font-size: 15px; color: #808080; font-weight: 600; } ul { display: block; width: 100%; margin-top: 25px; } li { list-style: none; a { text-decoration: none; color: #000; font-size: 14px; font-weight: 600; line-height: 25px; text-transform: uppercase; &:hover { color: #4876ee; } } } } @media screen and (max-width: 1023px) { display: block; width: 100%; div { border-bottom: 1px solid #eee; ul { display: block; width: 100%; margin: 12.5px 0; opacity: 0; max-height: 0; font-size: 0; } .checkbox { display: none; } .checkbox:checked ~ ul { opacity: 1; font-size: inherit; max-height: 999em; margin-bottom: 25px; } .checkbox ~ .color-strong:before { content: '+ '; } .checkbox:checked ~ .color-strong:before { content: '- '; } .color-strong { cursor: pointer; font-size: 15px; color: #808080; font-weight: 600; } } } `; export const ProductList = styled.ul` display: grid; height: 100%; grid-template-columns: repeat(3, 1fr); grid-gap: 7px; list-style: none; width: 75%; li { display: flex; flex-direction: column; background: #fff; padding: 20px; position: relative; border-radius: 10px; margin-bottom: 25px; &:hover { width: calc(100% + 20px); margin-bottom: 0px; z-index: 99; box-shadow: 0 0 30px 0 rgba(0, 0, 0, 0.1); } img { width: 100%; align-self: center; max-width: 250px; } /* > - faz com que os estilos só funcionem dentro da li */ strong { font-size: 15px; line-height: 20px; color: #333; } .price { font-size: 14px; font-weight: 500; margin-top: 10px; display: flex; .regular_price { color: #808080; margin-right: 10px; text-decoration: line-through; opacity: 0.5; } .actual_price { color: #222; } } .discount_percentage { display: flex; position: absolute; background-color: #ff0000; border-radius: 4px; top: 30px; left: 30px; span { color: #fff; font-size: 14px; padding: 0 10px; font-weight: 600; } } a { text-decoration: none; color: #111; } } @media screen and (max-width: 1023px) { width: 100%; margin-top: 25px; #container { padding-right: 0; } li { margin-bottom: 0px; text-align: center; &:hover { width: 100%; box-shadow: 0 0 30px 0 rgba(0, 0, 0, 0.1); } img { /* max-width: 100%; */ } div { text-align: left; } } } @media screen and (max-width: 600px) { grid-template-columns: repeat(2, 1fr); grid-gap: 0px; width: 100%; #container { padding-right: 0; } li { margin-bottom: 0px; &:hover { width: 100%; box-shadow: 0 0 30px 0 rgba(0, 0, 0, 0.1); } } } `;
7d91b64ce733bd8ea084c148dcdd885c499ab0ba
[ "JavaScript", "Markdown" ]
9
JavaScript
lucasbcosta92/basic-commerce
d1b000503d833ac0618b7e684dcdf22fd188357e
660f14c12470ed0bc4e2a90821d6db732fc884cc
refs/heads/main
<repo_name>Dinxor/tstore<file_sep>/tasks/backup.sql backup database test to disk = 'c:\Backup\test.bak' WITH INIT, NOFORMAT, SKIP, NOUNLOAD <file_sep>/modules/static/js/temp.js $(document).ready(function(){ // Create a client instance var clientId = 'a:myOrgId:'+Math.random().toString(16).substr(2, 8); client = new Paho.Client ("10.0.0.4", 1884, clientId); // set callback handlers client.onConnectionLost = onConnectionLost; client.onMessageArrived = onMessageArrived; // connect the client client.connect({onSuccess:onConnect, userName : "test", password : "<PASSWORD>"}); // called when the client connects function onConnect() { // Once a connection has been made, make a subscription and send a message. console.log("onConnect"); client.subscribe("oil/#"); } // called when the client loses its connection function onConnectionLost(responseObject) { if (responseObject.errorCode !== 0) { console.log("onConnectionLost:"+responseObject.errorMessage); } } function onMessageArrived(message) { var dest = message.destinationName; var mrows = dest.split('/', 4) var rowId = '#'+mrows[1]+mrows[2]+mrows[3]; // console.log("onMessageArrived:"+message.destinationName+" id: "+rowId); $(rowId).html(message.payloadString); } });<file_sep>/modules/sqlite.py import os.path from time import sleep import sqlite3 def init_db(file): if os.path.isfile(file): conn = sqlite3.connect(file) else: conn = sqlite3.connect(file) cur = conn.cursor() cur.execute('''CREATE TABLE storage (id integer primary key autoincrement, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, code int, value int)''') conn.commit() return conn def sqlite(tt): name = 'sqlite' sleep(1) cnt = 0 source = tt[name].get('queue') db_file = tt[name].get('filename') conn = init_db(db_file) cur = conn.cursor() mode = tt['modules'][name] if mode != '1': tt[name].update({'is_enable': False}) while 1: if not tt[name].get('is_working', False) and tt[name].get('is_enable', False): tt[name].update({'is_working': True}) elif tt[name].get('is_working', False) and not tt[name].get('is_enable', False): tt[name].update({'is_working': False}) while not source.empty(): new_data = source.get(block=True) if tt[name].get('is_enable', False): if new_data[0] == 'web': code, val = new_data[1] print(code, val) cur.execute("INSERT INTO storage (code, value) VALUES (%s, %s)" % (code, val)) conn.commit() cnt += 1 else: pass tt[name].update({'cnt': cnt}) sleep(1) <file_sep>/modules/manager_modbus.py import time from channels.modbus import modb, get_data def manager(tt): name = 'manager' tt[name].update({'is_working': True}) direction = tt[name]['target'] target = tt[direction]['queue'] cnt = 0 prev_s = 0 state1 = 3 addr = tt['plc2']['addr'] port = int(tt['plc2']['port']) start = int(tt['plc2']['start']) amount = int(tt['plc2']['amount']) while tt[name].get('is_enable', False): if state1 > 0: conn1 = modb(addr, port) if curr_s - prev_s > 59: state1 = get_data(conn1, start, amount, target, 'modbus') prev_s = curr_s cnt += 1 tt[name].update({'cnt': cnt}) time.sleep(1) conn1.close() tt[name].update({'is_working': False}) tt[name].pop('is_enable') <file_sep>/modules/readmqtt.py from time import sleep import paho.mqtt.client as mqtt def on_message(client, userdata, message): target = userdata['target'] target.put(['mqtt', [str(message.topic), str(message.payload.decode("utf-8"))]], block=True) def readmqtt(tt): name = 'readmqtt' tt[name].update({'is_working':True}) tt[name].update({'cnt':0}) saver_input = tt['saver']['queue'] ip=tt['mqtt1']['ip'] port=int(tt['mqtt1']['port']) timeout=int(tt['mqtt1']['timeout']) username=tt['mqtt1']['username'] password=tt['<PASSWORD>']['<PASSWORD>'] read_topic=tt['mqtt1']['read_topic'] mq_userdata = {'target':saver_input} client = mqtt.Client(userdata=mq_userdata) client.on_message=on_message client.username_pw_set(username=username,password=password) while tt[name].get('is_enable', False): try: client.connect(ip,port,timeout) client.subscribe(read_topic) client.loop_start() while tt[name].get('is_enable', False): sleep(1) except: sleep(5) client.loop_stop() client.disconnect() tt[name].update({'is_working':False}) tt[name].pop('is_enable') <file_sep>/modules/manager.py import time def manager(tt): name = 'manager' tt[name].update({'is_working': True}) direction = tt[name]['target'] target = tt[direction]['queue'] cnt = 0 prev_s = 0 while tt[name].get('is_enable', False): curr_s = int(time.time()) if curr_s - prev_s > 59: tstamp = time.strftime("%d.%m.%Y %H:%M:%S") target.put(['manager', tstamp], block=True) prev_s = curr_s time.sleep(1) cnt += 1 tt[name].update({'cnt': cnt}) tt[name].update({'is_working': False}) tt[name].pop('is_enable') <file_sep>/modules/scheduler.py import os import time import subprocess def scheduler(tt): name = 'scheduler' tt[name].update({'is_working': True}) direction = tt[name]['target'] target = tt[direction]['queue'] cnt = 0 prev_s = 0 state = '' tasks = tt['tasks'] while tt[name].get('is_enable', False): curr_s = int(time.time()) if curr_s - prev_s > 59: currtime = time.strftime('%H%M') if currtime in tasks.keys(): command = tasks[currtime] try: rezult = subprocess.run([command], timeout=59, capture_output=True) if rezult.returncode ==0: state = 'OK' else: state = 'Code %s' % (rezult.returncode) except: state = 'Timeout' target.put(['scheduler', [currtime, state]], block=True) prev_s = curr_s cnt += 1 time.sleep(1) if state != '': print(state) state = '' tt[name].update({'cnt': cnt}) tt[name].update({'is_working': False}) tt[name].pop('is_enable') <file_sep>/modules/manager_opc.py import time from channels.opc import opc_client, get_opc_data def manager(tt): name = 'manager' tt[name].update({'is_working': True}) saver_input = tt['saver']['queue'] cnt = 0 prev_s = 0 state1 = 3 url = tt['opc']['url'] nodes_ = tt['opc']['nodes'] nodes = list(nodes_.split(',')) while tt[name].get('is_enable', False): if state1 > 0: conn1 = opc_client(url) curr_s = int(time.time()) if curr_s - prev_s > 59: state1 = get_opc_data(conn1, nodes, saver_input, 'opc') prev_s = curr_s cnt += 1 tt[name].update({'cnt': cnt}) time.sleep(1) conn1.disconnect() tt[name].update({'is_working': False}) tt[name].pop('is_enable') <file_sep>/channels/modbus.py import modbus_tk import modbus_tk.defines as cst from modbus_tk import modbus_tcp, hooks def modb(host, port): def on_before_connect(args): master._host = host master._port = port hooks.install_hook("modbus_tcp.TcpMaster.before_connect", on_before_connect) def on_after_recv(args): response = args[1] hooks.install_hook("modbus_tcp.TcpMaster.after_recv", on_after_recv) try: master = modbus_tcp.TcpMaster() master.set_timeout(5.0) return master except Exception as msg: print('error', msg) return '' def get_data(conn, start, amount, target, label): try: rez = list(conn.execute(1, cst.READ_HOLDING_REGISTERS, start, amount)) target.put([label, rez], block=True) except: return 1 return 0 <file_sep>/channels/snap.py import snap7 import struct def get_float(plc_addr, plc_area, target, label): try: plc = snap7.client.Client() plc.connect(*plc_addr) rezult = plc.read_area(*plc_area) plc.disconnect() rez = [] for i in range(0, len(rezult), 4): f = int.from_bytes([rezult[x] for x in range (i, i+4)], byteorder='big') tval = struct.unpack('f', struct.pack('I', f))[0] rez.append(round(tval, 2)) target.put([label, rez], block=True) except: return 1 return 0 def get_int(plc_addr, plc_area, target, label): try: plc = snap7.client.Client() plc.connect(*plc_addr) rezult = plc.read_area(*plc_area) plc.disconnect() rez = [] for i in range(0, len(rezult), 2): f = int.from_bytes([rezult[x] for x in range (i, i+2)], byteorder='big') rez.append(f) target.put([label, rez], block=True) except: return 1 return 0 <file_sep>/modules/sendmqtt.py from time import sleep import paho.mqtt.client as mqtt def sendmqtt(tt): name = 'sendmqtt' cnt = 0 ip=tt['mqtt1']['ip'] port=int(tt['mqtt1']['port']) timeout=int(tt['mqtt1']['timeout']) username=tt['mqtt1']['username'] password=tt['mqtt1']['password'] source = tt[name].get('queue') client = mqtt.Client() client.username_pw_set(username=username,password=password) while 1: if not tt[name].get('is_working', False) and tt[name].get('is_enable', False): tt[name].update({'is_working':True}) elif tt[name].get('is_working', False) and not tt[name].get('is_enable', False): tt[name].update({'is_working':False}) try: client.connect(ip,port,timeout) while not source.empty(): new_data = source.get(block=True) if tt[name].get('is_enable', False): topic, val = new_data client.publish(topic,val,qos=0,retain=True) cnt +=1 tt[name].update({'cnt':cnt}) else: pass sleep(1) except: sleep(5) <file_sep>/modules/manager_snap7.py import time from channels.snap import get_float def manager(tt): name = 'manager' tt[name].update({'is_working': True}) direction = tt[name]['target'] target = tt[direction]['queue'] cnt = 0 prev_s = 0 addr = tt['plc1']['addr'] rack = int(tt['plc1']['rack']) cpu = int(tt['plc1']['cpu']) dbnumber = int(tt['plc1']['db']) start = int(tt['plc1']['start']) amount = int(tt['plc1']['amount']) area = int(tt['plc1']['area']) plc_addr = [addr, rack, cpu] plc_area = [area, dbnumber, start, amount] while tt[name].get('is_enable', False): curr_s = int(time.time()) if curr_s - prev_s > 59: get_float(plc_addr, plc_area, target, 'test_S7') prev_s = curr_s cnt += 1 tt[name].update({'cnt': cnt}) time.sleep(1) tt[name].update({'is_working': False}) tt[name].pop('is_enable') <file_sep>/README.md # tstore Multi-source data collection system <file_sep>/modules/database.py from time import sleep import sqlalchemy as db def database(tt): name = 'database' cnt = 0 tt[name].update({'is_working': True}) source = tt[name].get('queue') db_uri = tt[name].get('uri') engine = db.create_engine(db_uri) conn = engine.connect() metadata = db.MetaData() storage = db.Table('storage', metadata, autoload=True, autoload_with=engine) while tt[name].get('is_enable', False): while not source.empty(): new_data = source.get(block=True) if tt[name].get('is_enable', False): if new_data[0] == 'web': code, val = new_data[1] conn.execute(storage.insert().values(code=code, value=val)) cnt += 1 tt[name].update({'cnt': cnt}) sleep(1) tt[name].update({'is_working': False}) tt[name].pop('is_enable') <file_sep>/channels/opc.py from opcua import Client def opc_client(url): try: client = Client(url) client.connect() return client except: return '' def get_opc_data(conn, nodes, target, label): try: rezult = [] for node in nodes: channel = conn.get_node(node) rez = channel.get_value() rezult.append(rez) target.put([label, rezult], block=True) except: return 1 return 0 <file_sep>/modules/worker.py from time import sleep def worker(tt): name = 'worker' sleep(1) cnt = 0 source = tt[name].get('queue') while 1: if not tt[name].get('is_working', False) and tt[name].get('is_enable', False): tt[name].update({'is_working':True}) elif tt[name].get('is_working', False) and not tt[name].get('is_enable', False): tt[name].update({'is_working':False}) while not source.empty(): new_data = source.get(block=True) if tt[name].get('is_enable', False): print(new_data) cnt +=1 else: pass tt[name].update({'cnt':cnt}) sleep(1) <file_sep>/modules/param.py par = {0:{'topic':'oil/boil/2/suppl'}, 1:{'topic':'oil/boil/2/ret'}, 2:{'topic':'oil/boil/1/suppl'}, 3:{'topic':'oil/boil/1/ret'}, 7:{'topic':'oil/dry/4/in1'}, 8:{'topic':'oil/dry/4/out1'}, 9:{'topic':'oil/dry/4/in2'}, 10:{'topic':'oil/dry/4/out2'}, 11:{'topic':'oil/dry/4/in3'}, 12:{'topic':'oil/dry/4/out3'}, 13:{'topic':'oil/dry/3/in1'}, 14:{'topic':'oil/dry/3/out1'}, 15:{'topic':'oil/dry/3/in2'}, 16:{'topic':'oil/dry/3/out2'}} if __name__ == '__main__': print(par[1]['topic']) <file_sep>/modules/saver.py from time import sleep from modules.param import par def saver(tt): name = 'saver' cnt = 0 tt[name].update({'is_working': True}) source = tt[name]['queue'] direction = tt[name]['target'] target = tt[direction]['queue'] while tt[name].get('is_enable', False): while not source.empty(): new_data = source.get(block=True) if new_data[0] == 'temp': rez = new_data[1] for i in range(len(rez)): param = par.get(i, '') if param != '': val = str(rez[i]) topic = param['topic'] target.put([topic, val], block=True) cnt +=1 tt[name].update({'cnt': cnt}) sleep(1) tt[name].update({'is_working': False}) tt[name].pop('is_enable') <file_sep>/modules/logger.py from time import sleep, strftime import time def logname(): return strftime('%Y%m%d')+'.txt' def logger(tt): name = 'logger' cnt = 0 logfile = None source = tt[name]['queue'] mode = tt['modules'][name] if mode != '1': tt[name].update({'is_enable': False}) while 1: if not tt[name].get('is_working', False) and tt[name].get('is_enable', False): tt[name].update({'is_working':True}) elif tt[name].get('is_working', False) and not tt[name].get('is_enable', False): tt[name].update({'is_working':False}) while not source.empty(): new_data = source.get(block=True) if tt[name].get('is_enable', False): if logfile == None: logfile = open('./logs/'+logname(), 'a') str = '%s %s' % (new_data[0], new_data[1]) logfile.write(str + '\n') cnt += 1 else: if logfile != None: logfile.close() logfile = None tt[name].update({'cnt':cnt}) sleep(1) if __name__ == '__main__': print(logname()) <file_sep>/settings.ini [MODULES] saver=1 ;sqlite=1 database=1 ;sendmqtt=1 ;readmqtt=1 manager=1 ;scheduler=1 logger=2 web=1 ; autostart: 0 - off, 1,2 - on ; mode of satrt: 1 - active, 2 - paused (if possible) [MANAGER] target=saver [SAVER] target=database [SCHEDULER] target=logger [WEB] target=database [DATABASE] uri=sqlite:///.//test.db ;uri=sqlite:///d://Work//Python//tstore//test.db ;uri=mssql+pyodbc://user:password@127.0.0.1/database?driver=SQL+Server ;uri=firebird+fdb://SYSDBA:masterkey@127.0.0.1/c:/temp/database.fb [SQLITE] ;filename=:memory: ;filename=d://Work//Python//tstore//test.db filename=.//test.db [MQTT1] ip=127.0.0.1 port=1883 timeout=60 username=test password=<PASSWORD> read_topic=temp/# [PLC1] # snap7 PLC addr=10.0.0.104 rack=0 cpu=2 db=897 start=88 amount=68 area=132 ;132=snap7.snap7types.areas.DB [PLC2] # modbus_tcp PLC addr=192.168.8.101 port=502 start=0 amount=64 [OPC] url=opc.tcp://localhost:4840 nodes=ns=2;i=2,ns=2;i=4 [TASKS] 0853=.\\tasks\\test.cmd 2244=d:\\Work\\Python\\tstore3\\tasks\\test.cmd <file_sep>/main.py from tkinter import Tk, Button, Label from threading import Thread from queue import Queue import configparser import sys import os def init_config(path): config.optionxform = str config.read(path) def maingui(): for name in tt['modules'].keys(): tt[name]['label'].config(text=str(tt[name].get('cnt', 0)), bg=('lime' if (tt[name].get('is_working', False)) else 'white')) root.after(1000, maingui) def rstart(name): if not tt[name].get('is_enable', True): tt[name].update({'is_enable': True}) elif not tt[name].get('is_enable', False): tt[name].update({'is_enable': True}) thread = Thread(target=eval(name), args=(tt,)) thread.daemon = True thread.start() def rstop(name): if tt[name].get('is_enable', False): tt[name].update({'is_enable': False}) if __name__ == '__main__': root = Tk() root.geometry('+200+200') root.overrideredirect(0) # uncomment for minimize # root.iconify() tt = {} modules = [] if len(sys.argv) < 2: path = './settings.ini' else: print(sys.argv[1]) path = './%s' % (sys.argv[1]) if not os.path.exists(path): print('Settings file %s not found' % (path)) sys.exit() config = configparser.ConfigParser() init_config(path) for section in config.sections(): tt.update({section.lower():dict(config[section])}) if section == 'MODULES': for key in config[section]: modules.append([key, config[section][key]]) exec('from modules.%s import %s' % (key, key)) for [name, autostart] in modules: module = tt.get(name, {}) q = Queue() module.update({'queue': q}) module.update({'cnt': 0}) tt.update({name: module}) for i, [name, autostart] in enumerate(modules): module = tt.get(name, {}) Label(text=name).grid(row=i, column=0) Button(text="Start", command=lambda x=name: rstart(x)).grid(row=i, column=1) Button(text="Stop", command=lambda x=name: rstop(x)).grid(row=i, column=2) label = Label(root, bg='white', text='0') label.grid(row=i, column=3) module.update({'label': label}) tt.update({name: module}) if autostart: rstart(name) root.after(100, maingui) root.mainloop()
b639a3fbda373b0efb5e6eac6ca682f0be789cb0
[ "SQL", "JavaScript", "Markdown", "INI", "Python" ]
21
SQL
Dinxor/tstore
ff2bb229ad2169926046076022b5a37025e98877
98b497c873124c492a9b35ff1f87df218e4d2bfd
refs/heads/master
<repo_name>anderson-joyle/D365FO-ReportLatestLogFile<file_sep>/README.md # Reporting service latest log file Opens latest reporting service log file. From Visual Studio menu bar: **Dynamics 365 > Add-ins > Report latest logs...**<file_sep>/D365FO_ReportLog/Addin/MainMenuAddIn.cs namespace Addin { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.ComponentModel.Composition; using System.Drawing; using Microsoft.Dynamics.Framework.Tools.Extensibility; using Microsoft.Dynamics.Framework.Tools.MetaModel.Core; using Microsoft.Dynamics.Framework.Tools.Configuration; using Metadata = Microsoft.Dynamics.AX.Metadata; using System.Diagnostics; /// <summary> /// TODO: Say a few words about what your AddIn is going to do /// </summary> [Export(typeof(IMainMenu))] public class MainMenuAddIn : MainMenuBase { #region Member variables private const string addinName = "Addin"; private Metadata.Providers.IMetadataProvider metadataProvider = null; private Metadata.Service.IMetaModelService metaModelService = null; private IDevelopmentConfiguration configuration = null; #endregion #region Properties /// <summary> /// Caption for the menu item. This is what users would see in the menu. /// </summary> public override string Caption { get { return AddinResources.MainMenuAddInCaption; } } /// <summary> /// Unique name of the add-in /// </summary> public override string Name { get { return MainMenuAddIn.addinName; } } public Metadata.Providers.IMetadataProvider MetadataProvider { get { if (this.metadataProvider == null) { this.metadataProvider = DesignMetaModelService.Instance.CurrentMetadataProvider; } return this.metadataProvider; } } public Metadata.Service.IMetaModelService MetaModelService { get { if (this.metaModelService == null) { this.metaModelService = DesignMetaModelService.Instance.CurrentMetaModelService; } return this.metaModelService; } } public IDevelopmentConfiguration Configuration { get { if (this.configuration == null) { this.configuration = DesignMetaModelService.Instance.CurrentConfiguration; } return this.configuration; } } #endregion #region Callbacks /// <summary> /// Called when user clicks on the add-in menu /// </summary> /// <param name="e">The context of the VS tools and metadata</param> public override void OnClick(AddinEventArgs e) { try { // TODO: Do your magic for your add-in DirectoryInfo dirInfo = Directory.GetParent(this.Configuration.SSRSReportingLocation); string logPath = Path.Combine(dirInfo.FullName,"LogFiles"); if (Directory.Exists(logPath)) { DirectoryInfo dirInfoLogs = new DirectoryInfo(logPath); var latestFile = dirInfoLogs.GetFiles() .OrderByDescending(f => f.LastWriteTime) .Where(f => f.Name.StartsWith("ReportServerService__")) .First(); if (latestFile != null) { Process.Start(latestFile.FullName); } } } catch (Exception ex) { CoreUtility.HandleExceptionWithErrorMessage(ex); } } #endregion } }
0e704f4fa7fcc70c417c6648c3ad32187daa9f00
[ "Markdown", "C#" ]
2
Markdown
anderson-joyle/D365FO-ReportLatestLogFile
ee8b89b0be2455c3e419c5cfb8ef3ba5adbdd4d8
f0f0a8666b4ffe9107b6289fcdd6f99d9c06edef
refs/heads/master
<file_sep>import datetime import zlib from hyperquant.api import Platform, Sorting, Interval, Direction from hyperquant.clients import WSClient, Endpoint, Trade, Error, \ ParamName, WSConverter, RESTConverter, PrivatePlatformRESTClient, Candle, ItemObject # REST class OkexRESTConverterV1(RESTConverter): # Main params: base_url = "https://www.okex.com/api/v{version}/" # Settings: # Converting info: # For converting to platform endpoint_lookup = { Endpoint.TRADE_HISTORY: "trades.do", Endpoint.CANDLE: "kline.do", } param_name_lookup = { ParamName.SYMBOL: "symbol", ParamName.LIMIT: 'size', ParamName.IS_USE_MAX_LIMIT: None, ParamName.INTERVAL: "type", ParamName.TIMESTAMP: None, ParamName.FROM_ITEM: "since", ParamName.FROM_TIME: "since", } param_value_lookup = { Sorting.DEFAULT_SORTING: Sorting.ASCENDING, Interval.MIN_1: "1min", Interval.MIN_3: "3min", Interval.MIN_5: "5min", Interval.MIN_15: "15min", Interval.MIN_30: "30min", Interval.HRS_1: "1hour", Interval.HRS_2: "2hour", Interval.HRS_4: "4hour", Interval.HRS_6: "6hour", Interval.HRS_12: "12hour", Interval.DAY_1: "1day", Interval.WEEK_1: "1week", } max_limit_by_endpoint = { Endpoint.TRADE_HISTORY: 60, Endpoint.CANDLE: 2000, } # For parsing param_lookup_by_class = { # Error Error: { "code": "code", "msg": "message", }, # Data Trade: { "date_ms": ParamName.TIMESTAMP, "tid": ParamName.ITEM_ID, "price": ParamName.PRICE, "amount": ParamName.AMOUNT, "type": ParamName.DIRECTION, }, Candle: [ ParamName.TIMESTAMP, ParamName.PRICE_OPEN, ParamName.PRICE_HIGH, ParamName.PRICE_LOW, ParamName.PRICE_CLOSE, ParamName.AMOUNT ], } # For converting time is_source_in_milliseconds = True # timestamp_platform_names = [ParamName.TIMESTAMP] class OkexRESTClient(PrivatePlatformRESTClient): # Settings: platform_id = Platform.OKEX version = "1" _converter_class_by_version = { "1": OkexRESTConverterV1, } # ratelimit_error_in_row_count = 0 is_source_in_timestring = True @property def headers(self): result = super().headers result["Content-Type"] = "application/x-www-form-urlencoded" return result # WebSocket class OkexWSConverterV1(WSConverter): # Main params: base_url = "wss://real.okex.com:10440/ws/v1" is_source_in_milliseconds = True endpoint_lookup = { Endpoint.TRADE: '{symbol}:deals', Endpoint.CANDLE: '{symbol}:kline_{interval}', } param_lookup_by_class = { Candle: [ ParamName.TIMESTAMP, ParamName.PRICE_OPEN, ParamName.PRICE_HIGH, ParamName.PRICE_LOW, ParamName.PRICE_CLOSE, ParamName.AMOUNT, ParamName.INTERVAL, ParamName.SYMBOL ], Trade: [ ParamName.ITEM_ID, ParamName.PRICE, ParamName.AMOUNT, ParamName.TIMESTAMP, ParamName.DIRECTION, ParamName.SYMBOL, ], } param_value_lookup = { Interval.MIN_1: "1min", Interval.MIN_3: "3min", Interval.MIN_5: "5min", Interval.MIN_15: "15min", Interval.MIN_30: "30min", Interval.HRS_1: "1hour", Interval.HRS_2: "2hour", Interval.HRS_4: "4hour", Interval.HRS_6: "6hour", Interval.HRS_12: "12hour", Interval.DAY_1: "1day", Interval.WEEK_1: "1week", } @staticmethod def convert_to_timestamp(time_str): h_m_s = list(map(int, time_str.split(':'))) now_datetime = datetime.datetime.utcnow() deal_datetime = now_datetime.replace(hour=h_m_s[0], minute=h_m_s[1], second=h_m_s[2], microsecond=0) # Hong Kong Time deal_datetime -= datetime.timedelta(hours=8) timediff = deal_datetime - datetime.datetime(1970, 1, 1) return timediff.total_seconds() * 1000 def _parse_item(self, endpoint, item_data): item_data = [self.to_float(item) for item in item_data] if endpoint == 'trade': item_data[3] = self.convert_to_timestamp(item_data[3]) item = super()._parse_item(endpoint, item_data) if item and isinstance(item, ItemObject): if isinstance(item, Trade): item.direction = Direction.BUY if item.direction == "bid" else ( Direction.SELL if item.direction == "ask" else None) return item @staticmethod def to_float(string): try: return float(string) except ValueError: return string def parse(self, endpoint, data): # Skip list checking if not data: self.logger.warning("Data argument is empty in parse(). endpoint: %s, data: %s", endpoint, data) return data return self._parse_item(endpoint, data) class OkexWSClient(WSClient): platform_id = Platform.OKEX version = "1" subscriptions_info = {} # fast track ws connections _converter_class_by_version = { "1": OkexWSConverterV1 } def subscribe(self, endpoints=None, symbols=None, **params): if not endpoints and not symbols: self._subscribe(self.current_subscriptions) else: platform_params = {self.converter._get_platform_param_name(key): self.converter._process_param_value(key, value) for key, value in params.items() if value is not None} if params else {} super().subscribe(endpoints, symbols, **platform_params) def _send_subscribe(self, subscriptions): for sub in subscriptions: sub_info = sub.split(':') event_data = { "event": "addChannel", "channel": 'ok_sub_spot_{}_{}'.format(*sub_info)} self.save_subscription(event_data["channel"], sub_info) self._send(event_data) def save_subscription(self, channel, info): # save subscription info to dict. Allow fast find subscription parameters endpoint = None interval = None self.subscriptions_info[channel] = [] if 'kline' in info[1]: endpoint = Endpoint.CANDLE interval = info[1].split('_')[1] interval = self.convert_to_interval(interval) if 'deals' in info[1]: endpoint = Endpoint.TRADE if interval: self.subscriptions_info[channel] = [interval] self.subscriptions_info[channel].extend([info[0], endpoint]) def convert_to_interval(self, param): # back conversion from platform value to Interval class for key, value in self.converter.param_value_lookup.items(): if param == value: return key def _on_message(self, message): def inflate(data): #Encode Okex ws data decompress = zlib.decompressobj( -zlib.MAX_WBITS # see above ) inflated = decompress.decompress(data) inflated += decompress.flush() return inflated message = inflate(message) super()._on_message(message.decode('utf-8')) def _parse(self, endpoint, data): if data: if isinstance(data, list): # standard okex ws message format data = data[0] endpoint, data = self._merge_channel_info(data) if 'data' in data: data = data['data'] if not endpoint: return return super()._parse(endpoint, data) def _merge_channel_info(self, items_data): # append subscription information to ws message endpoint = None if 'channel' in items_data and 'ok_sub' in items_data['channel']: loaddata = list(self.subscriptions_info[items_data['channel']]) endpoint = loaddata.pop() for item in items_data['data']: item.extend(loaddata) return endpoint, items_data
85c6a80d87734e919bf7904a91b8da47f438c15f
[ "Python" ]
1
Python
A-Tarski/hq_for_okex
844dbcdaed4135ea69d46f4fba1e3e3d923c8d47
dd193e9b1be4542ef7b2f39dd05f9e1529dec9e7
refs/heads/master
<file_sep># nyaaJS A light weight javascript framework. <file_sep>$nyaa.register( 'ajax', [], { onLoad: function(){ if(typeof(jQuery) === 'undefined'){ this.nyaa.error('nyaa.ajax requires jQuery'); return false; } this.nyaa.debug('ajax onLoad'); }, _ajax: function(method, url, data, success, error){ $.ajax({ crossDomain: true, cache: false, xhrFields: { withCredentials: true }, type: method, url: url, data: data, success: success, error: error, dataType: 'json' }); }, post: function(url, data, success, error){ if(typeof(data) === 'undefined') data = {}; if(typeof(data) === 'function'){ error = success; success = data; data = {}; } data[$('meta[name=csrf-param]').attr('content')] = $('meta[name=csrf-token]').attr('content'); this._ajax('POST', url, data, success, error); }, get: function(url, data, success, error){ if(typeof(data) === 'undefined') data = {}; if(typeof(data) === 'function'){ error = success; success = data; data = {}; } data[$('meta[name=csrf-param]').attr('content')] = $('meta[name=csrf-token]').attr('content'); var query = ''; for(var key in data){ if(query !== '') query += '&'; query += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) } if(query !== '') url += '?' + query; this._ajax('GET', url, {}, success, error); } } );<file_sep>$nyaa.register( 'templete', [], { onLoad: function(){ if(typeof(jQuery) === 'undefined'){ this.nyaa.error('nyaa.templete requires jQuery'); return false; } this.nyaa.debug('templete onLoad'); }, use: function(name, data){ var html = $('templetes > templete[name='+name+']').first().html(); for(var key in data){ var value = $('<a></a>').text(data[key]).html(); /*use jQuery to implement html_entity()*/ value = value.replace(/\{\{/g, '&#123;&#123;'); /*prevent duplicate replace*/ value = value.replace(/\}\}/g, '&#125;&#125;'); /*prevent duplicate replace*/ var re = RegExp('\\{\\{\\s*' + key + '\\s*\\}\\}', 'g'); html = html.replace(re, value); } return html; } } );
57704f1fc947e42fbb9a12c630053db039d1099c
[ "Markdown", "JavaScript" ]
3
Markdown
st0rm23/nyaaJS
106ff770868ebb4743818bd1c591ea210bdb92c5
a04e2dee254ab9f18b71852fd508ef44bd893b43
refs/heads/main
<repo_name>cerner/cucumber-forge-report-generator<file_sep>/types/templates/scripts.d.ts declare let pauseScrollActions: boolean; declare function toggleSettingsDrawer(): void; declare function toggleTagDisplay(): void; declare function toggleFunctionAccordion(element: any): void; declare function toggleScenarioButton(element: any): void; declare function scrollTo(element: any): void; declare function checkVisible(elm: any): boolean; declare function getVisibleAnchor(): undefined; declare function updateActiveScenarioWhenScrolling(): void; declare function toggleDisplayedFeature(element: any): void; declare function toggleDirectoryButton(element: any): void; declare function toggleParentDirectoryButtons(element: any): void; declare function init(): void; <file_sep>/CONTRIBUTORS.md # Contributors ## Cerner Corporation - <NAME> [@jkuester] - <NAME> [@TobiTenno] - <NAME> [@nikitaprabhakar] ## Community - [@beersonthewall] [@jkuester]: https://github.com/jkuester [@TobiTenno]: https://github.com/TobiTenno [@beersonthewall]: https://github.com/beersonthewall [@nikitaprabhakar]: https://github.com/nikitaprabhakar<file_sep>/types/Generator.d.ts export = Generator; declare class Generator { generate(directoryPath: any, name?: any, tag?: any, dialect?: string): any; } <file_sep>/features/support/world.js const { setWorldConstructor, After, Before } = require('cucumber'); const { JSDOM, VirtualConsole } = require('jsdom'); const fs = require('fs'); class CustomWorld { constructor() { this.featureFiles = []; this.featureDirs = []; this.output = null; this.window = null; this.outputHTML = null; this.tag = null; this.scrolledIntoView = null; this.exceptionScenario = false; } createWindow(url, outputConsole) { const virtualConsole = new VirtualConsole(); if (outputConsole) { virtualConsole.sendTo(outputConsole); } this.window = new JSDOM(this.output, { url, virtualConsole, runScripts: 'dangerously', pretendToBeVisual: true, }).window; this.outputHTML = this.window.document; } setOutput(output) { this.output = output; if (this.output.length > 0) { this.createWindow('https://localhost/', console); } else { this.window = null; this.outputHTML = null; } } getScenarioButtonByIndex(index) { const activeFeatureButton = this.outputHTML.getElementsByClassName('feature-button active')[0]; const scenarioPanel = activeFeatureButton.nextElementSibling; return scenarioPanel.getElementsByClassName('scenario-button')[index]; } } Before({ tags: '@exception' }, function () { this.exceptionScenario = true; }); After(function () { // Clean up any feature files that got written. this.featureFiles.forEach((filePath) => fs.unlinkSync(filePath)); this.featureDirs.reverse().forEach((featureDir) => fs.rmdirSync(featureDir)); }); setWorldConstructor(CustomWorld); <file_sep>/README.md <p align="center"> <img src="logo.png"> </p> <h1 align="center"> Cucumber Forge Report Generator </h1> [![Cerner OSS](https://badgen.net/badge/Cerner/OSS/blue)](http://engineering.cerner.com/2014/01/cerner-and-open-source/) [![License](https://badgen.net/badge/license/Apache-2.0/blue)](https://github.com/cerner/cucumber-forge-report-generator/blob/main/LICENSE) [![Actions](https://github.com/cerner/cucumber-forge-report-generator/actions/workflows/ci.yaml/badge.svg)](https://github.com/cerner/cucumber-forge-report-generator/actions/workflows/ci.yaml) # _About_ _Note: this repository contains the library for generating Cucumber reports. [Cucumber Forge Desktop](https://github.com/cerner/cucumber-forge-desktop) is a user-friendly desktop application for creating reports with cucumber-forge-report-generator._ The cucumber-forge-report-generator can be used to create clean HTML reports without having to build the project or run the tests. Of course, no pass/fail information for the scenarios is included in the report since the tests are not executed. Many other solutions exist for creating reports based on the output of Cucumber test runs. The goal of *cucumber-forge-report-generator* is to create reports directly from the feature files without any of the environment/runtime overhead required to build projects and run the Cucumber tests. # _Usage_ Sample - Generates a report for the feature files in a given directory with the scenarios filtered by a tag: ```js const Generator = require('cucumber-forge-report-generator'); const generator = new Generator(); const htmlReportString = generator.generate(featureDirectoryPath, 'Project Name', 'TagFilter'); ``` Detailed usage documentation can be found [here](https://engineering.cerner.com/cucumber-forge-report-generator/). # _Availability_ Artifacts can be downloaded from the [latest release](https://github.com/cerner/cucumber-forge-report-generator/releases). This library can be added as an [NPM dependency](https://www.npmjs.com/package/cucumber-forge-report-generator) via `npm i -S cucumber-forge-report-generator` # _Building_ Development Environment: * [NPM](https://www.npmjs.com/) - ^6.4.1 * [Node.Js](https://nodejs.org) - ^10.14.1 To build the project, simply run `npm install` from the project directory. Linting is available and can be run via `npm lint`. To execute the automated tests, simply run `npm test` from the project directory. # _Conventions_ The project extends the `eslint-config-airbnb-base` [ESLint](https://eslint.org/) configuration. This provides formatting standards for breaks, line length, declarations, etc. Tests for the project are written with [cucumber-js](https://github.com/cucumber/cucumber-js) # _Communication_ If you have any issues or questions, please log a [GitHub issue](https://github.com/cerner/cucumber-forge-report-generator/issues) for this repository. See our [contribution guidelines](CONTRIBUTING.md) for tips on how to submit a helpful issue. # _Contributing_ See [CONTRIBUTING.md](CONTRIBUTING.md) # _LICENSE_ Copyright 2019 Cerner Innovation, Inc. 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 &nbsp;&nbsp;&nbsp;&nbsp;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. <file_sep>/features/support/usageSteps.js const path = require('path'); const { Given, When, Then, } = require('cucumber'); const { expect } = require('chai'); const Generator = require('../../src/Generator'); Given('there is a report for the {string} directory', function (fileDirectory) { const filePath = path.resolve(__dirname, ...fileDirectory.split('/')); this.setOutput(new Generator().generate(filePath)); }); When(/^the (first|second) directory button is clicked$/, function (directoryIndex) { const index = directoryIndex === 'first' ? 0 : 1; this.outputHTML.getElementsByClassName('directory-button')[index].click(); }); When(/^the (first|second) feature button is clicked$/, function (featureIndex) { const index = featureIndex === 'first' ? 0 : 1; const featureButton = this.outputHTML.getElementsByClassName('feature-button')[index]; const scrolledElement = this.outputHTML.getElementById(featureButton.getAttribute('scroll-to-id')); scrolledElement.scrollIntoView = () => { this.scrolledIntoView = scrolledElement; }; featureButton.click(); }); When(/^the (first|second) scenario button is clicked$/, function (scenarioIndex) { const index = scenarioIndex === 'first' ? 0 : 1; const scenarioButton = this.getScenarioButtonByIndex(index); const scrolledElement = this.outputHTML.getElementById(scenarioButton.getAttribute('scroll-to-id')); // Mock the scrollIntoView call scrolledElement.scrollIntoView = () => { this.scrolledIntoView = scrolledElement; }; scenarioButton.click(); }); When(/^the (first|second) scenario is scrolled into view$/, function (scenarioIndex) { const index = scenarioIndex === 'first' ? 0 : 1; const activeFeature = this.outputHTML.getElementsByClassName('feature-wrapper active')[0]; const scenarioAnchors = Array.from(activeFeature.getElementsByClassName('anchor')).filter((anchor) => anchor.hasAttribute('scenario-button')); const scenarioAnchor = scenarioAnchors[index]; // To simulate scrolling, set the active class on our desired anchor // and then trigger the scroll event. scenarioAnchor.classList.add('active'); Array.from(this.outputHTML.getElementsByClassName('anchor')).some((anchor) => { if (scenarioAnchor !== anchor) { anchor.classList.remove('active'); return false; } return true; }); const scrollEvt = this.outputHTML.createEvent('HTMLEvents'); scrollEvt.initEvent('scroll', false, true); this.outputHTML.body.dispatchEvent(scrollEvt); }); When('the settings button is clicked', function () { this.outputHTML.getElementById('settingsButton').click(); }); When('the box is checked to show tags', function () { this.outputHTML.getElementById('tagsCheckbox').click(); }); When(/^the report is opened with a link for the (first|second) feature title$/, function (featureIndex) { const index = featureIndex === 'first' ? 0 : 1; const featureWrappers = this.outputHTML.getElementsByClassName('feature-wrapper'); const featureAnchor = featureWrappers[index].getElementsByClassName('anchor')[0]; this.createWindow(`https://localhost/#${featureAnchor.id}`); }); When(/^the report is opened with a link for the (first|second) scenario title in the (first|second) feature$/, function (scenarioIndex, featureIndex) { const fIndex = featureIndex === 'first' ? 0 : 1; const featureWrappers = this.outputHTML.getElementsByClassName('feature-wrapper'); const sIndex = scenarioIndex === 'first' ? 0 : 1; const scenarioAnchors = Array.from(featureWrappers[fIndex].getElementsByClassName('anchor')) .filter((anchor) => anchor.hasAttribute('scenario-button')); this.createWindow(`https://localhost/#${scenarioAnchors[sIndex].id}`); }); Then(/^the (first|second) feature (?:is|will be) displayed$/, function (featureIndex) { const index = featureIndex === 'first' ? 0 : 1; const featureWrappers = this.outputHTML.getElementsByClassName('feature-wrapper'); const selectedFeatureWrapper = featureWrappers[index]; expect(selectedFeatureWrapper.classList.contains('active')).to.be.true; Array.from(featureWrappers).forEach((featureWrapper) => { if (selectedFeatureWrapper !== featureWrapper) { expect(featureWrapper.classList.contains('active')).to.be.false; } }); }); Then(/^the feature button for the (first|second) directory (?:is|will be) expanded in the sidebar/, function (directoryIndex) { const index = directoryIndex === 'first' ? 0 : 1; const selectedDirectoryButton = this.outputHTML.getElementsByClassName('directory-button')[index]; expect(selectedDirectoryButton.classList.contains('active')).to.be.true; const featurePanel = selectedDirectoryButton.nextElementSibling; expect(featurePanel.classList.contains('active')).to.be.true; const selectedIcon = selectedDirectoryButton.getElementsByTagName('i')[0]; expect(selectedIcon.classList.contains('fa-folder-open')).to.be.true; expect(selectedIcon.classList.contains('fa-folder')).to.be.false; }); Then(/^the feature button for the (first|second) directory (?:is not|will not be) expanded in the sidebar/, function (directoryIndex) { const index = directoryIndex === 'first' ? 0 : 1; const selectedDirectoryButton = this.outputHTML.getElementsByClassName('directory-button')[index]; expect(selectedDirectoryButton.classList.contains('active')).to.be.false; const featurePanel = selectedDirectoryButton.nextElementSibling; expect(featurePanel.classList.contains('active')).to.be.false; const selectedIcon = selectedDirectoryButton.getElementsByTagName('i')[0]; expect(selectedIcon.classList.contains('fa-folder-open')).to.be.false; expect(selectedIcon.classList.contains('fa-folder')).to.be.true; }); Then(/^the scenario buttons for the (first|second) feature (?:are|will be) expanded in the sidebar$/, function (featureIndex) { const index = featureIndex === 'first' ? 0 : 1; const selectedFeatureButton = this.outputHTML.getElementsByClassName('feature-button')[index]; expect(selectedFeatureButton.classList.contains('active')).to.be.true; const scenarioPanel = selectedFeatureButton.nextElementSibling; expect(scenarioPanel.classList.contains('active')).to.be.true; const selectedIcon = selectedFeatureButton.getElementsByTagName('i')[0]; expect(selectedIcon.classList.contains('fa-angle-down')).to.be.true; expect(selectedIcon.classList.contains('fa-angle-right')).to.be.false; }); Then(/^the scenario buttons for the (first|second) feature (?:are not|will not be) expanded in the sidebar$/, function (featureIndex) { const index = featureIndex === 'first' ? 0 : 1; const featureButton = this.outputHTML.getElementsByClassName('feature-button')[index]; expect(featureButton.classList.contains('active')).to.be.false; const panel = featureButton.nextElementSibling; expect(panel.classList.contains('active')).to.be.false; const icon = featureButton.getElementsByTagName('i')[0]; expect(icon.classList.contains('fa-angle-down')).to.be.false; expect(icon.classList.contains('fa-angle-right')).to.be.true; }); Then(/^the (first|second) scenario button will be highlighted$/, function (scenarioIndex) { const index = scenarioIndex === 'first' ? 0 : 1; const selectedScenarioButton = this.getScenarioButtonByIndex(index); expect(selectedScenarioButton.classList.contains('active')).to.be.true; Array.from(this.outputHTML.getElementsByClassName('scenario-button')).forEach((scenarioButton) => { if (selectedScenarioButton !== scenarioButton) { expect(scenarioButton.classList.contains('active')).to.be.false; } }); }); Then(/^the (first|second) scenario will be scrolled into view$/, function (scenarioIndex) { const index = scenarioIndex === 'first' ? 0 : 1; const activeFeature = this.outputHTML.getElementsByClassName('feature-wrapper active')[0]; const scenarioAnchors = Array.from(activeFeature.getElementsByClassName('anchor')).filter((anchor) => anchor.hasAttribute('scenario-button')); expect(this.scrolledIntoView).to.eql(scenarioAnchors[index]); }); Then(/^the settings drawer will be (displayed|hidden)$/, function (visibility) { const settingsDrawer = this.outputHTML.getElementById('settingsDrawer'); const visibilityStatus = settingsDrawer.classList.contains('active'); if (visibility === 'displayed') { expect(visibilityStatus).to.be.true; } else { expect(visibilityStatus).to.be.false; } }); Then('the tags displayed for the feature will be {string}', function (expectedTagString) { const activeFeature = this.outputHTML.getElementsByClassName('feature-wrapper active')[0]; const actualTagString = activeFeature.getElementsByClassName('tags')[0].textContent; expect(actualTagString.trim()).to.eql(expectedTagString); }); Then('the tags displayed for the {word} scenario will be {string}', function (scenarioIndex, expectedTagString) { const activeFeature = this.outputHTML.getElementsByClassName('feature-wrapper active')[0].getElementsByClassName('feature-body')[0]; const index = scenarioIndex === 'first' ? 0 : 1; const actualTagString = activeFeature.getElementsByClassName('tags')[index].textContent; expect(actualTagString.trim()).to.eql(expectedTagString); }); <file_sep>/src/templates/scripts.js /* globals window, document */ const persistentSettingsEnabled = typeof (Storage) !== 'undefined'; let pauseScrollActions = false; const toggleSettingsDrawer = () => { document.getElementById('settingsDrawer').classList.toggle('active'); }; const toggleTagDisplay = () => { Array.from(document.getElementsByClassName('tags')).forEach((tagBlock) => { tagBlock.classList.toggle('active'); }); }; const toggleFunctionAccordion = (element) => { element.classList.toggle('active'); const icon = element.getElementsByTagName('i')[0]; const panel = element.nextElementSibling; panel.classList.toggle('active'); if (panel.classList.contains('active')) { icon.classList.add('fa-angle-down'); icon.classList.remove('fa-angle-right'); } else { icon.classList.remove('fa-angle-down'); icon.classList.add('fa-angle-right'); } }; const toggleScenarioButton = (element) => { // Clear all the other buttons Array.from(document.getElementsByClassName('scenario-button')).forEach((scenarioButton) => { scenarioButton.classList.remove('active'); }); element.classList.add('active'); }; const scrollTo = (element) => { // Pause the scroll actions while we jump to a new location: pauseScrollActions = true; setTimeout(() => { pauseScrollActions = false; }, (1000)); const target = document.getElementById(element.getAttribute('scroll-to-id')); target.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'end', }); }; const checkVisible = (elm) => { const rect = elm.getBoundingClientRect(); const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight); return !(rect.bottom < 0 || rect.top - viewHeight >= 0); }; const getVisibleAnchor = () => { let visibleAnchor; Array.from(document.getElementsByClassName('anchor active')).some((anchor) => { if (checkVisible(anchor)) { visibleAnchor = anchor; return true; } return false; }); return visibleAnchor; }; const updateActiveScenarioWhenScrolling = () => { if (pauseScrollActions) return; const visibleAnchor = getVisibleAnchor(); if (visibleAnchor) { if (visibleAnchor.getAttribute('scenario-button')) { const visibleScenarioButton = document.getElementById(visibleAnchor.getAttribute('scenario-button')); if (!visibleScenarioButton.classList.contains('active')) { toggleScenarioButton(visibleScenarioButton); } } } }; const toggleDisplayedFeature = (element) => { // Deactivate all features Array.from(document.getElementsByClassName('feature-wrapper')).forEach((featureWrapper) => { featureWrapper.classList.remove('active'); }); // Deactivate all anchors Array.from(document.getElementsByClassName('anchor')).forEach((anchor) => { anchor.classList.remove('active'); }); // Activate selected feature const featureWrapper = document.getElementById(element.getAttribute('feature-wrapper-id')); featureWrapper.classList.add('active'); Array.from(featureWrapper.querySelectorAll('.anchor')).forEach((anchor) => { anchor.classList.add('active'); }); }; const toggleDirectoryButton = (element) => { element.classList.toggle('active'); const icon = element.getElementsByTagName('i')[0]; const panel = element.nextElementSibling; panel.classList.toggle('active'); if (panel.classList.contains('active')) { icon.classList.remove('fa-folder'); icon.classList.add('fa-folder-open'); } else { icon.classList.add('fa-folder'); icon.classList.remove('fa-folder-open'); } }; const toggleParentDirectoryButtons = (element) => { toggleDirectoryButton(element); // Recuse on any directory buttons above const parentDirectoryButton = element.parentNode.parentNode.previousElementSibling; if (parentDirectoryButton && parentDirectoryButton.classList.contains('directory-button')) { toggleParentDirectoryButtons(parentDirectoryButton); } }; const tagsCheckboxClicked = () => { toggleTagDisplay(); if (persistentSettingsEnabled) { const { localStorage } = window; const currentState = localStorage.getItem('cfDisplayTags'); localStorage.setItem('cfDisplayTags', currentState != null && currentState === 'true' ? 'false' : 'true'); } }; const toggleDarkModeDisplay = () => { if (document.body.classList.contains('dark')) { document.body.classList.remove('dark'); } else { document.body.classList.add('dark'); } }; const darkModeClicked = () => { toggleDarkModeDisplay(); if (persistentSettingsEnabled) { const { localStorage } = window; const currentState = localStorage.getItem('darkMode') || 'false'; localStorage.setItem('darkMode', currentState === 'false' ? 'true' : 'false'); } }; const init = () => { // Add listeners for directory buttons Array.from(document.getElementsByClassName('directory-button')).forEach((directoryButton) => { directoryButton.addEventListener('click', function click() { toggleDirectoryButton(this); }); }); // Add listeners for feature buttons Array.from(document.getElementsByClassName('feature-button')).forEach((featureButton) => { featureButton.addEventListener('click', function click() { toggleFunctionAccordion(this); if (this.classList.contains('active')) { toggleDisplayedFeature(this); scrollTo(this); // Toggle the first scenario button of the feature const scenarioButton = this.nextElementSibling.getElementsByTagName('button')[0]; toggleScenarioButton(scenarioButton); } }); }); // Add listeners for scenario buttons Array.from(document.getElementsByClassName('scenario-button')).forEach((scenarioButton) => { scenarioButton.addEventListener('click', function click() { // Make sure the scenario's feature is active const featureButton = this.parentNode.parentNode.previousElementSibling; if (!this.classList.contains('active')) { toggleDisplayedFeature(featureButton); } toggleScenarioButton(this); scrollTo(this); }); }); // Make sure the right scenario is active when scrolling window.addEventListener('scroll', updateActiveScenarioWhenScrolling, true); // Add listeners to settings controls const settingsButton = document.getElementById('settingsButton'); if (settingsButton) { settingsButton.addEventListener('click', toggleSettingsDrawer); } const tagsCheckbox = document.getElementById('tagsCheckbox'); if (tagsCheckbox) { tagsCheckbox.addEventListener('click', tagsCheckboxClicked); } const darkModeCheckbox = document.getElementById('darkModeCheckbox'); if (darkModeCheckbox) { darkModeCheckbox.addEventListener('click', darkModeClicked); } // Open the identified feature/scenario (if specified in the URL) else open the first feature const { hash } = window.location; let openDefaultFeature = true; if (hash) { const elementId = hash.substring(1, hash.length); const element = document.getElementById(elementId); if (element) { const scenarioButtonId = element.getAttribute('scenario-button'); const featureButtonId = element.getAttribute('feature-button'); if (scenarioButtonId) { // It is a scenario link const scenarioButton = document.getElementById(scenarioButtonId); const featureButton = scenarioButton.parentNode.parentNode.previousElementSibling; const directoryButton = featureButton.parentNode.parentNode.previousElementSibling; toggleParentDirectoryButtons(directoryButton); featureButton.click(); scenarioButton.click(); openDefaultFeature = false; } else if (featureButtonId) { // It is a feature link const featureButton = document.getElementById(featureButtonId); const directoryButton = featureButton.parentNode.parentNode.previousElementSibling; toggleParentDirectoryButtons(directoryButton); featureButton.click(); openDefaultFeature = false; } } } if (openDefaultFeature) { // Open the first feature. const firstFeatureButton = document.getElementsByClassName('feature-button')[0]; if (firstFeatureButton) { // Open any parent directory buttons const directoryButton = firstFeatureButton.parentNode.parentNode.previousElementSibling; toggleParentDirectoryButtons(directoryButton); toggleFunctionAccordion(firstFeatureButton); toggleDisplayedFeature(firstFeatureButton); } } // Initialize the settings if (persistentSettingsEnabled) { // Display the tags if necessary const { localStorage } = window; if (localStorage.getItem('cfDisplayTags') != null && localStorage.getItem('cfDisplayTags') === 'true') { toggleTagDisplay(); if (tagsCheckbox) { tagsCheckbox.checked = 'true'; } } if (localStorage.getItem('darkMode') !== null && localStorage.getItem('darkMode') === 'true') { toggleDarkModeDisplay(); if (darkModeCheckbox) { darkModeCheckbox.checked = 'true'; } } } }; init(); <file_sep>/RELEASE.md # How to Release This project uses [semantic-release](https://github.com/semantic-release/semantic-release) to automatically release new versions when commits are merged to the main branch. The semantic-release process is triggered as part of the [Travis build](https://travis-ci.com/cerner/cucumber-forge-report-generator). To ensure that releases are triggered properly, the [AngularJS commit message standards](https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit#) should be applied to commit messages for the main branch. ## Format of the commit message ```.txt <type>(<scope>): <subject> <BLANK LINE> <body> <BLANK LINE> <footer> ``` ## Message header The message header is a single line that contains succinct description of the change containing a type, an optional scope and a subject. ### `<type>` This describes the kind of change that this commit is providing. - `feat` (feature) - `fix` (bug fix) - `docs` (documentation) - `style` (formatting, missing semi colons, …) - `refactor` - `test` (when adding missing tests) - `chore` (maintain) ### `<scope>` Scope can be anything specifying place of the commit change. For example $location, $browser, $compile, $rootScope, ngHref, ngClick, ngView, etc... You can use * if there isn't a more fitting scope. ### `<subject>` This is a very short description of the change. - Use imperative, present tense: "change" not "changed" nor "changes" - Don't capitalize first letter - No dot (.) at the end ## Message body - Just as in `<subject>` use imperative, present tense: "change" not "changed" nor "changes" - Includes motivation for the change and contrasts with previous behavior ## Message footer ### Breaking changes All breaking changes have to be mentioned as a breaking change block in the footer, which should start with the word `BREAKING CHANGE: ` with a space or two newlines. The rest of the commit message is then the description of the change, justification and migration notes. ### Referencing issues Closed bugs should be listed on a separate line in the footer prefixed with `Closes` keyword like this: `Closes #234` Or in case of multiple issues: `Closes #123, #245, #992` ## Examples ```.txt -------------------------------------------------------------------------------- feat($browser): onUrlChange event (popstate/hashchange/polling) Added new event to $browser: - forward popstate event if available - forward hashchange event if popstate not available - do polling when neither popstate nor hashchange available Breaks $browser.onHashChange, which was removed (use onUrlChange instead) -------------------------------------------------------------------------------- fix($compile): couple of unit tests for IE9 Older IEs serialize html uppercased, but IE9 does not... Would be better to expect case insensitive, unfortunately jasmine does not allow to user regexps for throw expectations. Closes #392 Breaks foo.bar api, foo.baz should be used instead -------------------------------------------------------------------------------- feat(directive): ng:disabled, ng:checked, ng:multiple, ng:readonly, ng:selected New directives for proper binding these attributes in older browsers (IE). Added coresponding description, live examples and e2e tests. Closes #351 -------------------------------------------------------------------------------- style($location): add couple of missing semi colons -------------------------------------------------------------------------------- docs(guide): updated fixed docs from Google Docs Couple of typos fixed: - indentation - batchLogbatchLog -> batchLog - start periodic checking - missing brace -------------------------------------------------------------------------------- feat($compile): simplify isolate scope bindings Changed the isolate scope binding options to: - @attr - attribute binding (including interpolation) - =model - by-directional model binding - &expr - expression execution binding This change simplifies the terminology as well as number of choices available to the developer. It also supports local name aliasing from the parent. BREAKING CHANGE: isolate scope bindings definition has changed and the inject option for the directive controller injection was removed. To migrate the code follow the example below: Before: scope: { myAttr: 'attribute', myBind: 'bind', myExpression: 'expression', myEval: 'evaluate', myAccessor: 'accessor' } After: scope: { myAttr: '@', myBind: '@', myExpression: '&', // myEval - usually not useful, but in cases where the expression is assignable, you can use '=' myAccessor: '=' // in directive's template change myAccessor() to myAccessor } The removed `inject` wasn't generally useful for directives so there should be no code using it. -------------------------------------------------------------------------------- ``` <file_sep>/features/support/generationSteps.js const fs = require('fs'); const moment = require('moment'); const os = require('os'); const path = require('path'); const { Given, When, Then, } = require('cucumber'); const { expect } = require('chai'); const FILE_ENCODING = 'utf-8'; // eslint-disable-next-line no-unused-vars const Generator = require('../../src/Generator'); Given('there is a file named {string} in the {string} directory with the following contents:', function (fileName, fileDirectory, contents) { const dirPaths = fileDirectory.split('/'); let dirPath = path.resolve(__dirname, dirPaths[0]); if (!fs.existsSync(dirPath)) { fs.mkdirSync(dirPath); this.featureDirs.push(dirPath); } if (dirPaths.length > 1) { dirPath = path.resolve(dirPath, dirPaths[1]); if (!fs.existsSync(dirPath)) { fs.mkdirSync(dirPath); this.featureDirs.push(dirPath); } } const filePath = path.resolve(dirPath, fileName); this.featureFiles.push(filePath); fs.writeFileSync(filePath, contents, FILE_ENCODING); }); Given('the variable {string} contains the path to the {string} directory', function (variableName, fileName) { this[variableName] = path.resolve(__dirname, ...fileName.split('/')); }); Given('the variable {string} contains the path to a directory with no feature files', function (variableName) { const dirPath = path.resolve(__dirname, 'noFeatures'); fs.mkdirSync(dirPath); this.featureDirs.push(dirPath); this[variableName] = dirPath; }); Given(/^the current date is \{current_date\}$/, function () { this.currentDate = moment().format('LL'); }); Given(/^the username of the current user is \{username\}$/, function () { this.username = os.userInfo().username; }); When('a report is generated with the code {string}', function (generationFunction) { try { // eslint-disable-next-line no-eval this.setOutput(eval(generationFunction)); } catch (error) { if (!this.exceptionScenario) { throw error; } this.setOutput(error); } }); Then('an error will be thrown with the message {string}', function (errMsg) { expect(this.output.message).to.eq(errMsg); }); Then('an error will be thrown with a message that matches {string}', function (errMsg) { expect(this.output.message).to.match(new RegExp(errMsg)); }); Then('the title on the report will be {string}', function (reportTitle) { const title = reportTitle.replace('{current_date}', this.currentDate); expect(this.outputHTML.title).to.eql(title); }); Then('the report will include CSS styling', function () { const styles = this.outputHTML.getElementsByTagName('STYLE'); expect(styles.length).to.eql(1); const style = styles.item(0); // eslint-disable-next-line no-unused-expressions expect(style.innerHTML).to.be.an('string').that.is.not.empty; }); Then('the report will include a favicon', function () { const link = this.outputHTML.querySelector("link[rel='shortcut icon']"); expect(link.type).to.eql('image/png'); expect(link.href).to.have.lengthOf(3214); }); Then('the report name on the sidebar will be {string}', function (reportName) { expect(this.outputHTML.getElementById('sidenavTitle').textContent).to.eql(reportName); }); Then('the project title on the sidebar will be {string}', function (projectTitle) { expect(this.outputHTML.getElementById('headerTitle').textContent).to.eql(projectTitle); }); Then('the header on the sidebar will be {string}', function (header) { let headerText = header.replace('{username}', this.username); headerText = headerText.replace('{current_date}', this.currentDate); expect(this.outputHTML.getElementById('authorAside').innerHTML).to.eql(headerText); }); Then('the footer on the sidebar will be {string}', function (footer) { expect(this.outputHTML.getElementById('sidenavFooter').textContent).to.contain(footer); }); Then('the report will contain {int} feature(s)', function (featureCount) { const features = this.outputHTML.getElementsByClassName('feature-wrapper'); expect(features.length).to.eql(featureCount); }); Then('the report will contain {int} scenario(s)', function (scenarioCount) { // There is no divider for the first scenario in a feature. const featureCount = this.outputHTML.getElementsByClassName('feature-wrapper').length; const scenarioDividers = this.outputHTML.getElementsByClassName('scenario-divider'); expect(scenarioDividers.length).to.eql(scenarioCount - featureCount); }); Then('the report will not contain gherkin comments', function () { const commentPattern = new RegExp('^#.*'); const comments = Array.from(this.outputHTML.getElementsByTagName('*')) .filter((obj) => commentPattern.test(obj.innerHTML)); expect(comments.length).to.eql(0); }); Then('the sidebar will contain {int} directory button(s)', function (directoryButtonCount) { const directoryButtons = this.outputHTML.getElementsByClassName('directory-button'); expect(directoryButtons.length).to.eql(directoryButtonCount); }); Then('the sidebar will contain {int} feature button(s)', function (featureButtonCount) { const featureButtons = this.outputHTML.getElementsByClassName('feature-button'); expect(featureButtons.length).to.eql(featureButtonCount); }); Then('the sidebar will contain {int} scenario button(s)', function (scenarioButtonCount) { const scenarioButtons = this.outputHTML.getElementsByClassName('scenario-button'); expect(scenarioButtons.length).to.eql(scenarioButtonCount); }); <file_sep>/.github/ISSUE_TEMPLATE.md <!-- Please fill out the below template as best you can. --------------------------------------------------------> ### Description of Issue <!-- Describe the issue as best you can. Screenshots, logs, and stack traces can be very helpful! --> ### System Configuration #### Project Version #### Additional Details (optional) ### Steps to Reproduce the Issue 1. Step 1 1. Step 2 ### Expected Outcomes <!-- - Links can be styled as buttons - Disabled links behave the same as disabled buttons -->
7c81f0f423a29a7eb09101939badc56c9310a8a9
[ "Markdown", "TypeScript", "JavaScript" ]
10
TypeScript
cerner/cucumber-forge-report-generator
bd38905cc127b3334202db4bc8d99fcb1978634a
53bbe99a8ba369b1a2a760426f944d2a5fc47a4d
refs/heads/master
<file_sep>package main.java; import java.io.File; import java.util.Scanner; public class Problem_11 { public static void main(String[] args) { File file = new File("src/main/resources/problem_11.txt"); try { Scanner sc = new Scanner(file); // read the first line to create the NxN array (assume the file contains NxN numbers). String line = sc.nextLine(); String[] lineNumbers = line.split(" "); int[][] numbers = new int[lineNumbers.length][lineNumbers.length]; int i = 0; for (int j = 0; j < numbers.length; j++) { numbers[i][j] = Integer.parseInt(lineNumbers[j]); } while (sc.hasNextLine()) { i++; line = sc.nextLine(); lineNumbers = line.split(" "); for (int j = 0; j < numbers.length; j++) { numbers[i][j] = Integer.parseInt(lineNumbers[j]); } } int max = 0; for (i = 0; i < numbers.length; i++) { for (int j = 0; j < numbers.length; j++) { if (i < numbers.length - 3 && j < numbers.length - 3) { int rightDiagonalProduct = numbers[i][j] * numbers[i + 1][j + 1] * numbers[i + 2][j + 2] * numbers[i + 3][j + 3]; max = Math.max(max, rightDiagonalProduct); } if (i < numbers.length - 3) { int rightProduct = numbers[i][j] * numbers[i + 1][j] * numbers[i + 2][j] * numbers[i + 3][j]; max = Math.max(max, rightProduct); } if (j < numbers.length - 3) { int downProduct = numbers[i][j] * numbers[i][j + 1] * numbers[i][j + 2] * numbers[i][j + 3]; max = Math.max(max, downProduct); } if (i < numbers.length - 3 && j > 2) { int leftDiagonalProduct = numbers[i][j] * numbers[i + 1][j - 1] * numbers[i + 2][j - 2] * numbers[i + 3][j - 3]; max = Math.max(max, leftDiagonalProduct); } } } System.out.println("max product: " + max); } catch (Exception e) { e.printStackTrace(); } finally { return; } } } <file_sep>package main.java; import static main.java.Problem_3.isPrime; public class Problem_7 { public static void main(String[] args) { int count = 1; int i = 3; while (count < 10001) { if (isPrime(i)) { count++; } i += 2; } System.out.println("result: " + (i - 2)); // subtract 2 from i to get the correct result } } <file_sep>package main.java; public class Problem_6 { public static void main(String[] args) { int sum = 0; int sumSQ = 0; for (double i = 1; i <= 100; i++) { sum += i; sumSQ += i * i; } sum *= sum; System.out.println(sum - sumSQ); } } <file_sep>package main.java; import java.math.BigInteger; import static main.java.Problem_3.isPrime; public class Problem_10 { public static void main(String[] args) { BigInteger sum = BigInteger.ZERO; // 0 : number not checked // 1 : number checked int[] numbers = new int[2000000]; numbers[0] = 1; numbers[1] = 1; for (int i = 2; i < 2000000; i++) { if (numbers[i] == 0) { if (isPrime(i)) { sum = sum.add(new BigInteger(Integer.toString(i))); } } int k = i * 2; while (k < 2000000) { numbers[k] = 1; k += i; } } System.out.println("Result: " + sum.toString()); } } <file_sep>package main.java; public class Problem_4 { public static void main(String[] args) { int max = 0; for (int i = 100; i < 1000; i++) { for (int j = 100; j < 1000; j++) { int product = i * j; if (isPalindrome(product)) { if (product > max) { max = product; } } } } System.out.println(max); } public static boolean isPalindrome(int number) { String string = Integer.toString(number); StringBuilder builder = new StringBuilder(); builder.append(string); builder.reverse(); if (string.equals(builder.toString())) { return true; } else { return false; } } } <file_sep>package main.java; /** * The sequence of triangle numbers is generated by adding the natural numbers. * So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. * The first ten terms would be: * 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... * What is the value of the first triangle number to have over five hundred divisors? */ public class Problem_12 { public static void main(String[] args) { long number = 1L; long nextNatural = 1L; long count = 0L; while (count < 500) { int i = 1; count = 0; while (i <= number) { if (number % i == 0) { count++; } i++; } System.out.println(number + " has " + count + " divisors."); nextNatural++; number += nextNatural; } System.out.println(number - nextNatural); } }
3f5fbc8e54d4f51cbb4175ff4a6f8fed37bcd8ed
[ "Java" ]
6
Java
lyrakisk/project-euler
d7690c5f248ff444143b177ff9829a14f068d77e
0b8492605ea100cca83293a8e234f35af52e69cb
refs/heads/main
<file_sep>@file:JsModule("bootstrap") @file:JsNonModule <file_sep>package data data class KotlinVideo( override val id: Int, override val title: String, override val speaker: String, override val videoUrl: String ) : Video<file_sep>import components.App import kotlinx.browser.document import react.dom.render fun main() { /** * Grabs the "root" div element defined in index.html as the top * and renders that using as the child the component class App:class. */ render(document.getElementById("root")) { child(App::class) {} } } <file_sep>package util import kotlinx.browser.window import kotlinx.coroutines.* import data.Video suspend fun fetchVideo(id: Int): Video { val response = window .fetch("https://my-json-server.typicode.com/kotlin-hands-on/kotlinconf-json/videos/$id") .await() .json() .await() return response as Video } suspend fun fetchVideos(): List<Video> = coroutineScope { (1..25).map { id -> async { fetchVideo(id) } }.awaitAll() }
a2d889081177191c12838c8029691016b77dc91b
[ "Kotlin" ]
4
Kotlin
douglasselph/conf-explorer
30e746be6de33f9ad752b4712887c9f7563c4b2f
a047f465b669704bd3b7ae2b37373a62439616bb
refs/heads/master
<file_sep># PrescriptionAnalysis-Kaggle Dataset Link: https://www.kaggle.com/roamresearch/prescriptionbasedprediction Predict the speciality, region and experience of the doctors based on the analysis of 250k prescriptions. Visualization of the result (probability) after adding each medicine to the prescription using seaborn and matplotlib. <file_sep>import numpy import json import csv import collections import operator import codecs import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import matplotlib.pyplot as plt; plt.rcdefaults() # import matplotlib.axes.Axes as axis import numpy as np import matplotlib.pyplot as plt # # objects = ('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp') # y_pos = np.arange(len(objects)) # performance = [10,8,6,4,2,1] def generate_visualization(): experience_data=collections.defaultdict(dict) pkmn_type_colors = ['#78C850', # Grass '#F08030', # Fire '#6890F0', # Water '#A8B820', # Bug '#A8A878', # Normal '#A040A0', # Poison '#F8D030', # Electric '#E0C068', # Ground '#EE99AC', # Fairy '#C03028', # Fighting '#F85888', # Psychic '#B8A038', # Rock '#705898', # Ghost '#98D8D8', # Ice '#7038F8', # Dragon, '#1A1D1E', '#4B4A4C' ] with open("abc.jsonl") as f: for line in f: j_content = json.loads(line) speciality=j_content.get('provider_variables').get('specialty') if speciality.find("General Practice"): years_of_practicing = j_content.get('provider_variables').get('years_of_practicing') # experience_data['years_of_practicing']=years_of_practicing if years_of_practicing not in experience_data.keys(): experience_data[years_of_practicing]=1 else: experience_data[years_of_practicing]+=1 x=list(experience_data.keys()) print(x) print(type(x)) y_pos= x.__len__() print(y_pos) y=[] for p in x: y.append(int(experience_data[p])) print(y) # plt.bar(y_pos, y, align='center', alpha=0.5) # plt.xticks(y_pos, x) # plt.ylabel('Usage') # plt.title('Programming language usage') # # plt.show() x=['General Practice','Neurology','Medical',''] ax=sns.barplot(x=x,y=y,orient="v",saturation=0.8) ax.set(xlabel='Experience in years', ylabel='Number of General Practice Doctors') # ax.savefig("output.png") sns.plt.savefig("output5.png") sns.plt.show() # sns.save # vis_data=pd.DataFrame(list(experience_data.items()), columns=['year','value']) # sns.countplot(x=vis_data['year'],data=vis_data, palette=pkmn_type_colors) # sns.jointplot(x='year', y='value', data=experience_data) # Rotate x-labels # plt.xticks(rotation=-45) return # read_medicine_median_from_csv() generate_visualization()<file_sep>import numpy import json import csv import collections import operator import codecs import matplotlib.pyplot as plt import seaborn as sns import pandas as pd region=[] list_of_specialities=[] spec_patient_analysis = collections.defaultdict(dict) analyzed_data=collections.defaultdict(dict) medicine_array=collections.defaultdict(dict) speciality_region_data=collections.defaultdict(dict) speciality_settlement_type_data=collections.defaultdict(dict) speciality_gender_data=collections.defaultdict(dict) medicine_median=collections.defaultdict(dict) medicine_region_data=collections.defaultdict(dict) output_data=collections.defaultdict(dict) def generate_medicine_region_data(region,medicine): if region in medicine_region_data[medicine].keys(): medicine_region_data[medicine][region]+=1 else: medicine_region_data[medicine][region]=1 return def create_speciality_data(region,settlement_type,gender,speciality): if region in speciality_region_data[speciality].keys(): speciality_region_data[speciality][region]+=1 else: speciality_region_data[speciality][region]=1 if settlement_type in speciality_settlement_type_data[speciality].keys(): speciality_settlement_type_data[speciality][settlement_type] += 1 else: speciality_settlement_type_data[speciality][settlement_type] = 1 if gender in speciality_gender_data[speciality].keys(): speciality_gender_data[speciality][gender]+=1 else: speciality_gender_data[speciality][gender]=1 return def write_gender_data_as_csv(speciality_gender_data): with open('speciality_gender_data.csv', 'w') as csv_file: writer = csv.writer(csv_file) writer.writerow(["speciality","Male","Female"]) for key, value in speciality_gender_data.items(): if 'M' in speciality_gender_data[key].keys(): male = speciality_gender_data[key]["M"] else: male=0 if 'F' in speciality_gender_data[key].keys(): female = speciality_gender_data[key]["F"] else: female=0 key=key.encode("utf-8") writer.writerow([key,male,female]) return def write_medicine_region_data_as_csv(medicine_region_data): with open('medicine_region_data.csv', 'w') as f: writer = csv.writer(f) writer.writerow(["speciality", "South", "Midwest", "West", "Northeast"]) for key, value in medicine_region_data.items(): if 'South' in medicine_region_data[key].keys(): south = medicine_region_data[key]["South"] else: south = 0 if 'Midwest' in medicine_region_data[key].keys(): Midwest = medicine_region_data[key]["Midwest"] else: Midwest = 0 if 'West' in medicine_region_data[key].keys(): West = medicine_region_data[key]["West"] else: West = 0 if 'Northeast' in medicine_region_data[key].keys(): Northeast = medicine_region_data[key]["Northeast"] else: Northeast = 0 key = key.encode("utf-8") # print(key, south, Midwest, West, Northeast) writer.writerow([key, south, Midwest, West, Northeast]) return def write_region_data_as_csv(speciality_region_data): with open('speciality_region_data.csv','w') as f: writer = csv.writer(f) writer.writerow(["speciality","South", "Midwest", "West", "Northeast"]) for key, value in speciality_region_data.items(): if 'South' in speciality_region_data[key].keys(): south = speciality_region_data[key]["South"] else: south = 0 if 'Midwest' in speciality_region_data[key].keys(): Midwest = speciality_region_data[key]["Midwest"] else: Midwest = 0 if 'West' in speciality_region_data[key].keys(): West = speciality_region_data[key]["West"] else: West = 0 if 'Northeast' in speciality_region_data[key].keys(): Northeast = speciality_region_data[key]["Northeast"] else: Northeast = 0 key = key.encode("utf-8") print(key,south,Midwest,West,Northeast) writer.writerow([key,south,Midwest,West,Northeast]) return def write_settlement_data_as_csv(speciality_settlement_type_data): with open('speciality_settlement_type_data.csv', 'w') as f: writer = csv.writer(f) writer.writerow(["speciality", "Urban","Non-Urban"]) for key, value in speciality_settlement_type_data.items(): if 'non-urban' in speciality_settlement_type_data[key].keys(): nonUrban=speciality_settlement_type_data[key]["non-urban"] else: nonUrban = 0 if 'urban' in speciality_settlement_type_data[key].keys(): urban = speciality_settlement_type_data[key]['urban'] else: urban = 0 key=key.encode("utf-8") print(key,nonUrban,urban) writer.writerow([key,nonUrban,urban]) return def write_medicine_median_as_csv(medicine_median): with open("medicine_median.csv",'w') as f: writer = csv.writer(f) writer.writerow(["medicine","median"]) for key,value in medicine_median.items(): writer.writerow([key,value]) return def write_medicine_speciality_probability_as_csv(analyzed_data): with open("medicine_speciality_probability.csv",'w') as f: writer = csv.writer(f) arr=[] arr.append("medicine") arr.append(list_of_specialities) writer.writerow(arr) arr=[] for key,value in analyzed_data.items(): arr=[] arr.append(key) for i in list_of_specialities: if i in analyzed_data[medicines].keys(): arr.append(analyzed_data[medicines][i]) else: arr.append(0) writer.writerow(arr) print("Lakhai Gayu") return def generate_medicine_median(medicine,value): if medicine in medicine_array.keys(): medicine_array[medicine].append(value) array=medicine_array[medicine] median=numpy.median(array) else: arr=[] arr.append(value) medicine_array[medicine]=arr median=value # print(medicine_median) medicine_median[medicine] = median # if speciality in value_data[medicine].keys(): # value_data[medicine][speciality].append(value) # medicine_array=value_data[medicine][speciality] # medicine_speciality_median = numpy.median(medicine_array) # else: # arr=[] # arr.append(value) # value_data[medicine][speciality] = arr # medicine_speciality_median=arr[0] # change_median(medicine,speciality,medicine_speciality_median) return def insert_into_analysis(medicine,speciality,years_of_practicing,value): if value > float(medicine_median[medicine]): median_factor=1+(value-float(medicine_median[medicine]))/value else: median_factor=1 if years_of_practicing > 5: years_of_practicing = numpy.floor((years_of_practicing - 5)/5) exp_factor = 1 + years_of_practicing/10 else: exp_factor = 1 analyzed_value = value * median_factor * exp_factor if speciality in analyzed_data[medicine].keys(): analyzed_data[medicine][speciality]+=analyzed_value else: analyzed_data[medicine][speciality]=analyzed_value # print(analyzed_data) #print(freq_data[medicine]) return def read_spec_patient_from_csv(speciality,region): print(speciality) print(region) with open('spec.csv') as f: reader=csv.DictReader(f,delimiter=',') for line in reader: # print(line["Specialty"]) if speciality in line["Specialty"]: patients="Patients in "+region doctors="Doctors in "+region ratio ="Actual P/D ratio in "+region recommended_ratio="recommended P/D value" print("Patients in "+region+": "+line[patients]) print("Doctors in "+region+": "+line[doctors]) print("Actual P/D ratio in"+region+": "+line[ratio]) print("Recommended P/D value: "+line[recommended_ratio]) print(line[ratio]) print(line[recommended_ratio]) if int(line[recommended_ratio]) > int(line[ratio]): print("There are sufficient doctors") else: print() print() print("There has to be more doctors as patients are more") print("Possible solutions:") print("1:Transfer doctors from one region to another") print("2:Improve Medical Infrastructure of that region") print("3:Promote similar courses in medical colleges") print() print() print() break def read_medicine_median_from_csv(): with open('medicine_median.csv') as f: reader=csv.DictReader(f, delimiter=',') for line in reader: medicine_median[line["medicine"]] = line["median"] # print(medicine_median) return def generate_visualize_probability(x): for key,value in analyzed_data.items(): total = 0 for ky,val in value.items(): total = total + val for ky,val in value.items(): analyzed_data[key][ky]=analyzed_data[key][ky]/total return def generate_output(medicine,x): print(output_data) print(analyzed_data[medicine]) for key,value in analyzed_data[medicine].items(): if key in output_data.keys(): output_data[key]=output_data[key]+value # print(type(output_data[key])) # print(output_data[key]) else: output_data[key]=value for key,value in output_data.items(): output_data[key]=output_data[key]/x print(output_data) print("Predicted field & probability") predicted_field = "Please Enter Valid Medicine" probability="Do you want to try again?" if output_data.__len__()>0: # print("Below is ------------------------------") # print(sorted(output_data.iteritems(), key=lambda x: -x[1])[:5]) predicted_field = max(output_data.items(), key=operator.itemgetter(1))[0] probability=max(output_data.items(), key=operator.itemgetter(1))[1] print(predicted_field) print(probability) return def suggest_doctors(spec): print(spec) with open("abc.jsonl") as f: x=0 for line in f: # print(x) j_content = json.loads(line) speciality = j_content.get('provider_variables').get('specialty') region = j_content.get('provider_variables').get('region') settlement_type = j_content.get('provider_variables').get('settlement_type') years_of_practicing = j_content.get('provider_variables').get('years_practicing') gender=j_content.get('provider_variables').get('gender') # print(speciality) # print(spec) npi= j_content.get('npi') # print(npi) if speciality == spec: x = x + 1 print("npi: ",npi," region: ",region," settlement_type: ",settlement_type," experience: ",years_of_practicing,"gender: ",gender) if x > 10: break read_medicine_median_from_csv() with open("ok.jsonl") as f: # x=0 for line in f: # print(x) # x=x+1 j_content = json.loads(line) speciality = j_content.get('provider_variables').get('specialty') if speciality not in list_of_specialities: list_of_specialities.append(speciality) region = j_content.get('provider_variables').get('region') settlement_type = j_content.get('provider_variables').get('settlement_type') years_of_practicing = j_content.get('provider_variables').get('years_practicing') # create_speciality_data(region,settlement_type,years_of_practicing,speciality) #print(speciality) medicines = j_content.get('cms_prescription_counts') #print(medicines) # for key,value in medicines.items(): # if key not in list_of_medicines: # list_of_medicines.append(key) for key, value in medicines.items(): # if key not in list_of_medicines: insert_into_analysis(key,speciality,years_of_practicing,value) # generate_medicine_median(key,value) # generate_medicine_region_data(region,key) # print(analyzed_data) # generate_probability(analyzed_data) # read_spec_patient_from_csv("'Acute Care'","Northeast") # print(analyzed_data) # print(medicine_median) # print(value_data) # print(speciality_region_data) # print(speciality_gender_data) # print(speciality_settlement_type_data) # write_medicine_median_as_csv(medicine_median) # write_gender_data_as_csv(speciality_gender_data) # write_region_data_as_csv(speciality_region_data) # write_settlement_data_as_csv(speciality_settlement_type_data) # write_medicine_region_data_as_csv(medicine_region_data) # write_medicine_speciality_probability_as_csv(analyzed_data) # read_medicine_median_from_csv() # print(freq_data) # print(value_data) x=0 choice=0 while(choice!="4"): print("1. Predict speciality from prescription") print("2.Suggest Doctors") print("3.Show Statistics") print("4.Exit") choice = input("What do you want to do?") if choice =="2": spec=input("Enter speciality") suggest_doctors(spec) if choice == "1": x = 1 generate_output(input("Enter Medicine:"),x) add_more=input("Do you want to add more?") while(add_more!="N"): x=x+1 generate_output(input("Enter Medicine:"), x) add_more = input("Do you want to add more?") if output_data.__len__()>0: predicted_field="'"+max(output_data.items(), key=operator.itemgetter(1))[0]+"'" print(predicted_field) else: print("You have not entered valid medicine") # print("1.Suggest Doctors") print("2.Show statistics") print("3.exit") ai=input("Enter input:") if(ai=="2"): print("1.South") print("2.Midwest") print("3.West") print("4.Northeast") region_input=input("Enter Region from above to show statistics and recommendation") if region_input == "1": region_input = "South" elif region_input == "2": region_input = "Midwest" elif region_input == "3": region_input = "West" else: region_input = "Northeast" if predicted_field.__len__()>1: read_spec_patient_from_csv(predicted_field,region_input) else: print("Invalid medicine entered") else: choice=4 elif choice =="3": specialty=input("Enter Specialty:") print("1.South") print("2.Midwest") print("3.West") print("4.Northeast") region_input = input("Enter Region from above to show statistics and recommendation") if region_input == "1": region_input="South" elif region_input=="2": region_input="Midwest" elif region_input=="3": region_input="West" else: region_input="Northeast" read_spec_patient_from_csv(specialty,region_input) # while(input("Do you want to predict more?")!="N"): # x =x +1 # generate_output(input("Enter Medicine:"), x) # print(output_data) # generate_output(output_data) # else: # if speciality in key.items(): # key[speciality]+=value # else: # key[speciality]=value #print(spec.dumps()) #print(spec.values()) # if spec not in region: # region.append(spec) # print("changed") # print(region.__len__()) # print(region) ##to read region # with open("roam_prescription_based_prediction.jsonl") as f: # for line in f: # j_content = json.loads(line) # spec=j_content.get('provider_variables').get('region') # if spec not in region: # region.append(spec) # print("changed") # print(region.__len__()) # print(region) <file_sep>import numpy import json import csv import collections import operator import codecs import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd from textwrap import wrap import matplotlib.pyplot as plt; plt.rcdefaults() cool_colors = ['#78C850', # Grass '#F08030', # Fire '#6890F0', # Water '#A8B820', # Bug '#A8A878', # Normal '#A040A0', # Poison '#F8D030', # Electric '#E0C068', # Ground '#EE99AC', # Fairy '#C03028', # Fighting '#F85888', # Psychic '#B8A038', # Rock '#705898', # Ghost '#98D8D8', # Ice '#7038F8', # Dragon, '#1A1D1E', '#4B4A4C' ] region=[] list_of_specialities=[] medicines_array = [] spec_patient_analysis = collections.defaultdict(dict) one_medicine = collections.defaultdict(dict) freq_data=collections.defaultdict(dict) analyzed_data=collections.defaultdict(dict) medicine_array=collections.defaultdict(dict) speciality_region_data=collections.defaultdict(dict) speciality_settlement_type_data=collections.defaultdict(dict) speciality_gender_data=collections.defaultdict(dict) medicine_median=collections.defaultdict(dict) medicine_region_data=collections.defaultdict(dict) output_data = collections.defaultdict(dict) def generate_medicine_region_data(region,medicine): if region in medicine_region_data[medicine].keys(): medicine_region_data[medicine][region]+=1 else: medicine_region_data[medicine][region]=1 return def create_speciality_data(region,settlement_type,gender,speciality): if region in speciality_region_data[speciality].keys(): speciality_region_data[speciality][region]+=1 else: speciality_region_data[speciality][region]=1 if settlement_type in speciality_settlement_type_data[speciality].keys(): speciality_settlement_type_data[speciality][settlement_type] += 1 else: speciality_settlement_type_data[speciality][settlement_type] = 1 if gender in speciality_gender_data[speciality].keys(): speciality_gender_data[speciality][gender]+=1 else: speciality_gender_data[speciality][gender]=1 return def write_gender_data_as_csv(speciality_gender_data): with open('speciality_gender_data.csv', 'w') as csv_file: writer = csv.writer(csv_file) writer.writerow(["speciality","Male","Female"]) for key, value in speciality_gender_data.items(): if 'M' in speciality_gender_data[key].keys(): male = speciality_gender_data[key]["M"] else: male=0 if 'F' in speciality_gender_data[key].keys(): female = speciality_gender_data[key]["F"] else: female=0 key=key.encode("utf-8") writer.writerow([key,male,female]) return def write_medicine_region_data_as_csv(medicine_region_data): with open('medicine_region_data.csv', 'w') as f: writer = csv.writer(f) writer.writerow(["speciality", "South", "Midwest", "West", "Northeast"]) for key, value in medicine_region_data.items(): if 'South' in medicine_region_data[key].keys(): south = medicine_region_data[key]["South"] else: south = 0 if 'Midwest' in medicine_region_data[key].keys(): Midwest = medicine_region_data[key]["Midwest"] else: Midwest = 0 if 'West' in medicine_region_data[key].keys(): West = medicine_region_data[key]["West"] else: West = 0 if 'Northeast' in medicine_region_data[key].keys(): Northeast = medicine_region_data[key]["Northeast"] else: Northeast = 0 key = key.encode("utf-8") # print(key, south, Midwest, West, Northeast) writer.writerow([key, south, Midwest, West, Northeast]) return def write_region_data_as_csv(speciality_region_data): with open('speciality_region_data.csv','w') as f: writer = csv.writer(f) writer.writerow(["speciality","South", "Midwest", "West", "Northeast"]) for key, value in speciality_region_data.items(): if 'South' in speciality_region_data[key].keys(): south = speciality_region_data[key]["South"] else: south = 0 if 'Midwest' in speciality_region_data[key].keys(): Midwest = speciality_region_data[key]["Midwest"] else: Midwest = 0 if 'West' in speciality_region_data[key].keys(): West = speciality_region_data[key]["West"] else: West = 0 if 'Northeast' in speciality_region_data[key].keys(): Northeast = speciality_region_data[key]["Northeast"] else: Northeast = 0 key = key.encode("utf-8") print(key,south,Midwest,West,Northeast) writer.writerow([key,south,Midwest,West,Northeast]) return def write_settlement_data_as_csv(speciality_settlement_type_data): with open('speciality_settlement_type_data.csv', 'w') as f: writer = csv.writer(f) writer.writerow(["speciality", "Urban","Non-Urban"]) for key, value in speciality_settlement_type_data.items(): if 'non-urban' in speciality_settlement_type_data[key].keys(): nonUrban=speciality_settlement_type_data[key]["non-urban"] else: nonUrban = 0 if 'urban' in speciality_settlement_type_data[key].keys(): urban = speciality_settlement_type_data[key]['urban'] else: urban = 0 key=key.encode("utf-8") print(key,nonUrban,urban) writer.writerow([key,nonUrban,urban]) return def write_medicine_median_as_csv(medicine_median): with open("medicine_median.csv",'w') as f: writer = csv.writer(f) writer.writerow(["medicine","median"]) for key,value in medicine_median.items(): writer.writerow([key,value]) return def write_medicine_speciality_probability_as_csv(analyzed_data): with open("medicine_speciality_probability.csv",'w') as f: writer = csv.writer(f) arr=[] arr.append("medicine") arr.append(list_of_specialities) writer.writerow(arr) arr=[] for key,value in analyzed_data.items(): arr=[] arr.append(key) for i in list_of_specialities: if i in analyzed_data[medicines].keys(): arr.append(analyzed_data[medicines][i]) else: arr.append(0) writer.writerow(arr) print("Lakhai Gayu") return def generate_medicine_median(medicine,value): if medicine in medicine_array.keys(): medicine_array[medicine].append(value) array=medicine_array[medicine] median=numpy.median(array) else: arr=[] arr.append(value) medicine_array[medicine]=arr median=value # print(medicine_median) medicine_median[medicine] = median # if speciality in value_data[medicine].keys(): # value_data[medicine][speciality].append(value) # medicine_array=value_data[medicine][speciality] # medicine_speciality_median = numpy.median(medicine_array) # else: # arr=[] # arr.append(value) # value_data[medicine][speciality] = arr # medicine_speciality_median=arr[0] # change_median(medicine,speciality,medicine_speciality_median) return def insert_into_analysis(medicine,speciality,years_of_practicing,value,region): frequencies = "frequencies" _region_ = "region" _mean_ = "mean" _experience_ = "experience" total = "total" if _region_ not in analyzed_data[medicine].keys(): analyzed_data[medicine][_region_]=collections.defaultdict(dict) analyzed_data[medicine][_region_][region]=1 else: if region in analyzed_data[medicine][_region_].keys(): analyzed_data[medicine][_region_][region] += 1 else: analyzed_data[medicine][_region_][region] = 1 if frequencies not in analyzed_data[medicine].keys(): analyzed_data[medicine][frequencies]=collections.defaultdict(dict) analyzed_data[medicine][frequencies][speciality] = 1 analyzed_data[medicine][frequencies][total]=1 else: analyzed_data[medicine][frequencies][total]+=1 if speciality in analyzed_data[medicine][frequencies].keys(): analyzed_data[medicine][frequencies][speciality]+=1 else: analyzed_data[medicine][frequencies][speciality]=1 if _mean_ not in analyzed_data[medicine].keys(): analyzed_data[medicine][_mean_] = collections.defaultdict(dict) analyzed_data[medicine][_mean_][speciality] = value else: if speciality in analyzed_data[medicine][_mean_].keys(): p = analyzed_data[medicine][_mean_][speciality]* (analyzed_data[medicine][frequencies][speciality]-1) p = p + value p = p / analyzed_data[medicine][frequencies][speciality] analyzed_data[medicine][_mean_][speciality]= p else: analyzed_data[medicine][_mean_][speciality] = value if _experience_ not in analyzed_data[medicine].keys(): analyzed_data[medicine][_experience_] = collections.defaultdict(dict) analyzed_data[medicine][_experience_][speciality] = years_of_practicing analyzed_data[medicine][_experience_][_mean_]=years_of_practicing else: analyzed_data[medicine][_experience_][_mean_]= analyzed_data[medicine][_experience_][_mean_]*(analyzed_data[medicine][frequencies][total]-1) analyzed_data[medicine][_experience_][_mean_]=analyzed_data[medicine][_experience_][_mean_]+ years_of_practicing analyzed_data[medicine][_experience_][_mean_] = analyzed_data[medicine][_experience_][_mean_]/analyzed_data[medicine][frequencies][total] if speciality in analyzed_data[medicine][_experience_].keys(): temp = analyzed_data[medicine][_experience_][speciality] * (analyzed_data[medicine][frequencies][speciality] - 1) temp = temp + years_of_practicing temp = temp / analyzed_data[medicine][frequencies][speciality] analyzed_data[medicine][_experience_][speciality] = temp else: analyzed_data[medicine][_experience_][speciality] = years_of_practicing return def read_spec_patient_from_csv(speciality,region): print(speciality) print(region) with open('spec.csv') as f: reader=csv.DictReader(f,delimiter=',') for line in reader: # print(line["Specialty"]) if speciality in line["Specialty"]: patients="Patients in "+region doctors="Doctors in "+region ratio ="Actual P/D ratio in "+region recommended_ratio="recommended P/D value" print("Patients in "+region+": "+line[patients]) print("Doctors in "+region+": "+line[doctors]) print("Actual P/D ratio in"+region+": "+line[ratio]) print("Recommended P/D value: "+line[recommended_ratio]) print(line[ratio]) print(line[recommended_ratio]) if int(line[recommended_ratio]) > int(line[ratio]): print("There are sufficient doctors") else: print() print() print("There has to be more doctors as patients are more") print("Possible solutions:") print("1:Transfer doctors from one region to another") print("2:Improve Medical Infrastructure of that region") print("3:Promote similar courses in medical colleges") print() print() print() break def read_medicine_median_from_csv(): with open('medicine_median.csv') as f: reader=csv.DictReader(f, delimiter=',') for line in reader: medicine_median[line["medicine"]] = line["median"] # print(medicine_median) return def generate_probability(analyzed_data): for key,value in analyzed_data.items(): total = 0 for ky,val in value.items(): total = total + val for ky,val in value.items(): analyzed_data[key][ky]=analyzed_data[key][ky]/total return def generate_visualize_output(one_medicine, x, output_data): sss=x print(one_medicine) print(type(x),x) fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) if sss ==1: output_data = one_medicine else: odk = output_data.keys() odv = output_data.values() p=[] odk = ['\n'.join(wrap(l, 20)) for l in odk] order = collections.OrderedDict(sorted(output_data.items(), key=lambda t: t[1], reverse=True)[:6]) print(order) order = collections.OrderedDict(sorted(order.items(), key=lambda t: t[0])) for x in order: p.append(float(output_data[x])) prob_show = ['\n'.join(wrap(l, 20)) for l in order] prescription = "" i = 0 for medicine in medicines_array: if i < len(medicines_array) - 1: if prescription == "": prescription += medicines_array[i] else: prescription += "," + medicines_array[i] i = i + 1 ax2.barh(np.arange(len(order)), p, align='center', color=cool_colors) ax2.set_yticks(np.arange(len(order))) ax2.set_yticklabels(prob_show) ax2.set_title(prescription) for p in output_data.keys(): if p in one_medicine.keys(): temp = float(output_data[p]) * (sss-1) temp += one_medicine[p] temp = temp/sss output_data[p] = temp else: temp = float(output_data[p]) * (sss - 1) temp = temp / sss output_data[p] = temp for p in one_medicine.keys(): if p not in output_data.keys(): output_data[p] = one_medicine[p]/sss odk = output_data.keys() odv = output_data.values() odk = ['\n'.join(wrap(l, 20)) for l in odk] # odk = ['\n'.join(wrap(l, 20)) for l in odk] order = collections.OrderedDict(sorted(output_data.items(), key=lambda t: t[1], reverse=True)[:6]) print(order) order = collections.OrderedDict(sorted(order.items(), key=lambda t: t[0])) p=[] for x in order: p.append(float(output_data[x])) prob_spec = ['\n'.join(wrap(l, 20)) for l in order] ax1.barh(np.arange(len(order)), p, align='center', color=cool_colors) # ax1.barh(np.arange(len(odk)), odv, align='center', color=cool_colors) ax1.set_yticks(np.arange(len(order))) ax1.set_yticklabels(prob_spec) prescription="" i=0 for medicine in medicines_array: if prescription=="": prescription+=medicines_array[i] else: prescription +=","+medicines_array[i] i=i+1 print(prescription) ax1.set_title(prescription) predicted_field = max(output_data.items(), key=operator.itemgetter(1))[0] probability=max(output_data.items(), key=operator.itemgetter(1))[1] print(predicted_field) print(probability) sns.plt.savefig("output101.png") sns.plt.show() return output_data def suggest_doctors(spec): print(spec) with open("abc.jsonl") as f: x=0 for line in f: # print(x) j_content = json.loads(line) speciality = j_content.get('provider_variables').get('specialty') region = j_content.get('provider_variables').get('region') settlement_type = j_content.get('provider_variables').get('settlement_type') years_of_practicing = j_content.get('provider_variables').get('years_practicing') gender=j_content.get('provider_variables').get('gender') # print(speciality) # print(spec) npi= j_content.get('npi') # print(npi) if speciality == spec: x = x + 1 print("npi: ",npi," region: ",region," settlement_type: ",settlement_type," experience: ",years_of_practicing,"gender: ",gender) if x > 10: break def generate_graphs(medicine,x,output_data): medicines_array.append(medicine) temp =x # medicine_array.append(medicine) # print(analyzed_data) fig = plt.figure() ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) freq_data = analyzed_data[medicine]["frequencies"] total_freq = analyzed_data[medicine]["frequencies"]["total"] every_speciality = freq_data.keys() max_freq = max(freq_data.items(), key=operator.itemgetter(1))[1] mean = analyzed_data[medicine]["mean"] max_mean = max(mean.items(), key=operator.itemgetter(1))[1] max_difference = max_mean - float(medicine_median[medicine]) # print( type(analyzed_data[medicine]["mean"][every_speciality[0]])) print(type(medicine_median[medicine])) print(every_speciality) total = 0 one_medicine={} for x in every_speciality: if "total" not in x: if max_freq > 5 : freq_weight = 1+ (max_freq/int(analyzed_data[medicine]["frequencies"][x])) else: freq_weight = 1 mean_weight = (float(analyzed_data[medicine]["mean"][x]) - float(medicine_median[medicine]))/max_difference # print(mean_weight) if mean_weight < 0: mean_weight = 1 / (1+abs(mean_weight)) else: mean_weight = 1 + mean_weight experience_weight = (float(analyzed_data[medicine]["experience"][x]) - float(analyzed_data[medicine]["experience"]["mean"]))/analyzed_data[medicine]["experience"]["mean"] # print(experience_weight) if experience_weight <= 0: experience_weight = 1 / (1+abs(experience_weight)) else: experience_weight = 1 + experience_weight # print(x,freq_weight,mean_weight,experience_weight) one_medicine[x] = freq_weight*mean_weight*experience_weight*500 total += one_medicine[x] for x in one_medicine.keys(): one_medicine[x] = one_medicine[x]/total print(one_medicine) order = collections.OrderedDict(sorted(one_medicine.items(), key=lambda t: t[1], reverse=True)[:6]) # print(order) order = collections.OrderedDict(sorted(order.items(), key=lambda t: t[0])) probability_spec = list(order.keys()) probability_value = list(order.values()) print(probability_value) # order = collections.OrderedDict(sorted(freq_data.items(), key=lambda t: t[1],reverse=True)[:6]) # # print(order) # order=collections.OrderedDict(sorted(order.items(), key=lambda t: t[0])) # # print(order) # print(freq_data) freq_graph_spec_list = probability_spec # index1 = freq_graph_spec_list.index('total') freq_graph_value_list = np.zeros(len(freq_graph_spec_list)) # freq_graph_spec_list.remove('total') # del freq_graph_value_list[index1] i=0 length = len(freq_graph_value_list) for spec in freq_graph_spec_list: freq_graph_value_list[i]=int(freq_data[spec]) i = i+1 print(freq_graph_spec_list) print(freq_graph_value_list) freq_graph_spec = [ '\n'.join(wrap(l, 20)) for l in freq_graph_spec_list ] ax1.barh(np.arange(length), freq_graph_value_list, align='center',color=cool_colors) ax1.set_yticks(np.arange(length)) ax1.set_yticklabels(freq_graph_spec) ax1.set_title("Frequency") ax1.legend() # ax1.yticks(length, freq_graph_spec_list) # ax1.xlabel('Usage') # ax1.barh(freq_graph_value_list, freq_graph_spec_list, color='red') # sns.barplot(x=freq_graph_spec_list, y=freq_graph_value_list,orient="v", saturation=0.8,ax=ax1) # ax1.set(xlabel='Experience in years', ylabel='Number of General Practice Doctors') # ax.savefig("output.png") # Plot # ax2.pie(sizes, explode=explode, labels=labels, colors=colors, # autopct='%1.1f%%', shadow=True, startangle=140) # # plt.axis('equal') # plt.show() region_data = analyzed_data[medicine]["region"] region_order = collections.OrderedDict(sorted(region_data.items(), key=lambda t: t[1], reverse=True)[:5]) print(region_order) order = collections.OrderedDict(sorted(order.items(), key=lambda t: t[0])) print(region_order) # print(freq_data) # # region_graph_spec_list = list(region_order.keys()) # region_graph_value_list = list(region_order.values()) # i = 0 # length = len(region_graph_value_list) # while i < 5 & i < length: # region_graph_value_list[i] = int(region_graph_value_list[i]) # i = i + 1 # print(region_graph_spec_list) # print(region_graph_value_list) # ax2.pie(region_graph_value_list, labels=region_graph_spec_list,autopct='%1.1f%%') # ax2.axis('equal') # ax2.set_title("Region Wise Distribution") # ax2.set(xlabel='Experience in years', ylabel='Number of General Practice Doctors') # ax.savefig("output.png") # sns.plt.subplot(212,ax) # print(freq_data) # mean_graph_spec_list = list(order.keys()) # mean_graph_value_list = list(order.values()) mean_graph_value_list=[] mean_graph_spec_list = freq_graph_spec_list for x in mean_graph_spec_list: mean_graph_value_list.append(analyzed_data[medicine]["mean"][x]) i = 0 length = len(mean_graph_value_list) while i < 5 & i < length: mean_graph_value_list[i] = int(mean_graph_value_list[i]) i = i + 1 print(mean_graph_spec_list) print(mean_graph_value_list) median_medicine = float(medicine_median[medicine]) # sns.barplot(x=mean_graph_spec_list, y=mean_graph_value_list, orient="v", saturation=0.8, ax=ax2) ax2.barh(np.arange(length), mean_graph_value_list, color=cool_colors,align='center') ax2.set_yticks(np.arange(length)) ax2.set_yticklabels(freq_graph_spec) ax2.set_title("Mean of value(prescribed in one year)") # ax2.yticks(length,mean_graph_spec_list) # ax2.axline(y=median_medicine) experience = analyzed_data[medicine]["experience"] # print(analyzed_data) order = collections.OrderedDict(sorted(experience.items(), key=lambda t: t[1], reverse=True)[:5]) print(order) order = collections.OrderedDict(sorted(experience.items(), key=lambda t: t[0])) print(order) # print(freq_data) experience_graph_spec_list = freq_graph_spec_list experience_graph_value_list = [] i = 0 length = len(experience_graph_value_list) for x in experience_graph_spec_list: experience_graph_value_list.append(analyzed_data[medicine]["experience"][x]) i = 0 length = len(experience_graph_value_list) while i < 5 & i < length: experience_graph_value_list[i] = int(experience_graph_value_list[i]) i = i + 1 print(experience_graph_spec_list) print(experience_graph_value_list) # sns.barplot(x=experience_graph_spec_list, y=experience_graph_value_list, orient="v", saturation=0.8, ax=ax3) ax3.barh(np.arange(length),experience_graph_value_list,color=cool_colors,align='center') ax3.set_yticks(np.arange(length)) ax3.set_yticklabels(freq_graph_spec) ax3.set_title("Mean of Experience") # ax3.yticks(length,experience_graph_spec_list) probability_spec_show = ['\n'.join(wrap(l, 20)) for l in probability_spec] ax4.barh(np.arange(len(probability_spec)), probability_value, align='center', color=cool_colors) ax4.set_yticks(np.arange(len(probability_spec))) ax4.set_yticklabels(probability_spec_show) ax4.set_title("Calculated probability just for " + medicine) ax4.legend() sns.plt.savefig("output10.png") sns.plt.show() ss=generate_visualize_output(one_medicine,temp,output_data) # generate_output(medicine,x) return ss read_medicine_median_from_csv() with open("ok.jsonl") as f: # x=0 for line in f: # print(line) # print(x) # x=x+1 j_content = json.loads(line) speciality = j_content.get('provider_variables').get('specialty') if speciality not in list_of_specialities: list_of_specialities.append(speciality) region = j_content.get('provider_variables').get('region') settlement_type = j_content.get('provider_variables').get('settlement_type') years_of_practicing = j_content.get('provider_variables').get('years_practicing') # create_speciality_data(region,settlement_type,years_of_practicing,speciality) #print(speciality) medicines = j_content.get('cms_prescription_counts') #print(medicines) # for key,value in medicines.items(): # if key not in list_of_medicines: # list_of_medicines.append(key) # print(medicines,speciality,years_of_practicing) for key, value in medicines.items(): # if key not in list_of_medicines: insert_into_analysis(key,speciality,years_of_practicing,value,region) # generate_medicine_median(key,value) # generate_medicine_region_data(region,key) # print(analyzed_data) # generate_probability(analyzed_data) # read_spec_patient_from_csv("'Acute Care'","Northeast") # print(analyzed_data) # print(medicine_median) # print(value_data) # print(speciality_region_data) # print(speciality_gender_data) # print(speciality_settlement_type_data) # write_medicine_median_as_csv(medicine_median) # write_gender_data_as_csv(speciality_gender_data) # write_region_data_as_csv(speciality_region_data) # write_settlement_data_as_csv(speciality_settlement_type_data) # write_medicine_region_data_as_csv(medicine_region_data) # write_medicine_speciality_probability_as_csv(analyzed_data) # read_medicine_median_from_csv() # print(freq_data) # print(value_data) x=0 choice=0 while(choice!="4"): print("1. Predict speciality from prescription") print("2.Suggest Doctors") print("3.Show Statistics") print("4.Exit") choice = input("What do you want to do?") ss={} if choice =="2": spec=input("Enter speciality") suggest_doctors(spec) if choice == "1": x = 1 ss=generate_graphs(input("Enter Medicine:"),x,output_data=None) # generate_output(input("Enter Medicine:"),x) add_more=input("Do you want to add more?") while(add_more!="N"): x=x+1 generate_graphs(input("Enter Medicine:"), x,ss) add_more = input("Do you want to add more?") if output_data.__len__()>0: predicted_field="'"+max(ss.items(), key=operator.itemgetter(1))[0]+"'" print(predicted_field) else: print("You have not entered valid medicine") # print("1.Suggest Doctors") print("2.Show statistics") print("3.exit") ai=input("Enter input:") if(ai=="2"): print("1.South") print("2.Midwest") print("3.West") print("4.Northeast") region_input=input("Enter Region from above to show statistics and recommendation") if region_input == "1": region_input = "South" elif region_input == "2": region_input = "Midwest" elif region_input == "3": region_input = "West" else: region_input = "Northeast" if predicted_field.__len__()>1: read_spec_patient_from_csv(predicted_field,region_input) else: print("Invalid medicine entered") else: choice=4 elif choice =="3": specialty=input("Enter Specialty:") print("1.South") print("2.Midwest") print("3.West") print("4.Northeast") region_input = input("Enter Region from above to show statistics and recommendation") if region_input == "1": region_input="South" elif region_input=="2": region_input="Midwest" elif region_input=="3": region_input="West" else: region_input="Northeast" read_spec_patient_from_csv(specialty,region_input) # while(input("Do you want to predict more?")!="N"): # x =x +1 # generate_output(input("Enter Medicine:"), x) # print(output_data) # generate_output(output_data) # else: # if speciality in key.items(): # key[speciality]+=value # else: # key[speciality]=value #print(spec.dumps()) #print(spec.values()) # if spec not in region: # region.append(spec) # print("changed") # print(region.__len__()) # print(region) ##to read region # with open("roam_prescription_based_prediction.jsonl") as f: # for line in f: # j_content = json.loads(line) # spec=j_content.get('provider_variables').get('region') # if spec not in region: # region.append(spec) # print("changed") # print(region.__len__()) # print(region)
902ad2e05519503490808df7a9f6f1532661cb6d
[ "Markdown", "Python" ]
4
Markdown
Dhrumil29/PrescriptionAnalysis-Kaggle
d524d7c0694b268e837c63a0880653592fc4b4b9
76a3ba1d04b0d46f3741dcb1932cabcec838d35a
refs/heads/master
<file_sep> /** * Module dependencies. */ var express = require('express') , routes = require('./routes') , pg = require('pg').native; var app = module.exports = express.createServer(); // Configuration app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); // Routes app.get('/', routes.index); app.post('/manage', routes.manage); app.listen(3000); console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); //Socket IO ------------ var io = require('socket.io').listen(app); var users = 0; io.sockets.on('connection', function (socket) { //Get the latest messages from database dump to screen. users++; //Increase number of online users. socket.broadcast.emit('useractivity', {users: users}); //Load all previous Messages var connectionString = "pg://postgres:postgres@localhost:5432/chatdb"; pg.connect(connectionString, function(err, client) { client.query('SELECT * FROM messages', function(err, result) { for(var i=0; i<result.rows.length; i++) { socket.emit('load', { message: result.rows[i].message, time: result.rows[i].tstamp, users: users }); //Load all previous Messages for real } }); }); socket.on('disconnect', function () { //Signal that user Left. users--; //Remove one user. socket.broadcast.emit('useractivity', {users: users}); }); socket.on('message', function(data){ //Send Messages to all users. socket.broadcast.emit('message', {user: "", message: data.message, time:data.time}); }); }); //Socket IO ------------ /* Database Testing function var pg = require('pg').native; var connectionString = "pg://postgres:postgres@localhost:5432/chatdb"; pg.connect(connectionString, function(err, client) { client.query('SELECT * FROM messages', function(err, result) { console.log("Number " + result.rows[0].message); for(var i=0; i<result.rows.length; i++) { console.log(result.rows[i].message + " " + result.rows[i].tstamp); } }); }); */<file_sep>var pg = require('pg').native; /* * GET home page. */ exports.index = function(req, res){ res.render('index', { title: 'MaxChat' }) }; exports.manage = function(req, res){ //Post to database //console.log('Message: ' + req.body.message); //Sanatize imput for the love of god. if(req.body.message.length <= 140){ //Make sure message is not to long if the client side JS fails. var connectionString = "pg://postgres:postgres@localhost:5432/chatdb"; pg.connect(connectionString, function(err, client) { client.query('INSERT INTO messages VALUES(default, $1, now())',[req.body.message], function(err, result) { //Return something if message was inserted correctly. res.render('manage', { title: 'yup', data: 'Yup' }) }); }); } };//<file_sep>// JavaScript Document bitch $(document).ready(function() { //Submit Message Function $('#textbox').keyup(function(event){ var t = $('#textbox').val(); //Message in text box. $('#lettercount').text("" +(t.length - 140)); if(t.length >= 140){//Alert stupid user that message is to long. $('#textbox').val(t.substring(0,140)); //Cut off last letter $('#lettercount').hide().text("Character Limit").fadeIn(500); //Redo Number } var keycode = (event.keyCode ? event.keyCode : event.which); if(keycode == '13'){ $('#textbox').hide().val("").fadeIn(500); $('#lettercount').hide().text("-140").fadeIn(500); //Redo Number $.post("/manage", { message: t}, function(data) { socket.emit('message',{message:t, date: goodDate() }); //Only works if server returns info. addMessage(0, t, goodDate(), 1); //Add Users Own Message. }); } }); //Make the textbox super pretty. $('#textbox').focus(function(srcc){ if ($(this).val() == $(this)[0].title){ $(this).removeClass("defaultTextActive"); $(this).val(""); }}); $('#textbox').blur(function(){ if ($(this).val() == ""){ $(this).addClass("defaultTextActive"); $(this).val($(this)[0].title); }}); $('#textbox').blur(); }); //Functions for adding chat messages. function addMessage(user, message, time, owner){ var ul = ""; if(owner == 1){ ul = " color2"; } $('#conversationbox').append('<div class="color'+color+ul+'">'+message+'<div class=tstamp>'+time+'</div></div>'); $('#conversationbox').scrollTop($('#conversationbox')[0].scrollHeight); //Scroll to bottom of chat box. alternateRow(); } var color = 0; function alternateRow(){ if(color == 0){ color = 1} else { color = 0; } } function goodDate(){ var currentTime = new Date() var month = currentTime.getMonth()+1 var day = currentTime.getDate() var year = currentTime.getFullYear() return year + "-" + (("0"+month).slice(-2)) + "-" + (("0"+day).slice(-2)); } //Socket.io var socket = io.connect('http://localhost'); socket.on('useractivity', function(data){ $('#usersonline').hide().text("Users Online: "+data.users).fadeIn('slow'); //Load number of users. }); socket.on('load', function (data) { //Load previous messages on connect addMessage("", data.message, data.time, 0); $('#usersonline').text("Users Online: "+data.users); //Load number of users. }); socket.on('message', function (data) { //Adds new message when it comes in addMessage(data.user, data.message, goodDate(), 0); });
d77addf272c50840329403facd391d1a28dfa1f8
[ "JavaScript" ]
3
JavaScript
stimularity/Node-Chat
5b840ae433539d1e33262bc14c42c7db0be68d89
3e1fbf32821844243c6c7a5b9fa81fd87d03523d
refs/heads/master
<file_sep>"""pytest-localstack constants.""" import botocore from pytest_localstack import utils # IP for localhost LOCALHOST = "127.0.0.1" # The default AWS region. DEFAULT_AWS_REGION = "us-east-1" # The default AWS access key. DEFAULT_AWS_ACCESS_KEY_ID = "accesskey" # The default AWS secret access key. DEFAULT_AWS_SECRET_ACCESS_KEY = "secretkey" # The default AWS session token. DEFAULT_AWS_SESSION_TOKEN = "token" DEFAULT_CONTAINER_START_TIMEOUT = 60 DEFAULT_CONTAINER_STOP_TIMEOUT = 10 BOTOCORE_VERSION = utils.get_version_tuple(botocore.__version__) <file_sep>from pytest_localstack.service_checks import port_check, botocore_check_response_type class Service: def __init__(self, name, check, pro=False): self.pro = pro self.name = name self.check = check SERVICES = { s.name: s for s in [ Service("apigateway", port_check("apigateway")), Service("amplify", botocore_check_response_type("amplify", "list_apps", list, "apps"), True), Service("appsync", botocore_check_response_type("appsync", "list_graphql_apis", list, "graphqlApis"), True), Service("athena", botocore_check_response_type("athena", "list_data_catalogs", list, "DataCatalogsSummary"), True), Service("cloudformation", botocore_check_response_type("cloudformation", "list_stacks", list, "StackSummaries")), Service("cloudfront", botocore_check_response_type("cloudfront", "list_distributions", list, "DistributionList"), True), Service("cloudtrail", botocore_check_response_type("cloudtrail", "list_trails", list, "Trails"), True), Service("cloudwatch", botocore_check_response_type("cloudwatch", "list_dashboards", list, "DashboardEntries")), Service("codecommit", botocore_check_response_type("codecommit", "list_repositories", list, "repositories"), True), Service("cognito", botocore_check_response_type("cognito-identity", "list_identity_pools", list, "IdentityPools"), True), Service("dynamodb", botocore_check_response_type("dynamodb", "list_tables", list, "TableNames")), Service("dynamodbstreams", botocore_check_response_type("dynamodbstreams", "list_streams", list, "Streams")), Service("ecr", botocore_check_response_type("ecr", "describe_repositories", list, "repositories"), True), Service("ecs", botocore_check_response_type("ecs", "list_clusters", list, "clusterArns"), True), Service("eks", botocore_check_response_type("eks", "list_clusters", list, "clusters"), True), Service("ec2", botocore_check_response_type("ec2", "describe_regions", list, "Regions")), Service("elasticache", botocore_check_response_type("elasticache", "describe_cache_clusters", list, "CacheClusters")), Service("elb", botocore_check_response_type("elb", "describe_load_balancers", list, "LoadBalancerDescriptions")), Service("emr", botocore_check_response_type("emr", "list_clusters", list, "Clusters")), Service("events", botocore_check_response_type("events", "list_event_buses", list, "EventBuses")), Service("es", botocore_check_response_type("es", "list_domain_names", list, "DomainNames")), Service("firehose", botocore_check_response_type("firehose", "list_delivery_streams", list, "DeliveryStreamNames")), Service("glacier", botocore_check_response_type("glacier", "list_vaults", list, "VaultList")), Service("glue", botocore_check_response_type("glue", "list_crawlers", list, "CrawlerNames")), Service("iot", botocore_check_response_type("iot", "list_streams", list, "streams")), Service("iam", botocore_check_response_type("iam", "list_roles", list, "Roles")), Service("kinesis", botocore_check_response_type("kinesis", "list_streams", list, "StreamNames")), Service("kafka", botocore_check_response_type("kafka", "list_clusters", list, "ClusterInfoList")), Service("kinesisanalytics", botocore_check_response_type("kinesisanalytics", "list_applications", list, "ApplicationSummaries")), Service("kms", botocore_check_response_type("kms", "list_keys", list, "Keys")), Service("lambda", botocore_check_response_type("lambda", "list_functions", list, "Functions")), Service("mediastore", botocore_check_response_type("mediastore", "list_containers", list, "Containers")), Service("organizations", botocore_check_response_type("organizations", "list_accounts", list, "Accounts")), Service("logs", botocore_check_response_type("logs", "describe_log_groups", list, "logGroups")), Service("redshift", botocore_check_response_type("redshift", "describe_clusters", list, "Clusters")), Service("route53", port_check("route53")), Service("qldb", botocore_check_response_type("qldb", "list_ledgers", list, "Ledgers")), Service("rds", botocore_check_response_type("rds", "describe_db_instances", list, "DBInstances")), Service("s3", botocore_check_response_type("s3", "list_buckets", list, "Buckets")), Service("secretsmanager", botocore_check_response_type("secretsmanager", "list_secrets", list, "SecretList")), Service("ses", botocore_check_response_type("ses", "list_identities", list, "Identities")), Service("sns", botocore_check_response_type("sns", "list_topics", list, "Topics")), # https://github.com/boto/boto3/issues/1813 Service("sqs", botocore_check_response_type("sqs", "list_queues", dict)), Service("ssm", botocore_check_response_type("ssm", "describe_parameters", list, "Parameters")), Service("stepfunctions", botocore_check_response_type("stepfunctions", "list_activities", list, "activities")), Service("timestream", botocore_check_response_type("timestream-query", "describe_endpoints", list, "Endpoints")), Service("transfer", botocore_check_response_type("transfer", "list_servers", list, "Servers")), Service("xray", port_check("xray")), ]}
a28bb10edae1db1fccfc72bf913768f0cf7839e2
[ "Python" ]
2
Python
foxglove-tech/pytest-localstack
9e6ef4f9f72ec5cf4adf5df234c7c9a9b7631b87
49c8a39a63946cee6a8915d540bdefd751afd6dc
refs/heads/master
<repo_name>urield94/BPjs-Web<file_sep>/Hanoi/js/Display.js function getName(num) { return num === 0 ? "pole.gif" : "disk" + num + ".gif"; } function message(str, force) { if (force || !game_is_over && !show_messages) document.disp.message.value = str; } function draw_board() { for (let j = 0; j < board.length; j++) { let td = document.createElement("td"); let a1 = document.createElement("a"); a1.setAttribute("href", "javascript:poll_clicked(" + j + ")"); a1.setAttribute("class", "poll("+j+")"); let img1 = document.createElement("img"); img1.setAttribute("src", imgdir + "poletop.gif"); a1.appendChild(img1); a1.appendChild(document.createElement("br")); td.appendChild(a1); for (let i = 0; i < board[j].length; i++) { let a2 = document.createElement("a"); if (board[j][i] === 0) { a2.setAttribute("href", "javascript:poll_clicked(" + j + ")"); a2.setAttribute("id", "poll("+i+","+j+")"); } else { a2.setAttribute("href", "javascript:disk_clicked(" + i + "," + j + ")"); a2.setAttribute("id", "disk("+i+","+j+")"); } let img2 = document.createElement("img"); img2.setAttribute("src", imgdir + getName(board[j][i])); img2.setAttribute("name", "pos" + j + i); a2.appendChild(img2); a2.appendChild(document.createElement("br")); td.appendChild(a2); } document.getElementById("gameTableRow").appendChild(td); } message("You may begin! Select a piece to move."); } function init_board(start_pole, disks) { let len = max_disks + 1; selected_col = null; selected_row = null; game_is_over = false; end_pole = (start_pole - 1 < 0 ? max_poles - 1 : start_pole - 1); for (let i = 0; i < len; i++) { for (let j = 0; j < max_poles; j++) { board[j][i] = 0; } } for (let i = len - disks, j = 0; i < len; i++, j++) { board[start_pole][i] = len - j - 1; } } function init() { init_board(start_pole, disks); start(); draw_board(); } <file_sep>/Hanoi/js/Hanoi.js <!-- Original: <NAME> (<EMAIL>) --> <!-- (c) Copyright 1998-99 <NAME>. All Rights Reserved --> <!-- You have permission to republish this code provided --> <!-- that you do not remove this copyright notice --> // change this to where you upload the images to your site imgdir = "img/"; function preload() { this.length = preload.arguments.length; for (let i = 0; i < this.length; i++) { this[i] = new Image(); this[i].src = imgdir + preload.arguments[i]; } } let pics = new preload("disk1.gif", "disk2.gif", "disk3.gif", "disk4.gif", "disk5.gif", "disk6.gif", "disk7.gif", "disk1h.gif", "disk2h.gif", "disk3h.gif", "disk4h.gif", "disk5h.gif", "disk6h.gif", "disk7h.gif"); let selected_row; let selected_col; let end_pole; let game_is_over; let max_poles = 3; let max_disks = 7; let all_poles = 3; let start_pole = 1; let disks = 3; let show_messages = false; let board = new Array(max_poles); for (let i = 0; i < max_poles; i++) { board[i] = new Array(max_disks + 1); } function check_selection(j) { return selected_col === j; } function is_empty(num) { for (let i = 0; i < board[num].length; i++) { if (board[num][i] !== 0) return false; } return true; } function top_most(num) { for (let i = 0; i < board[num].length; i++) { if (board[num][i] !== 0) return i; } return -1; } function is_pole(i, j) { return (board[j][i] === 0); } function legal_step(j) { if (is_empty(j)) return true; return (board[j][top_most(j)] < board[selected_col][selected_row]); } function is_selection() { return selected_col != null; } function choose_disk(num) { let top_pos = top_most(num); //Check if the piece that was selected is the most top in the array if (selected_col === num && selected_row === top_pos) { selected_col = null; selected_row = null; animate(num, top_pos, "disk" + board[num][top_pos] + ".gif"); message("Select a piece to move."); return; } if (is_selection()) { animate(selected_col, selected_row, "disk" + board[selected_col][selected_row] + ".gif"); } selected_col = num; selected_row = top_pos; animate(num, top_pos, "disk" + board[num][top_pos] + "h.gif"); message("Click on the pole to which you want to move the disk."); } function move(num) { let top_pos = (!is_empty(num) ? top_most(num) : board[num].length); board[num][top_pos - 1] = board[selected_col][selected_row]; board[selected_col][selected_row] = 0; animate(selected_col, selected_row, "pole.gif"); animate(num, top_pos - 1, "disk" + board[num][top_pos - 1] + ".gif"); move_disk_to_poll(num, top_pos); selected_col = null; selected_row = null; message("Select a piece to move."); } function move_disk_to_poll(num, top_pos) { let disk_to_poll = document.getElementById("disk(" + selected_row + "," + selected_col + ")"); let poll_to_disk = document.getElementById("poll(" + (top_pos - 1) + "," + num + ")"); disk_to_poll.setAttribute("id", "poll(" + selected_row + "," + selected_col + ")"); disk_to_poll.setAttribute("href", "javascript:poll_clicked(" + selected_col + ")"); poll_to_disk.setAttribute("id", "disk(" + (top_pos - 1) + "," + num + ")"); poll_to_disk.setAttribute("href", "javascript:disk_clicked(" + (top_pos - 1) + "," + num + ")"); } function hanoi(no_of_disks, start_pole, goal_pole) { if (no_of_disks > 0) { let free_pole = all_poles - start_pole - goal_pole; hanoi(no_of_disks - 1, start_pole, free_pole); disk_clicked(top_most(start_pole), start_pole); poll_clicked(goal_pole); hanoi(no_of_disks - 1, free_pole, goal_pole); } } function check_game_status() { let filled_pole = null; let val = 0; for (let k = 0; k < board.length; k++) { val += (is_empty(k) ? 1 : 0); if (!is_empty(k)) filled_pole = k; } if (val === 2 && is_empty(start_pole)) { game_end(filled_pole); } } <file_sep>/BPjs_runner.js /** * collect_initial_snapshot - For every generator, invoke and restore the returned value along with the generator. * * @param bThreads - List of generator functions received at initialisation. * * @return - snapshots: List of snapshot as described at update_snapshot. **/ function collect_initial_snapshot(bThreads) { let snapshots = []; bThreads.forEach(function (bt) { let snapshot = bt.next(); snapshot['bt'] = bt; snapshots.push(snapshot); }); return snapshots; } /** * next_event - Collect all 'request' event that aren't blocked. * * @param snapshots - List of snapshot as described at update_snapshot. * * @return - List of 'request' event, or false if there are none or they all blocked. **/ function next_event(snapshots) { let requested = []; blocked = []; snapshots.forEach(function (snapshot) { if (snapshot.value) { if (snapshot.value['request']) { requested = requested.concat(snapshot.value['request']); } if (snapshot.value['block']) { blocked = blocked.concat(snapshot.value['block']); } } }); // candidates = requested - blocked let candidates = requested.filter(function (x) { return blocked.includes(x); }); if (candidates.length > 0) { return candidates[Math.floor(Math.random() * candidates.length)]; } else { return false; } } /** * update_snapshot - Invoke event e out of snapshot['bt'], and change the value of snapshot with the returned value of the event. * * @param snapshot - * snapshot.value - Dict of b-threads {'wait-for': list, 'request': list, 'block': list}. * snapshot['bt'] - The generator that wait-for\request the event e. * @param e - The event that will be invoked **/ function update_snapshot(snapshot, e) { snapshot.value['wait_for'] = []; snapshot.value['request'] = []; snapshot.value['block'] = []; snapshot.value = snapshot['bt'].next(e).value; //Wait here for the b-thread to finish it job and return new yield value. } /** * advance_bthrads - Search the event e in every snapshot wait-for/request entry, and invoke if found. * * @param snapshots - List of snapshot as described at update_snapshot. * @param e - The event that will be invoked. * * @return - snapshots **/ function advance_bthrads(snapshots, e) { snapshots.forEach(function (snapshot) { if (snapshot.value) { let wf = snapshot.value['wait_for']; let req = snapshot.value['request']; if ((wf && wf.includes(e)) || (req && req.includes(e))) { update_snapshot(snapshot, e); } } }); return snapshots; } /** * run (Generator)- Collect snapshot from the received b-threads, and get the new requested events. * If there were no 'request' events that aren't blocked, wait for the controller to receive an event. * When event e occur, the run generator will activate and will invoke the e unless it blocked. * In every iteration the b-threads that were activated by the generator invoke new b-threads, unless they dead. * * @param bThreads - List of generator functions. **/ function* run(bThreads) { let snapshots = collect_initial_snapshot(bThreads); while (true) { let e = next_event(snapshots); if (!e) { do { e = yield; } while (blocked.includes(e)) } snapshots = advance_bthrads(snapshots, e); } } <file_sep>/Hanoi/js/Animation.js function Animation() { this.imageNum = []; // Array of indicies document.images to be changed this.imageSrc = []; // Array of new srcs for imageNum array this.frameIndex = 0; // the frame to play next this.alreadyPlaying = false; // semaphore to ensure we play smoothly this.getFrameCount = get_frame_count; // the total numebr of frame so far this.moreFrames = more_frames; // tells us if there are more frames to play this.addFrame = add_frame; // add a frame to the animation this.drawNextFrame = draw_next_frame; // draws the next frame this.startAnimation = start_animation; // init the animation if necessary } function get_frame_count() { return this.imageNum.length; } function more_frames() { return this.frameIndex < this.getFrameCount(); } function start_animation() { if (!this.alreadyPlaying) { theAnim.alreadyPlaying = true; setTimeout('theAnim.drawNextFrame()', 5); } } function add_frame(num, src) { let theIndex = theAnim.imageNum.length; theAnim.imageSrc[theIndex] = src; theAnim.imageNum[theIndex] = num; theAnim.startAnimation(); } function draw_next_frame() { if (theAnim.moreFrames()) { document.images[theAnim.imageNum[theAnim.frameIndex]].src = theAnim.imageSrc[theAnim.frameIndex]; theAnim.frameIndex++; setTimeout('theAnim.drawNextFrame()', 30); } else { theAnim.alreadyPlaying = false; } } function animate(x, y, name) { theAnim.addFrame("pos" + x + "" + y, imgdir + name); } let theAnim = new Animation(); <file_sep>/README.md # BPjs-Web BPjs-Web is a b-thread runner that allow inegration of b-threads in web pages using javascript. The main function of the runner is run which described as follow (from the documentation): run (Generator)- Collect snapshot from the received b-threads, and get the new requested events. If there were no 'request' events that aren't blocked, wait for the controller to receive an event. When event e occur, the run generator will activate and will invoke the e unless it blocked. In every iteration the b-threads that were activated by the generator invoke new b-threads, unless they dead. @param bThreads - List of generator functions. In the 'Hanoi' example we use the BPjs-Web runner as controller, that collect events from the user and pass them to the runner for execution. * http://www.hanoi-bpjs.rf.gd/?i=1 More information about BPjs can be found here- * https://github.com/bThink-BGU/BPjs * https://bpjs.readthedocs.io/ <file_sep>/Hanoi/js/Controller.js let controller; let diskClick = []; let pollClick = []; let restartEvents = []; let terminate = []; function start() { console.log("starting..."); for (let j = 0; j < max_poles; j++) { restartEvents.push('restarter(' + j + ')'); pollClick.push("poll_clicker(" + j + ")"); terminate.push('terminate(' + j + ')'); for (let i = 0; i < max_disks + 1; i++) { diskClick.push("disk_clicker(" + i + ',' + j + ')'); } } controller = run([ disk_clicker(), poll_clicker(), restarter(), terminator()]); controller.next(); } function restart(start_pole) { controller.next("restarter(" + start_pole + ")"); } function disk_clicked(i, j) { controller.next('disk_clicker(' + i + ',' + j + ')'); } function poll_clicked(j) { controller.next('poll_clicker(' + j + ')'); check_game_status(); } function game_end(filled_pole) { controller.next('terminate(' + filled_pole + ')'); } function hanoi_solve(disks, start_pole, end_pole) { restart(start_pole); hanoi(disks, start_pole, end_pole); } function change_start_pole() { start_pole = document.forms[0].start_select.options[document.forms[0].start_select.selectedIndex].text - 1; restart(start_pole); }
f4e609fb731e239961a4b3b2f8d9ac4fc972185d
[ "JavaScript", "Markdown" ]
6
JavaScript
urield94/BPjs-Web
4fabc7ece250908a20f250fcdc2787bbaed49db3
32b6e95a365198e77b73a607aea09cab1cab1ce6
refs/heads/master
<file_sep> const sequelize = require('sequelize') const db = new sequelize('shopdb','shopper','shoppass',{ host : 'localhost', dialect : 'mysql', pool :{ min:0, max:5, } }) const User = db.define('users',{ id : { type :sequelize.INTEGER, autoIncrement : true, primaryKey : true }, name : { type : sequelize.STRING, allowNULL :false, } }) const Product = db.define('product',{ id : { type :sequelize.INTEGER, autoIncrement : true, primaryKey : true }, name :{ type : sequelize.STRING, allowNULL : false }, manufacturer : sequelize.STRING, price :{ type : sequelize.FLOAT, allowNULL : false, defaultValue : 0.0 } }) // for db to be created db.sync() .then(()=> console.log("database has been synced")) .catch(()=> console.error("error in creating database")) exports = module.exports ={ User , Product }
c4c2608c1b14c595a7eb492d31b7e86dc7ffdef5
[ "JavaScript" ]
1
JavaScript
truly-indian/web14-shoppingcart
bb60122fd8bb86654e221d25439ea271e00c7682
c6c131b547067349a8609458c51bf215100b2480
refs/heads/master
<repo_name>1768012206/python<file_sep>/setup.py from distutils.core import setup import py2exe setup(console = ['server.py'], windows = ['login.py','server_sql.py'])<file_sep>/client-chat.py #!/usr/bin/python # encoding: utf-8 import wx import argparse import socket import thread sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) a = 0 class ChatFrame(wx.Frame): """ 聊天窗口 """ def __init__(self, parent, id, title, size): '初始化,添加控件并绑定事件' wx.Frame.__init__(self, parent, id, title) self.SetSize(size) self.Center() self.chatFrame = wx.TextCtrl(self, pos = (5, 5), size = (490, 310), style = wx.TE_MULTILINE | wx.TE_READONLY) self.message = wx.TextCtrl(self, pos = (5, 320), size = (300, 25)) self.sendButton = wx.Button(self, label = "Send", pos = (310, 320), size = (58, 25)) #self.usersButton = wx.Button(self, label = "connect", pos = (373, 320), size = (58, 25)) self.closeButton = wx.Button(self, label = "Close", pos = (436, 320), size = (58, 25)) self.sendButton.Bind(wx.EVT_BUTTON, self.send) self.closeButton.Bind(wx.EVT_BUTTON, self.close) #self.usersButton.Bind(wx.EVT_BUTTON,self.connect) thread.start_new_thread(self.connect,()) thread.start_new_thread(self.recv, ()) self.Show() #---------------------------------------------------------------------- def connect(self): host = "localhost" port = 6666 socket_address = (host, port) sock.connect(socket_address) print "success" #while True: #result = sock.recv(1024) ##if result != '': #self.chatFrame.AppendText(result) def send(self, event): '发送消息' message = str(self.message.GetLineText(0)).strip() if message != '': sock.send(message.encode(encoding="utf-8")) self.message.Clear() def close(self, event): '关闭窗口' sock.close() self.Close() #---------------------------------------------------------------------- def recv(self): while True: result = sock.recv(1024) self.chatFrame.AppendText(result) '程序运行' if __name__ == '__main__': app = wx.App() ChatFrame(None, -1, title = "chat", size = (500, 600)) app.MainLoop()<file_sep>/server_sql.py #coding:utf-8 from tkinter import * import pymssql from tkinter import ttk import _mssql import decimal import uuid _mssql.__doc__ decimal.__doc__ uuid.__author__ """SQL""" class Mssql(object): def __init__(self, config): self.cf = config def __Connect(self): try: self.conn = pymssql.connect(host=self.cf['host'],user=self.cf['user'],password=self.cf['pwd'],database=self.cf['db']) cur = self.conn.cursor() except Exception: print("fail to access") sys.exit(1) return cur def select(self, sql): try: cur = self.__Connect() cur.execute(sql) rows = cur.fetchall() cur.close() self.conn.close() return rows except Exception: print ("Error decoding config file: select") sys.exit(1) def delete(self, sql): try: cur = self.__Connect() cur.execute(sql) cur.close() self.conn.commit() self.conn.close() except Exception: print ("Error decoding config file: delete") sys.exit(2) def insert(self, sql): try: cur = self.__Connect() cur.execute(sql) cur.close() self.conn.commit() self.conn.close() except Exception: print ("Error decoding config file: insert") sys.exit(1) #---------------------------------------------------------------------- def item_connect(): hint = "无数据!" listbox.delete(0,listbox.size()) config = {'host':'localhost','user':'sa','pwd':'<PASSWORD>','db':'test2'} mssql = Mssql(config) sql = "select * from users" rows = mssql.select(sql) if rows: i = 0 while(i < len(rows)): for index in range(1): rows_list = list(rows[i]) listbox.insert(0,rows_list) i = i + 1 return rows_list else: listbox.insert(0,hint) #---------------------------------------------------------------------- def item_delect(Event): """delect item and flush""" temp_list = list(listbox.selection_get()) i = 2 temp_str = '' use_str = '' while temp_list[i] != '\'': temp_str = temp_list[i] use_str += temp_str i += 1 config = {'host':'localhost','user':'sa','pwd':'<PASSWORD>','db':'test2'} sql = "delete users where username = " yinghao = "\'" use_str = yinghao + use_str + yinghao sql += use_str mssql = Mssql(config) row = mssql.delete(sql) item_connect() #---------------------------------------------------------------------- def item_insert(): top = Toplevel() top.geometry('180x120+50+50') top.title('新增用户窗口') l1 = Label(top, text = '用户名:') l2 = Label(top, text = '密 码:') l3 = Label(top, text = '') l1.grid(row = 0, column = 0) l2.grid(row = 1, column = 0) l3.grid(row = 3, column = 0) users = StringVar() password = StringVar() entry1 = ttk.Entry(top, width = 10, textvariable = users) entry1.grid(column = 2, columnspan = 2, row = 0, sticky = (W, E)) entry2 = ttk.Entry(top, width = 10, textvariable = password) entry2.grid(column = 2, columnspan = 2, row = 1, sticky = (W, E)) rows_list = item_connect() def _send(): _users = users.get() _password = password.get() if _users.strip() == "" or _password.strip() == "": l3.config(text = "输入不正确") elif len(_password) < 6: l3.config(text = "密码不要少于6位") elif rows_list: if _users.strip() == rows_list[0]: l3.config(text = "此用户已存在") else: config = {'host':'localhost','user':'sa','pwd':'<PASSWORD>','db':'test2'} mssql = Mssql(config) sql = "insert into users values('" sql += _users sql += '\'' sql += ',' sql += '\'' sql += _password sql += '\'' sql += ',' sql += '\'' sql += "vip" sql += '\'' sql += ')' mssql.insert(sql) top.destroy() item_connect() else: config = {'host':'localhost','user':'sa','pwd':'<PASSWORD>','db':'test2'} mssql = Mssql(config) sql = "insert into users values('" sql += _users sql += '\'' sql += ',' sql += '\'' sql += _password sql += '\'' sql += ',' sql += '\'' sql += "vip" sql += '\'' sql += ')' mssql.insert(sql) top.destroy() item_connect() btn_send = Button(top, text = "确 认", command = _send) btn_send.grid(column = 2, columnspan = 2, row = 3, sticky = (W, E)) #---------------------------------------------------------------------- def item_change1(): temp_list = list(listbox.selection_get()) i = 2 temp_str = '' use_str = '' while temp_list[i] != '\'': temp_str = temp_list[i] use_str += temp_str i += 1 config = {'host':'localhost','user':'sa','pwd':'<PASSWORD>','db':'test2'} sql = "update users set vip = 'vip' where username = " yinghao = "\'" use_str = yinghao + use_str + yinghao sql += use_str mssql = Mssql(config) row = mssql.delete(sql) item_connect() def item_change2(): temp_list = list(listbox.selection_get()) i = 2 temp_str = '' use_str = '' while temp_list[i] != '\'': temp_str = temp_list[i] use_str += temp_str i += 1 config = {'host':'localhost','user':'sa','pwd':'<PASSWORD>','db':'test2'} sql = "update users set vip = 'p' where username = " yinghao = "\'" use_str = yinghao + use_str + yinghao sql += use_str mssql = Mssql(config) row = mssql.delete(sql) item_connect() #---------------------------------------------------------------------- def item_passchange(): """change password""" temp_list = list(listbox.selection_get()) i = 2 temp_str = '' use_str = '' while temp_list[i] != '\'': temp_str = temp_list[i] use_str += temp_str i += 1 top = Toplevel() top.geometry('180x120+50+50') top.title('新增用户窗口') l1 = Label(top, text = '请输入新密码:') l1.grid(row = 0, column = 0) l2 = Label(top, text = '') l2.grid(row = 1, column = 0) newpassword = StringVar() entry1 = ttk.Entry(top, width = 10, textvariable = newpassword) entry1.grid(column = 2, columnspan = 2, row = 0, sticky = (W, E)) def _changepassword(): if entry1.get(): if len(entry1.get()) < 6: l2.config(text = "密码不要小于6位!") else: config = {'host':'localhost','user':'sa','pwd':'<PASSWORD>','db':'test2'} sql = "update users set password = " yinghao = "\'" sql += yinghao sql += entry1.get() sql += yinghao sql += "where username = " nonlocal use_str use_str = yinghao + use_str + yinghao sql += use_str mssql = Mssql(config) row = mssql.delete(sql) top.destroy() item_connect() else: l2.config(text = '密码不能为空!') _btn = Button(top, text = "确 认", command = _changepassword) _btn.grid(column = 1, columnspan = 2, row = 1, sticky = (W, E)) root = Tk() """btn1""" btn1 = Button(root, text = "查 看 用 户", command = item_connect) btn1.grid(row = 0, column = 0, sticky = W) """btn2""" btn2 = Button(root, text = "删 除 用 户") btn2.bind("<Button-1>",item_delect) btn2.grid(row = 0, column = 0, sticky = E) """btn3""" btn3 = Button(root, text = "新 增 用 户", command = item_insert) btn3.grid(row = 1, column = 0, sticky = W) btn4 = Button(root, text = "提 升 为 vip", command = item_change1) btn4.grid(row = 1, column = 0, sticky = E) """btn5""" btn5 = Button(root, text = "降为普通用户", command = item_change2) btn5.grid(row = 2, column = 0, sticky = W) """btn6""" btn6 = Button(root, text = "更 改 密 码", command = item_passchange) btn6.grid(row = 2, column = 0, sticky = E) listbox = Listbox(root, width = 30) listbox.grid(row = 4, column = 0) root.mainloop()<file_sep>/login.py #coding:utf-8 from tkinter import * from tkinter import ttk import socket #---------------------------------------------------------------------- def _socket(): """socket连接""" name = users.get() secret = password.get() name = bytes(name,'utf-8') secret = bytes(secret,'utf-8') host = "localhost"#"192.168.127.12" post = 2002 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (host, post) sock.connect(server_address) sock.send(name) sock.send(b',') sock.send(secret) recall = sock.recv(1024).decode('utf-8') hint.config(text = recall) """主界面""" root = Tk() root.title("登陆界面") """mainframe""" mainframe = ttk.Frame(root, padding = "3 3 12 12") mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S)) mainframe.columnconfigure(0, weight = 1) mainframe.rowconfigure(0, weight = 1) users = StringVar() password = StringVar() ttk.Label(mainframe, text = "密码").grid(column = 1, row = 2, sticky = (W, E)) pass_entry = ttk.Entry(mainframe, width = 10, textvariable = password) pass_entry.grid(column = 2, columnspan = 2, row = 2, sticky = (W, E)) hint = Label(mainframe, text = "提示") hint.grid(column = 1, row = 3, sticky = (W, E)) ttk.Label(mainframe, text = "用户名").grid(column = 1, row = 1, sticky = (W, E)) uname_entry = ttk.Entry(mainframe, width = 10, textvariable = users) uname_entry.grid(column = 2, columnspan = 2, row = 1, sticky = (W, E)) ttk.Button(mainframe, text = "确 定", command = _socket).grid(column = 2, row = 3, sticky = W) ttk.Button(mainframe, text = "取 消").grid(column = 3, row = 3, sticky = W) for child in mainframe.winfo_children(): child.grid_configure(padx = 5, pady = 5) uname_entry.focus() root.mainloop() <file_sep>/server-chat.py #!/usr/bin/python # encoding: utf-8 import socket import argparse port = 6666 #端口 host = 'localhost' #---------------------------------------------------------------------- def server(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_adress = (host,port) sock.bind(server_adress) sock.listen(5) client, address = sock.accept() while True: data = client.recv(1024) data = str(data) print data if data: client.send(data.encode(encoding="utf-8")) if __name__ == '__main__': server()
766fc45b371696cc15822a52d32b7c28b28de76e
[ "Python" ]
5
Python
1768012206/python
7d2a70aa4167a5ce76e2d044474f5bba9f01a9d7
b0edb9d25e72c46b0c59a5bb7be5328396ff1f96
refs/heads/master
<repo_name>pierreclr/datananas-test<file_sep>/public/mainController.js /** * Created by pierreclr on 10/03/2016. */ var app = angular.module('app', []); angular.module('app').controller('mainController', ['$scope','$http', function($scope, $http) { $scope.subject = "Subject"; $scope.message = "Here you can paste your message !"; $scope.responses = null; $scope.sendMail = function(obj, msg){ $http.post('/analyse', {obj: obj, msg: msg}) .success(function(res){ console.log(res); $scope.responses = res; }); } }]);<file_sep>/README.md # Rate my cold email <file_sep>/app.js 'use strict'; var path = require('path'); var express = require('express'), bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.json()); app.use(express.static(path.join(__dirname, 'public'), {index: false})); app.get('/*', function (req, res) { res.sendFile(path.resolve(__dirname, 'public', 'index.html')); }); app.post('/analyse', function (req, res) { if (!req.body.obj || !req.body.msg) { return res.status(400).json({ error: 'MISSING_PARAMS', message: '`obj` & `body` are mandatory' }); } require('./analyse.js')(req.param('obj'), req.param('body'), function (err, result) { if (err) { return res.status(400).json({ error: 'ANALYSING_ERROR', message: err }); } res.json(result); }); }); app.listen(3000, function () { console.log('Server started on 3000!'); }); <file_sep>/rules/variables.js 'use strict'; module.exports = { name: 'Variables', description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Omnis inventore labore quo fugit aliquid ab reiciendis! Omnis earum, eos accusantium ab voluptatibus corporis quisquam quam nobis maxime totam similique, dolore!', rule: function (obj, msg) { var reg = /{{\w*}}|(\[\w\])|#{\w*}|%\w*%/gm; return (msg.match(reg) === null) ? false : true; } };
8332b08198448df69a58758f579af6b2c18e22fe
[ "JavaScript", "Markdown" ]
4
JavaScript
pierreclr/datananas-test
7b318b33fa555065c6b973765027d6bbabcf4d0c
dcb9ad6de02beb712e55e91e17c9dcbf9a644cc6
refs/heads/master
<repo_name>adolfo-tamayo/cra-build-watch<file_sep>/bin/cra-build-watch.js #!/usr/bin/env node 'use strict'; /* eslint-disable no-process-exit */ const spawn = require('cross-spawn'); const chalk = require('chalk'); const resolveCwd = require('resolve-cwd'); // require it here to handle --help before checking prerequisites require('../utils/cliHandler'); // quick way of checking that react-scripts is installed in the current project if (!resolveCwd.silent('react-scripts/bin/react-scripts')) { console.log(); console.log(chalk`[{redBright.bold ERROR}] react-scripts must be installed in your project`); process.exit(1); } const [, , ...restArgs] = process.argv; const scriptPath = require.resolve('../scripts'); const scriptArgs = [scriptPath, ...restArgs]; const result = spawn.sync('node', scriptArgs, { stdio: 'inherit', cwd: process.cwd() }); process.exit(result.status);
7665c59c787cdc6f47aa474c98dc8bdb86fc3c97
[ "JavaScript" ]
1
JavaScript
adolfo-tamayo/cra-build-watch
2c78f3a406d1d8af72206a7124c54374a228397f
bc7ad67c242d6255771a081f6ce6763fe8c1ac0d
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { #region 冒泡排序 int temp; int[] arrSort = new int[] { 10, 8, 3, 5, 6, 7, 9 }; for (int i = 0; i < arrSort.Length; i++) { for (int j = i + 1; j < arrSort.Length; j++) { if (arrSort[j] < arrSort[i]) { temp = arrSort[j]; arrSort[j] = arrSort[i]; arrSort[i] = temp; } } } for (int i = 0; i < arrSort.Length; i++) { Console.WriteLine(arrSort[i]); } #endregion 冒泡排序 } } }
73771dded27beaa853e595e8c813661398c00832
[ "C#" ]
1
C#
cn-wwl/WWL
0c0f6c32b37a6d89b191b3c326d2c5fd1dcee037
3c9483cd92b6c4be6cfc0fe2b4badf9c474eb4e7
refs/heads/master
<file_sep>package main.kotlin import java.util.* import kotlin.system.measureTimeMillis fun bfs(board: Board, startPosition: Position): Int { val startNode = Node(position = startPosition) val bfsQueue: Queue<Node> = LinkedList() val visited: MutableSet<Node> = mutableSetOf() bfsQueue.add(startNode) visited.add(startNode) while (!bfsQueue.isEmpty()) { val currentNode = bfsQueue.remove() val currentNodePosition = currentNode.position val currentNodeRank = currentNode.rank if (board.isGoal(currentNodePosition)) { return currentNodeRank } val nonVisitedSuccessors = board.getSuccessors(currentNodePosition) .filter { !visited.any { visitedNode -> it == visitedNode.position } }.filter { !visited.any { visitedNode -> it.transpose() == visitedNode.position } } nonVisitedSuccessors.forEach { val successorNode = Node(position = it, rank = currentNodeRank + 1) visited.add(successorNode) bfsQueue.add(successorNode) } } return -1 } fun main() { val board = Board(10, 1, 1) val startPosition = Position(0, 0) println(measureTimeMillis { println(bfs(board, startPosition)) } / 1000f) }<file_sep>package main.kotlin class Board(private val size: Int, deltaX: Int, deltaY: Int) { private val displacements: List<Position> = listOf( Position(deltaX, deltaY), Position(deltaX, -deltaY), Position(-deltaX, deltaY), Position(-deltaX, -deltaY), Position(deltaY, deltaX), Position(deltaY, -deltaX), Position(-deltaY, deltaX), Position(-deltaY, -deltaX) ) fun isGoal(position: Position): Boolean { return position == Position(x = size - 1, y = size - 1) } fun getSuccessors(position: Position): List<Position> { return displacements .map { position.addDelta(it) } .filter { it.isValid(size) } } }<file_sep>package main.kotlin data class Position(val x: Int, val y: Int) { fun isValid(maxSize: Int): Boolean = x >= 0 && y >= 0 && x < maxSize && y < maxSize fun addDelta(positionDelta: Position): Position = copy(x = x + positionDelta.x, y = y + positionDelta.y) fun transpose(): Position = copy(x = y, y = x) }<file_sep>package main.kotlin data class Node(val position: Position, val rank: Int = 0)
b74148655ce66fa4f67e3af3f2991af2f9e18aea
[ "Kotlin" ]
4
Kotlin
Solero93/knightl-hackerrank
a4453de250ddcd0c031a587abf232a40078c4d0f
cfdf7c4db2b91d5b6752192463ae3229242b8f7f
refs/heads/main
<repo_name>Gixon1/Introduccion-a-pruebas-unitarias<file_sep>/Autenticar Test/UnitTest1Base.cs using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Autenticar_Test { [TestClass] public class UnitTest1Base { [TestMethod] public void TestLoginTrue() { bool result = Autenticar.Program.Login("Gixon", "<PASSWORD>"); Assert.AreEqual(true, result); } } }<file_sep>/Autenticar Test/UnitTest1.cs using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Autenticar_Test { [TestClass] public class UnitTest1 : UnitTest1Base { [TestMethod] public void TestMethod1() { string result = Autenticar.Program.Something(); Assert.AreEqual("Algo", result); } } }
1ed03244241f6377796b2f17dd55e89d84396505
[ "C#" ]
2
C#
Gixon1/Introduccion-a-pruebas-unitarias
d5061791660882beb09d50d69f26771bfdacf7cb
68279f9db0e2dbe55245b3f4114d2b59e4ac708a
refs/heads/master
<repo_name>miridstein/ReactPplTable<file_sep>/5-30-19hmwk/ClientApp/src/App.js import React from 'react'; import { render } from 'react-dom' export default class App extends Component { displayName = App.name render() { return ( <Layout> </Layout> ); } }
c7e8aa1f948b363af8511625df213e1098d39ccc
[ "JavaScript" ]
1
JavaScript
miridstein/ReactPplTable
15ebb7e604335c04066c76f2165334843bfd90ea
43c8502abc70125169be85c26efab38f1ae5fb8a
refs/heads/master
<repo_name>wangsx07/hhsadas<file_sep>/src/main/java/com/jeesite/modules/alarm/dao/AlarmInfoDao.java /** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. */ package com.jeesite.modules.alarm.dao; import com.jeesite.common.dao.CrudDao; import com.jeesite.common.mybatis.annotation.MyBatisDao; import com.jeesite.modules.alarm.entity.AlarmInfo; /** * alarm_infoDAO接口 * @author wsx * @version 2019-05-09 */ @MyBatisDao public interface AlarmInfoDao extends CrudDao<AlarmInfo> { }<file_sep>/src/main/java/com/jeesite/modules/context/Task.java package com.jeesite.modules.context; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Task implements Runnable { private Map<String, Long> m = null; public Task(Map m) { this.m = m; } @Override public void run() { // updateStatus("111111"); while (true) { long currenttime = System.currentTimeMillis(); Set<Entry<String, Long>> set = m.entrySet(); for (Entry<String, Long> entry : set) { if (currenttime - entry.getValue() > 2 * 60 * 1000) { updateStatus(entry.getKey()); m.remove(entry.getKey()); } } try { Thread.sleep(1000);// sleep 1s } catch (InterruptedException e) { e.printStackTrace(); } } } // 更新表中在线状态 private void updateStatus(String key) { String sql = Constant.sql; Connection conn = null; PreparedStatement stat = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(Constant.mysql_url, "root", "root"); stat = conn.prepareStatement(sql); stat.setString(1, key); stat.execute(); } catch (Exception e) { e.printStackTrace(); } finally { try { stat.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }<file_sep>/README.md # hhsadas 华慧视车辆管理 <file_sep>/src/main/java/com/jeesite/modules/car/dao/CarInfoDao.java /** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. */ package com.jeesite.modules.car.dao; import java.util.List; import org.springframework.context.annotation.Lazy; import com.jeesite.common.dao.CrudDao; import com.jeesite.common.mybatis.annotation.MyBatisDao; import com.jeesite.modules.car.entity.CarDriverMsg; import com.jeesite.modules.car.entity.CarInfo; import com.jeesite.modules.driver.entity.DriverInfo; /** * car_infoDAO接口 * @author wsx * @version 2019-04-23 */ @MyBatisDao public interface CarInfoDao extends CrudDao<CarInfo> { void addRelate(String driver_id, String car_id); void deleteAllRelate(String id); CarInfo findCarByImei(String imei); List<DriverInfo> findallDrivers(String carId); CarDriverMsg findMsgByCarId(String carId); //判断imei是否存在 int findImei(String imei); //更新为离线状态 void updateSta(String imei); void intiStatus(String imei); }<file_sep>/src/main/java/com/jeesite/modules/car/utils/ReturnJson.java package com.jeesite.modules.car.utils; import java.io.Serializable; import java.util.Map; public class ReturnJson implements Serializable{ private static final long serialVersionUID = 1L; private String msg; private int code; private Map data; public ReturnJson() {} public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public Map getData() { return data; } public void setDate(Map data) { this.data = data; } public ReturnJson(String msg, int code, Map data) { super(); this.msg = msg; this.code = code; this.data = data; } @Override public String toString() { return "ReturnJson [msg=" + msg + ", code=" + code + ", date=" + data + "]"; } } <file_sep>/src/main/java/com/jeesite/modules/report/entity/ReportImg.java /** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. */ package com.jeesite.modules.report.entity; import javax.validation.constraints.NotBlank; import org.hibernate.validator.constraints.Length; import com.jeesite.common.entity.DataEntity; import com.jeesite.common.mybatis.annotation.Column; import com.jeesite.common.mybatis.annotation.Table; /** * report_imgEntity * @author wsx * @version 2019-04-27 */ @Table(name="report_img", alias="a", columns={ @Column(name="id", attrName="id", label="举报id", isPK=true), @Column(name="imei", attrName="imei", label="车辆imei"), @Column(name="facefile", attrName="facefile", label="上传图片"), @Column(name="timetag",attrName="timetag", label="时间戳"), @Column(name="create_date", attrName="createDate", label="创建时间", isUpdate=false, isQuery=false), }, orderBy="a.id DESC" ) public class ReportImg extends DataEntity<ReportImg> { private static final long serialVersionUID = 1L; private String imei; // 车辆imei private String facefile; // 上传图片 private String timetag; //时间戳 public ReportImg() { this(null); } public ReportImg(String id){ super(id); } public String getImei() { return imei; } public void setImei(String imei) { this.imei = imei; } public String getTimetag() { return timetag; } public void setTimetag(String timetag) { this.timetag = timetag; } @NotBlank(message="上传图片不能为空") @Length(min=0, max=128, message="上传图片长度不能超过 128 个字符") public String getFacefile() { return facefile; } public void setFacefile(String facefile) { this.facefile = facefile; } @Override public String toString() { return "ReportImg [imei=" + imei + ", facefile=" + facefile + "]"; } }<file_sep>/src/main/java/com/jeesite/modules/car/entity/CarInfo.java /** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. */ package com.jeesite.modules.car.entity; import java.util.List; import javax.validation.constraints.NotBlank; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotNull; import com.jeesite.common.entity.DataEntity; import com.jeesite.common.mybatis.annotation.Column; import com.jeesite.common.mybatis.annotation.Table; import com.jeesite.common.mybatis.mapper.query.QueryType; import com.jeesite.modules.driver.entity.DriverInfo; /** * car_infoEntity * @author wsx * @version 2019-04-23 */ @Table(name="car_info", alias="a", columns={ @Column(name="id", attrName="id", label="车辆id", isPK=true), @Column(name="platenum", attrName="platenum", label="车牌号"), @Column(name="organization", attrName="organization", label="所属车队组织"), @Column(name="imei", attrName="imei", label="终端IMEI"), @Column(name="onlinestate", attrName="onlinestate", label="车辆在线状态", comment="车辆在线状态(0-不在线,1-在线)"), }, orderBy="a.id DESC" ) public class CarInfo extends DataEntity<CarInfo> { private static final long serialVersionUID = 1L; private String id; //id private String platenum; // 车牌号 private String organization; // 所属车队组织 private String imei; // 终端IMEI private Long onlinestate; // 车辆在线状态(0-不在线,1-在线) private List<DriverInfo> driverList; //所有驾驶员 private String flag; //标识信息 public CarInfo() { this(null); } public CarInfo(String id){ super(id); } @NotBlank(message="车牌号不能为空") @Length(min=0, max=64, message="车牌号长度不能超过 64 个字符") public String getPlatenum() { return platenum; } public void setPlatenum(String platenum) { this.platenum = platenum; } @NotBlank(message="所属车队组织不能为空") @Length(min=0, max=64, message="所属车队组织长度不能超过 64 个字符") public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } @NotBlank(message="终端IMEI不能为空") @Length(min=0, max=64, message="终端IMEI长度不能超过 64 个字符") public String getImei() { return imei; } public void setImei(String imei) { this.imei = imei; } public Long getOnlinestate() { return onlinestate; } public void setOnlinestate(Long onlinestate) { this.onlinestate = onlinestate; } public List<DriverInfo> getDriverList() { return driverList; } public void setDriverList(List<DriverInfo> driverList) { this.driverList = driverList; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String toString() { return "CarInfo [id=" + id + ", platenum=" + platenum + ", organization=" + organization + ", imei=" + imei + ", onlinestate=" + onlinestate + ", driverList=" + driverList + ", flag=" + flag + "]"; } }<file_sep>/src/main/java/com/jeesite/modules/report/dao/ReportImgDao.java /** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. */ package com.jeesite.modules.report.dao; import com.jeesite.common.dao.CrudDao; import com.jeesite.common.mybatis.annotation.MyBatisDao; import com.jeesite.modules.report.entity.ReportImg; /** * report_imgDAO接口 * @author wsx * @version 2019-04-27 */ @MyBatisDao public interface ReportImgDao extends CrudDao<ReportImg> { }<file_sep>/src/main/java/com/jeesite/modules/car/dao/CarDriverMsgDao.java /** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. */ package com.jeesite.modules.car.dao; import com.jeesite.common.dao.CrudDao; import com.jeesite.common.mybatis.annotation.MyBatisDao; import com.jeesite.modules.car.entity.CarDriverMsg; /** * car_driver_msgDAO接口 * @author wsx * @version 2019-04-27 */ @MyBatisDao public interface CarDriverMsgDao extends CrudDao<CarDriverMsg> { void updateState(String id); }<file_sep>/src/main/java/com/jeesite/modules/context/PollingStatus.java package com.jeesite.modules.context; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component public class PollingStatus { public static Map<String, Long> infoMap = new ConcurrentHashMap<String, Long>(); static { System.out.println("开始加载PollingStatus类"); new Thread(new Task(infoMap)).start(); } }<file_sep>/src/main/java/com/jeesite/modules/alarm/entity/AlarmInfo.java /** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. */ package com.jeesite.modules.alarm.entity; import javax.validation.constraints.NotBlank; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotNull; import com.jeesite.common.entity.DataEntity; import com.jeesite.common.mybatis.annotation.Column; import com.jeesite.common.mybatis.annotation.Table; import com.jeesite.common.mybatis.mapper.query.QueryType; /** * alarm_infoEntity * @author wsx * @version 2019-05-09 */ @Table(name="alarm_info", alias="a", columns={ @Column(name="id", attrName="id", label="警报id", isPK=true), @Column(name="type", attrName="type", label="类型"), @Column(name="comment", attrName="comment", label="内容"), @Column(name="img", attrName="img", label="图片路径"), @Column(name="imei", attrName="imei", label="车辆imei"), @Column(name="driver_id", attrName="driverId", label="司机id"), }, orderBy="a.id DESC" ) public class AlarmInfo extends DataEntity<AlarmInfo> { private static final long serialVersionUID = 1L; private String type; // 类型 private String comment; // 内容 private String img; // 图片路径 private String imei; // 车辆imei private Long driverId; // 司机id public AlarmInfo() { this(null); } public AlarmInfo(String id){ super(id); } @NotBlank(message="类型不能为空") @Length(min=0, max=16, message="类型长度不能超过 16 个字符") public String getType() { return type; } public void setType(String type) { this.type = type; } @NotBlank(message="内容不能为空") @Length(min=0, max=512, message="内容长度不能超过 512 个字符") public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } @NotBlank(message="图片路径不能为空") @Length(min=0, max=512, message="图片路径长度不能超过 512 个字符") public String getImg() { return img; } public void setImg(String img) { this.img = img; } @NotBlank(message="车辆imei不能为空") @Length(min=0, max=32, message="车辆imei长度不能超过 32 个字符") public String getImei() { return imei; } public void setImei(String imei) { this.imei = imei; } @NotNull(message="司机id不能为空") public Long getDriverId() { return driverId; } public void setDriverId(Long driverId) { this.driverId = driverId; } }<file_sep>/src/main/java/com/jeesite/modules/intercepter/MyInterceptor.java package com.jeesite.modules.intercepter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MyInterceptor implements HandlerInterceptor{ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { /* String path=request.getContextPath(); int code=response.getStatus(); System.out.println("--------postHandle------------>"+code+":"+path); if(code==302) { response.sendRedirect("http://172.16.58.3:8188/hhscar/admin/login"); }*/ } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // String path=request.getContextPath(); // int code=response.getStatus(); // System.out.println("--------afterCompletion------------>"+code+":"+path); // int code=response.getStatus(); // System.out.println("--------------------->"+code); /* if(code==200) { response.addHeader("location", "http://172.16.58.3:8188/hhscar/admin/login"); response.setHeader("Location", "https://www.baidu.com"); //response.sendRedirect("https://www.baidu.com"); } */ } } <file_sep>/src/main/java/com/jeesite/modules/filter/MyFilter.java package com.jeesite.modules.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { /* HttpServletRequest request = (HttpServletRequest) servletRequest; System.out.println("this is MyFilter,url :"+request.getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); HttpServletResponse res= (HttpServletResponse)servletResponse; int code=res.getStatus(); System.out.println("==doffilter="+code); if(code==302) { System.out.println(res.getHeader("Location")); res.setHeader("Location", "https://www.baidu.com"); res.addHeader("test", "https://www.baidu.com"); System.out.println("test"+":"+res.getHeader("test")); }*/ } @Override public void destroy() { } }
fecb8c1f1c2f005092551fb909f595a3b092fa79
[ "Markdown", "Java" ]
13
Java
wangsx07/hhsadas
4183a325af91976826ed7096be89342a4cc1e6f3
995f76a875dfad0cb7bdf696632402536bfb41a7
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; using Newtonsoft.Json; using System.Xml.Linq; namespace WiPi { /// <summary> /// Scratch Extension to talk to WebIOPi running on a Raspberry Pi device, to control the GPIO. /// </summary> class Program { static readonly HttpListener listener = new HttpListener(); // handles the http connection with Scratch static int port = 8080; // default port is 8080. If changed then s2e file needs to reflect this static string rpihost = "raspberrypi"; static int rpiport = 8000; static string rpiusername = "webiopi"; static string rpipwd = "<PASSWORD>"; static string revision = "2"; static RPiREST rpi = null; public static bool debug = false; static void Main(string[] args) { Console.WriteLine("WiPi Extension (c) 2014 Procd"); // Check for wipi.cfg configuration file if (File.Exists("wipi.cfg")) { Console.WriteLine("Found wipi.cfg"); try { XElement cfg = XElement.Load("wipi.cfg"); int tryport = 0; if (int.TryParse(cfg.Element("Port").Value, out tryport)) { port = tryport; } if (cfg.Attribute("Debug") != null && cfg.Attribute("Debug").Value == "on") { debug = true; } XElement rpicfg = cfg.Element("RaspberryPi"); if (rpicfg != null) { if (rpicfg.Attribute("revision") != null) { revision = rpicfg.Attribute("revision").Value; } if (int.TryParse(rpicfg.Element("port").Value, out tryport)) { rpiport = tryport; } if (!string.IsNullOrWhiteSpace(rpicfg.Element("host").Value)) { rpihost = rpicfg.Element("host").Value; } if (!string.IsNullOrWhiteSpace(rpicfg.Element("username").Value)) { rpiusername = rpicfg.Element("username").Value; } if (!string.IsNullOrWhiteSpace(rpicfg.Element("password").Value)) { rpipwd = rpicfg.Element("password").Value; } } } catch (Exception e) { Console.WriteLine(e.Message); } } // accept -p=<int> to change port number from default 8080 // and -d for debug foreach(string arg in args) { if (arg.StartsWith("-p=")) { int newport = 0; if (int.TryParse(arg.Substring(3),out newport)) { port = newport; } } else if (arg.StartsWith("-d")) { debug = true; Console.WriteLine("Debug mode on"); } } // Set up the connection to WebIOPi Console.WriteLine("Connecting to Raspberry pi at {0}:{1}", rpihost, rpiport); rpi = new RPiREST(rpihost, rpiport, rpiusername, rpipwd,revision); rpi.init(); // Start listening for Scratch requests listener.Prefixes.Add(string.Format("http://+:{0}/", port)); listener.Start(); listener.BeginGetContext(new AsyncCallback(ListenerCallback),listener); // If get access denied then need to run program as Administrator or give URL admin priveledges with // netsh http add urlacl url=http://+:8080/MyUri user=DOMAIN\user Console.WriteLine(String.Format("Listening on port {0}",port)); Console.WriteLine("Press return to exit."); Console.ReadLine(); listener.Close(); } // Flash cross domain policy that Scratch needs. static string crossdomainpolicy = @"<cross-domain-policy><allow-access-from domain=""*"" to-ports=""{0}""/></cross-domain-policy>\0"; /// <summary> /// Called each time Scratch makes a request /// </summary> /// <param name="result"></param> public static void ListenerCallback(IAsyncResult result) { HttpListener listener = (HttpListener)result.AsyncState; // Call EndGetContext to complete the asynchronous operation. HttpListenerContext context = listener.EndGetContext(result); // start listening for another request listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); // carry on with response HttpListenerRequest request = context.Request; string responseString = ""; string msg = request.RawUrl; switch (msg) { // Basic Scratch requests case "/crossdomain.xml": if (debug) { Console.WriteLine("Cross domain policy requested"); } responseString = string.Format(crossdomainpolicy, port); break; case "/poll": responseString = rpi.Poll(); break; case "/reset_all": if (debug) { Console.WriteLine("Resest all requested"); } rpi.Reset(); break; // Scratch command requests default: string decoded = Uri.UnescapeDataString(msg); if (debug) { Console.Write("Scratch Request : "); Console.WriteLine(decoded); } string[] tokens = decoded.Split('/'); //tokens[0] will be "" for "/..../...../", so ignore if (tokens.Length > 1) { switch (tokens[1]) { case "setGPIO": rpi.SetGPIOValue(rpi.ConvertRPIToBCM(tokens[2]), tokens[3] == "true" ? "1" : "0"); break; case "setPin": rpi.SetGPIOValue(rpi.ConvertPinToBCM(tokens[2]), tokens[3] == "ON" ? "1" : "0"); break; case "setGPIOFn": rpi.SetGPIOFunction(rpi.ConvertRPIToBCM(tokens[2]), tokens[3]); break; case "setPinFn": rpi.SetGPIOFunction(rpi.ConvertPinToBCM(tokens[2]), tokens[3]); break; default: break; } } break; } // Obtain a response object. HttpListenerResponse response = context.Response; response.StatusCode = (int)HttpStatusCode.OK; // Construct a response. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); // Get a response stream and write the response to it. response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); // You must close the output stream. output.Close(); } } /// <summary> /// GPIO class, contains GPIO function and value /// </summary> public class GPIO { public string function { get; set; } public string value { get; set; } } /// <summary> /// Class to contact WebIOPi REST interface /// </summary> class RPiREST { UriBuilder uri; Dictionary<string, GPIO> dictGPIO = new Dictionary<string, GPIO>();// Hold all the GPIO data for the Pi static object dictLock = new Object(); volatile bool updating = false; string user; string pwd; string problem = ""; string revision; private RPiREST() { } /// <summary> /// Constructor /// </summary> /// <param name="host">RasberryPPi hostname or IP address</param> /// <param name="port">Raspberry Pi port</param> /// <param name="user">WebIOPI username credential</param> /// <param name="pwd"><PASSWORD></param> public RPiREST(string host, int port, string user, string pwd, string revision) { uri = new UriBuilder("http", host, port); this.user = user; this.pwd = pwd; this.revision = revision; } /// <summary> /// Convert RPi GPIO numbers to BCM GPIO numbers /// </summary> /// <param name="gpio">RPI GPIO Number</param> /// <returns>BCM GPIO Number</returns> public string ConvertRPIToBCM(string gpio) { switch (gpio) { case "0": return "17"; case "1": return "18"; case "2": if (revision == "2") return "27"; return "21"; case "3": return "22"; case "4": return "23"; case "5": return "24"; case "6": return "25"; case "7": return "4"; default: return "";// should never get } } /// <summary> /// Convert RPi Pin number to BCMGPIO number /// </summary> /// <param name="pin"></param> /// <returns></returns> public string ConvertPinToBCM(string pin) { switch (pin) { case "11": return "17"; case "12": return "18"; case "13": if (revision == "2") return "27"; return "21"; case "15": return "22"; case "16": return "23"; case "18": return "24"; case "22": return "25"; case "7": return "4"; default: return "";// should never get } } /// <summary> /// Scratch Polls 30 times per second /// </summary> /// <returns>All the reporter name value pairs and and problems</returns> public string Poll() { PollForState(); StringBuilder sb = new StringBuilder(); try { lock (dictLock) { sb.Append(string.Format("gpio0 {0}", dictGPIO["17"].value == "0" ? "false" : "true")); sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio1 {0}", dictGPIO["18"].value == "0" ? "false" : "true")); sb.Append((char)0xA);// new line char if (revision == "2") { sb.Append(string.Format("gpio2 {0}", dictGPIO["27"].value == "0" ? "false" : "true")); } else { sb.Append(string.Format("gpio2 {0}", dictGPIO["21"].value == "0" ? "false" : "true")); } sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio3 {0}", dictGPIO["22"].value == "0" ? "false" : "true")); sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio4 {0}", dictGPIO["23"].value == "0" ? "false" : "true")); sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio5 {0}", dictGPIO["24"].value == "0" ? "false" : "true")); sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio6 {0}", dictGPIO["25"].value == "0" ? "false" : "true")); sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio7 {0}", dictGPIO["4"].value == "0" ? "false" : "true")); sb.Append((char)0xA);// new line char sb.Append(string.Format("pin7 {0}", dictGPIO["4"].value)); sb.Append((char)0xA);// new line char sb.Append(string.Format("pin11 {0}", dictGPIO["17"].value)); sb.Append((char)0xA);// new line char sb.Append(string.Format("pin12 {0}", dictGPIO["18"].value)); sb.Append((char)0xA);// new line char if (revision == "2") { sb.Append(string.Format("pin13 {0}", dictGPIO["27"].value)); } else { sb.Append(string.Format("pin13 {0}", dictGPIO["21"].value)); } sb.Append((char)0xA);// new line char sb.Append(string.Format("pin15 {0}", dictGPIO["22"].value)); sb.Append((char)0xA);// new line char sb.Append(string.Format("pin16 {0}", dictGPIO["23"].value)); sb.Append((char)0xA);// new line char sb.Append(string.Format("pin18 {0}", dictGPIO["24"].value)); sb.Append((char)0xA);// new line char sb.Append(string.Format("pin22 {0}", dictGPIO["25"].value)); sb.Append((char)0xA);// new line char sb.Append(string.Format("pin7fn {0}", dictGPIO["4"].function)); sb.Append((char)0xA);// new line char sb.Append(string.Format("pin11fn {0}", dictGPIO["17"].function)); sb.Append((char)0xA);// new line char sb.Append(string.Format("pin12fn {0}", dictGPIO["18"].function)); sb.Append((char)0xA);// new line char if (revision == "2") { sb.Append(string.Format("pin13fn {0}", dictGPIO["27"].function)); } else { sb.Append(string.Format("pin13fn {0}", dictGPIO["21"].function)); } sb.Append((char)0xA);// new line char sb.Append(string.Format("pin15fn {0}", dictGPIO["22"].function)); sb.Append((char)0xA);// new line char sb.Append(string.Format("pin16fn {0}", dictGPIO["23"].function)); sb.Append((char)0xA);// new line char sb.Append(string.Format("pin18fn {0}", dictGPIO["24"].function)); sb.Append((char)0xA);// new line char sb.Append(string.Format("pin22fn {0}", dictGPIO["25"].function)); sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio0fn {0}", dictGPIO["17"].function)); sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio1fn {0}", dictGPIO["18"].function)); sb.Append((char)0xA);// new line char if (revision == "2") { sb.Append(string.Format("gpio2fn {0}", dictGPIO["27"].function)); } else { sb.Append(string.Format("gpio2fn {0}", dictGPIO["21"].function)); } sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio3fn {0}", dictGPIO["22"].function)); sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio4fn {0}", dictGPIO["23"].function)); sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio5fn {0}", dictGPIO["24"].function)); sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio6fn {0}", dictGPIO["25"].function)); sb.Append((char)0xA);// new line char sb.Append(string.Format("gpio7fn {0}", dictGPIO["4"].function)); sb.Append((char)0xA);// new line char } } catch (KeyNotFoundException) { } if (!string.IsNullOrEmpty(problem)) { sb.Append(string.Format("_problem {0}", problem)); sb.Append((char)0xA);// new line char } return sb.ToString(); } public void Reset() { problem = ""; // do nothing } /// <summary> /// HTTP POST /GPIO/(gpioNumber)/function/("in" or "out" or "pwm") /// Returns new setup : "in" or "out" or "pwm" /// </summary> /// <param name="gpio"></param> /// <param name="function"></param> public void SetGPIOFunction(string gpio, string function) { lock (dictLock) { if (!dictGPIO.ContainsKey(gpio)) return; } uri.Path = string.Format("GPIO/{0}/function/{1}", gpio, function); HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri.Uri); wr.Method = "POST"; if (Program.debug) { Console.Write("POSTing WebIOPi : "); Console.WriteLine(uri.Path); } wr.Credentials = new NetworkCredential(user, pwd); try { using (HttpWebResponse resp = (HttpWebResponse)wr.GetResponse()) // Make async? { using (Stream responseStream = resp.GetResponseStream()) { using (StreamReader sr = new StreamReader(responseStream)) { string response = sr.ReadToEnd(); lock (dictLock) { dictGPIO[gpio].function = response; } if (Program.debug) { Console.Write("WebIOPi response : "); Console.WriteLine(response); } } } } } catch (WebException) { // Timeout? } } /// <summary> /// HTTP GET /GPIO/(gpioNumber)/function /// Returns "in" or "out" /// </summary> /// <param name="gpio"></param> /// <returns></returns> public string GetGPIOFunction(string gpio) { lock (dictLock) { if (!dictGPIO.ContainsKey(gpio)) return ""; } uri.Path = string.Format("GPIO/{0}/function", gpio); HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri.Uri); wr.Credentials = new NetworkCredential(user, pwd); if (Program.debug) { Console.Write("GETing WebIOPi : "); Console.WriteLine(uri.Path); } try { using (HttpWebResponse resp = (HttpWebResponse)wr.GetResponse()) // Make async? { using (Stream responseStream = resp.GetResponseStream()) { using (StreamReader sr = new StreamReader(responseStream)) { string response = sr.ReadToEnd(); lock (dictLock) { dictGPIO[gpio].function = response; } if (Program.debug) { Console.Write("WebIOPi response : "); Console.WriteLine(response); } return response; } } } } catch (WebException) { // Timeout? } return ""; } /// <summary> /// HTTP POST /GPIO/(gpioNumber)/value/(0 or 1) /// Returns new value : 0 or 1 /// </summary> /// <param name="gpio"></param> /// <param name="value"></param> public void SetGPIOValue(string gpio, string value) { lock (dictLock) { if (!dictGPIO.ContainsKey(gpio)) return; } uri.Path = string.Format("GPIO/{0}/value/{1}", gpio, value); HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri.Uri); wr.Method = "POST"; wr.Credentials = new NetworkCredential(user, pwd); if (Program.debug) { Console.Write("POSTing WebIOPi : "); Console.WriteLine(uri.Path); } try { using (HttpWebResponse resp = (HttpWebResponse)wr.GetResponse()) // Make async? { using (Stream responseStream = resp.GetResponseStream()) { using (StreamReader sr = new StreamReader(responseStream)) { string response = sr.ReadToEnd(); lock (dictLock) { dictGPIO[gpio].value = response; } if (Program.debug) { Console.Write("WebIOPi response : "); Console.WriteLine(response); } } } } } catch (WebException) { // Timeout? } } /// <summary> /// HTTP GET /GPIO/(gpioNumber)/value /// Returns 0 or 1 /// </summary> /// <param name="gpio"></param> /// <returns></returns> public string GetGPIOValue(string gpio) { lock (dictLock) { if (!dictGPIO.ContainsKey(gpio)) return ""; } uri.Path = string.Format("GPIO/{0}/value", gpio); HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri.Uri); wr.Credentials = new NetworkCredential(user, pwd); if (Program.debug) { Console.Write("GETing WebIOPi : "); Console.WriteLine(uri.Path); } try { using (HttpWebResponse resp = (HttpWebResponse)wr.GetResponse()) // Make async? { using (Stream responseStream = resp.GetResponseStream()) { using (StreamReader sr = new StreamReader(responseStream)) { string response = sr.ReadToEnd(); lock (dictLock) { dictGPIO[gpio].value = response; } if (Program.debug) { Console.Write("WebIOPi response : "); Console.WriteLine(response); } return response; } } } } catch (WebException) { // Timeout? } return ""; } /// <summary> /// Cal to initialise by getting state for the Raspberry Pi /// </summary> public void init() { GetState(); } /// <summary> /// Use when Scratch polls for data. /// If still waiting for a response then just return the data we have otherwise request new data and return what we have /// </summary> public void PollForState() { // Is update pending? if so leave it to finish if (updating) return; updating = true; problem = ""; uri.Path = "GPIO/*"; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri.Uri); wr.ContentType = "application/json"; wr.Credentials = new NetworkCredential(user, pwd); try { wr.BeginGetResponse(new AsyncCallback(FinishGetStateWebRequest), wr); } catch (WebException we) { problem = we.Message; } } /// <summary> /// Asynchronous callback for Raspberry Pi response. Allows the Pi to determine how quick it responds to requests /// without being flooded by Scratch's polling. /// </summary> /// <param name="result"></param> private void FinishGetStateWebRequest(IAsyncResult result) { using (HttpWebResponse resp = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse) { using (Stream responseStream = resp.GetResponseStream()) { using (StreamReader sr = new StreamReader(responseStream)) { string response = sr.ReadToEnd(); lock (dictLock) { dictGPIO.Clear(); dictGPIO = JsonConvert.DeserializeObject<Dictionary<string, GPIO>>(response); } } } } updating = false; } /// <summary> /// Get State synchronously. Used for initialisation /// </summary> public void GetState() { problem = ""; uri.Path = "GPIO/*"; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri.Uri); wr.ContentType = "application/json"; wr.Credentials = new NetworkCredential(user, pwd); try { using (HttpWebResponse resp = (HttpWebResponse)wr.GetResponse()) { using (Stream responseStream = resp.GetResponseStream()) { using (StreamReader sr = new StreamReader(responseStream)) { string response = sr.ReadToEnd(); lock (dictLock) { dictGPIO.Clear(); dictGPIO = JsonConvert.DeserializeObject<Dictionary<string, GPIO>>(response); } } } } } catch (WebException we) { problem = we.Message; if (Program.debug) { Console.WriteLine(problem); } } } } }
aa5a3499f60fb343196d59655063b4d388b6a33b
[ "C#" ]
1
C#
WildGenie/WiPi
bc77c9bf6af3083e8888586ee09c0b5e9990c73c
0189a0207d0f2a9919a8764f98a375178e73396a
refs/heads/master
<repo_name>jjw9014/GoodLuck<file_sep>/GoodLuck-server/src/main/java/com/help/server/controller/SysUserController.java package com.help.server.controller; import com.help.api.ResultDTO; import com.help.server.common.LoginHelper; import com.help.server.common.ResultHandler; import com.help.server.common.RsaUtils; import com.help.server.model.SysUser; import com.help.server.service.SysUserService; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.interfaces.RSAPublicKey; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping(path = "/sysUser/") public class SysUserController { @Autowired private SysUserService sysUserService; /** * * @return */ @RequestMapping("/getPublicKey") public Object getPublicKey() { RSAPublicKey publicKey = RsaUtils.getDefaultPublicKey(); Map<String,String> publicKeyMap = new HashMap<String,String>(); publicKeyMap.put("modulus", new String(Hex.encodeHex(publicKey.getModulus().toByteArray()))); publicKeyMap.put("exponent", new String(Hex.encodeHex(publicKey.getPublicExponent().toByteArray()))); return publicKeyMap; } /** * 用户登录 * @param userName 用户名 * @param password 密码 * @param request * @return */ @RequestMapping(value = "/login") public ResultDTO login(String userName, String password, HttpServletRequest request) { if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)){ return ResultHandler.createErrorResult("用户名或密码不能为空"); } return sysUserService.login(userName,password); } /** * 注销用户 * @param request * @param response * @return */ @RequestMapping(value = "/logout") public void loginout(HttpServletRequest request, HttpServletResponse response) throws IOException { LoginHelper.removeLoginUser(); response.sendRedirect("/login"); } /** * 添加用户 * @param userName 用户名 * @param password 密码 * @return */ @RequestMapping(value = "/addSysUser") public ResultDTO addSysUser(String userName, String password) { if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)){ return ResultHandler.createErrorResult("用户名或密码不能为空"); } boolean result = sysUserService.addSysUser(userName,password); if(result){ return ResultHandler.handleSuccess("添加用户成功",result); }else{ return ResultHandler.createErrorResult("添加用户失败"); } } /** * 修改用户名 * @param userName 用户名 * @param password 密码 * @return */ @RequestMapping(value = "/editSysUser") public ResultDTO editSysUser(String userName, String password) { if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)){ return ResultHandler.createErrorResult("用户名或密码不能为空"); } boolean result = sysUserService.editSysUser(userName,password); if(result){ return ResultHandler.handleSuccess("修改用户信息成功",result); }else{ return ResultHandler.createErrorResult("修改用户信息失败"); } } /** * 获取登录用户 * @return */ @RequestMapping(value = "/getLoginUser") public ResultDTO getLoginUser(HttpServletRequest request, HttpServletResponse response) { SysUser user = LoginHelper.getLoginUser(); if(user != null){ return ResultHandler.handleSuccess("获取登录信息成功",user); }else{ return ResultHandler.createErrorResult("获取登录信息失败"); } } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/common/CommonUtils.java package com.help.server.common; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import java.lang.reflect.Field; import java.math.BigDecimal; import java.util.*; public class CommonUtils { public static String getUUID() { return UUID.randomUUID().toString().replaceAll("-", ""); } public static List<List> splitList(List sourceList, int maxSize) { List<List> listList = new ArrayList<List>(); if (sourceList.size() != 0) { int size = sourceList.size(); int step = maxSize; int times = size/step + ((size % step == 0) ? 0 : 1); for (int idx = 0; idx < times; idx++) { int fromIndex = step * idx; int toIndex = (times - 1 == idx) ? size : (step + fromIndex); List<String> subList = sourceList.subList(fromIndex, toIndex); String[] srcStringArray = subList.toArray(new String[0]); String[] destStringArray = new String[srcStringArray.length]; System.arraycopy(srcStringArray, 0, destStringArray, 0, srcStringArray.length); List<String> list = Arrays.asList(destStringArray); listList.add(list); } } return listList; } public static List subtract(List aList, List bList) { if (CollectionUtils.isEmpty(aList) || CollectionUtils.isEmpty(bList)) { return aList; } aList.removeAll(bList); return aList; } public static List add(List aList, List bList) { if (CollectionUtils.isEmpty(aList)) { return bList; } if (CollectionUtils.isEmpty(bList)) { return aList; } List cList = new ArrayList(bList); cList.retainAll(aList); bList.removeAll(cList); aList.addAll(bList); return aList; } public static String list2String(List aList) { if (CollectionUtils.isEmpty(aList)) { return null; } StringBuilder sb = new StringBuilder(); for (Object obj : aList) { sb.append(",").append(obj.toString()); } return sb.substring(1); } public static String list2StringWithQuote(List list) { if (list == null || list.size() == 0) { return null; } StringBuilder sb = new StringBuilder(); for (Object str : list) { sb.append(String.format("'%s',", str.toString())); } sb.setLength(sb.length()-1); return sb.toString(); } public static List string2List(String str) { if (StringUtils.isEmpty(str)) { return null; } List<String> list = new ArrayList(); String [] edinfoList = str.split(","); for(String item : edinfoList){ list.add(item); } return list; } public static void assertLessThanField(int value, int maxValue, ResultCodeEnum resultCodeEnum) { if (value < maxValue) { throw new ResultException(resultCodeEnum); } } public static void assertMoreThanField(int value, int threshod, ResultCodeEnum resultCodeEnum) { if (value > threshod) { throw new ResultException(resultCodeEnum); } } public static void assertEmptyField(Object value, ResultCodeEnum resultCodeEnum) { if (isEmpty(value)) { throw new ResultException(resultCodeEnum); } } private static boolean isEmpty(Object value) { if (value instanceof Collection) { if (CollectionUtils.isEmpty((Collection)value)) { return true; } } else if (value instanceof Map) { if (MapUtils.isEmpty((Map)value)) { return true; } } else if (value instanceof String) { if (StringUtils.isBlank((String)value)) { return true; } } else { return isNullField(value); } return false; } public static void assertNullField(Object value, ResultCodeEnum resultCodeEnum) { assertNullField(value, null, resultCodeEnum); } public static void assertNullField(Object value, Object nullValue, ResultCodeEnum resultCodeEnum) { if (isNullField(value, nullValue)) { throw new ResultException(resultCodeEnum); } } public static boolean isNullField(Object value) { return isNullField(value, null); } public static boolean isNullField(Object value, Object nullValue) { if (value == null) { return true; } if (nullValue != null && nullValue.equals(value)) { return true; } return false; } public static String[] combinStringArray(String[] array1, String... array2) { if (array1 == null || array2 == null) { return (array1 != null) ? array1 : array2; } String[] array = new String[array1.length + array2.length]; System.arraycopy(array1, 0, array, 0, array1.length); System.arraycopy(array2, 0, array, array1.length, array2.length); return array; } public static Object combin(Object obj, Object... objs) { if (objs == null || objs.length == 0) { return obj; } try { for (int idx = 0; idx < objs.length; idx++) { Object combinObject = objs[idx]; Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { Object value = field.get(combinObject); if (value != null) { field.set(obj, value); } } } } catch (IllegalAccessException e) { e.printStackTrace(); } return obj; } public static String getDefaultIfNull(String obj, String defaultValue) { if (obj == null) { return defaultValue; } return obj; } public static BigDecimal getDefaultIfNull(BigDecimal obj, BigDecimal defaultValue) { if (obj == null) { return defaultValue; } return obj; } public static Integer getDefaultIfNull(Integer obj, Integer defaultValue) { if (obj == null) { return defaultValue; } return obj; } public static String getDefaultIfBlank(String obj, String defaultValue) { if (StringUtils.isBlank(obj)) { return defaultValue; } return obj; } private static void print(List<String> list) { System.out.print("["); for (String str : list) { System.out.print(str + ","); } System.out.print("]"); System.out.println(); } public static Object getNullIfNoChange(Object updateValue, Object currentValue) { if (updateValue == null) { return null; } if (!updateValue.equals(currentValue)) { return updateValue; } return null; } public static void main (String[] args) { CommonUtils commonUtils = new CommonUtils(); // commonUtils.testSplitList(); // commonUtils.testCombin(); } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/service/IAreaService.java package com.help.server.service; import com.help.api.AreaParam; import com.help.server.model.Area; import java.util.List; public interface IAreaService { public List<AreaParam> list(AreaParam param); public AreaParam get(AreaParam param); } <file_sep>/GoodLuck-server/src/main/java/com/help/server/common/StateEnum.java package com.help.server.common; public enum StateEnum { RESOLVED("resolved", "已解决"), UNRESOLVED("unresolved", "未解决"), DELETED("deleted", "已删除"); private String code; private String desc; StateEnum(String code, String desc) { this.code = code; this.desc = desc; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } } <file_sep>/GoodLuck-api/src/main/java/com/help/api/QuestionPageParam.java package com.help.api; import java.io.Serializable; import java.util.List; public class QuestionPageParam implements Serializable { private static final long serialVersionUID = 1L; private String tag; private String pubTimeStart; private String pubTimeEnd; private int starsMin; private int starsMax; private String state; private String auditState; private List<String> auditStates; private String number; private String pubUserId; private String province; private String city; private String district; private String street; private String mobile; private String wxNumber; private int pageSize; private int pageNo; private String orderBy; public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getPubTimeStart() { return pubTimeStart; } public void setPubTimeStart(String pubTimeStart) { this.pubTimeStart = pubTimeStart; } public String getPubTimeEnd() { return pubTimeEnd; } public void setPubTimeEnd(String pubTimeEnd) { this.pubTimeEnd = pubTimeEnd; } public int getStarsMin() { return starsMin; } public void setStarsMin(int starsMin) { this.starsMin = starsMin; } public int getStarsMax() { return starsMax; } public void setStarsMax(int starsMax) { this.starsMax = starsMax; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getAuditState() { return auditState; } public void setAuditState(String auditState) { this.auditState = auditState; } public List<String> getAuditStates() { return auditStates; } public void setAuditStates(List<String> auditStates) { this.auditStates = auditStates; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getPubUserId() { return pubUserId; } public void setPubUserId(String pubUserId) { this.pubUserId = pubUserId; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getWxNumber() { return wxNumber; } public void setWxNumber(String wxNumber) { this.wxNumber = wxNumber; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public String getOrderBy() { return orderBy; } public void setOrderBy(String orderBy) { this.orderBy = orderBy; } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/filter/WxAuthFilter.java package com.help.server.filter; import java.io.IOException; import java.util.*; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.help.server.common.*; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; /** * 微信授权登录过滤器 * * @Author LY * @Date 2020/2/2 10:00 * @Version 1.0 */ @Component @Slf4j @WebFilter(urlPatterns = "/*", filterName = "wxAuthFilter") public class WxAuthFilter extends OncePerRequestFilter { private static final List<String> FILTER_URL_LIST ; private static final List<String> SYS_UN_FILTER_URL_LIST; static{ String[] FILTER_URL = CommonConfigUtil.getValue("wx_auth_url_array").split(","); FILTER_URL_LIST = Arrays.asList(FILTER_URL); String[] SYS_UN_FILTER_URL = CommonConfigUtil.getValue("sys_un_filter_url_array").split(","); SYS_UN_FILTER_URL_LIST = Arrays.asList(SYS_UN_FILTER_URL); } private static final String SYS_LOGIN_URL = "/login"; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 请求的uri String uri = request.getRequestURI(); //系统名称,若sysName为sys_goodluck,则为后端管理系统 String sysName = request.getParameter("system"); if (sysName != null && sysName.equals("sys_goodluck")) { if (SYS_UN_FILTER_URL_LIST.contains(uri)) { filterChain.doFilter(request, response); } else { // 执行过滤 if (!LoginHelper.isLogin()) { response.sendRedirect(SYS_LOGIN_URL); } else { // 如果session中存在登录者实体,则继续 filterChain.doFilter(request, response); } } } else { if (FILTER_URL_LIST.contains(uri)) { String openId = AuthUtil.getAuthOpenIdFromCookie(request); if (openId != null) { Object user = JedisUtils.getObject(openId); if (user != null) { filterChain.doFilter(request, response); } else { log.info("没有openid对应的记录,用户未授权,即将进入微信授权页面"); response.sendRedirect(AuthUtil.WX_AUTH_URL); } } else { log.info("openid不存在,用户未授权,即将进入微信授权页面"); response.sendRedirect(AuthUtil.WX_AUTH_URL); } } else { filterChain.doFilter(request, response); } } } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/GoodLuckServerApplication.java package com.help.server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration; @SpringBootApplication(exclude = {KafkaAutoConfiguration.class}) public class GoodLuckServerApplication { public static void main(String[] args) { SpringApplication.run(GoodLuckServerApplication.class, args); } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/service/PictureService.java package com.help.server.service; import com.help.api.PictureParam; import java.util.List; public interface PictureService { public int submit(PictureParam param); public List<PictureParam> list(List<String> md5List); } <file_sep>/GoodLuck-server/src/main/java/com/help/server/controller/BaseDicController.java package com.help.server.controller; import com.help.api.ResultDTO; import com.help.server.common.ResultHandler; import com.help.server.service.BaseDicService; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * 字典控制类 */ @RestController @RequestMapping("/dic/") public class BaseDicController { @Resource private BaseDicService baseDicService; /** * 获取身份集合 * @return */ @RequestMapping(value = "/getIdentityMap") public ResultDTO getIdentityMap() { return ResultHandler.handleSuccess(baseDicService.getIndentityTypes()); } /** * 获取无黑名单的身份集合 * @return */ @RequestMapping(value = "/getIdentityNoBlackMap") public ResultDTO getIdentityNoBlackMap() { return ResultHandler.handleSuccess(baseDicService.getIndentityNoBlackTypes()); } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/common/AuditStateEnum.java package com.help.server.common; public enum AuditStateEnum { AUDITING("auditing", "正在审核"), AUIDTED("audited", "️审核通过"), AUDITED_FAILURE("audited_failure", "审核驳回"), VERIFIED("verified", "验证通过"), VERIFIED_FAILURE("verified_failure", "验证驳回"), ; private String code; private String desc; AuditStateEnum(String code, String desc) { this.code = code; this.desc = desc; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/dao/BaseDicMapper.java package com.help.server.dao; import com.help.server.model.BaseDic; import com.help.server.model.BaseDicExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface BaseDicMapper { int countByExample(BaseDicExample example); int deleteByExample(BaseDicExample example); int deleteByPrimaryKey(Integer id); int insert(BaseDic record); int insertSelective(BaseDic record); List<BaseDic> selectByExample(BaseDicExample example); BaseDic selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") BaseDic record, @Param("example") BaseDicExample example); int updateByExample(@Param("record") BaseDic record, @Param("example") BaseDicExample example); int updateByPrimaryKeySelective(BaseDic record); int updateByPrimaryKey(BaseDic record); }<file_sep>/GoodLuck-server/src/main/java/com/help/server/model/WxUserInfo.java package com.help.server.model; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.UUID; /** * 微信用户信息 */ public class WxUserInfo implements Serializable { private static final long serialVersionUID = 1L; private String id; private String code; private String nickName; private int gender; private String avatarUrl; private String country; private String province; private String city; public String getNickName() { return nickName; } public int getGender() { return gender; } public String getAvatarUrl() { return avatarUrl; } public String getCountry() { return country; } public String getProvince() { return province; } public String getCity() { return city; } public void setNickName(String nickName) { this.nickName = nickName; } public void setGender(int gender) { this.gender = gender; } public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; } public void setCountry(String country) { this.country = country; } public void setProvince(String province) { this.province = province; } public void setCity(String city) { this.city = city; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Tuser wxUserToTuser(){ Tuser user = new Tuser(); if(StringUtils.isNotBlank(this.getId())){ user.setId(this.getId()); }else{ user.setId( UUID.randomUUID().toString().replaceAll("-","")); } user.setNickName(this.getNickName()); user.setSex(this.getGender()); user.setHeadImgUrl(this.getAvatarUrl()); user.setCountry(this.getCountry()); user.setProvince(this.getProvince()); user.setCity(this.getCity()); return user; } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/model/PictureExample.java package com.help.server.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class PictureExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public PictureExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(String value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(String value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(String value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(String value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(String value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(String value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdLike(String value) { addCriterion("id like", value, "id"); return (Criteria) this; } public Criteria andIdNotLike(String value) { addCriterion("id not like", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<String> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<String> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(String value1, String value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(String value1, String value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andPicNameIsNull() { addCriterion("pic_name is null"); return (Criteria) this; } public Criteria andPicNameIsNotNull() { addCriterion("pic_name is not null"); return (Criteria) this; } public Criteria andPicNameEqualTo(String value) { addCriterion("pic_name =", value, "picName"); return (Criteria) this; } public Criteria andPicNameNotEqualTo(String value) { addCriterion("pic_name <>", value, "picName"); return (Criteria) this; } public Criteria andPicNameGreaterThan(String value) { addCriterion("pic_name >", value, "picName"); return (Criteria) this; } public Criteria andPicNameGreaterThanOrEqualTo(String value) { addCriterion("pic_name >=", value, "picName"); return (Criteria) this; } public Criteria andPicNameLessThan(String value) { addCriterion("pic_name <", value, "picName"); return (Criteria) this; } public Criteria andPicNameLessThanOrEqualTo(String value) { addCriterion("pic_name <=", value, "picName"); return (Criteria) this; } public Criteria andPicNameLike(String value) { addCriterion("pic_name like", value, "picName"); return (Criteria) this; } public Criteria andPicNameNotLike(String value) { addCriterion("pic_name not like", value, "picName"); return (Criteria) this; } public Criteria andPicNameIn(List<String> values) { addCriterion("pic_name in", values, "picName"); return (Criteria) this; } public Criteria andPicNameNotIn(List<String> values) { addCriterion("pic_name not in", values, "picName"); return (Criteria) this; } public Criteria andPicNameBetween(String value1, String value2) { addCriterion("pic_name between", value1, value2, "picName"); return (Criteria) this; } public Criteria andPicNameNotBetween(String value1, String value2) { addCriterion("pic_name not between", value1, value2, "picName"); return (Criteria) this; } public Criteria andPicSizeIsNull() { addCriterion("pic_size is null"); return (Criteria) this; } public Criteria andPicSizeIsNotNull() { addCriterion("pic_size is not null"); return (Criteria) this; } public Criteria andPicSizeEqualTo(Integer value) { addCriterion("pic_size =", value, "picSize"); return (Criteria) this; } public Criteria andPicSizeNotEqualTo(Integer value) { addCriterion("pic_size <>", value, "picSize"); return (Criteria) this; } public Criteria andPicSizeGreaterThan(Integer value) { addCriterion("pic_size >", value, "picSize"); return (Criteria) this; } public Criteria andPicSizeGreaterThanOrEqualTo(Integer value) { addCriterion("pic_size >=", value, "picSize"); return (Criteria) this; } public Criteria andPicSizeLessThan(Integer value) { addCriterion("pic_size <", value, "picSize"); return (Criteria) this; } public Criteria andPicSizeLessThanOrEqualTo(Integer value) { addCriterion("pic_size <=", value, "picSize"); return (Criteria) this; } public Criteria andPicSizeIn(List<Integer> values) { addCriterion("pic_size in", values, "picSize"); return (Criteria) this; } public Criteria andPicSizeNotIn(List<Integer> values) { addCriterion("pic_size not in", values, "picSize"); return (Criteria) this; } public Criteria andPicSizeBetween(Integer value1, Integer value2) { addCriterion("pic_size between", value1, value2, "picSize"); return (Criteria) this; } public Criteria andPicSizeNotBetween(Integer value1, Integer value2) { addCriterion("pic_size not between", value1, value2, "picSize"); return (Criteria) this; } public Criteria andPicSuffixIsNull() { addCriterion("pic_suffix is null"); return (Criteria) this; } public Criteria andPicSuffixIsNotNull() { addCriterion("pic_suffix is not null"); return (Criteria) this; } public Criteria andPicSuffixEqualTo(String value) { addCriterion("pic_suffix =", value, "picSuffix"); return (Criteria) this; } public Criteria andPicSuffixNotEqualTo(String value) { addCriterion("pic_suffix <>", value, "picSuffix"); return (Criteria) this; } public Criteria andPicSuffixGreaterThan(String value) { addCriterion("pic_suffix >", value, "picSuffix"); return (Criteria) this; } public Criteria andPicSuffixGreaterThanOrEqualTo(String value) { addCriterion("pic_suffix >=", value, "picSuffix"); return (Criteria) this; } public Criteria andPicSuffixLessThan(String value) { addCriterion("pic_suffix <", value, "picSuffix"); return (Criteria) this; } public Criteria andPicSuffixLessThanOrEqualTo(String value) { addCriterion("pic_suffix <=", value, "picSuffix"); return (Criteria) this; } public Criteria andPicSuffixLike(String value) { addCriterion("pic_suffix like", value, "picSuffix"); return (Criteria) this; } public Criteria andPicSuffixNotLike(String value) { addCriterion("pic_suffix not like", value, "picSuffix"); return (Criteria) this; } public Criteria andPicSuffixIn(List<String> values) { addCriterion("pic_suffix in", values, "picSuffix"); return (Criteria) this; } public Criteria andPicSuffixNotIn(List<String> values) { addCriterion("pic_suffix not in", values, "picSuffix"); return (Criteria) this; } public Criteria andPicSuffixBetween(String value1, String value2) { addCriterion("pic_suffix between", value1, value2, "picSuffix"); return (Criteria) this; } public Criteria andPicSuffixNotBetween(String value1, String value2) { addCriterion("pic_suffix not between", value1, value2, "picSuffix"); return (Criteria) this; } public Criteria andPicMd5IsNull() { addCriterion("pic_md5 is null"); return (Criteria) this; } public Criteria andPicMd5IsNotNull() { addCriterion("pic_md5 is not null"); return (Criteria) this; } public Criteria andPicMd5EqualTo(String value) { addCriterion("pic_md5 =", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5NotEqualTo(String value) { addCriterion("pic_md5 <>", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5GreaterThan(String value) { addCriterion("pic_md5 >", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5GreaterThanOrEqualTo(String value) { addCriterion("pic_md5 >=", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5LessThan(String value) { addCriterion("pic_md5 <", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5LessThanOrEqualTo(String value) { addCriterion("pic_md5 <=", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5Like(String value) { addCriterion("pic_md5 like", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5NotLike(String value) { addCriterion("pic_md5 not like", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5In(List<String> values) { addCriterion("pic_md5 in", values, "picMd5"); return (Criteria) this; } public Criteria andPicMd5NotIn(List<String> values) { addCriterion("pic_md5 not in", values, "picMd5"); return (Criteria) this; } public Criteria andPicMd5Between(String value1, String value2) { addCriterion("pic_md5 between", value1, value2, "picMd5"); return (Criteria) this; } public Criteria andPicMd5NotBetween(String value1, String value2) { addCriterion("pic_md5 not between", value1, value2, "picMd5"); return (Criteria) this; } public Criteria andPicUrlIsNull() { addCriterion("pic_url is null"); return (Criteria) this; } public Criteria andPicUrlIsNotNull() { addCriterion("pic_url is not null"); return (Criteria) this; } public Criteria andPicUrlEqualTo(String value) { addCriterion("pic_url =", value, "picUrl"); return (Criteria) this; } public Criteria andPicUrlNotEqualTo(String value) { addCriterion("pic_url <>", value, "picUrl"); return (Criteria) this; } public Criteria andPicUrlGreaterThan(String value) { addCriterion("pic_url >", value, "picUrl"); return (Criteria) this; } public Criteria andPicUrlGreaterThanOrEqualTo(String value) { addCriterion("pic_url >=", value, "picUrl"); return (Criteria) this; } public Criteria andPicUrlLessThan(String value) { addCriterion("pic_url <", value, "picUrl"); return (Criteria) this; } public Criteria andPicUrlLessThanOrEqualTo(String value) { addCriterion("pic_url <=", value, "picUrl"); return (Criteria) this; } public Criteria andPicUrlLike(String value) { addCriterion("pic_url like", value, "picUrl"); return (Criteria) this; } public Criteria andPicUrlNotLike(String value) { addCriterion("pic_url not like", value, "picUrl"); return (Criteria) this; } public Criteria andPicUrlIn(List<String> values) { addCriterion("pic_url in", values, "picUrl"); return (Criteria) this; } public Criteria andPicUrlNotIn(List<String> values) { addCriterion("pic_url not in", values, "picUrl"); return (Criteria) this; } public Criteria andPicUrlBetween(String value1, String value2) { addCriterion("pic_url between", value1, value2, "picUrl"); return (Criteria) this; } public Criteria andPicUrlNotBetween(String value1, String value2) { addCriterion("pic_url not between", value1, value2, "picUrl"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andIdLikeInsensitive(String value) { addCriterion("upper(id) like", value.toUpperCase(), "id"); return (Criteria) this; } public Criteria andPicNameLikeInsensitive(String value) { addCriterion("upper(pic_name) like", value.toUpperCase(), "picName"); return (Criteria) this; } public Criteria andPicSuffixLikeInsensitive(String value) { addCriterion("upper(pic_suffix) like", value.toUpperCase(), "picSuffix"); return (Criteria) this; } public Criteria andPicMd5LikeInsensitive(String value) { addCriterion("upper(pic_md5) like", value.toUpperCase(), "picMd5"); return (Criteria) this; } public Criteria andPicUrlLikeInsensitive(String value) { addCriterion("upper(pic_url) like", value.toUpperCase(), "picUrl"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }<file_sep>/GoodLuck-api/src/main/java/com/help/api/AreaParam.java package com.help.api; import java.io.Serializable; public class AreaParam implements Serializable { private Integer id; private String areaCode; private String areaName; private String areaParentCode; private Integer areaType; private static final long serialVersionUID = 1L; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAreaCode() { return areaCode; } public void setAreaCode(String areaCode) { this.areaCode = areaCode; } public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } public String getAreaParentCode() { return areaParentCode; } public void setAreaParentCode(String areaParentCode) { this.areaParentCode = areaParentCode; } public Integer getAreaType() { return areaType; } public void setAreaType(Integer areaType) { this.areaType = areaType; } }<file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> <relativePath/> </parent> <groupId>com.help</groupId> <!-- 版本号不变 --> <version>1.0-SNAPSHOT</version> <modelVersion>4.0.0</modelVersion> <artifactId>GoodLuck</artifactId> <packaging>pom</packaging> <properties> <!-- api版本号 --> <version.com.help.goodluck.api>1.0.0-SNAPSHOT</version.com.help.goodluck.api> <!-- server版本号 --> <version.com.help.goodluck.server>1.0.0.0-SNAPSHOT</version.com.help.goodluck.server> </properties> <!--配置私服工厂 --> <repositories> <repository> <id>nexus-aliyun</id> <url>http://maven.aliyun.com/nexus/content/groups/public</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>nexus-aliyun</id> <url>http://maven.aliyun.com/nexus/content/groups/public</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> <!-- 配置发布文件到私服 --> <distributionManagement> <repository> <id>nexus-aliyun</id> <name>Nexus Release Repository</name> <url>http://maven.aliyun.com/nexus/content/groups/public</url> </repository> </distributionManagement> <modules> <module>GoodLuck-api</module> <module>GoodLuck-server</module> </modules> </project><file_sep>/GoodLuck-server/src/main/java/com/help/server/service/PictureServiceImpl.java package com.help.server.service; import com.help.api.PictureParam; import com.help.server.dao.PictureMapper; import com.help.server.model.Picture; import com.help.server.model.PictureExample; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.Calendar; import java.util.List; @Service public class PictureServiceImpl implements PictureService { @Autowired private PictureMapper pictureMapper; @Override public int submit(PictureParam param) { Picture picture = new Picture(); BeanUtils.copyProperties(param, picture); picture.setCreateTime(Calendar.getInstance().getTime()); return pictureMapper.insert(picture); } @Override public List<PictureParam> list(List<String> md5List) { PictureExample example = new PictureExample(); example.createCriteria().andPicMd5In(md5List); List<Picture> list = pictureMapper.selectByExample(example); if (CollectionUtils.isEmpty(list)) { return new ArrayList<>(); } List<PictureParam> paramList = new ArrayList<>(); for (Picture picture : list) { PictureParam param = new PictureParam(); BeanUtils.copyProperties(picture, param); paramList.add(param); } return paramList; } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/service/SenInfoCheckService.java package com.help.server.service; import org.springframework.web.multipart.MultipartFile; /** * 敏感内容校验 */ public interface SenInfoCheckService { /** * 校验图片 * @param file 文件 * @return */ boolean checkPic(MultipartFile file); /** * 校验文字内容 * @param content 文字 * @return */ boolean checkContent(String content); } <file_sep>/GoodLuck-server/src/main/java/com/help/server/controller/HelloController.java package com.help.server.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/") public class HelloController { // http://127.0.0.1:9090/hello @RequestMapping(value="/hello") @ResponseBody public String hello() { return "Hello, 祝大家新年快乐,身体健康"; } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/controller/TuserClaimController.java package com.help.server.controller; import com.help.api.ResultDTO; import com.help.server.service.TuserClaimService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 用户认领控制层接口 * @Author LY * @Date 2020/1/30 11:18 * @Version 1.0 **/ @RestController @RequestMapping(path = "/claim/") public class TuserClaimController { private static final Logger LOGGER = LoggerFactory.getLogger(TuserClaimController.class); @Autowired private TuserClaimService tuserClaimService; /** * 通过问题id获取问题联系信息 * @param questionId 问题id * @return */ @RequestMapping(value = "/get") public ResultDTO getInfoByQuestionId(String questionId) { return tuserClaimService.getInfoByQuestionId(questionId); } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/common/DateUtils.java package com.help.server.common; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; public class DateUtils { private static String format = "yyyy-MM-dd HH:mm:ss"; private static String formatYYYYMM = "yyyyMM"; private static String formatYYYYMMDD = "yyyyMMdd"; private static String formatYYYYMMDD_HHMM = "yyyyMMdd HHmm"; private static String formatYYYYMMDDHHMM = "yyyyMMddhhmm"; private static String formatyyyymmdd = "yyyy/MM/dd"; private static String defaultFormat = "yyyy-MM-dd"; private static String defaultFormatyyyyMMddHHmmss = "yyyyMMddHHmmss"; private static String formatYYYYPMMPDD = "yyyy.MM.dd"; private static String formatMMdd_HHMM = "MM月dd日 HH:mm"; public DateUtils() { } public static String formatDate(Date date) { if (date == null) { return null; } return (new SimpleDateFormat(format)).format(date); } public static String formatDateYYYYMMDD(Date date) { if (date == null) { return null; } SimpleDateFormat dfYYYYMMDD = new SimpleDateFormat(formatYYYYMMDD); return dfYYYYMMDD.format(date); } public static Date getCurrentDate() { return new Date(); } public static Date parseDate(String date) { SimpleDateFormat df = new SimpleDateFormat(format); try { return df.parse(date); } catch (ParseException var3) { throw new RuntimeException("日期格式错误,转换日期对象失败"); } } public static String formatDate2(Date date) { if (date == null) { return null; } SimpleDateFormat df = new SimpleDateFormat(format); return df.format(date); } public static String formatDateByPattern(Date date, String pattern) { if (date == null) { return null; } SimpleDateFormat df = new SimpleDateFormat(pattern); return df.format(date); } public static Date parseDate2(String date) { SimpleDateFormat df2 = new SimpleDateFormat(defaultFormatyyyyMMddHHmmss); try { return df2.parse(date); } catch (ParseException var3) { throw new RuntimeException("日期格式错误,转换日期对象失败"); } } public static Date parseDate3(String date) throws ParseException { SimpleDateFormat df3 = new SimpleDateFormat(formatYYYYMMDD_HHMM); return df3.parse(date); } public static List<Date[]> splitTimeByHours(Date start, Date end, int hours) { ArrayList dl; Date _end; for(dl = new ArrayList(); start.compareTo(end) < 0; start = _end) { _end = addHours(start, hours); if (_end.compareTo(end) > 0) { _end = end; } Date[] dates = new Date[]{(Date)start.clone(), (Date)_end.clone()}; dl.add(dates); } return dl; } public static List<Date[]> splitTimeBySeconds(Date start, Date end, int Seconds) { ArrayList dl; Date _end; for(dl = new ArrayList(); start.compareTo(end) < 0; start = addSeconds(_end, 1)) { _end = addSeconds(start, Seconds); if (_end.compareTo(end) > 0) { _end = end; } Date[] dates = new Date[]{(Date)start.clone(), (Date)_end.clone()}; dl.add(dates); } return dl; } public static Date getTimeOf000000() { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.set(11, 0); cal.set(12, 0); cal.set(13, 0); cal.set(14, 0); cal.add(5, 0); return cal.getTime(); } public static Date getYestoday235959() { Calendar cal = Calendar.getInstance(); cal.setTime(getTimeOf000000()); cal.set(11, 0); cal.set(12, 0); cal.set(13, -1); cal.set(14, 0); cal.add(5, 0); return cal.getTime(); } public static Date getNowDay235959() { Calendar cal = Calendar.getInstance(); cal.set(cal.get(1), cal.get(2), cal.get(5), 23, 59, 59); return cal.getTime(); } public static Date addDays(Date date, int amount) { Calendar c = Calendar.getInstance(); c.setTime(date); c.add(5, amount); return c.getTime(); } public static Date addHours(Date date, int amount) { Calendar c = Calendar.getInstance(); c.setTime(date); c.add(11, amount); return c.getTime(); } public static Date addMonths(Date date, int amount) { Calendar c = Calendar.getInstance(); c.setTime(date); c.add(2, amount); return c.getTime(); } public static Date addSeconds(Date date, int amount) { Calendar c = Calendar.getInstance(); c.setTime(date); c.add(13, amount); return c.getTime(); } public static Date addMinus(Date date, int amount) { Calendar c = Calendar.getInstance(); c.setTime(date); c.add(12, amount); return c.getTime(); } public static String getYYYYMM() { return getYYYYMM(new Date()); } public static String getYYYYMMDD() { return getYYYYMMDD(new Date()); } public static String getYYYYMM(Date date) { return (new SimpleDateFormat(formatYYYYMM)).format(date); } public static String getYYYYMMDD(Date date) { return (new SimpleDateFormat(formatYYYYMMDD)).format(date); } public static String getYYYYMMDDHHMM() { return (new SimpleDateFormat(formatYYYYMMDDHHMM)).format(new Date()); } public static String getyyyymmdd(Date date) { return (new SimpleDateFormat(formatyyyymmdd)).format(date); } public static String formatDateToString(Date date) { if (date == null) { return null; } SimpleDateFormat f = new SimpleDateFormat(defaultFormat); return f.format(date); } public static Date getDate(Long time) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time * 1000L); return cal.getTime(); } public static Date getTimeOf000000(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(11, 0); cal.set(12, 0); cal.set(13, 0); cal.set(14, 0); cal.add(5, 0); return cal.getTime(); } public static long getNumberOfSeconds(Date startDay, Date endDay) { return (endDay.getTime() - startDay.getTime()) / 1000L; } public static String getMMddHHmm(String dateStr) { SimpleDateFormat df = new SimpleDateFormat(format); try { Date date = df.parse(dateStr); return (new SimpleDateFormat(formatMMdd_HHMM)).format(date); } catch (ParseException var3) { throw new RuntimeException("日期格式错误,转换日期对象失败"); } } public static void main(String[] args) throws ParseException { Date curDate = new Date(); Date endDate = addDays(getYestoday235959(), 4); System.out.println(curDate.compareTo(endDate)); } } <file_sep>/GoodLuck-api/src/main/java/com/help/api/PictureFacade.java package com.help.api; import java.util.List; public interface PictureFacade { public ResultDTO<PictureParam> upload(PictureParam param); public ResultDTO<List<PictureParam>> list(List<String> md5List); public ResultDTO<PictureParam> info(String md5); } <file_sep>/GoodLuck-api/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>com.help</groupId> <artifactId>GoodLuck</artifactId> <version>1.0-SNAPSHOT</version> </parent> <groupId>com.help</groupId> <version>${version.com.help.goodluck.api}</version> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.37</version> </dependency> </dependencies> <modelVersion>4.0.0</modelVersion> <artifactId>GoodLuck-api</artifactId> <packaging>jar</packaging> <!--配置私服工厂 --> <repositories> <repository> <id>nexus-aliyun</id> <url>http://maven.aliyun.com/nexus/content/groups/public</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>nexus-aliyun</id> <url>http://maven.aliyun.com/nexus/content/groups/public</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.6</maven.compiler.source> <maven.compiler.target>1.6</maven.compiler.target> <maven.plugin.clean>2.5</maven.plugin.clean> <maven.plugin.compiler>2.4</maven.plugin.compiler> <maven.plugin.source>2.2</maven.plugin.source> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>${maven.plugin.clean}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven.plugin.compiler}</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> <optimize>true</optimize> <encoding>${project.build.sourceEncoding}</encoding> <debug>true</debug> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>${maven.plugin.source}</version> <executions> <execution> <id>attach-sources</id> <phase>verify</phase><!-- 要绑定到的生命周期的阶段 在verify之后,install之前执行下面指定的goal --> <goals> <goal>jar-no-fork</goal><!-- 类似执行mvn source:jar --> </goals> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/GoodLuck-server/src/main/java/com/help/server/service/ISuggestService.java package com.help.server.service; import com.help.server.model.Suggest; import java.util.List; public interface ISuggestService { public int submit(Suggest suggest); public List<Suggest> list(Integer pageSize, Integer pageNo); public int count(); } <file_sep>/GoodLuck-api/src/main/java/com/help/api/QuestionFacade.java package com.help.api; import java.util.List; public interface QuestionFacade { public ResultDTO pub(QuestionParam param); public ResultDTO focus(String number, String userId); public ResultDTO updateInfo(QuestionUpdateParam updateParam); public ResultDTO resolve(String number, String userId); public ResultDTO audit(String number, String userId, String auditState); public ResultDTO<List> list(QuestionPageParam pageParam); public ResultDTO<QuestionParam> info(String number); public ResultDTO<QuestionCountDTO> count(); public ResultDTO depreate(String number, String userId); } <file_sep>/GoodLuck-server/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>com.help</groupId> <artifactId>GoodLuck</artifactId> <version>1.0-SNAPSHOT</version> </parent> <groupId>com.help</groupId> <modelVersion>4.0.0</modelVersion> <artifactId>GoodLuck-server</artifactId> <packaging>jar</packaging> <!--<version>${version.com.help.goodluck.server}</version>--> <version>1.0.0.0-SNAPSHOT</version> <name>GoodLuck-server</name> <properties> <maven.deploy.skip>true</maven.deploy.skip> <maven.install.skip>true</maven.install.skip> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.plugin.clean>2.5</maven.plugin.clean> <maven.plugin.compiler>3.3</maven.plugin.compiler> <version.fastjson>1.2.61</version.fastjson> <version.jackson>2.9.9</version.jackson> <version.jackson.databind>2.9.9.1</version.jackson.databind> <version.httpclient>4.5.2</version.httpclient> <version.spring>4.2.5.RELEASE</version.spring> <version.commons.lang>2.6</version.commons.lang> <version.commons.io>2.6</version.commons.io> <version.slf4j>1.7.2</version.slf4j> <version.logback>1.1.11</version.logback> <version.log4j.over.slf4j>1.7.2</version.log4j.over.slf4j> <version.servlet.api>3.1.0</version.servlet.api> <version.dom4j>1.6.1</version.dom4j> <version.dubbo>2.5.3</version.dubbo> <version.javassist>3.20.0-GA</version.javassist> <version.spring.mybatis>1.2.2</version.spring.mybatis> <version.mybatis>3.2.7</version.mybatis> <version.commons.dbcp>1.3</version.commons.dbcp> <version.zookeeper>3.4.6</version.zookeeper> <version.zkclient>0.7</version.zkclient> <version.redis>2.4.2</version.redis> <version.junit>4.12</version.junit> <version.protostuff>1.0.9</version.protostuff> <version.protobuf>2.5.0</version.protobuf> <version.ehcache>2.6.0</version.ehcache> <version.kafka.client>1.0.1</version.kafka.client> <version.guava>18.0</version.guava> <version.drools>6.0.0.CR1</version.drools> <version.lombok>1.14.4</version.lombok> <version.protobuf>2.5.0</version.protobuf> <version.protobuf.format>1.2</version.protobuf.format> <version.spring.redis>1.2.0.RELEASE</version.spring.redis> <version.mysql>5.1.38</version.mysql> <version.druid>1.1.18</version.druid> <version.jackson.dataformat>2.3.0</version.jackson.dataformat> <version.spring-boot-starter-dubbo>1.0.1</version.spring-boot-starter-dubbo> <version.mybatis-spring-boot-starter>1.3.1</version.mybatis-spring-boot-starter> <version.mapper-spring-boot-starter>1.1.0</version.mapper-spring-boot-starter> <version.mybatis-typehandlers-jsr310>1.0.2</version.mybatis-typehandlers-jsr310> <version.spring.kafka>2.1.6.RELEASE</version.spring.kafka> <version.c3p0>0.9.2</version.c3p0> <version.mybatis.pageHelper>5.1.6</version.mybatis.pageHelper> <version.easymock>2.5.2</version.easymock> <version.easymockclassextension>2.5.2</version.easymockclassextension> <version.mockito>1.10.19</version.mockito> <version.powermock>1.6.4</version.powermock> <commons-pool2.version>2.5.0</commons-pool2.version> </properties> <!--配置私服工厂 --> <repositories> <repository> <id>nexus-aliyun</id> <url>http://maven.aliyun.com/nexus/content/groups/public</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>nexus-aliyun</id> <url>http://maven.aliyun.com/nexus/content/groups/public</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${version.fastjson}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${version.jackson}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${version.jackson.databind}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${version.jackson}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>${version.jackson}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> <version>${version.zkclient}</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> <exclusion> <artifactId>log4j</artifactId> <groupId>log4j</groupId> </exclusion> <exclusion> <artifactId>slf4j-log4j12</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${version.mybatis-spring-boot-starter}</version> </dependency> <!--pagehelper--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${version.mybatis.pageHelper}</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-autoconfigure</artifactId> <version>1.2.3</version> <exclusions> <exclusion> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </exclusion> </exclusions> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${version.mysql}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${version.druid}</version> </dependency> <!--dubbo--> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>${version.dubbo}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </exclusion> <exclusion> <artifactId>javassist</artifactId> <groupId>org.javassist</groupId> </exclusion> </exclusions> </dependency> <dependency> <artifactId>javassist</artifactId> <groupId>org.javassist</groupId> <version>${version.javassist}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>${version.logback}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${version.logback}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId> <version>${version.log4j.over.slf4j}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${version.slf4j}</version> </dependency> <!-- commons-lang --> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>${version.commons.lang}</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${version.commons.io}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>${version.jackson.dataformat}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${version.junit}</version> <scope>test</scope> </dependency> <!--资源接口包--> <dependency> <groupId>com.help</groupId> <artifactId>GoodLuck-api</artifactId> <version>${version.com.help.goodluck.api}</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>org.easymock</groupId> <artifactId>easymock</artifactId> <version>${version.easymock}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.easymock</groupId> <artifactId>easymockclassextension</artifactId> <version>${version.easymockclassextension}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>${version.mockito}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>${version.mockito}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>${version.powermock}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>${version.powermock}</version> <scope>test</scope> </dependency> <!--httpclient--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${version.httpclient}</version> </dependency> <!-- redis 相关包--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency> <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <!-- 2019.2最新版本 caffeine是2015年才面市的,发展还是很迅速的--> <version>2.7.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>5.0.6.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on --> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.60</version> </dependency> </dependencies> <profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <profile.active>dev</profile.active> <mysql.jdbc.url>jdbc:mysql://xxxxxxx:3306/goodluck</mysql.jdbc.url> <mysql.jdbc.username>root</mysql.jdbc.username> <mysql.jdbc.password><PASSWORD></mysql.jdbc.password> </properties> </profile> <profile> <id>uat</id> <properties> <profile.active>uat</profile.active> <mysql.jdbc.url>jdbc:mysql://127.0.0.1:3306/goodluck?</mysql.jdbc.url> <mysql.jdbc.username>root</mysql.jdbc.username> <mysql.jdbc.password><PASSWORD></mysql.jdbc.password> </properties> </profile> <profile> <id>prd</id> <properties> <profile.active>prd</profile.active> <mysql.jdbc.url>jdbc:mysql://xxxxxxxxx:3306/goodluck</mysql.jdbc.url> <mysql.jdbc.username>root</mysql.jdbc.username> <mysql.jdbc.password><PASSWORD></mysql.jdbc.password> </properties> </profile> </profiles> <build> <finalName>GoodLuck-server</finalName> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <excludes> <exclude>mybatis-generator/*.*</exclude> <exclude>*.keystore</exclude> <exclude>*.jks</exclude> </excludes> </resource> <resource> <directory>src/main/resources</directory> <filtering>false</filtering> <includes> <include>*.keystore</include> <include>*.jks</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <configurationFile>src/main/resources/mybatis-generator/generatorConfigMysql.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${version.mysql}</version> <scope>runtime</scope> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>${maven.plugin.clean}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven.plugin.compiler}</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> <optimize>true</optimize> <encoding>${project.build.sourceEncoding}</encoding> <debug>true</debug> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project><file_sep>/GoodLuck-server/src/main/java/com/help/server/common/GetParamsUtils.java package com.help.server.common; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; public class GetParamsUtils { private static final Logger log = LoggerFactory.getLogger(GetParamsUtils.class); public static String jsonReq(HttpServletRequest request) { BufferedReader br; StringBuilder sb = null; String reqBody = null; try { br = new BufferedReader(new InputStreamReader(request.getInputStream())); String line = null; sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } br.close(); if (sb.length() < 1) return ""; reqBody = URLDecoder.decode(sb.toString(), "UTF-8"); reqBody = reqBody.substring(reqBody.indexOf("{")); return reqBody; } catch (IOException e) { log.error("获取json参数错误!{}", e.getMessage()); return ""; } } public static Map<String, Object> getParamsMap(HttpServletRequest request) { Map<String, Object> paramsMap = new HashMap<>(); String json = jsonReq(request); if (StringUtils.isNotBlank(json)) { return JSONObject.parseObject(json, Map.class); } return paramsMap; } public static Map<String, Object> getParamsMap() { Map<String, Object> paramsMap = new HashMap<>(); try { ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = sra.getRequest(); String json = jsonReq(request); if (StringUtils.isNotBlank(json)) { return JSONObject.parseObject(json, Map.class); } } catch (Exception e) { log.error("json参数转换错误!{}", e.getMessage()); } return paramsMap; } public static Object getValue(String key) { return getParamsMap().get(key); } public static Object getValueIfNull(Object value, Object requestParam) { return (value == null) ? requestParam : value; } public static Object getValueIfNull(Object value, Object requestParam, Object defaultValue) { return (value == null) ? (requestParam==null?defaultValue:requestParam) : value; } public static <T> T getParamsObject(Class clazz) { T t = null; try { ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = sra.getRequest(); String json = jsonReq(request); if ("{}".equals(json) || StringUtils.isBlank(json)) { return null; } if (StringUtils.isNotBlank(json)) { return (T)JSONObject.parseObject(json, clazz); } } catch (Exception e) { log.error("json参数转换错误!{}", e.getMessage()); } return t; } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/controller/TuserController.java package com.help.server.controller; import com.alibaba.fastjson.JSONObject; import com.help.api.ResultDTO; import com.help.api.TuserPageParam; import com.help.api.TuserParam; import com.help.server.common.AuthUtil; import com.help.server.common.HttpClientUtil; import com.help.server.common.ResultHandler; import com.help.server.common.SenInfoCheckUtil; import com.help.server.model.Tuser; import com.help.server.model.WxUserInfo; import com.help.server.service.SenInfoCheckService; import com.help.server.service.TuserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; /** * 用户控制层接口 * @Author LY * @Date 2020/1/30 11:00 * @Version 1.0 **/ @RestController @RequestMapping(path = "/user/") public class TuserController { @Autowired private TuserService tuserService; @Autowired private SenInfoCheckService senInfoCheckService; /** * 获取用户信息 * @param openId * @return */ @RequestMapping(value = "/get") public ResultDTO get(String openId, HttpServletRequest request) { if(openId == null){ openId = AuthUtil.getAuthOpenIdFromCookie(request); } if(openId != null){ TuserParam tuser = tuserService.getUserInfoByOpenId(openId); if(tuser != null){ return ResultHandler.handleSuccess(tuser); }else{ return ResultHandler.createErrorResult("获取用户信息失败"); } }else{ return ResultHandler.createErrorResult("缺少用户标识信息,无法获取"); } } /** * 通过条件获取用户信息 * @param param 用户信息 * @return */ @RequestMapping(value = "/getUsersByCondition") public ResultDTO get(TuserPageParam param, HttpServletRequest request) { return tuserService.getListByConditon(param); } /** * 用户信息修改 * @param user 用户信息 * @return */ @RequestMapping(value = "/edit") public ResultDTO editUserInfo(Tuser user,HttpServletRequest request) { String content = SenInfoCheckUtil.makeUpParams(request); if(!senInfoCheckService.checkContent(content)){ return ResultHandler.createErrorResult("输入内容非法"); } boolean result = tuserService.editUserInfo(user); if(result){ return ResultHandler.handleSuccess("修改用户信息成功",null); }else{ return ResultHandler.createErrorResult("修改用户信息失败,请稍后重试"); } } /** * 用户身份认证 * @param userId * @param identityType * @return */ @RequestMapping(value = "/indentityUser") public ResultDTO indentityUser(String userId, int identityType) { boolean result = tuserService.indentityUser(userId,identityType); if(result){ return ResultHandler.handleSuccess("修改用户身份成功",null); }else{ return ResultHandler.createErrorResult("修改用户身份失败"); } } /** * 通过不同身份的数量 * @param param 用户信息 * @return */ @RequestMapping(value = "/getIndentityCount") public ResultDTO getIndentityCount(TuserPageParam param, HttpServletRequest request) { return ResultHandler.handleSuccess(tuserService.selectIdentityCount(param)); } /** * 用户信息新增 * @param user 用户信息 * @return */ @RequestMapping(value = "/addWxUserInfo") public ResultDTO register(WxUserInfo user) { if(user.getId() == null){ String code = user.getCode(); if(code == null){ return ResultHandler.createErrorResult("登录code不存在"); } String url = AuthUtil.MINI_PRO_LOGIN_VALIDATE_URL + "?appid=" + AuthUtil.MINI_PRO_APP_ID + "&secret=" + AuthUtil.MINI_PRO_APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code"; JSONObject json = HttpClientUtil.doGetJson(url); String openId = json.getString("openid"); if(openId == null){ return ResultHandler.createErrorResult(json.getString("errmsg")); } user.setId(openId); } Tuser tuser= user.wxUserToTuser(); tuserService.register(tuser); if(tuser != null){ return ResultHandler.handleSuccess("注册成功",tuser); }else{ return ResultHandler.createErrorResult("注册失败,请稍后重试"); } } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/model/Suggest.java package com.help.server.model; import java.io.Serializable; import java.util.Date; public class Suggest implements Serializable { private String id; private String userId; private String remark; private String mobile; private Date createTime; private static final long serialVersionUID = 1L; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }<file_sep>/GoodLuck-api/src/main/java/com/help/api/AreaFacade.java package com.help.api; import java.util.List; public interface AreaFacade { public ResultDTO<List> getProvinces(); public ResultDTO<List> getCitysByProvince(String code); public ResultDTO<List> getDistrictsByCity(String code); public ResultDTO<AreaParam> getAreaByCode(String code); public ResultDTO<AreaParam> getAreaByName(String name); } <file_sep>/GoodLuck-server/src/main/java/com/help/server/model/QuestionExample.java package com.help.server.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class QuestionExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public QuestionExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andNumberIsNull() { addCriterion("number is null"); return (Criteria) this; } public Criteria andNumberIsNotNull() { addCriterion("number is not null"); return (Criteria) this; } public Criteria andNumberEqualTo(String value) { addCriterion("number =", value, "number"); return (Criteria) this; } public Criteria andNumberNotEqualTo(String value) { addCriterion("number <>", value, "number"); return (Criteria) this; } public Criteria andNumberGreaterThan(String value) { addCriterion("number >", value, "number"); return (Criteria) this; } public Criteria andNumberGreaterThanOrEqualTo(String value) { addCriterion("number >=", value, "number"); return (Criteria) this; } public Criteria andNumberLessThan(String value) { addCriterion("number <", value, "number"); return (Criteria) this; } public Criteria andNumberLessThanOrEqualTo(String value) { addCriterion("number <=", value, "number"); return (Criteria) this; } public Criteria andNumberLike(String value) { addCriterion("number like", value, "number"); return (Criteria) this; } public Criteria andNumberNotLike(String value) { addCriterion("number not like", value, "number"); return (Criteria) this; } public Criteria andNumberIn(List<String> values) { addCriterion("number in", values, "number"); return (Criteria) this; } public Criteria andNumberNotIn(List<String> values) { addCriterion("number not in", values, "number"); return (Criteria) this; } public Criteria andNumberBetween(String value1, String value2) { addCriterion("number between", value1, value2, "number"); return (Criteria) this; } public Criteria andNumberNotBetween(String value1, String value2) { addCriterion("number not between", value1, value2, "number"); return (Criteria) this; } public Criteria andTagIsNull() { addCriterion("tag is null"); return (Criteria) this; } public Criteria andTagIsNotNull() { addCriterion("tag is not null"); return (Criteria) this; } public Criteria andTagEqualTo(String value) { addCriterion("tag =", value, "tag"); return (Criteria) this; } public Criteria andTagNotEqualTo(String value) { addCriterion("tag <>", value, "tag"); return (Criteria) this; } public Criteria andTagGreaterThan(String value) { addCriterion("tag >", value, "tag"); return (Criteria) this; } public Criteria andTagGreaterThanOrEqualTo(String value) { addCriterion("tag >=", value, "tag"); return (Criteria) this; } public Criteria andTagLessThan(String value) { addCriterion("tag <", value, "tag"); return (Criteria) this; } public Criteria andTagLessThanOrEqualTo(String value) { addCriterion("tag <=", value, "tag"); return (Criteria) this; } public Criteria andTagLike(String value) { addCriterion("tag like", value, "tag"); return (Criteria) this; } public Criteria andTagNotLike(String value) { addCriterion("tag not like", value, "tag"); return (Criteria) this; } public Criteria andTagIn(List<String> values) { addCriterion("tag in", values, "tag"); return (Criteria) this; } public Criteria andTagNotIn(List<String> values) { addCriterion("tag not in", values, "tag"); return (Criteria) this; } public Criteria andTagBetween(String value1, String value2) { addCriterion("tag between", value1, value2, "tag"); return (Criteria) this; } public Criteria andTagNotBetween(String value1, String value2) { addCriterion("tag not between", value1, value2, "tag"); return (Criteria) this; } public Criteria andStateIsNull() { addCriterion("state is null"); return (Criteria) this; } public Criteria andStateIsNotNull() { addCriterion("state is not null"); return (Criteria) this; } public Criteria andStateEqualTo(String value) { addCriterion("state =", value, "state"); return (Criteria) this; } public Criteria andStateNotEqualTo(String value) { addCriterion("state <>", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThan(String value) { addCriterion("state >", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThanOrEqualTo(String value) { addCriterion("state >=", value, "state"); return (Criteria) this; } public Criteria andStateLessThan(String value) { addCriterion("state <", value, "state"); return (Criteria) this; } public Criteria andStateLessThanOrEqualTo(String value) { addCriterion("state <=", value, "state"); return (Criteria) this; } public Criteria andStateLike(String value) { addCriterion("state like", value, "state"); return (Criteria) this; } public Criteria andStateNotLike(String value) { addCriterion("state not like", value, "state"); return (Criteria) this; } public Criteria andStateIn(List<String> values) { addCriterion("state in", values, "state"); return (Criteria) this; } public Criteria andStateNotIn(List<String> values) { addCriterion("state not in", values, "state"); return (Criteria) this; } public Criteria andStateBetween(String value1, String value2) { addCriterion("state between", value1, value2, "state"); return (Criteria) this; } public Criteria andStateNotBetween(String value1, String value2) { addCriterion("state not between", value1, value2, "state"); return (Criteria) this; } public Criteria andAuditStateIsNull() { addCriterion("audit_state is null"); return (Criteria) this; } public Criteria andAuditStateIsNotNull() { addCriterion("audit_state is not null"); return (Criteria) this; } public Criteria andAuditStateEqualTo(String value) { addCriterion("audit_state =", value, "auditState"); return (Criteria) this; } public Criteria andAuditStateNotEqualTo(String value) { addCriterion("audit_state <>", value, "auditState"); return (Criteria) this; } public Criteria andAuditStateGreaterThan(String value) { addCriterion("audit_state >", value, "auditState"); return (Criteria) this; } public Criteria andAuditStateGreaterThanOrEqualTo(String value) { addCriterion("audit_state >=", value, "auditState"); return (Criteria) this; } public Criteria andAuditStateLessThan(String value) { addCriterion("audit_state <", value, "auditState"); return (Criteria) this; } public Criteria andAuditStateLessThanOrEqualTo(String value) { addCriterion("audit_state <=", value, "auditState"); return (Criteria) this; } public Criteria andAuditStateLike(String value) { addCriterion("audit_state like", value, "auditState"); return (Criteria) this; } public Criteria andAuditStateNotLike(String value) { addCriterion("audit_state not like", value, "auditState"); return (Criteria) this; } public Criteria andAuditStateIn(List<String> values) { addCriterion("audit_state in", values, "auditState"); return (Criteria) this; } public Criteria andAuditStateNotIn(List<String> values) { addCriterion("audit_state not in", values, "auditState"); return (Criteria) this; } public Criteria andAuditStateBetween(String value1, String value2) { addCriterion("audit_state between", value1, value2, "auditState"); return (Criteria) this; } public Criteria andAuditStateNotBetween(String value1, String value2) { addCriterion("audit_state not between", value1, value2, "auditState"); return (Criteria) this; } public Criteria andPubTimeIsNull() { addCriterion("pub_time is null"); return (Criteria) this; } public Criteria andPubTimeIsNotNull() { addCriterion("pub_time is not null"); return (Criteria) this; } public Criteria andPubTimeEqualTo(Date value) { addCriterion("pub_time =", value, "pubTime"); return (Criteria) this; } public Criteria andPubTimeNotEqualTo(Date value) { addCriterion("pub_time <>", value, "pubTime"); return (Criteria) this; } public Criteria andPubTimeGreaterThan(Date value) { addCriterion("pub_time >", value, "pubTime"); return (Criteria) this; } public Criteria andPubTimeGreaterThanOrEqualTo(Date value) { addCriterion("pub_time >=", value, "pubTime"); return (Criteria) this; } public Criteria andPubTimeLessThan(Date value) { addCriterion("pub_time <", value, "pubTime"); return (Criteria) this; } public Criteria andPubTimeLessThanOrEqualTo(Date value) { addCriterion("pub_time <=", value, "pubTime"); return (Criteria) this; } public Criteria andPubTimeIn(List<Date> values) { addCriterion("pub_time in", values, "pubTime"); return (Criteria) this; } public Criteria andPubTimeNotIn(List<Date> values) { addCriterion("pub_time not in", values, "pubTime"); return (Criteria) this; } public Criteria andPubTimeBetween(Date value1, Date value2) { addCriterion("pub_time between", value1, value2, "pubTime"); return (Criteria) this; } public Criteria andPubTimeNotBetween(Date value1, Date value2) { addCriterion("pub_time not between", value1, value2, "pubTime"); return (Criteria) this; } public Criteria andPubUserIdIsNull() { addCriterion("pub_user_id is null"); return (Criteria) this; } public Criteria andPubUserIdIsNotNull() { addCriterion("pub_user_id is not null"); return (Criteria) this; } public Criteria andPubUserIdEqualTo(String value) { addCriterion("pub_user_id =", value, "pubUserId"); return (Criteria) this; } public Criteria andPubUserIdNotEqualTo(String value) { addCriterion("pub_user_id <>", value, "pubUserId"); return (Criteria) this; } public Criteria andPubUserIdGreaterThan(String value) { addCriterion("pub_user_id >", value, "pubUserId"); return (Criteria) this; } public Criteria andPubUserIdGreaterThanOrEqualTo(String value) { addCriterion("pub_user_id >=", value, "pubUserId"); return (Criteria) this; } public Criteria andPubUserIdLessThan(String value) { addCriterion("pub_user_id <", value, "pubUserId"); return (Criteria) this; } public Criteria andPubUserIdLessThanOrEqualTo(String value) { addCriterion("pub_user_id <=", value, "pubUserId"); return (Criteria) this; } public Criteria andPubUserIdLike(String value) { addCriterion("pub_user_id like", value, "pubUserId"); return (Criteria) this; } public Criteria andPubUserIdNotLike(String value) { addCriterion("pub_user_id not like", value, "pubUserId"); return (Criteria) this; } public Criteria andPubUserIdIn(List<String> values) { addCriterion("pub_user_id in", values, "pubUserId"); return (Criteria) this; } public Criteria andPubUserIdNotIn(List<String> values) { addCriterion("pub_user_id not in", values, "pubUserId"); return (Criteria) this; } public Criteria andPubUserIdBetween(String value1, String value2) { addCriterion("pub_user_id between", value1, value2, "pubUserId"); return (Criteria) this; } public Criteria andPubUserIdNotBetween(String value1, String value2) { addCriterion("pub_user_id not between", value1, value2, "pubUserId"); return (Criteria) this; } public Criteria andProvinceIsNull() { addCriterion("province is null"); return (Criteria) this; } public Criteria andProvinceIsNotNull() { addCriterion("province is not null"); return (Criteria) this; } public Criteria andProvinceEqualTo(String value) { addCriterion("province =", value, "province"); return (Criteria) this; } public Criteria andProvinceNotEqualTo(String value) { addCriterion("province <>", value, "province"); return (Criteria) this; } public Criteria andProvinceGreaterThan(String value) { addCriterion("province >", value, "province"); return (Criteria) this; } public Criteria andProvinceGreaterThanOrEqualTo(String value) { addCriterion("province >=", value, "province"); return (Criteria) this; } public Criteria andProvinceLessThan(String value) { addCriterion("province <", value, "province"); return (Criteria) this; } public Criteria andProvinceLessThanOrEqualTo(String value) { addCriterion("province <=", value, "province"); return (Criteria) this; } public Criteria andProvinceLike(String value) { addCriterion("province like", value, "province"); return (Criteria) this; } public Criteria andProvinceNotLike(String value) { addCriterion("province not like", value, "province"); return (Criteria) this; } public Criteria andProvinceIn(List<String> values) { addCriterion("province in", values, "province"); return (Criteria) this; } public Criteria andProvinceNotIn(List<String> values) { addCriterion("province not in", values, "province"); return (Criteria) this; } public Criteria andProvinceBetween(String value1, String value2) { addCriterion("province between", value1, value2, "province"); return (Criteria) this; } public Criteria andProvinceNotBetween(String value1, String value2) { addCriterion("province not between", value1, value2, "province"); return (Criteria) this; } public Criteria andCityIsNull() { addCriterion("city is null"); return (Criteria) this; } public Criteria andCityIsNotNull() { addCriterion("city is not null"); return (Criteria) this; } public Criteria andCityEqualTo(String value) { addCriterion("city =", value, "city"); return (Criteria) this; } public Criteria andCityNotEqualTo(String value) { addCriterion("city <>", value, "city"); return (Criteria) this; } public Criteria andCityGreaterThan(String value) { addCriterion("city >", value, "city"); return (Criteria) this; } public Criteria andCityGreaterThanOrEqualTo(String value) { addCriterion("city >=", value, "city"); return (Criteria) this; } public Criteria andCityLessThan(String value) { addCriterion("city <", value, "city"); return (Criteria) this; } public Criteria andCityLessThanOrEqualTo(String value) { addCriterion("city <=", value, "city"); return (Criteria) this; } public Criteria andCityLike(String value) { addCriterion("city like", value, "city"); return (Criteria) this; } public Criteria andCityNotLike(String value) { addCriterion("city not like", value, "city"); return (Criteria) this; } public Criteria andCityIn(List<String> values) { addCriterion("city in", values, "city"); return (Criteria) this; } public Criteria andCityNotIn(List<String> values) { addCriterion("city not in", values, "city"); return (Criteria) this; } public Criteria andCityBetween(String value1, String value2) { addCriterion("city between", value1, value2, "city"); return (Criteria) this; } public Criteria andCityNotBetween(String value1, String value2) { addCriterion("city not between", value1, value2, "city"); return (Criteria) this; } public Criteria andDistrictIsNull() { addCriterion("district is null"); return (Criteria) this; } public Criteria andDistrictIsNotNull() { addCriterion("district is not null"); return (Criteria) this; } public Criteria andDistrictEqualTo(String value) { addCriterion("district =", value, "district"); return (Criteria) this; } public Criteria andDistrictNotEqualTo(String value) { addCriterion("district <>", value, "district"); return (Criteria) this; } public Criteria andDistrictGreaterThan(String value) { addCriterion("district >", value, "district"); return (Criteria) this; } public Criteria andDistrictGreaterThanOrEqualTo(String value) { addCriterion("district >=", value, "district"); return (Criteria) this; } public Criteria andDistrictLessThan(String value) { addCriterion("district <", value, "district"); return (Criteria) this; } public Criteria andDistrictLessThanOrEqualTo(String value) { addCriterion("district <=", value, "district"); return (Criteria) this; } public Criteria andDistrictLike(String value) { addCriterion("district like", value, "district"); return (Criteria) this; } public Criteria andDistrictNotLike(String value) { addCriterion("district not like", value, "district"); return (Criteria) this; } public Criteria andDistrictIn(List<String> values) { addCriterion("district in", values, "district"); return (Criteria) this; } public Criteria andDistrictNotIn(List<String> values) { addCriterion("district not in", values, "district"); return (Criteria) this; } public Criteria andDistrictBetween(String value1, String value2) { addCriterion("district between", value1, value2, "district"); return (Criteria) this; } public Criteria andDistrictNotBetween(String value1, String value2) { addCriterion("district not between", value1, value2, "district"); return (Criteria) this; } public Criteria andStreetIsNull() { addCriterion("street is null"); return (Criteria) this; } public Criteria andStreetIsNotNull() { addCriterion("street is not null"); return (Criteria) this; } public Criteria andStreetEqualTo(String value) { addCriterion("street =", value, "street"); return (Criteria) this; } public Criteria andStreetNotEqualTo(String value) { addCriterion("street <>", value, "street"); return (Criteria) this; } public Criteria andStreetGreaterThan(String value) { addCriterion("street >", value, "street"); return (Criteria) this; } public Criteria andStreetGreaterThanOrEqualTo(String value) { addCriterion("street >=", value, "street"); return (Criteria) this; } public Criteria andStreetLessThan(String value) { addCriterion("street <", value, "street"); return (Criteria) this; } public Criteria andStreetLessThanOrEqualTo(String value) { addCriterion("street <=", value, "street"); return (Criteria) this; } public Criteria andStreetLike(String value) { addCriterion("street like", value, "street"); return (Criteria) this; } public Criteria andStreetNotLike(String value) { addCriterion("street not like", value, "street"); return (Criteria) this; } public Criteria andStreetIn(List<String> values) { addCriterion("street in", values, "street"); return (Criteria) this; } public Criteria andStreetNotIn(List<String> values) { addCriterion("street not in", values, "street"); return (Criteria) this; } public Criteria andStreetBetween(String value1, String value2) { addCriterion("street between", value1, value2, "street"); return (Criteria) this; } public Criteria andStreetNotBetween(String value1, String value2) { addCriterion("street not between", value1, value2, "street"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andAuditTimeIsNull() { addCriterion("audit_time is null"); return (Criteria) this; } public Criteria andAuditTimeIsNotNull() { addCriterion("audit_time is not null"); return (Criteria) this; } public Criteria andAuditTimeEqualTo(Date value) { addCriterion("audit_time =", value, "auditTime"); return (Criteria) this; } public Criteria andAuditTimeNotEqualTo(Date value) { addCriterion("audit_time <>", value, "auditTime"); return (Criteria) this; } public Criteria andAuditTimeGreaterThan(Date value) { addCriterion("audit_time >", value, "auditTime"); return (Criteria) this; } public Criteria andAuditTimeGreaterThanOrEqualTo(Date value) { addCriterion("audit_time >=", value, "auditTime"); return (Criteria) this; } public Criteria andAuditTimeLessThan(Date value) { addCriterion("audit_time <", value, "auditTime"); return (Criteria) this; } public Criteria andAuditTimeLessThanOrEqualTo(Date value) { addCriterion("audit_time <=", value, "auditTime"); return (Criteria) this; } public Criteria andAuditTimeIn(List<Date> values) { addCriterion("audit_time in", values, "auditTime"); return (Criteria) this; } public Criteria andAuditTimeNotIn(List<Date> values) { addCriterion("audit_time not in", values, "auditTime"); return (Criteria) this; } public Criteria andAuditTimeBetween(Date value1, Date value2) { addCriterion("audit_time between", value1, value2, "auditTime"); return (Criteria) this; } public Criteria andAuditTimeNotBetween(Date value1, Date value2) { addCriterion("audit_time not between", value1, value2, "auditTime"); return (Criteria) this; } public Criteria andLastUpdateTimeIsNull() { addCriterion("last_update_time is null"); return (Criteria) this; } public Criteria andLastUpdateTimeIsNotNull() { addCriterion("last_update_time is not null"); return (Criteria) this; } public Criteria andLastUpdateTimeEqualTo(Date value) { addCriterion("last_update_time =", value, "lastUpdateTime"); return (Criteria) this; } public Criteria andLastUpdateTimeNotEqualTo(Date value) { addCriterion("last_update_time <>", value, "lastUpdateTime"); return (Criteria) this; } public Criteria andLastUpdateTimeGreaterThan(Date value) { addCriterion("last_update_time >", value, "lastUpdateTime"); return (Criteria) this; } public Criteria andLastUpdateTimeGreaterThanOrEqualTo(Date value) { addCriterion("last_update_time >=", value, "lastUpdateTime"); return (Criteria) this; } public Criteria andLastUpdateTimeLessThan(Date value) { addCriterion("last_update_time <", value, "lastUpdateTime"); return (Criteria) this; } public Criteria andLastUpdateTimeLessThanOrEqualTo(Date value) { addCriterion("last_update_time <=", value, "lastUpdateTime"); return (Criteria) this; } public Criteria andLastUpdateTimeIn(List<Date> values) { addCriterion("last_update_time in", values, "lastUpdateTime"); return (Criteria) this; } public Criteria andLastUpdateTimeNotIn(List<Date> values) { addCriterion("last_update_time not in", values, "lastUpdateTime"); return (Criteria) this; } public Criteria andLastUpdateTimeBetween(Date value1, Date value2) { addCriterion("last_update_time between", value1, value2, "lastUpdateTime"); return (Criteria) this; } public Criteria andLastUpdateTimeNotBetween(Date value1, Date value2) { addCriterion("last_update_time not between", value1, value2, "lastUpdateTime"); return (Criteria) this; } public Criteria andMobileIsNull() { addCriterion("mobile is null"); return (Criteria) this; } public Criteria andMobileIsNotNull() { addCriterion("mobile is not null"); return (Criteria) this; } public Criteria andMobileEqualTo(String value) { addCriterion("mobile =", value, "mobile"); return (Criteria) this; } public Criteria andMobileNotEqualTo(String value) { addCriterion("mobile <>", value, "mobile"); return (Criteria) this; } public Criteria andMobileGreaterThan(String value) { addCriterion("mobile >", value, "mobile"); return (Criteria) this; } public Criteria andMobileGreaterThanOrEqualTo(String value) { addCriterion("mobile >=", value, "mobile"); return (Criteria) this; } public Criteria andMobileLessThan(String value) { addCriterion("mobile <", value, "mobile"); return (Criteria) this; } public Criteria andMobileLessThanOrEqualTo(String value) { addCriterion("mobile <=", value, "mobile"); return (Criteria) this; } public Criteria andMobileLike(String value) { addCriterion("mobile like", value, "mobile"); return (Criteria) this; } public Criteria andMobileNotLike(String value) { addCriterion("mobile not like", value, "mobile"); return (Criteria) this; } public Criteria andMobileIn(List<String> values) { addCriterion("mobile in", values, "mobile"); return (Criteria) this; } public Criteria andMobileNotIn(List<String> values) { addCriterion("mobile not in", values, "mobile"); return (Criteria) this; } public Criteria andMobileBetween(String value1, String value2) { addCriterion("mobile between", value1, value2, "mobile"); return (Criteria) this; } public Criteria andMobileNotBetween(String value1, String value2) { addCriterion("mobile not between", value1, value2, "mobile"); return (Criteria) this; } public Criteria andWxNumberIsNull() { addCriterion("wx_number is null"); return (Criteria) this; } public Criteria andWxNumberIsNotNull() { addCriterion("wx_number is not null"); return (Criteria) this; } public Criteria andWxNumberEqualTo(String value) { addCriterion("wx_number =", value, "wxNumber"); return (Criteria) this; } public Criteria andWxNumberNotEqualTo(String value) { addCriterion("wx_number <>", value, "wxNumber"); return (Criteria) this; } public Criteria andWxNumberGreaterThan(String value) { addCriterion("wx_number >", value, "wxNumber"); return (Criteria) this; } public Criteria andWxNumberGreaterThanOrEqualTo(String value) { addCriterion("wx_number >=", value, "wxNumber"); return (Criteria) this; } public Criteria andWxNumberLessThan(String value) { addCriterion("wx_number <", value, "wxNumber"); return (Criteria) this; } public Criteria andWxNumberLessThanOrEqualTo(String value) { addCriterion("wx_number <=", value, "wxNumber"); return (Criteria) this; } public Criteria andWxNumberLike(String value) { addCriterion("wx_number like", value, "wxNumber"); return (Criteria) this; } public Criteria andWxNumberNotLike(String value) { addCriterion("wx_number not like", value, "wxNumber"); return (Criteria) this; } public Criteria andWxNumberIn(List<String> values) { addCriterion("wx_number in", values, "wxNumber"); return (Criteria) this; } public Criteria andWxNumberNotIn(List<String> values) { addCriterion("wx_number not in", values, "wxNumber"); return (Criteria) this; } public Criteria andWxNumberBetween(String value1, String value2) { addCriterion("wx_number between", value1, value2, "wxNumber"); return (Criteria) this; } public Criteria andWxNumberNotBetween(String value1, String value2) { addCriterion("wx_number not between", value1, value2, "wxNumber"); return (Criteria) this; } public Criteria andStarsIsNull() { addCriterion("stars is null"); return (Criteria) this; } public Criteria andStarsIsNotNull() { addCriterion("stars is not null"); return (Criteria) this; } public Criteria andStarsEqualTo(Integer value) { addCriterion("stars =", value, "stars"); return (Criteria) this; } public Criteria andStarsNotEqualTo(Integer value) { addCriterion("stars <>", value, "stars"); return (Criteria) this; } public Criteria andStarsGreaterThan(Integer value) { addCriterion("stars >", value, "stars"); return (Criteria) this; } public Criteria andStarsGreaterThanOrEqualTo(Integer value) { addCriterion("stars >=", value, "stars"); return (Criteria) this; } public Criteria andStarsLessThan(Integer value) { addCriterion("stars <", value, "stars"); return (Criteria) this; } public Criteria andStarsLessThanOrEqualTo(Integer value) { addCriterion("stars <=", value, "stars"); return (Criteria) this; } public Criteria andStarsIn(List<Integer> values) { addCriterion("stars in", values, "stars"); return (Criteria) this; } public Criteria andStarsNotIn(List<Integer> values) { addCriterion("stars not in", values, "stars"); return (Criteria) this; } public Criteria andStarsBetween(Integer value1, Integer value2) { addCriterion("stars between", value1, value2, "stars"); return (Criteria) this; } public Criteria andStarsNotBetween(Integer value1, Integer value2) { addCriterion("stars not between", value1, value2, "stars"); return (Criteria) this; } public Criteria andPicMd5IsNull() { addCriterion("pic_md5 is null"); return (Criteria) this; } public Criteria andPicMd5IsNotNull() { addCriterion("pic_md5 is not null"); return (Criteria) this; } public Criteria andPicMd5EqualTo(String value) { addCriterion("pic_md5 =", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5NotEqualTo(String value) { addCriterion("pic_md5 <>", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5GreaterThan(String value) { addCriterion("pic_md5 >", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5GreaterThanOrEqualTo(String value) { addCriterion("pic_md5 >=", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5LessThan(String value) { addCriterion("pic_md5 <", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5LessThanOrEqualTo(String value) { addCriterion("pic_md5 <=", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5Like(String value) { addCriterion("pic_md5 like", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5NotLike(String value) { addCriterion("pic_md5 not like", value, "picMd5"); return (Criteria) this; } public Criteria andPicMd5In(List<String> values) { addCriterion("pic_md5 in", values, "picMd5"); return (Criteria) this; } public Criteria andPicMd5NotIn(List<String> values) { addCriterion("pic_md5 not in", values, "picMd5"); return (Criteria) this; } public Criteria andPicMd5Between(String value1, String value2) { addCriterion("pic_md5 between", value1, value2, "picMd5"); return (Criteria) this; } public Criteria andPicMd5NotBetween(String value1, String value2) { addCriterion("pic_md5 not between", value1, value2, "picMd5"); return (Criteria) this; } public Criteria andNumberLikeInsensitive(String value) { addCriterion("upper(number) like", value.toUpperCase(), "number"); return (Criteria) this; } public Criteria andTagLikeInsensitive(String value) { addCriterion("upper(tag) like", value.toUpperCase(), "tag"); return (Criteria) this; } public Criteria andStateLikeInsensitive(String value) { addCriterion("upper(state) like", value.toUpperCase(), "state"); return (Criteria) this; } public Criteria andAuditStateLikeInsensitive(String value) { addCriterion("upper(audit_state) like", value.toUpperCase(), "auditState"); return (Criteria) this; } public Criteria andPubUserIdLikeInsensitive(String value) { addCriterion("upper(pub_user_id) like", value.toUpperCase(), "pubUserId"); return (Criteria) this; } public Criteria andProvinceLikeInsensitive(String value) { addCriterion("upper(province) like", value.toUpperCase(), "province"); return (Criteria) this; } public Criteria andCityLikeInsensitive(String value) { addCriterion("upper(city) like", value.toUpperCase(), "city"); return (Criteria) this; } public Criteria andDistrictLikeInsensitive(String value) { addCriterion("upper(district) like", value.toUpperCase(), "district"); return (Criteria) this; } public Criteria andStreetLikeInsensitive(String value) { addCriterion("upper(street) like", value.toUpperCase(), "street"); return (Criteria) this; } public Criteria andRemarkLikeInsensitive(String value) { addCriterion("upper(remark) like", value.toUpperCase(), "remark"); return (Criteria) this; } public Criteria andMobileLikeInsensitive(String value) { addCriterion("upper(mobile) like", value.toUpperCase(), "mobile"); return (Criteria) this; } public Criteria andWxNumberLikeInsensitive(String value) { addCriterion("upper(wx_number) like", value.toUpperCase(), "wxNumber"); return (Criteria) this; } public Criteria andPicMd5LikeInsensitive(String value) { addCriterion("upper(pic_md5) like", value.toUpperCase(), "picMd5"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }<file_sep>/GoodLuck-server/src/main/java/com/help/server/service/AreaServiceImpl.java package com.help.server.service; import com.help.api.AreaParam; import com.help.server.dao.AreaMapper; import com.help.server.model.Area; import com.help.server.model.AreaExample; import org.apache.commons.lang.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; @Service public class AreaServiceImpl implements IAreaService { @Autowired private AreaMapper areaMapper; @Override public List<AreaParam> list(AreaParam param) { AreaExample example = new AreaExample(); AreaExample.Criteria criteria = example.createCriteria(); if (StringUtils.isNotEmpty(param.getAreaCode())) { criteria.andAreaCodeEqualTo(param.getAreaCode()); } if (StringUtils.isNotEmpty(param.getAreaName())) { criteria.andAreaNameLike("%" +param.getAreaName() +"%"); } if (StringUtils.isNotEmpty(param.getAreaParentCode())) { criteria.andAreaParentCodeEqualTo(param.getAreaParentCode()); } if (param.getAreaType() != null) { criteria.andAreaTypeEqualTo(param.getAreaType()); } List<Area> list = areaMapper.selectByExample(example); if (!CollectionUtils.isEmpty(list)) { List<AreaParam> paramList = new ArrayList<>(); for (Area area : list) { paramList.add(area2Param(area)); } return paramList; } return new ArrayList<>(); } private AreaParam area2Param(Area area) { AreaParam param = new AreaParam(); BeanUtils.copyProperties(area, param); return param; } @Override public AreaParam get(AreaParam param) { List<AreaParam> areaList = list(param); return CollectionUtils.isEmpty(areaList) ? null : areaList.get(0); } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/dao/SuggestMapper.java package com.help.server.dao; import com.help.server.model.Suggest; import com.help.server.model.SuggestExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface SuggestMapper { int countByExample(SuggestExample example); int deleteByExample(SuggestExample example); int deleteByPrimaryKey(String id); int insert(Suggest record); int insertSelective(Suggest record); List<Suggest> selectByExample(SuggestExample example); Suggest selectByPrimaryKey(String id); int updateByExampleSelective(@Param("record") Suggest record, @Param("example") SuggestExample example); int updateByExample(@Param("record") Suggest record, @Param("example") SuggestExample example); int updateByPrimaryKeySelective(Suggest record); int updateByPrimaryKey(Suggest record); }<file_sep>/GoodLuck-server/src/main/resources/stop.sh #!/bin/bash #please remove all OTS(uppercase) to your own service/application name JAR_NAME="`pwd`/GoodLuck-server.jar" echo --------------------------stop begin---------------------------------------- echo ----jar is $JAR_NAME PID=$(ps -ef | grep $JAR_NAME | grep -v grep | awk '{ print $2 }') if [ -z "$PID" ] then echo ----$JAR_NAME Application is already stopped else echo ----kill $PID kill -9 $PID echo ----killed $PID $JAR_NAME Application. sleep 1s fi echo ----ps check $JAR_NAME. ps -ef | grep --color=auto $JAR_NAME | grep -v grep echo ----ps check $JAR_NAME end. echo --------------------------stop end----------------------------------------- <file_sep>/GoodLuck-server/src/main/resources/start.sh #!/bin/bash #input your service/application name JAR_NAME="`pwd`/GoodLuck-server.jar" echo --------------------------start/restart begin---------------------------------------- echo ----jar is $JAR_NAME # dump目录 DIR_DUMP="`pwd`/dump" if [ ! -d $DIR_DUMP ]; then mkdir $DIR_DUMP fi PID=$(ps -ef | grep $JAR_NAME | grep -v grep | awk '{ print $2 }') # flag , only Y will restart YES_OR_NO='Y' if [ -z "$PID" ] then echo ----$JAR_NAME service/application is already stopped else #if will kill and restart echo -n "$JAR_NAME service/application is already running ,do you want to restart it? type:Y(restart)/N(no operation) >" read YES_OR_NO if [[ $YES_OR_NO = 'Y' ]]; then echo "----you type $YES_OR_NO,now will restart .... " echo ----kill $PID kill $PID echo ----killed $PID $JAR_NAME service/application. sleep 1s else echo "$YES_OR_NO,no the shell will exist" fi fi sleep 1s if [[ $YES_OR_NO = 'Y' ]]; then CURRENT_PATH=$(pwd) echo ----pwd is $CURRENT_PATH echo ----now will start up the Application nohup java -Xms512M -Xmx512M -XX:PermSize=128M -XX:MaxPermSize=128M -XX:+UseParallelOldGC -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=$DIR_DUMP -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -Xloggc:dump/heap_trace.txt -jar $JAR_NAME > console.out 2>&1 & sleep 1s echo ----ps check $JAR_NAME. ps -ef | grep --color=auto $JAR_NAME | grep -v grep echo ----ps check $JAR_NAME end. echo ---- java -jar $JAR_NAME '&' executed , please check. else echo "..." fi echo --------------------------start/restart end-----------------------------------------<file_sep>/GoodLuck-server/src/main/java/com/help/server/model/Tuser.java package com.help.server.model; import java.io.Serializable; import java.util.Date; public class Tuser implements Serializable { private String id; private String name; private String nickName; private Integer sex; private String birthday; private String province; private String city; private String country; private String wxNumber; private String mobile; private String headImgUrl; private String school; private String profession; private String unionId; private Integer identityType; private Date createTime; private Date lastUpdateTime; private Date lastLoginTime; private static final long serialVersionUID = 1L; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getWxNumber() { return wxNumber; } public void setWxNumber(String wxNumber) { this.wxNumber = wxNumber; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getHeadImgUrl() { return headImgUrl; } public void setHeadImgUrl(String headImgUrl) { this.headImgUrl = headImgUrl; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public String getProfession() { return profession; } public void setProfession(String profession) { this.profession = profession; } public String getUnionId() { return unionId; } public void setUnionId(String unionId) { this.unionId = unionId; } public Integer getIdentityType() { return identityType; } public void setIdentityType(Integer identityType) { this.identityType = identityType; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(Date lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } public Date getLastLoginTime() { return lastLoginTime; } public void setLastLoginTime(Date lastLoginTime) { this.lastLoginTime = lastLoginTime; } public Tuser(String id, String nickName, Integer sex, String province, String city, String country, String headImgUrl, String unionId,Date createTime) { this.id = id; this.nickName = nickName; this.sex = sex; this.province = province; this.city = city; this.country = country; this.headImgUrl = headImgUrl; this.unionId = unionId; this.createTime = createTime; } public Tuser() { } }<file_sep>/GoodLuck-server/src/main/java/com/help/server/properties/MysqlDatasourceConfig.java package com.help.server.properties; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.boot.autoconfigure.SpringBootVFS; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = {"com.help.server.dao"},sqlSessionTemplateRef = "mysqlSqlSessionTemplate") public class MysqlDatasourceConfig { @Bean(name = "mysqlDatasource") @ConfigurationProperties(prefix="mysql.jdbc") public DataSource dataSource() { return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build(); } @Bean(name = "mysqlSqlSessionFactory") public SqlSessionFactory setSqlSessionFactory(@Qualifier("mysqlDatasource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mysqlmappers/*.xml")); bean.setVfs(SpringBootVFS.class); bean.setTypeAliasesPackage("com.help.server.model"); return bean.getObject(); } @Bean(name = "mysqlTransactionManager") public PlatformTransactionManager platformTransactionManager(@Qualifier("mysqlDatasource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "mysqlSqlSessionTemplate") @Primary public SqlSessionTemplate sqlSessionTemplate(@Qualifier("mysqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } <file_sep>/GoodLuck-server/src/main/java/com/help/server/facade/AreaFacadeImpl.java package com.help.server.facade; import com.help.api.AreaFacade; import com.help.api.AreaParam; import com.help.api.ResultDTO; import com.help.server.common.CommonUtils; import com.help.server.common.ResultCodeEnum; import com.help.server.common.ResultHandler; import com.help.server.service.IAreaService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.List; @Service public class AreaFacadeImpl implements AreaFacade { @Autowired private IAreaService areaService; @Override @Cacheable(value="AREA_PROVINCE", sync=true) public ResultDTO<List> getProvinces() { AreaParam areaParam = new AreaParam(); areaParam.setAreaType(2); return ResultHandler.handleSuccess(areaService.list(areaParam)); } @Override @Cacheable(value="AREA_CITY", sync=true, condition ="#code != '' ") public ResultDTO<List> getCitysByProvince(String code) { CommonUtils.assertEmptyField(code, ResultCodeEnum.AREA_PROVINCE_CODE_IS_NULL); AreaParam areaParam = new AreaParam(); areaParam.setAreaType(3); areaParam.setAreaParentCode(code); return ResultHandler.handleSuccess(areaService.list(areaParam)); } @Override @Cacheable(value="AREA_DISTRICT", sync=true, condition ="#code != '' ") public ResultDTO<List> getDistrictsByCity(String code) { CommonUtils.assertEmptyField(code, ResultCodeEnum.AREA_CITY_CODE_IS_NULL); AreaParam areaParam = new AreaParam(); areaParam.setAreaType(4); areaParam.setAreaParentCode(code); return ResultHandler.handleSuccess(areaService.list(areaParam)); } @Override @Cacheable(value="AREA", sync=true, condition ="#code != '' ") public ResultDTO<AreaParam> getAreaByCode(String code) { CommonUtils.assertEmptyField(code, ResultCodeEnum.AREA_CODE_IS_NULL); AreaParam areaParam = new AreaParam(); areaParam.setAreaCode(code); return ResultHandler.handleSuccess(areaService.get(areaParam)); } @Override public ResultDTO<AreaParam> getAreaByName(String name) { AreaParam areaParam = new AreaParam(); areaParam.setAreaName(name); return ResultHandler.handleSuccess(areaService.get(areaParam)); } } <file_sep>/README.md # goodluck 祝大家好运
a7c16e07a64778efb491e85702ea0f4a62156134
[ "Markdown", "Java", "Maven POM", "Shell" ]
38
Java
jjw9014/GoodLuck
ed6b2aef74abde7c159db3913f0030d89e04e340
61d11741dc2d982c6f8b35bd6a3dcf056cf7be1d
refs/heads/master
<file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AccesoComponent } from './acceso/acceso.component'; import { BodyLandingComponent } from './body-landing/body-landing.component'; import { AdminPrincipalComponent } from './Administracion/admin-principal/admin-principal.component'; import { InicioComponent } from './Administracion/inicio/inicio.component'; import { UsuariosComponent } from './Administracion/usuarios/usuarios.component'; import { NuevoUsuarioComponent } from './nuevo-usuario/nuevo-usuario.component'; import { PaginasComponent } from './Administracion/paginas/paginas.component'; import { HomePrincipalComponent } from './Home/home-principal/home-principal.component'; import { RecursosComponent } from './Administracion/recursos/recursos.component'; import { RegistroUsuarioComponent } from './registro-usuario/registro-usuario.component'; import { AccesoAdministradorComponent } from './Administracion/acceso-administrador/acceso-administrador.component'; import { RegistroAdministradorComponent } from './registro-administrador/registro-administrador.component'; import { PagesComponent } from './Administracion/pages/pages.component'; import { EntradasPostComponent } from './Administracion/entradas-post/entradas-post.component'; import { ComentariosComponent } from './Administracion/comentarios/comentarios.component'; import { PlantillasComponent } from './Administracion/plantillas/plantillas.component'; import { AppPrincipalComponent } from './UsuarioRegistrado/app-principal/app-principal.component'; import { SitioWebComponent } from './UsuarioRegistrado/sitio-web/sitio-web.component'; const routes: Routes = [ { path: 'liebe', component: HomePrincipalComponent, children:[ { path: '', component: BodyLandingComponent }, { path: 'acceso', component: AccesoComponent }, { path: 'inicio', component: BodyLandingComponent }, { path: 'registro-usuario', component: RegistroUsuarioComponent }, { path: 'registro-admin', component: RegistroAdministradorComponent } ] }, { path: 'admin', component: HomePrincipalComponent, children: [ { path: '', component: AccesoAdministradorComponent, } ] }, { path: 'admin', component: AdminPrincipalComponent, children:[ { path: 'usuarios', component: UsuariosComponent }, { path: 'paginas', component: PaginasComponent }, { path: 'pages', component: PagesComponent }, { path: 'home', component: InicioComponent, }, { path:'nuevo-usuario', component: NuevoUsuarioComponent }, { path: 'recursos', component: RecursosComponent }, { path: 'entradas', component: EntradasPostComponent }, { path: 'comentarios', component: ComentariosComponent }, { path: 'personalizacion', component: PlantillasComponent } ] }, { path: 'MiSitioWeb', component: AppPrincipalComponent, children:[{ path:'', component: SitioWebComponent }] } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep># Repositorio-liebe-cms Repositorio liebe, proyecto final, clase de desarrollo web. <file_sep>var mongoose = require('mongoose'); // Declaración de las variables necesarias para hacer la conexión con la base de datos en Liebe. let bd='liebedb'; let port='27017'; let host = 'localhost'; let usuario = 'liebeAdmin'; let password = '<PASSWORD>'; class Database{ constructor(){ this.conectar(); }; conectar(){ mongoose.connect(`mongodb://${usuario}:${password}@${host}:${port}/${bd}`) .then(result=>console.log('Conexión realizada con la base de datos')) .catch(result=>console.log('La conexión a la base de datos no es posible')); }; } module.exports = new Database();<file_sep>// Importación de módulos. var express = require('express'); var app = express(); var cors = require('cors'); var database = require('./modules/database'); var usuariosRouter = require('./routes/usuarios-routes'); var bodyParser = require('body-parser'); //Asignación de todas las funcionalidades del módulo Express a la variable app. // Empleo de middlewares. app.use(cors()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:true})); app.use('/usuarios', usuariosRouter); // Prueba para saber si el servidor recibe correctamente las peticiones. app.get('/', function(req, res){ res.send('Petición recibida correctamente'); }) app.listen('8888', function(){ console.log('Servidor levantado correctamente'); });<file_sep>import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-acceso', templateUrl: './acceso.component.html', styleUrls: ['./acceso.component.css'] }) export class AccesoComponent implements OnInit { // Creando instancia del tipo FormGroup para el acceso de usuarios normales. acessoUsuarioNormal = new FormGroup({ nombreDeUsuario:new FormControl('', [Validators.required, Validators.maxLength(12)]), passwordDeUsuario:new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(10)]) }); usuariosNormalesIngresados: any = []; get nombreDeUsuario(){ return this.acessoUsuarioNormal.get('nombreDeUsuario'); }; get passwordDeUsuario(){ return this.acessoUsuarioNormal.get('passwordDeUsuario'); }; guardarAccesoUsuarioNormal(){ this.usuariosNormalesIngresados.push(this.acessoUsuarioNormal.value); console.log(this.usuariosNormalesIngresados); console.log('Fomulario válido:', this.acessoUsuarioNormal.valid ); this.acessoUsuarioNormal.reset(); }; constructor() { } ngOnInit(): void { } } <file_sep>import { Component, OnInit } from '@angular/core'; import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-pages', templateUrl: './pages.component.html', styleUrls: ['./pages.component.css'] }) export class PagesComponent implements OnInit { // Creación de instancia tipo FormGroup para la creación de nuevas páginas. pagina = new FormGroup({ nombre:new FormControl('', [Validators.required, Validators.maxLength(10)]), descripcion:new FormControl('', [Validators.required, Validators.maxLength(30)]), nombreMenu:new FormControl('', [Validators.required, Validators.maxLength(10)]), palabrasClaves:new FormControl('', [Validators.required, Validators.maxLength(30)]), paginaPadre:new FormControl('', [Validators.required]), estado:new FormControl('', [Validators.required]), incluirEncabezado:new FormControl('', [Validators.required]), incluirMenu:new FormControl('', [Validators.required]), incluirPie:new FormControl('', [Validators.required]), incluirB:new FormControl('', [Validators.required]), textCkeditor:new FormControl('¡Hello, Liebe!', [Validators.required]) }); paginas:any = [{ nombre:'Página principal', descripcion:'Página promocional', nombreMenu:'Landing page', palabrasClaves: 'promocion, funciones', paginaPadre:'Sí', estado:'Activa', incluirEncabezado:'Sí', incluirMenu: 'Sí', incluirPie:'No', incluirB:'No' }]; get nombre(){ return this.pagina.get('nombre'); }; get descripcion(){ return this.pagina.get('descripcion'); }; get nombreMenu(){ return this.pagina.get('nombreMenu'); }; get palabrasClaves(){ return this.pagina.get('palabrasClaves'); }; get paginaPadre(){ return this.pagina.get('paginaPadre'); }; get estado(){ return this.pagina.get('estado'); }; get incluirEncabezado(){ return this.pagina.get('incluirEncabezado'); }; get incluirMenu(){ return this.pagina.get('incluirMenu'); }; get incluirPie(){ return this.pagina.get('incluirPie'); }; get incluirB(){ return this.pagina.get('incluirB'); }; get textCkeditor(){ return this.pagina.get('textCkeditor'); }; constructor() { } ngOnInit(): void { } public Editor = ClassicEditor; guardarPagina(){ this.paginas.push(this.pagina.value); console.log(this.paginas); console.log('Fomulario válido:', this.pagina.valid ); this.pagina.reset(); }; } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-registro-administrador', templateUrl: './registro-administrador.component.html', styleUrls: ['./registro-administrador.component.css'] }) export class RegistroAdministradorComponent implements OnInit { // Creando instancia del tipo FormGroup registrosUsuarios = new FormGroup({ nombreProyecto:new FormControl('', [Validators.required, Validators.maxLength(15)]), descripcionProyecto:new FormControl('', [Validators.required, Validators.maxLength(50)]), correo:new FormControl('', [Validators.required, Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$")]), nombreUsuario:new FormControl('', [Validators.required, Validators.maxLength(8)]), password:new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(10)]) }); usuarios:any = []; constructor() { } ngOnInit(): void { } get nombreProyecto(){ return this.registrosUsuarios.get('nombreProyecto'); }; get descripcionProyecto(){ return this.registrosUsuarios.get('descripcionProyecto'); }; get correo(){ return this.registrosUsuarios.get('correo'); }; get nombreUsuario(){ return this.registrosUsuarios.get('nombreUsuario'); }; get password(){ return this.registrosUsuarios.get('password'); }; guardarRegistroUsuario(){ this.usuarios.push(this.registrosUsuarios.value); console.log(this.usuarios); console.log('Fomulario válido:', this.registrosUsuarios.valid ); this.registrosUsuarios.reset(); }; } <file_sep>import { Component, OnInit } from '@angular/core'; import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-plantillas', templateUrl: './plantillas.component.html', styleUrls: ['./plantillas.component.css'] }) export class PlantillasComponent implements OnInit { // Creación de instancia tipo FormGroup para la creación de nuevas páginas. plantilla = new FormGroup({ nombre:new FormControl('', [Validators.required, Validators.maxLength(20)]), descripcion:new FormControl('', [Validators.required, Validators.maxLength(40)]), imagen:new FormControl('../../../assets/img/salud-2.jpg', [Validators.required]), textCkeditorPlantilla:new FormControl('¡Hello, Liebe!', [Validators.required]), }); plantillas:any = []; get nombre(){ return this.plantilla.get('nombre'); }; get descripcion(){ return this.plantilla.get('descripcion'); }; get imagen(){ return this.plantilla.get('imagen'); }; get textCkeditorPlantilla(){ return this.plantilla.get('textCkeditorPlantilla'); }; constructor() { } ngOnInit(): void { } guardarPlantilla(){ this.plantillas.push(this.plantilla.value); console.log(this.plantillas); console.log('Fomulario válido:', this.plantilla.valid ); this.plantilla.reset(); }; public Editor = ClassicEditor; } <file_sep>var mongoose = require('mongoose'); var esquema = new mongoose.Schema({ fecha:String, nombre:String, apellido:String, correo:String, rol:String, password:String }); module.exports = mongoose.model('usuarios', esquema);<file_sep>import { Component, OnInit } from '@angular/core'; import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-entradas-post', templateUrl: './entradas-post.component.html', styleUrls: ['./entradas-post.component.css'] }) export class EntradasPostComponent implements OnInit { // Creación de instancia tipo FormGroup para la creación de nuevas entradas. post = new FormGroup({ nombre:new FormControl('', [Validators.required, Validators.maxLength(20)]), imagen:new FormControl('../../../assets/img/post.png', [Validators.required]), permiso:new FormControl('', [Validators.required]), textCkeditorPost:new FormControl('¡Hello, Liebe!', [Validators.required]) }); posts:any = []; get nombre(){ return this.post.get('nombre'); }; get imagen(){ return this.post.get('imagen'); }; get permiso(){ return this.post.get('permiso'); }; get textCkeditorPost(){ return this.post.get('textCkeditorPost'); }; constructor() { } ngOnInit(): void { } public Editor = ClassicEditor; guardarPost(){ this.posts.push(this.post.value); console.log(this.posts); console.log('Fomulario válido:', this.post.valid ); this.post.reset(); }; } <file_sep>var express = require('express'); var router = express.Router(); var usuario = require('../models/usuario'); // Creación de un nuevo usuario y envío a la base de datos router.post('/', function(req, res){ let u = new usuario( { fecha:req.body.fecha, nombre: req.body.nombre, apellido:req.body.apellido, correo:req.body.correo, rol: req.body.rol, password: <PASSWORD> } ); u.save().then(result=>{ res.send(result); res.end(); }).catch(error=>{ res.send(error); res.end(); }); }); // Obtener un usuario desde la base de datos. router.get('/:id', function(req, res){ usuario.find({_id:req.params.id}).then(result=>{ res.send(result[0]); res.end(); }).catch(error=>{ res.send(error); res.end(); }) }); // Obtener todos los usuarios desde la base de datos. router.get('/', function(req, res){ usuario.find().then(result=>{ res.send(result); res.end(); }).catch(error=>{ res.send(error); res.end(); }) }); // Actualizar un usuario. router.put('/:id', function(req, res){ usuario.update( { _id:req.params.id }, { nombre: req.body.nombre, apellido:req.body.apellido, correo:req.body.correo, rol: req.body.rol, password: <PASSWORD> } ).then(result=>{ res.send(result); res.end(); }).catch(error=>{ res.send(error); res.end(); }); }); // Eliminar usuario. router.delete('/:id', function(req, res){ usuario.remove( { _id: req.params.id } ).then(result=>{ res.send(result); res.end(); }).catch(error=>{ res.send(error); res.end(); }); }); // Exportación del objeto router. module.exports = router;<file_sep>function cambiarContenido(){ document.getElementById("modo-registro").innerHTML = "User mode" }<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { SitioWebComponent } from './sitio-web.component'; describe('SitioWebComponent', () => { let component: SitioWebComponent; let fixture: ComponentFixture<SitioWebComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ SitioWebComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SitioWebComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-usuarios', templateUrl: './usuarios.component.html', styleUrls: ['./usuarios.component.css'] }) export class UsuariosComponent implements OnInit { modal: NgbModalRef; cerrar(){ this.modal.close(); } // Creación de instancia tipo FormGroup para la creación de nuevas páginas. myDate = new Date(); // Instancia del objeto "myDate" para obtener la fecha actual de creación de cada usuario usuario = new FormGroup({ fecha: new FormControl(this.myDate), nombre:new FormControl('', [Validators.required, Validators.maxLength(20)]), apellido: new FormControl('', [Validators.required, Validators.maxLength(20)]), correo: new FormControl('', [Validators.required, Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$")]), rol:new FormControl('', [Validators.required]), password:new FormControl('', [Validators.required, Validators.maxLength(15), Validators.minLength(8)]), }); usuarios:any = [{ nombre:'<NAME>', rol:'Administrador' }]; get fecha(){ return this.usuario.get('fecha'); }; get nombre(){ return this.usuario.get('nombre'); }; get apellido(){ return this.usuario.get('apellido'); }; get correo(){ return this.usuario.get('correo'); }; get rol(){ return this.usuario.get('rol'); }; get password(){ return this.usuario.get('password'); }; //URL principal para consumir los web services del backend. backendHost:String='http://localhost:8888'; constructor(private httpClient:HttpClient) { } ngOnInit(): void { // Consumo del recurso GET para obtener todos los usuarios creados y almacenados en la base de datos. this.httpClient.get(`${this.backendHost}/usuarios`) .subscribe(res=>{ this.usuarios = res; console.log(this.usuarios); }); } // Consumo del recurso POST para la creación de usuarios. guardarUsuario(){ console.log('Formulario válido:', this.usuario.valid); this.httpClient.post(`${this.backendHost}/usuarios`, this.usuario.value) .subscribe((res:any)=>{ console.log(res); this.usuarios.push(res); }); this.cerrar(); } // Consumo del recurso DELETE para eliminar usuarios. eliminar(id){ console.log('Se eliminará el usuario con el id' + id); this.httpClient.delete(`${this.backendHost}/usuarios/${id}`) this.httpClient.delete(`${this.backendHost}/usuarios/${id}`) .subscribe((res:any)=>{ console.log(res); if(res.ok==1){ this.usuarios = this.usuarios.filter(item=>item._id!=id); } }); this.cerrar(); }; } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; import { ReactiveFormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms'; import { CKEditorModule } from '@ckeditor/ckeditor5-angular'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { NavbarComponent } from './navbar/navbar.component'; import { BodyLandingComponent } from './body-landing/body-landing.component'; import { PiePaginaComponent } from './pie-pagina/pie-pagina.component'; import { AccesoComponent } from './acceso/acceso.component'; import { AdminPrincipalComponent } from './Administracion/admin-principal/admin-principal.component'; import { PanelComponent } from './Administracion/panel/panel.component'; import { InicioComponent } from './Administracion/inicio/inicio.component'; import { UsuariosComponent } from './Administracion/usuarios/usuarios.component'; import { NuevoUsuarioComponent } from './nuevo-usuario/nuevo-usuario.component'; import { EdicionUsuariosComponent } from './Administracion/edicion-usuarios/edicion-usuarios.component'; import { PaginasComponent } from './Administracion/paginas/paginas.component'; import { NuevaPaginaComponent } from './Administracion/nueva-pagina/nueva-pagina.component'; import { HomePrincipalComponent } from './Home/home-principal/home-principal.component'; import { FooterAdminComponent } from './Administracion/footer-admin/footer-admin.component'; import { RecursosComponent } from './Administracion/recursos/recursos.component'; import { EntradasComponent } from './Administracion/entradas/entradas.component'; import { NuevaEntradaComponent } from './Administracion/nueva-entrada/nueva-entrada.component'; import { RegistroUsuarioComponent } from './registro-usuario/registro-usuario.component'; import { DashboardComponent } from './Administracion/dashboard/dashboard.component'; import { AccesoAdministradorComponent } from './Administracion/acceso-administrador/acceso-administrador.component'; import { RegistroAdministradorComponent } from './registro-administrador/registro-administrador.component'; import { PagesComponent } from './Administracion/pages/pages.component'; import { CuentaUsuarioComponent } from './Administracion/cuenta-usuario/cuenta-usuario.component'; import { EntradasPostComponent } from './Administracion/entradas-post/entradas-post.component'; import { ComentariosComponent } from './Administracion/comentarios/comentarios.component'; import { PlantillasComponent } from './Administracion/plantillas/plantillas.component'; import { AppPrincipalComponent } from './UsuarioRegistrado/app-principal/app-principal.component'; import { NavbarUsuarioResgistradoComponent } from './UsuarioRegistrado/navbar-usuario-resgistrado/navbar-usuario-resgistrado.component'; import { SitioWebComponent } from './UsuarioRegistrado/sitio-web/sitio-web.component'; import { FooterComponent } from './UsuarioRegistrado/footer/footer.component'; @NgModule({ declarations: [ AppComponent, NavbarComponent, BodyLandingComponent, PiePaginaComponent, AccesoComponent, AdminPrincipalComponent, PanelComponent, InicioComponent, UsuariosComponent, NuevoUsuarioComponent, EdicionUsuariosComponent, PaginasComponent, NuevaPaginaComponent, HomePrincipalComponent, FooterAdminComponent, RecursosComponent, EntradasComponent, NuevaEntradaComponent, RegistroUsuarioComponent, DashboardComponent, AccesoAdministradorComponent, RegistroAdministradorComponent, PagesComponent, CuentaUsuarioComponent, EntradasPostComponent, ComentariosComponent, PlantillasComponent, AppPrincipalComponent, NavbarUsuarioResgistradoComponent, SitioWebComponent, FooterComponent, ], imports: [ BrowserModule, AppRoutingModule, NgbModule, ReactiveFormsModule, FormsModule, CKEditorModule, HttpClientModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-acceso-administrador', templateUrl: './acceso-administrador.component.html', styleUrls: ['./acceso-administrador.component.css'] }) export class AccesoAdministradorComponent implements OnInit { // Creación de instancia tipo FormGroup para accesos usuarios administradores accesoUsuarioAdmin = new FormGroup({ nombreDeAdmin:new FormControl('', [Validators.required, Validators.maxLength(15)]), passwordDeAdmin:new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(10)]) }); usuariosAdminIngresados: any = []; get nombreDeAdmin(){ return this.accesoUsuarioAdmin.get('nombreDeAdmin'); }; get passwordDeAdmin(){ return this.accesoUsuarioAdmin.get('passwordDeAdmin'); }; guardarAccesoUsuarioAdmin(){ this.usuariosAdminIngresados.push(this.accesoUsuarioAdmin.value); console.log(this.usuariosAdminIngresados); console.log('Fomulario válido:', this.accesoUsuarioAdmin.valid ); this.accesoUsuarioAdmin.reset(); }; constructor() { } ngOnInit(): void { } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-comentarios', templateUrl: './comentarios.component.html', styleUrls: ['./comentarios.component.css'] }) export class ComentariosComponent implements OnInit { comentarios:any = [ { nombrePost:'Tu nota de salud', autor:'<NAME>', detalle:'La salud es más importante que cualquier otra cosa en la vida', }, { nombrePost:'Secretos de belleza naturales', autor:'<NAME>', detalle:'Lo natural no siempre es tan efectivo como parece', }, { nombrePost:'Veneno en la mente', autor:'<NAME>', detalle:'Nuestra mente en muchas ocasiones está más contaminada que cualquier otra cosa', }, { nombrePost:'Nuestra piel', autor:'<NAME>', detalle:'No sé qué hago aquí, Diana se está quedando sin ideas', }, { nombrePost:'La vida es bella', autor:'<NAME>', detalle:'Ojalá y se mueran todos', } ]; constructor() { } ngOnInit(): void { } }
5390862df81dd3fde3a9278f9e39a96686925a8d
[ "Markdown", "TypeScript", "JavaScript" ]
17
TypeScript
Diana-Sanchez/Repositorio-liebe-cms
e48b1548706b53fbf0c757d2c658817c18ca6f07
37faf532c7295475f8ede697bcfe39064a1ad2c0
refs/heads/master
<file_sep>/* * PaintTraverse.cpp * * Created on: Jan 4, 2018 * Author: nullifiedcat */ #include "hooks/hooks.hpp" #include "hook.hpp" #include "interfaces.hpp" #include "visual/draw.hpp" #include <vgui/ISurface.h> vgui::VPANEL panel_top = 0, panel_focus = 0; void hooks::PaintTraverse(vgui::IPanel *this_, vgui::VPANEL vguiPanel, bool forceRepaint, bool allowForce) { typedef void(*PaintTraverse_t)(vgui::IPanel *, vgui::VPANEL, bool, bool); if (!panel_top) { const char *name = I<vgui::IPanel>()->GetName(vguiPanel); if (strlen(name) > 4) { if (name[0] == 'M' && name[3] == 'S') { panel_top = vguiPanel; } } } if (!panel_focus) { const char *name = I<vgui::IPanel>()->GetName(vguiPanel); if (strlen(name) > 5) { if (name[0] == 'F' && name[5] == 'O') { panel_focus = vguiPanel; } } } hook::original<PaintTraverse_t>(this_, 42)(this_, vguiPanel, forceRepaint, allowForce); if (vguiPanel != panel_focus) return; I<vgui::IPanel>()->SetTopmostPopup(panel_focus, true); draw_api::draw_begin(); draw_api::draw_string(200, 200, "Welcome to catbase!", draw::fonts::tf2build_large, colors::pink); draw_api::draw_end(); } <file_sep>/* * sharedobjects.hpp * * Created on: Nov 19, 2017 * Author: nullifiedcat */ #pragma once #include <string> #include <vector> struct link_map; namespace so { bool object_full_path(std::string &name, std::string &out_full_path); class shared_object { public: typedef void *(*CreateInterface_t)(const char *, int *); public: shared_object(const std::string &name, bool is_interface_factory); protected: void load(); void text_section_info(); public: std::string name_; std::string path_; bool factory_{ false }; bool loaded_{ false }; CreateInterface_t create_interface_fn{ nullptr }; link_map *lmap{ nullptr }; uintptr_t text_begin_{ 0 }; uintptr_t text_end_{ 0 }; }; shared_object &steamclient(); shared_object &client(); shared_object &engine(); shared_object &vstdlib(); shared_object &tier0(); shared_object &inputsystem(); shared_object &materialsystem(); shared_object &vguimatsurface(); shared_object &vgui2(); shared_object &studiorender(); shared_object &libsdl(); } <file_sep>/* * vfunc.hpp * * Created on: Nov 19, 2017 * Author: nullifiedcat */ #pragma once #include <stdint.h> template <typename T> inline T vfunc(void *object, unsigned index) { uintptr_t *vtable = *(uintptr_t **) object; return T(vtable[index]); } <file_sep>/* * hooks.cpp * * Created on: Jan 4, 2018 * Author: nullifiedcat */ #include "hooks/hooks.hpp" #include "hook.hpp" #include "interfaces.hpp" namespace hooks { hook::vmt_hook ipanel{}; hook::vmt_hook clientmode{}; void init() { ipanel.init(I<vgui::IPanel>()); ipanel.hook(hook::method_t(PaintTraverse), 42); ipanel.apply(); clientmode.init(I<IClientMode>()); clientmode.hook(hook::method_t(CreateMove), 22); clientmode.apply(); } } <file_sep>/* * interfaces.cpp * * Created on: Jan 4, 2018 * Author: nullifiedcat */ #include "interfaces.hpp" #include "signature.hpp" #include "log.hpp" class IClientEntityList; class IVEngineClient013; class IBaseClientDLL; class IClientMode; namespace vgui { class IPanel; class ISurface; } void interfaces_init_all() { I<IClientEntityList>::init(so::client(), "VClientEntityList", 0); I<IVEngineClient013>::init(so::engine(), "VEngineClient", 13); I<IBaseClientDLL>::init(so::client(), "VClient", 0); I<IClientMode>() = **signature::signature("A3 ? ? ? ? E8 ? ? ? ? 8B 10 89 04 24 C7 44 24 04").scan<IClientMode **>(so::client(), 1); I<vgui::IPanel>::init(so::vgui2(), "VGUI_Panel", 0); I<vgui::ISurface>::init(so::vguimatsurface(), "VGUI_Surface", 0); } <file_sep>/* * netvar.cpp * * Created on: Dec 30, 2017 * Author: nullifiedcat */ #include "netvar.hpp" #include "interfaces.hpp" #include "log.hpp" #include <cdll_int.h> #include <client_class.h> #include <dt_recv.h> namespace netvar { namespace internal { temporary_netvar_tree::temporary_netvar_tree() { auto *current = I<IBaseClientDLL>()->GetAllClasses(); while (current != nullptr) { nodes_[std::string(current->m_pRecvTable->m_pNetTableName)] = table_to_map(current->m_pRecvTable); current = current->m_pNext; } } void temporary_netvar_tree::dump(std::ostream& stream) { for (const auto& i : nodes_) { stream << i.first << '\n'; dump_recursive(stream, 1, 0, i.second); stream << "\n\n"; } } static const char *sendproptypenames[] = { "Int", "Float", "Vector", "VectorXY", "String", "Array", "Table", nullptr }; void temporary_netvar_tree::dump_recursive(std::ostream& stream, int depth, int accumulated, const temporary_netvar_tree::map_t& map) { for (const auto& i : map) { const auto& node = i.second; if (isdigit(node->prop->GetName()[0])) continue; stream << std::string(depth, '\t') << node->prop->GetName() << " [" << sendproptypenames[node->prop->GetType()] << "]: " << std::hex << accumulated + node->prop->GetOffset() << '\n'; if (node->prop->m_RecvType == SendPropType::DPT_DataTable) { dump_recursive(stream, depth + 1, accumulated + node->prop->GetOffset(), node->nodes); } } } temporary_netvar_tree::map_t temporary_netvar_tree::table_to_map(RecvTable *table) { map_t result{}; for (auto i = 0; i < table->m_nProps; ++i) { auto& prop = table->m_pProps[i]; std::unique_ptr<temporary_netvar_tree::node> node = std::make_unique<temporary_netvar_tree::node>(); if (prop.m_RecvType == SendPropType::DPT_DataTable) { node->nodes = table_to_map(prop.GetDataTable()); } node->prop = &prop; result.insert(std::make_pair(std::string(prop.m_pVarName), std::move(node))); } return result; } void netvar_base::init_offset(temporary_netvar_tree& tree) { offset_ = 0; auto& datatable = tree.nodes_.at(location_.front()); location_.pop(); temporary_netvar_tree::map_t *current = &datatable; while (!location_.empty()) { auto next = location_.front(); // Will throw an exception if tree does not contain the netvar temporary_netvar_tree::node& node = *current->at(next); offset_ += node.prop->GetOffset(); current = &node.nodes; location_.pop(); } } temporary_netvar_tree storage::init() { LOG_DEBUG("Initializing netvar tree"); temporary_netvar_tree tree{}; while (!init_list().empty()) { auto netvar = init_list().front(); try { netvar->init_offset(tree); } catch (std::exception& ex) { LOG_ERROR("Error while initializing NetVar: %s", ex.what()); } init_list().pop(); } return tree; } } } netvar::internal::storage netvars{}; <file_sep>/* * hook.cpp * * Created on: Nov 19, 2017 * Author: nullifiedcat */ #include "hook.hpp" #include "log.hpp" #include <string.h> #include <stdlib.h> namespace hook { unsigned count_methods(method_table_t table) { unsigned int i = -1; do ++i; while (table[i]); return i; } table_ref_t get_vmt(ptr_t inst, uintptr_t offset = 0) { return *reinterpret_cast<table_ptr_t>((uintptr_t) inst + offset); } inline bool is_hooked(ptr_t inst, uintptr_t offset = 0) { return get_vmt(inst, offset)[-1] == (method_t) GUARD; } vmt_hook::~vmt_hook() { release(); } void vmt_hook::init(ptr_t inst, uintptr_t offset) { vtable_ptr = &get_vmt(inst, offset); vtable_original = *vtable_ptr; int mc = count_methods(vtable_original); LOG_DEBUG("Hooking %08x with %d methods, vtable at %08x %08x", inst, mc, vtable_original, vtable_ptr); vtable_hooked = static_cast<method_table_t>(calloc(mc + 4, sizeof(ptr_t))); memcpy(&vtable_hooked[3], vtable_original, sizeof(ptr_t) * mc); vtable_hooked[0] = this; vtable_hooked[1] = vtable_original; vtable_hooked[2] = (method_t) GUARD; } void vmt_hook::hook(method_t func, uintptr_t idx) { LOG_DEBUG("Replacing method %u (%08x) with %08x", idx, vtable_original[idx], func); vtable_hooked[3 + idx] = func; } void vmt_hook::apply() { LOG_DEBUG("Applied hook"); *vtable_ptr = &vtable_hooked[3]; } void vmt_hook::release() { if (vtable_ptr && *vtable_ptr == &vtable_hooked[3]) { if ((*vtable_ptr)[-1] == (method_t) GUARD) { *vtable_ptr = vtable_original; } free(vtable_hooked); vtable_ptr = nullptr; vtable_hooked = nullptr; vtable_original = nullptr; } } method_t vmt_hook::get(uintptr_t idx) const { return vtable_original[idx]; } } <file_sep>/* * tools.cpp * * Created on: Nov 18, 2017 * Author: nullifiedcat */ #include "tools.hpp" #include <unistd.h> #include <pwd.h> namespace tools { void string_replace(std::string &string, const std::string &what, const std::string &with_what) { size_t index = string.find(what); while (index != std::string::npos) { string.replace(index, what.size(), with_what); index = string.find(what, index + with_what.size()); } } const std::string &get_user_name() { static std::string username = []() { passwd *pwd = getpwuid(getuid()); return (pwd && pwd->pw_name) ? std::string(pwd->pw_name) : "null"; }(); return username; } } <file_sep>#!/usr/bin/env bash echo Formatting sources... This may take a while. ./clang-format-all src ./clang-format-all include<file_sep>/* * draw.cpp * * Created on: Jan 4, 2018 * Author: nullifiedcat */ #include "visual/draw.hpp" #include "interfaces.hpp" #include <cdll_int.h> namespace draw { namespace fonts { draw_api::font_handle_t tf2build_large{}; draw_api::font_handle_t tf2build{}; } int width{ 0 }; int height{ 0 }; void init() { // TODO change it to font path fonts::tf2build = draw_api::create_font("TF2BUILD", 18); fonts::tf2build_large = draw_api::create_font("TF2BUILD", 30); I<IVEngineClient013>()->GetScreenSize(width, height); } } <file_sep>cmake_minimum_required(VERSION 3.3) project(catbase CXX) if (NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release) endif() set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -Wall -fPIC -std=gnu++1z") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g3 -ggdb") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -O3") file(GLOB_RECURSE SOURCES "src/*.cpp") add_definitions( -D_GLIBCXX_USE_CXX11_ABI=0 -D_LINUX=1 -DLINUX=1 -D_POSIX=1 -DPOSIX=1 -DRAD_TELEMETRY_DISABLED=1 -DUSE_SDL=1 -DGNUC=1 -DNO_MALLOC_OVERRIDE=1) add_library(catbase SHARED ${SOURCES}) set(SOURCE_SDK_HEADERS source-sdk-2013-headers/mp/src) include_directories(include) include_directories(SYSTEM ${SOURCE_SDK_HEADERS}/public ${SOURCE_SDK_HEADERS}/mathlib ${SOURCE_SDK_HEADERS}/common ${SOURCE_SDK_HEADERS}/public/tier0 ${SOURCE_SDK_HEADERS}/public/tier1 ${SOURCE_SDK_HEADERS}) set_target_properties(catbase PROPERTIES LIBRARY_OUTPUT_DIRECTORY "bin" OUTPUT_NAME "catbase" COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")<file_sep>/* * in_buttons.h * * Created on: Jan 4, 2018 * Author: nullifiedcat */ #pragma once #define IN_ATTACK (1 << 0) #define IN_JUMP (1 << 1) #define IN_DUCK (1 << 2) #define IN_FORWARD (1 << 3) #define IN_BACK (1 << 4) #define IN_USE (1 << 5) #define IN_CANCEL (1 << 6) #define IN_LEFT (1 << 7) #define IN_RIGHT (1 << 8) #define IN_MOVELEFT (1 << 9) #define IN_MOVERIGHT (1 << 10) #define IN_ATTACK2 (1 << 11) #define IN_RUN (1 << 12) #define IN_RELOAD (1 << 13) #define IN_ALT1 (1 << 14) #define IN_ALT2 (1 << 15) #define IN_SCORE (1 << 16) // Used by client.dll for when scoreboard is held down #define IN_SPEED (1 << 17) // Player is holding the speed key #define IN_WALK (1 << 18) // Player holding walk key #define IN_ZOOM (1 << 19) // Zoom key for HUD zoom #define IN_WEAPON1 (1 << 20) // weapon defines these bits #define IN_WEAPON2 (1 << 21) // weapon defines these bits #define IN_BULLRUSH (1 << 22) #define IN_GRENADE1 (1 << 23) // grenade 1 #define IN_GRENADE2 (1 << 24) // grenade 2 #define IN_ATTACK3 (1 << 25) <file_sep>/* * surface.cpp * * Created on: Jan 4, 2018 * Author: nullifiedcat */ #include "interfaces.hpp" #include <vgui/ISurface.h> #include <visual/surface.hpp> namespace draw_api_surface { font_handle_t create_font(const char *path, float size) { font_handle_t result{}; result.font = I<vgui::ISurface>()->CreateFont(); I<vgui::ISurface>()->SetFontGlyphSet(result.font, "TF2_BUILD", size, 200, 0, 0, vgui::ISurface::FONTFLAG_OUTLINE, 0, 0); return result; } void destroy_font(font_handle_t font) { return; } bool ready() { return true; } void initialize() { } void draw_rect(float x, float y, float w, float h, const colors::rgba_t &rgba) { I<vgui::ISurface>()->DrawSetColor(rgba); I<vgui::ISurface>()->DrawFilledRect(x, y, x + w, y + h); } void draw_rect_outlined(float x, float y, float w, float h, const colors::rgba_t &rgba, float thickness) { I<vgui::ISurface>()->DrawSetColor(rgba); I<vgui::ISurface>()->DrawOutlinedRect(x, y, x + w, y + h); } void draw_line(float x, float y, float dx, float dy, const colors::rgba_t &rgba, float thickness) { I<vgui::ISurface>()->DrawSetColor(rgba); I<vgui::ISurface>()->DrawLine(x, y, x + dx, y + dy); } void draw_circle(float x, float y, float radius, const colors::rgba_t &rgba, float thickness, int steps) { I<vgui::ISurface>()->DrawSetColor(rgba); I<vgui::ISurface>()->DrawOutlinedCircle(x, y, radius, steps); } void draw_string(float x, float y, const char *string, font_handle_t &font, const colors::rgba_t &rgba) { if (!string) return; wchar_t wstring[1024] = { 0 }; swprintf(wstring, 1024, L"%s", string); I<vgui::ISurface>()->DrawSetTextPos(x, y); I<vgui::ISurface>()->DrawSetTextFont(font.font); I<vgui::ISurface>()->DrawSetTextColor(rgba); I<vgui::ISurface>()->DrawPrintText(wstring, wcslen(wstring)); } void draw_string_with_outline(float x, float y, const char *string, font_handle_t &font, const colors::rgba_t &rgba, const colors::rgba_t &rgba_outline, float thickness) { if (!string) return; wchar_t wstring[1024] = { 0 }; swprintf(wstring, 1024, L"%s", string); I<vgui::ISurface>()->DrawSetTextPos(x, y); I<vgui::ISurface>()->DrawSetTextFont(font.font); I<vgui::ISurface>()->DrawSetTextColor(rgba); I<vgui::ISurface>()->DrawPrintText(wstring, wcslen(wstring)); } void get_string_size(const char *string, font_handle_t &font, float *x, float *y) { return; } void draw_begin() { return; } void draw_end() { return; } } <file_sep>/* * log.cpp * * Created on: Nov 18, 2017 * Author: nullifiedcat */ /* * This file is a monstrous mix of C and C++ */ #include "log.hpp" #include "tools.hpp" #include <time.h> #include <stdarg.h> #include <fstream> namespace catbase_logging { std::ofstream file; void setup(std::string filename) { tools::string_replace(filename, "%USER%", tools::get_user_name()); file = std::ofstream(filename, std::ios::out); } static const char *level_names[] = { "NONE", "ERROR", "WARNING", "INFO", "DEBUG", "SILLY" }; void log_internal(int lvl, const char *format, ...) { char buffer[1024]; struct tm *time_info = nullptr; time_t current_time; char time_string[10]; time(&current_time); time_info = localtime(&current_time); strftime(time_string, sizeof(time_string), "%H:%M:%S", time_info); int written = sprintf(buffer, "[%-7s] [%s] ", level_names[static_cast<int>(lvl)], time_string); va_list list; va_start(list, format); vsnprintf(buffer + 21, 1002, format, list); va_end(list); fprintf(stdout, "%s\n", buffer); fflush(stdout); if (file.good()) { // Write and flush file << buffer << std::endl; } } } <file_sep>/* * usercmd.h * * Created on: Jan 4, 2018 * Author: nullifiedcat */ #pragma once class CUserCmd { public: virtual ~CUserCmd() {}; int command_number; int tick_count; Vector viewangles; float forwardmove; float sidemove; float upmove; int buttons; uint8_t impulse; int weaponselect; int weaponsubtype; int random_seed; short mousedx; short mousedy; bool hasbeenpredicted; }; <file_sep>#!/usr/bin/env bash library=libcatbase.so line=$(pidof hl2_linux) arr=($line) inst=$1 if [ $# == 0 ]; then inst=0 fi if [ ${#arr[@]} == 0 ]; then echo TF2 isn\'t running! exit fi if [ $inst -gt ${#arr[@]} ] || [ $inst == ${#arr[@]} ]; then echo wrong index! exit fi echo Running instances: "${arr[@]}" echo Detaching from "${arr[$1]}" if grep -q "$(realpath bin/$library)" /proc/"${arr[$1]}"/maps; then gdb -n -q -batch \ -ex "attach ${arr[$1]}" \ -ex "set \$dlopen = (void*(*)(char*, int)) dlopen" \ -ex "set \$dlclose = (int(*)(void*)) dlclose" \ -ex "set \$library = \$dlopen(\"$(realpath bin/$library)\", 6)" \ -ex "print \$library" \ -ex "sharedlibrary ." \ -ex "call \$dlclose(\$library)" \ -ex "call \$dlclose(\$library)" \ -ex "continue" \ -ex "backtrace" echo "Detached" else echo "not found!" fi <file_sep>/* * cheat.hpp * * Created on: Nov 19, 2017 * Author: nullifiedcat */ #pragma once namespace cheat { void init(); void shutdown(); } <file_sep>/* * somain.cpp * * Created on: Nov 18, 2017 * Author: nullifiedcat */ #include <thread> #include <atomic> #include "cheat.hpp" #include <stdio.h> std::thread main_thread; void cheat_main_thread() { cheat::init(); } void __attribute__((constructor)) attach() { main_thread = std::thread{ cheat_main_thread }; } void __attribute__((destructor)) detach() { cheat::shutdown(); } <file_sep>/* * sharedobjects.cpp * * Created on: Nov 19, 2017 * Author: nullifiedcat */ #include "sharedobjects.hpp" #include "tools.hpp" #include "log.hpp" #include "defer.hpp" #include <fstream> #include <thread> #include <unistd.h> #include <dlfcn.h> #include <string.h> #include <link.h> #include <sys/stat.h> #include <stdlib.h> #include <elf.h> #include <sys/mman.h> #include <fcntl.h> namespace so { bool object_full_path(std::string &name, std::string &out_full_path) { std::ifstream maps(tools::makestring("/proc/", getpid(), "/maps"), std::ios::in); if (maps.bad()) { return false; } for (std::string line; getline(maps, line);) { size_t s_path = line.find_first_of('/'); size_t s_name = line.find_last_of('/'); if (s_name == std::string::npos || s_path == std::string::npos) { continue; } if (0 == name.compare(0, std::string::npos, line, s_name + 1, name.length())) { out_full_path = line.substr(s_path); if (out_full_path.back() == '\n') { out_full_path.pop_back(); } return true; } } return false; } shared_object::shared_object(const std::string &name, bool is_interface_factory) : name_(name), factory_(is_interface_factory) { load(); } void shared_object::load() { while (!object_full_path(name_, path_)) { std::this_thread::sleep_for(std::chrono::seconds(1)); } lmap = (link_map *) dlopen(path_.c_str(), RTLD_NOLOAD); while (lmap == nullptr) { std::this_thread::sleep_for(std::chrono::seconds(1)); char *error = dlerror(); if (error) { LOG_ERROR("dlerror: %s", error); } lmap = (link_map *) dlopen(path_.c_str(), RTLD_NOLOAD); } text_section_info(); LOG_DEBUG("Shared object %s loaded at 0x%08x, .text[%08x - %08x]", name_.c_str(), lmap->l_addr, text_begin_, text_end_); if (factory_) { create_interface_fn = reinterpret_cast<CreateInterface_t>(dlsym(lmap, "CreateInterface")); if (create_interface_fn == nullptr) { LOG_ERROR("Failed to create interface factory for %s", name_.c_str()); } } } void shared_object::text_section_info() { int fd = open(path_.c_str(), O_RDONLY); size_t size = lseek(fd, 0, SEEK_END); uintptr_t begin = uintptr_t(mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0)); defer(munmap((void *) begin, size); close(fd);) Elf32_Ehdr *ehdr = (Elf32_Ehdr *) begin; Elf32_Shdr *shdr = (Elf32_Shdr *) (begin + ehdr->e_shoff); int shnum = ehdr->e_shnum; Elf32_Shdr *shstr = &shdr[ehdr->e_shstrndx]; if (shstr == nullptr) { LOG_ERROR("ELF string table is NULL for %s", path_.c_str()); return; } if (shstr->sh_type != SHT_STRTAB) { LOG_ERROR("Invalid string table for %s", path_.c_str()); return; } char *strtab = (char *) (begin + shstr->sh_offset); int strtabnum = shstr->sh_size; for (int i = 0; i < ehdr->e_shnum; i++) { Elf32_Shdr *hdr = &shdr[i]; if (hdr && hdr->sh_name < strtabnum) { if (strcmp(strtab + hdr->sh_name, ".text") == 0) { text_begin_ = lmap->l_addr + hdr->sh_addr; text_end_ = text_begin_ + hdr->sh_size; return; } } } } shared_object &steamclient() { static shared_object object("steamclient.so", true); return object; } shared_object &client() { static shared_object object("client.so", true); return object; } shared_object &engine() { static shared_object object("engine.so", true); return object; } shared_object &vstdlib() { static shared_object object("libvstdlib.so", true); return object; } shared_object &tier0() { static shared_object object("libtier0.so", false); return object; } shared_object &inputsystem() { static shared_object object("inputsystem.so", true); return object; } shared_object &materialsystem() { static shared_object object("materialsystem.so", true); return object; } shared_object &vguimatsurface() { static shared_object object("vguimatsurface.so", true); return object; } shared_object &vgui2() { static shared_object object("vgui2.so", true); return object; } shared_object &studiorender() { static shared_object object("studiorender.so", true); return object; } shared_object &libsdl() { static shared_object object("libSDL2-2.0.so.0", false); return object; } } <file_sep>/* * cheat.cpp * * Created on: Nov 19, 2017 * Author: nullifiedcat */ #include "cheat.hpp" #include "log.hpp" #include "sharedobjects.hpp" #include "interfaces.hpp" #include "signature.hpp" #include "netvar.hpp" #include "hooks/hooks.hpp" #include "visual/draw.hpp" #include <fstream> #include <unistd.h> #include <cdll_int.h> #include <icliententitylist.h> namespace cheat { void init() { CATBASE_LOG_SETUP("/tmp/catbase-%USER%.log"); LOG_DEBUG("Initializing interfaces"); interfaces_init_all(); { auto tree = netvars.init(); std::ofstream dump("/tmp/catbase-netvar-dump.log"); if (dump) tree.dump(dump); } LOG_DEBUG("Initializing hooks"); hooks::init(); LOG_DEBUG("Initializing drawing"); draw::init(); LOG_DEBUG("Init done"); pause(); } void shutdown() { LOG_WARNING("Shutting down now"); } } <file_sep># catbase-2017 # NULLIFIEDCAT NEVER COMPLETED IT Simple TF2 base for Linux. Includes: * Logging * Hooks * NetVars * Basic ESP <file_sep>/* * colors.hpp * * Created on: Jan 4, 2018 * Author: nullifiedcat */ #pragma once #include <cstdint> #include <Color.h> namespace colors { struct rgba_t { union { struct { float r, g, b, a; }; float rgba[4]; }; constexpr rgba_t() : r(0.0f), g(0.0f), b(0.0f), a(0.0f){}; constexpr rgba_t(float _r, float _g, float _b, float _a = 1.0f) : r(_r), g(_g), b(_b), a(_a){}; constexpr operator bool() const { return r || g || b || a; } constexpr operator int() const = delete; operator float *() { return rgba; } constexpr operator const float *() const { return rgba; } constexpr rgba_t operator*(float value) const { return rgba_t(r * value, g * value, b * value, a * value); } constexpr operator unsigned() const { return unsigned( uint8_t(r * 255) << 24 | uint8_t(g * 255) << 16 | uint8_t(b * 255) << 8 | uint8_t(a * 255) ); } operator Color() const { return Color(r * 255, g * 255, b * 255, a * 255); } }; constexpr rgba_t rgba8(float r, float g, float b, float a) { return rgba_t{ r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f }; } constexpr rgba_t transparent(const rgba_t &in, float multiplier = 0.5f) { return rgba_t{ in.r, in.g, in.b, in.a * multiplier }; } constexpr rgba_t white{ 1, 1, 1, 1 }; constexpr rgba_t black{ 0, 0, 0, 1 }; constexpr rgba_t pink = rgba8(255, 105, 180, 255); constexpr rgba_t empty = rgba8(0, 0, 0, 0); constexpr rgba_t hsl(float h, float s, float v) { if (s <= 0.0) { // < is bogus, just shuts up warnings return rgba_t{ v, v, v, 1.0f }; } float hh = h; if (hh >= 360.0) hh = 0.0; hh /= 60.0; long i = long(hh); float ff = hh - i; float p = v * (1.0 - s); float q = v * (1.0 - (s * ff)); float t = v * (1.0 - (s * (1.0 - ff))); switch (i) { case 0: return rgba_t{ v, t, p, 1.0f }; case 1: return rgba_t{ q, v, p, 1.0f }; case 2: return rgba_t{ p, v, t, 1.0f }; case 3: return rgba_t{ p, q, v, 1.0f }; break; case 4: return rgba_t{ t, p, v, 1.0f }; case 5: default: return rgba_t{ v, p, q, 1.0f }; } } constexpr rgba_t health(int hp, int max) { float hf = float(hp) / float(max); if (hf > 1) { return colors::rgba8(64, 128, 255, 255); } return rgba_t{ (hf <= 0.5f ? 1.0f : 1.0f - 2.0f * (hf - 0.5f)), (hf <= 0.5f ? (2.0f * hf) : 1.0f), 0.0f, 1.0f }; } } <file_sep>/* * interfaces.hpp * * Created on: Dec 2, 2017 * Author: nullifiedcat */ #pragma once #include "sharedobjects.hpp" #include "log.hpp" void interfaces_init_all(); template <typename T> class I { public: inline static void init(const so::shared_object &object, const std::string &name, int version) { if (interface_pointer_) return; char ifname[name.length() + 4]; for (int i = version; i < 100; i++) { snprintf(ifname, sizeof(ifname), "%s%03d", name.c_str(), i); interface_pointer_ = reinterpret_cast<T *>( object.create_interface_fn(ifname, nullptr)); if (interface_pointer_ != nullptr) return; } LOG_ERROR("Failed to create interface '%s'", name.c_str()); } inline operator T *() const { return interface_pointer_; } inline T *operator()() const { return interface_pointer_; } inline T *operator->() const { return interface_pointer_; } inline void operator=(T *pointer) { interface_pointer_ = pointer; } public: static T *interface_pointer_; }; template <typename T> T *I<T>::interface_pointer_; <file_sep>/* * CreateMove.cpp * * Created on: Jan 4, 2018 * Author: nullifiedcat */ #include "hooks/hooks.hpp" #include "hook.hpp" #include "interfaces.hpp" #include <cdll_int.h> #include "sdk/in_buttons.h" bool hooks::CreateMove(IClientMode *this_, float flInputSampleTime, CUserCmd *cmd) { typedef bool(*CreateMove_t)(IClientMode *, float, CUserCmd *); if (cmd) { cmd->forwardmove = -cmd->forwardmove; cmd->sidemove = -cmd->sidemove; } return hook::original<CreateMove_t>(this_, 22)(this_, flInputSampleTime, cmd); } <file_sep>/* * surface.hpp * * Created on: Jan 4, 2018 * Author: nullifiedcat */ #pragma once #include "colors.hpp" namespace draw_api_surface { typedef unsigned long font_t; typedef unsigned long texture_t; typedef unsigned long color_t; struct font_handle_t { unsigned long font; }; font_handle_t create_font(const char *path, float size); void destroy_font(font_handle_t font); bool ready(); void initialize(); void draw_rect(float x, float y, float w, float h, const colors::rgba_t &rgba); void draw_rect_outlined(float x, float y, float w, float h, const colors::rgba_t &rgba, float thickness); void draw_line(float x, float y, float dx, float dy, const colors::rgba_t &rgba, float thickness); void draw_circle(float x, float y, float radius, const colors::rgba_t &rgba, float thickness, int steps); // Both of these functions draw string with outline. void draw_string(float x, float y, const char *string, font_handle_t &font, const colors::rgba_t &rgba); void draw_string_with_outline(float x, float y, const char *string, font_handle_t &font, const colors::rgba_t &rgba, const colors::rgba_t &rgba_outline, float thickness); // Not implemented void get_string_size(const char *string, font_handle_t &font, float *x, float *y); void draw_begin(); void draw_end(); } <file_sep>/* * log.hpp * * Created on: Nov 18, 2017 * Author: nullifiedcat */ #pragma once #include <string> /* * The reason I use macros instead of functions is because with macros, compiler won't embed unneeded strings in the binary, that is important for debug logging. * You wouldn't want plaintext description of what your functions do in the resulting library, it would make it really easy to reverse. * You should change the LOG_LEVEL if you want. * * And #defines don't like ::'s inside - so a global enum is used instead of an enum class. */ #define CBLL_NONE 0 #define CBLL_ERROR 1 #define CBLL_WARNING 2 #define CBLL_INFO 3 #define CBLL_DEBUG 4 #define CBLL_SILLY 5 namespace catbase_logging { void setup(std::string filename); void log_internal(int lvl, const char *format, ...); } #ifndef CATBASE_LOG_LEVEL #if DEBUG_BUILD # define CATBASE_LOG_LEVEL CBLL_DEBUG #else # define CATBASE_LOG_LEVEL CBLL_NONE #endif #endif #if CATBASE_LOG_LEVEL == CBLL_NONE # define CATBASE_LOG_SETUP(filename) #else # define CATBASE_LOG_SETUP(filename) catbase_logging::setup(filename) #endif #if CATBASE_LOG_LEVEL >= CBLL_SILLY # define LOG_SILLY(...) catbase_logging::log_internal(CBLL_SILLY, __VA_ARGS__) #else # define LOG_SILLY(...) #endif #if CATBASE_LOG_LEVEL >= CBLL_DEBUG # define LOG_DEBUG(...) catbase_logging::log_internal(CBLL_DEBUG, __VA_ARGS__) #else # define LOG_DEBUG(...) #endif #if CATBASE_LOG_LEVEL >= CBLL_INFO # define LOG_INFO(...) catbase_logging::log_internal(CBLL_INFO, __VA_ARGS__) #else # define LOG_INFO(...) #endif #if CATBASE_LOG_LEVEL >= CBLL_WARNING # define LOG_WARNING(...) catbase_logging::log_internal(CBLL_WARNING, __VA_ARGS__) #else # define LOG_WARNING(...) #endif #if CATBASE_LOG_LEVEL >= CBLL_ERROR # define LOG_ERROR(...) catbase_logging::log_internal(CBLL_ERROR, __VA_ARGS__) #else # define LOG_ERROR(...) #endif <file_sep>/* * signature.cpp * * Created on: May 27, 2017 * Author: nullifiedcat */ #include "signature.hpp" #include "log.hpp" #include <sys/uio.h> #include <vector> #include <memory> #include <stdio.h> #include <string.h> namespace signature { signature::signature(const std::string &ida) { for (size_t i = 0; i < ida.length(); i++) { char ch = ida.at(i); if (ch == '?') { if (i < ida.length() - 1) { if (ida.at(i + 1) == '?') ++i; } data_.push_back(0); mask_.push_back(false); ++i; continue; } if (ch == ' ') continue; if (i < ida.length() - 1) { char lower = ida.at(i + 1); char byte = (chtohex(ch) << 4) | chtohex(lower); data_.push_back(byte); mask_.push_back(true); ++i; continue; } } } signature::signature(const uint8_t *bytes, const char *mask) { for (size_t i = 0; i < strlen(mask); i++) { if (mask_[i] != '?') { data_.push_back(bytes[i]); mask_.push_back(true); } else { data_.push_back(0); mask_.push_back(false); } } } uintptr_t signature::scan(uintptr_t start, uintptr_t end) { LOG_DEBUG("scanning from %p to %p for %u bytes", start, end, data_.size()); size_t found = 0; for (; start < end; start++) { if (mask_.at(found)) { if (*(uint8_t *) start == data_.at(found)) ++found; else found = 0; } else { ++found; } if (found == data_.size()) { return start - found + 1; } } return 0; } } <file_sep>/* * draw.hpp * * Created on: Jan 4, 2018 * Author: nullifiedcat */ #pragma once #include "visual/surface.hpp" #define draw_api draw_api_surface namespace draw { namespace fonts { extern draw_api::font_handle_t tf2build_large; extern draw_api::font_handle_t tf2build; } extern int width; extern int height; void init(); } <file_sep>/* * hooks.hpp * * Created on: Nov 19, 2017 * Author: nullifiedcat */ #pragma once #include <vgui/IPanel.h> #include <cdll_int.h> #include "sdk/usercmd.h" class IClientMode; namespace hooks { void PaintTraverse(vgui::IPanel *this_, vgui::VPANEL vguiPanel, bool forceRepain, bool allowForce); bool CreateMove(IClientMode *this_, float flInputSampleTime, CUserCmd *cmd); void init(); } <file_sep>/* * defer.hh by F1ssi0N * * source: https://github.com/josh33901/blue/blob/master/blue/defer.hh */ #pragma once // helper class / macro for creating scope exit actions template <class Lambda> class AtScopeExit { Lambda &m_lambda; public: AtScopeExit(Lambda &action) : m_lambda(action) { } ~AtScopeExit() { m_lambda(); } }; #define Defer_INTERNAL2(lname, aname, ...) \ auto lname = [&]() { __VA_ARGS__; }; \ AtScopeExit<decltype(lname)> aname(lname); #define Defer_TOKENPASTE(x, y) Defer_##x##y #define Defer_INTERNAL1(ctr, ...) \ Defer_INTERNAL2(Defer_TOKENPASTE(func_, ctr), \ Defer_TOKENPASTE(instance_, ctr), __VA_ARGS__) #define defer(...) Defer_INTERNAL1(__COUNTER__, __VA_ARGS__) <file_sep>/* * signature.hpp * * Created on: May 27, 2017 * Author: nullifiedcat */ #pragma once #include "sharedobjects.hpp" #include <stdint.h> #include <string> #include <vector> namespace signature { constexpr char __attribute__((pure)) chtohex(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); return 0; } class signature { public: signature() = delete; /* * Convert from IDA style signature ("00 01 02 ?? AB") * to a signature_t */ signature(const std::string &ida); /* * Create signature from raw bytes ("\x00\x01\x02\x00\xAB", "xxx?x") */ signature(const uint8_t *bytes, const char *mask); public: uintptr_t scan(uintptr_t start, uintptr_t length); template <typename T> T *scan(const so::shared_object &object, uintptr_t offset) { uintptr_t found = scan(object.text_begin_, object.text_end_); if (found) return reinterpret_cast<T *>(found + offset); return 0; } protected: std::vector<uint8_t> data_{}; std::vector<bool> mask_{}; }; } <file_sep>/* * netvar.hpp * * Created on: Dec 30, 2017 * Author: nullifiedcat */ #pragma once #include <queue> #include <string> #include <cstdint> #include <unordered_map> #include <memory> #include <iostream> #include <dt_recv.h> class RecvTable; class RecvProp; namespace netvar { namespace internal { class netvar_base; inline std::queue<netvar_base *>& init_list() { static std::queue<netvar_base *> object{}; return object; } class temporary_netvar_tree { public: class node; typedef std::unordered_map<std::string, std::unique_ptr<node>> map_t; class node { public: map_t nodes{}; RecvProp *prop{ nullptr }; }; public: temporary_netvar_tree(); public: map_t table_to_map(RecvTable *table); void dump(std::ostream& stream); void dump_recursive(std::ostream& stream, int depth, int accumulated, const map_t& map); public: std::unordered_map<std::string, map_t> nodes_{}; }; class netvar_base { public: inline netvar_base(std::initializer_list<std::string> location) : location_{ location } { init_list().push(this); } public: public: inline uintptr_t offset() const { return offset_; } void init_offset(temporary_netvar_tree& tree); protected: uintptr_t offset_{ 0 }; std::queue<std::string> location_{}; }; template<typename T> class netvar: public netvar_base { public: template<typename X> inline T& operator()(X* instance) const { return *reinterpret_cast<T*>(uintptr_t(instance) + offset()); } protected: }; class storage { public: storage() = default; public: temporary_netvar_tree init(); public: struct { netvar<int> team{ {"DT_BaseEntity", "m_iTeamNum"} }; } entity; struct { netvar<int> health{ {"DT_BasePlayer", "m_iHealth"} }; netvar<uint32_t> flags{ {"DT_BasePlayer", "m_iHealth"} }; netvar<uint8_t> life_state{ {"DT_BasePlayer", "m_lifeState"} }; } player; }; } } extern netvar::internal::storage netvars; <file_sep>/* * tools.hpp * * Created on: Nov 18, 2017 * Author: nullifiedcat */ #pragma once #include <string> #include <sstream> namespace tools { void string_replace(std::string &string, const std::string &what, const std::string &with_what); const std::string &get_user_name(); /* Internal functions */ inline void makestring_internal(std::stringstream &stream) { } template <typename T, typename... Targs> void makestring_internal(std::stringstream &stream, T value, Targs... args) { stream << value; makestring_internal(stream, args...); } /* This is the one you want */ template <typename... Args> std::string makestring(const Args &... args) { std::stringstream stream; makestring_internal(stream, args...); return stream.str(); } } <file_sep>/* * hook.hpp * * Created on: Nov 19, 2017 * Author: nullifiedcat */ #pragma once #include <stdint.h> #include "log.hpp" namespace hook { typedef void *ptr_t; typedef void *method_t; typedef method_t *method_table_t; typedef method_table_t *table_ptr_t; typedef method_table_t &table_ref_t; constexpr uintptr_t GUARD = 0xD34DC477; template<typename T, typename X> inline T original(X *instance, unsigned index) { const method_table_t active = *reinterpret_cast<table_ptr_t>(uintptr_t(instance)); if (active[-1] != method_t(GUARD)) { LOG_ERROR("Tried to call original function on non-hooked instance. Fatal."); // C++ does not allow me to reinterpret_cast a nullptr into function pointer union { T fn; nullptr_t nfn; } u; u.nfn = nullptr; // Make the game crash return u.fn; } return reinterpret_cast<T>(reinterpret_cast<method_table_t>(active[-2])[index]); } class vmt_hook { public: vmt_hook() = default; ~vmt_hook(); public: void init(ptr_t inst, uintptr_t offset = 0); void hook(method_t func, uintptr_t idx); void apply(); method_t get(uintptr_t idx) const; void release(); public: ptr_t object{ nullptr }; table_ptr_t vtable_ptr{ nullptr }; method_table_t vtable_original{ nullptr }; method_table_t vtable_hooked{ nullptr }; }; }
3f76ec1a559f6bd985eedc3bbea419b24f350d3e
[ "CMake", "Markdown", "C", "C++", "Shell" ]
34
C++
Sudo0x22/catbase-2017
aef400ea31cb2a15d78b79a5351dbd8b24da7d5d
1171a6ee9127488f9cea8967631082df30af0bbd
refs/heads/main
<repo_name>JAKKARIN2544/project65<file_sep>/Include/admin_page/menu_admin.php <?php include '../sql/conn.php'; include '../sql/check_session.php'; include '../sql/session_start.php'; ?> <!-- --------------------------------------- sql --------------------------------------- --> <!-- --------------------------------------- sql --------------------------------------- --> <div class="header"> <div class="header-left"> <div class="menu-icon dw dw-menu"></div> <div class="" data-toggle="header_search"></div> </div> <div class="header-right"> <div class="dashboard-setting user-notification"> <div class="dropdown"> <a class="dropdown-toggle no-arrow" href="javascript:;" data-toggle="right-sidebar"> <i class="dw dw-settings2"></i> </a> </div> </div> <div class="user-notification"> <div class="dropdown"> <a class="dropdown-toggle no-arrow" href="#" role="button" data-toggle="dropdown"> <i class="icon-copy dw dw-notification"></i> <span class="badge notification-active"></span> </a> <div class="dropdown-menu dropdown-menu-right"> <div class="notification-list mx-h-350 customscroll"> <ul> <li> <a href="#"> <img src="../vendors/images/img.jpg" alt=""> <h3><NAME></h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed...</p> </a> </li> <li> <a href="#"> <img src="../vendors/images/photo1.jpg" alt=""> <h3><NAME></h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed...</p> </a> </li> <li> <a href="#"> <img src="../vendors/images/photo2.jpg" alt=""> <h3><NAME></h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed...</p> </a> </li> <li> <a href="#"> <img src="../vendors/images/photo3.jpg" alt=""> <h3><NAME></h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed...</p> </a> </li> <li> <a href="#"> <img src="../vendors/images/photo4.jpg" alt=""> <h3><NAME></h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed...</p> </a> </li> <li> <a href="#"> <img src="../vendors/images/img.jpg" alt=""> <h3><NAME></h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed...</p> </a> </li> </ul> </div> </div> </div> </div> <div class="user-info-dropdown"> <div class="dropdown"> <a class="dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <span class="user-icon"> <img src="../vendors/images/photo1.png" alt=""> </span> <span class="user-name"><?php echo $_SESSION['user']; ?></span> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="profile.html"><i class="dw dw-user1"></i> Profile</a> <a class="dropdown-item" href="../sql/change_pass.php"><i class="dw dw-settings2"></i> Change password</a> <a class="dropdown-item" href="../sql/logout.php"><i class="dw dw-logout"></i> Log Out</a> </div> </div> </div> </div> </div> <div class="right-sidebar"> <div class="sidebar-title"> <h3 class="weight-600 font-16 text-blue"> Layout Settings <span class="btn-block font-weight-400 font-12">User Interface Settings</span> </h3> <div class="close-sidebar" data-toggle="right-sidebar-close"> <i class="icon-copy ion-close-round"></i> </div> </div> <div class="right-sidebar-body customscroll"> <div class="right-sidebar-body-content"> <h4 class="weight-600 font-18 pb-10">Header Background</h4> <div class="sidebar-btn-group pb-30 mb-10"> <a href="javascript:void(0);" class="btn btn-outline-primary header-white active">White</a> <a href="javascript:void(0);" class="btn btn-outline-primary header-dark">Dark</a> </div> <h4 class="weight-600 font-18 pb-10">Sidebar Background</h4> <div class="sidebar-btn-group pb-30 mb-10"> <a href="javascript:void(0);" class="btn btn-outline-primary sidebar-light ">White</a> <a href="javascript:void(0);" class="btn btn-outline-primary sidebar-dark active">Dark</a> </div> <h4 class="weight-600 font-18 pb-10">Menu Dropdown Icon</h4> <div class="sidebar-radio-group pb-10 mb-10"> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="sidebaricon-1" name="menu-dropdown-icon" class="custom-control-input" value="icon-style-1" checked=""> <label class="custom-control-label" for="sidebaricon-1"><i class="fa fa-angle-down"></i></label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="sidebaricon-2" name="menu-dropdown-icon" class="custom-control-input" value="icon-style-2"> <label class="custom-control-label" for="sidebaricon-2"><i class="ion-plus-round"></i></label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="sidebaricon-3" name="menu-dropdown-icon" class="custom-control-input" value="icon-style-3"> <label class="custom-control-label" for="sidebaricon-3"><i class="fa fa-angle-double-right"></i></label> </div> </div> <h4 class="weight-600 font-18 pb-10">Menu List Icon</h4> <div class="sidebar-radio-group pb-30 mb-10"> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="sidebariconlist-1" name="menu-list-icon" class="custom-control-input" value="icon-list-style-1" checked=""> <label class="custom-control-label" for="sidebariconlist-1"><i class="ion-minus-round"></i></label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="sidebariconlist-2" name="menu-list-icon" class="custom-control-input" value="icon-list-style-2"> <label class="custom-control-label" for="sidebariconlist-2"><i class="fa fa-circle-o" aria-hidden="true"></i></label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="sidebariconlist-3" name="menu-list-icon" class="custom-control-input" value="icon-list-style-3"> <label class="custom-control-label" for="sidebariconlist-3"><i class="dw dw-check"></i></label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="sidebariconlist-4" name="menu-list-icon" class="custom-control-input" value="icon-list-style-4" checked=""> <label class="custom-control-label" for="sidebariconlist-4"><i class="icon-copy dw dw-next-2"></i></label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="sidebariconlist-5" name="menu-list-icon" class="custom-control-input" value="icon-list-style-5"> <label class="custom-control-label" for="sidebariconlist-5"><i class="dw dw-fast-forward-1"></i></label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="sidebariconlist-6" name="menu-list-icon" class="custom-control-input" value="icon-list-style-6"> <label class="custom-control-label" for="sidebariconlist-6"><i class="dw dw-next"></i></label> </div> </div> <div class="reset-options pt-30 text-center"> <button class="btn btn-danger" id="reset-settings">Reset Settings</button> </div> </div> </div> </div> <div class="left-side-bar"> <div class="brand-logo"> <a href="../Back End/dashboard.php"> <img src="../vendors/images/tamsung-logo.png" alt="" class="dark-logo"> <img src="../vendors/images/tamsung-logo.png" alt="" class="light-logo"> </a> <div class="close-sidebar" data-toggle="left-sidebar-close"> <i class="ion-close-round"></i> </div> </div> <div class="menu-block customscroll"> <div class="sidebar-menu"> <ul id="accordion-menu"> <li> <a href="../Back End/dashboard.php" class="dropdown-toggle no-arrow"> <span class="micon dw dw-house"></span><span class="mtext">Dashboard</span> </a> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle"> <span class="micon dw dw-user2"></span><span class="mtext">Customer</span> </a> <ul class="submenu"> <li><a href="../Back End/customer.php">List Customer</a></li> <li><a href="../Back End/add_customer.php">Add Customer</a></li> </ul> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle"> <span class="micon dw dw-group"></span><span class="mtext">Personnel</span> </a> <ul class="submenu"> <li><a href="../Back End/personnel.php">List Personnel</a></li> <li><a href="../Back End/add_personnel.php">Add Personnel</a></li> </ul> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle"> <span class="micon dw dw-chef"></span><span class="mtext">Chef</span> </a> <ul class="submenu"> <li><a href="../Back End/chef.php">List Chef</a></li> <li><a href="../Back End/add_chef.php">Add Chef</a></li> </ul> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle"> <span class="micon dw dw-fish"></span><span class="mtext">Food ingredients</span> </a> <ul class="submenu"> <li><a href="../Back End/food_ingredients.php">List Food ingredients</a></li> <li><a href="../Back End/add_food_ingredients.php">Add Food ingredients</a></li> </ul> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle"> <span class="micon dw dw-burger"></span><span class="mtext">Food menu</span> </a> <ul class="submenu"> <li><a href="../Back End/food_menu.php">List Food menu</a></li> <li><a href="../Back End/add_food_menu.php">Add Food menu</a></li> </ul> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle"> <span class="micon dw dw-table"></span><span class="mtext">Table</span> </a> <ul class="submenu"> <li><a href="../Back End/table.php">List Table</a></li> <li><a href="../Back End/add_table.php">Add Table</a></li> </ul> </li> <li> <div class="sidebar-small-cap">Report</div> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle"> <span class="micon dw dw-open-book-2"></span><span class="mtext">Report</span> </a> <ul class="submenu"> <li><a href="#">Report </a></li> <li><a href="#">Report </a></li> <li><a href="#">Report </a></li> <li><a href="#">Report </a></li> </ul> </li> <li> <div class="dropdown-divider"></div> </li> <li> <div class="sidebar-small-cap"></div> </li> <div class=""> <a href="../Back End/time_working.php" class="dropdown-toggle no-arrow "> <span class="micon dw dw-wall-clock1" data-color="#FF0000"></span><h6 class=" text-danger">Working Time</h6> </a> </div> <li> <div class="dropdown-divider"></div> </li> <li> <div class="sidebar-small-cap"></div> </li> <li> <a href="../sql/logout.php" class="dropdown-toggle no-arrow"> <span class="micon dw dw-logout"></span><span class="mtext">Logout</span> </a> </li> </ul> </div> </div> </div><file_sep>/Back End/modal.php <?php include '../Include/admin_page/header_admin.php';?> <div class="col-md-4 col-sm-12 mb-30"> <div class="modal fade bs-example-modal-lg" id="bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myLargeModalLabel">Large modal</h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> </div> <div class="modal-body"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </div> </div> <?php include '../Include/admin_page/footer_admin.php'; ?><file_sep>/Back End/bill_oder.php <?php include "../Include/admin_page/header_admin.php"; include "../Include/admin_page/menu_admin.php"; ?> <div class="mobile-menu-overlay"></div> <div class="main-container"> <div class="pd-ltr-20 xs-pd-20-10"> <div class="min-height-200px"> <div class="invoice-wrap"> <div class="invoice-box"> <div class="invoice-header"> <div class="logo text-center"> <img src="vendors/images/deskapp-logo.png" alt=""> </div> </div> <h4 class="text-center mb-30 weight-600">INVOICE</h4> <div class="row pb-30"> <div class="col-md-6"> <h5 class="mb-15">Client Name</h5> <p class="font-14 mb-5">Date Issued: <strong class="weight-600">10 Jan 2018</strong></p> <p class="font-14 mb-5">Invoice No: <strong class="weight-600">4556</strong></p> </div> <div class="col-md-6"> <div class="text-right"> <p class="font-14 mb-5">Your Name </strong> </p> <p class="font-14 mb-5">Your Address</p> <p class="font-14 mb-5">City</p> <p class="font-14 mb-5">Postcode</p> </div> </div> </div> <div class="invoice-desc pb-30"> <div class="invoice-desc-head clearfix"> <div class="invoice-sub">Description</div> <div class="invoice-rate">Rate</div> <div class="invoice-hours">Hours</div> <div class="invoice-subtotal">Subtotal</div> </div> <div class="invoice-desc-body"> <ul> <li class="clearfix"> <div class="invoice-sub">Website Design</div> <div class="invoice-rate">$20</div> <div class="invoice-hours">100</div> <div class="invoice-subtotal"><span class="weight-600">$2000</span></div> </li> <li class="clearfix"> <div class="invoice-sub">Logo Design</div> <div class="invoice-rate">$20</div> <div class="invoice-hours">100</div> <div class="invoice-subtotal"><span class="weight-600">$2000</span></div> </li> <li class="clearfix"> <div class="invoice-sub">Website Design</div> <div class="invoice-rate">$20</div> <div class="invoice-hours">100</div> <div class="invoice-subtotal"><span class="weight-600">$2000</span></div> </li> <li class="clearfix"> <div class="invoice-sub">Logo Design</div> <div class="invoice-rate">$20</div> <div class="invoice-hours">100</div> <div class="invoice-subtotal"><span class="weight-600">$2000</span></div> </li> </ul> </div> <div class="invoice-desc-footer"> <div class="invoice-desc-head clearfix"> <div class="invoice-sub">Bank Info</div> <div class="invoice-rate">Due By</div> <div class="invoice-subtotal">Total Due</div> </div> <div class="invoice-desc-body"> <ul> <li class="clearfix"> <div class="invoice-sub"> <p class="font-14 mb-5">Account No: <strong class="weight-600">123 456 789</strong></p> <p class="font-14 mb-5">Code: <strong class="weight-600">4556</strong></p> </div> <div class="invoice-rate font-20 weight-600">10 Jan 2018</div> <div class="invoice-subtotal"><span class="weight-600 font-24 text-danger">$8000</span></div> </li> </ul> </div> </div> </div> <h4 class="text-center pb-20">Thank You!!</h4> </div> </div> </div> </div> </div> <div><br></div> <?php include "../Include/admin_page/footer_admin.php"; ?> <file_sep>/Login/register.php <?php include "../Include/login_page/header_register.html"; ?> <body class="register-page"> <div class="login-header box-shadow"> <div class="container-fluid d-flex justify-content-between align-items-center"> <div class="brand-logo"> <a href="../Login/login.php"> <img src="../vendors/images/tamsung-logo.png" alt=""> </a> </div> <div class="login-menu"> <ul> <li> <i class="dw dw-login"> </i><a class="text-dark" href="../Login/login.php">LOGIN</a></li> </ul> </div> </div> </div> <div class="login-wrap d-flex align-items-center flex-wrap justify-content-center"> <div class="container"> <div class="row align-items-center"> <div class="col-md-8 col-lg-12"> <div class="login-box bg-white box-shadow border-radius-10"> <div class="login-title"> <h2 class="text-center text-dark">Register To DeskApp</h2> </div> <form action="../sql/check_register.php" method="post" name="loginform" onsubmit="return validateForm()"> <div class="input-group custom"> <input type="text" class="form-control form-control-lg" placeholder="Email" name="email" id="email"> <div class="input-group-append custom"> <span class="input-group-text"><i class="icon-copy dw dw-email"></i></span> </div> </div> <div class="input-group custom"> <input type="text" class="form-control form-control-lg" placeholder="username" name="username" id="username"> <div class="input-group-append custom"> <span class="input-group-text"><i class="icon-copy dw dw-user"></i></span> </div> </div> <div class="input-group custom"> <input type="text" class="form-control form-control-lg" placeholder="Frist name" name="fname" id="fname"> <div class="input-group-append custom"> </div> <input type="text" class="form-control form-control-lg" placeholder="Last name" name="lname" id="lname"> <div class="input-group-append custom"> </div> </div> <div class="input-group custom"> <input type="password" class="form-control form-control-lg" placeholder="<PASSWORD>" name="password" id="password"> <div class="input-group-append custom"> <span class="input-group-text"><i class="dw dw-padlock1"></i></span> </div> </div> <div class="input-group custom"> <input type="password" class="form-control form-control-lg" placeholder="Re - Password" name="re_password" id="re_password"> <div class="input-group-append custom"> <span class="input-group-text"><i class="dw dw-password"></i></span> </div> </div> <div class="form-group row align-items-center"> <div class="col-sm-10"> <div class="custom-control custom-radio custom-control-inline pb-0"> <input type="radio" id="male" name="gender" class="custom-control-input" value="male"> <label class="custom-control-label" for="male"><i class="icon-copy fa fa-mars" aria-hidden="true"></i> Male</label> </div> <div class="custom-control custom-radio custom-control-inline pb-0"> <input type="radio" id="female" name="gender" class="custom-control-input" value="female"> <label class="custom-control-label" for="female"><i class="icon-copy fa fa-venus" aria-hidden="true"></i> Female</label> </div> </div> </div> <div class="input-group custom"> <input type="text" class="form-control form-control-lg" placeholder="Phone number" name="phone_number" id="phone_number"> <div class="input-group-append custom"> <span class="input-group-text"><i class="dw dw-phone-call"></i></span> </div> </div> <div class="input-group custom"> <input type="text" class="form-control form-control-lg" placeholder="Address" name="address" id="address"> <div class="input-group-append custom"> <span class="input-group-text"><i class="dw dw-map"></i></span> </div> </div> <div class="row pb-30"> </div> <div class="row"> <div class="col-sm-12"> <div class="input-group mb-0"> <button class="btn btn-dark btn-lg btn-block">REGISTER</button> </div> <div class="font-16 weight-600 pt-10 pb-10 text-center" data-color="#707373">OR</div> <div class="input-group mb-0"> <a class="btn btn-outline-dark btn-lg btn-block" href="register.php">Register To Create Account</a> </div> </div> </div> </form> </div> </div> <!-- form --> </div> </div> </div> <script> function validateForm() { // alert ("form call js"); var x = document.forms["loginform"]["u_username"].value; var y = document.forms["loginform"]["u_password"].value; if (x == "") { document.getElementById("u_username").innerHTML = "<b> Please Your Enter username "; document.forms["loginform"]["u_username"].value = ""; document.forms["loginform"]["u_username"].focus(); return false; } else { document.getElementById("u_username").innerHTML = ""; } if (y == "") { document.getElementById("u_password").innerHTML = "<b> Please Your Enter password "; document.forms["loginform"]["u_password"].value = ""; document.forms["loginform"]["u_password"].focus(); return false; } else { document.getElementById("u_password").innerHTML = ""; } } </script> <?php include "../Include/login_page/footer_register.html"; ?> <file_sep>/sql/count_sql.php <?php include '../sql/conn.php'; $sql = "SELECT COUNT(id) FROM user"; $res = mysqli_query($conn, $sql); $row = mysqli_fetch_assoc($res); /*$sql1 = "SELECT COUNT(cus_id) FROM customer"; $res1 = mysqli_query($conn, $sql1); $row1 = mysqli_fetch_assoc($res1); $sql2 = "SELECT COUNT(pro_id) FROM product"; $res2 = mysqli_query($conn, $sql2); $row2 = mysqli_fetch_assoc($res2); $sql3 = "SELECT COUNT(id) FROM user"; $res3 = mysqli_query($conn, $sql3); $row3 = mysqli_fetch_assoc($res3); $sql6 = "SELECT COUNT(ser_id) FROM services"; $res6 = mysqli_query($conn, $sql6); $row6 = mysqli_fetch_assoc($res6); $sql7 = "SELECT COUNT(ser_det_id) FROM services_details"; $res7 = mysqli_query($conn, $sql7); $row7 = mysqli_fetch_assoc($res7); $sql4 = "SELECT COUNT(status) AS status FROM services WHERE status='กำลังดำเนินการ'"; $res4 = mysqli_query($conn, $sql4); $row4 = mysqli_fetch_assoc($res4); $sql5 = "SELECT COUNT(status) AS status FROM services WHERE status='เสร็จ'"; $res5 = mysqli_query($conn, $sql5); $row5 = mysqli_fetch_assoc($res5); */ ?><file_sep>/Back End/time_working.php <?php include "../Include/admin_page/header_admin.php"; include "../Include/admin_page/menu_admin.php"; ?> <style> .table-list { font-weight: bold; text-align: center; font-size: 30px; font-family: Courier New; } .form-control { font-size: 20px; font-weight: bold; text-align: center; } .time-date { color: blue; } .clock { width: 260px; margin: 0 auto; padding: 5px; font-weight: bold; } .clock ul { width: 300px; } .clock ul li { display: inline; font-size: 3em; text-align: center; font-family: "Arial", Helvetica, sans-serif; } #Date { font-family: 'Arial', Helvetica, sans-serif; font-size: 20px; text-align: center; padding-bottom: 20px; } #point { position: relative; -moz-animation: mymove 1s ease infinite; -webkit-animation: mymove 1s ease infinite; padding-left: 10px; padding-right: 10px } #sec { position: relative; -moz-animation: mymove 1s ease infinite; -webkit-animation: mymove 1s ease infinite; } /* Animasi Detik Kedap - Kedip */ @-webkit-keyframes mymove { 50% { opacity: 0; text-shadow: none; } 100% { opacity: 1.0; } } </style> <div class="mobile-menu-overlay"></div> <div class="main-container"> <div class="pd-ltr-20 xs-pd-20-10"> <div class="min-height-200px"> <!-- Default Basic Forms Start --> <div class="pd-20 card-box mb-30"> <h1 class="text-center text-danger">Record working Time</h1> <div> <div class="clock"> <div id="Date"></div> <div class="time-date"> <ul> <li id="hours"></li> <li id="point">:</li> <li id="min"></li> <li id="point">:</li> <li id="sec"></li> </ul> </div> </div> </div> <form align="center" action="../sql/timeworking_in.php" method="post"> <div class="row bg-dark"> <div class="col-md-4 col-sm-12"> <div class="form-group"> <br><br><br> <input type="text" class="form-control" name="per_id" id="random"> </div> </div> <div class="col-md-4 col-sm-10"> <div class="form-group"> <label class="text-light">Date</label> <input name="working_date" id="date" class="form-control" disabled> <label class="text-light">Time</label> <input name="time_in" id="Time" class="form-control" disabled> </div> </div> <div class="col-md-4 col-sm-12"> <div class="form-group"> <br><br><br> <button class="btn btn-success btn-lg" type="submit">Time In</button> <button class="btn btn-danger btn-lg" type="submit">Time Out</button> </div> </div> </div> </form> <br> <br> <div class="pb-20"> <table class="data-table table stripe hover nowrap"> <thead> <tr> <th class="table-plus datatable-nosort">Name</th> <th>Age</th> <th>Office</th> <th>Address</th> <th>Start Date</th> <th class="datatable-nosort">Action</th> </tr> </thead> <tbody> <tr> <td class="table-plus"><NAME></td> <td>25</td> <td>Sagittarius</td> <td>2829 Trainer Avenue Peoria, IL 61602 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Gemini</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>20</td> <td>Gemini</td> <td>2829 Trainer Avenue Peoria, IL 61602 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Sagittarius</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>25</td> <td>Gemini</td> <td>2829 Trainer Avenue Peoria, IL 61602 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>20</td> <td>Sagittarius</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>18</td> <td>Gemini</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Sagittarius</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Sagittarius</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Gemini</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Gemini</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Gemini</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> </tbody> </table> </div> </div> <!-- -------------------------------start rendom id number------------------------------- --> <script> document.getElementById("random").value = Math.floor(100000 + Math.random() * 900000); </script> <!-- -------------------------------end rendom id number------------------------------- --> <script> function clockTick() { currentTime = new Date(); month = currentTime.getMonth() + 1; day = currentTime.getDate(); year = currentTime.getFullYear(); // alert("hi"); var showdate = day + "/" + month + "/" + year; document.getElementById("date").value = showdate; } setInterval(function() { clockTick(); }, 1000); //setInterval(clockTick, 1000); will also work GetTime(); function GetTime() { var CurrentTime = new Date() var hour = CurrentTime.getHours() var minute = CurrentTime.getMinutes() var second = CurrentTime.getSeconds() if (minute < 10) { minute = "0" + minute } if (second < 10) { second = "0" + second } var GetCurrentTime = hour + ":" + minute; document.getElementById("Time").value = GetCurrentTime; setTimeout(GetTime, 1000) } </script> <script> // Function which returns a minimum of two digits in case the value is less than 10 const getTwoDigits = (value) => value < 10 ? `0${value}` : value; const formatDate = (date) => { const year = date.getFullYear(); const month = getTwoDigits(date.getMonth() + 1); // add 1 since getMonth returns 0-11 for the months const day = getTwoDigits(date.getDate()); return `${day}-${month}-${year}`; } const formatTime = (date) => { const hours = getTwoDigits(date.getHours()); const mins = getTwoDigits(date.getMinutes()); return `${hours}:${mins}`; } const date = new Date(); document.getElementById('currentDate').value = formatDate(date); document.getElementById('currentTime').value = formatTime(date); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { // Making 2 variable month and day var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] // make single object var newDate = new Date(); // make current time newDate.setDate(newDate.getDate()); // setting date and time $('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear()); setInterval(function() { // Create a newDate() object and extract the seconds of the current time on the visitor's var seconds = new Date().getSeconds(); // Add a leading zero to seconds value $("#sec").html((seconds < 10 ? "0" : "") + seconds); }, 1000); setInterval(function() { // Create a newDate() object and extract the minutes of the current time on the visitor's var minutes = new Date().getMinutes(); // Add a leading zero to the minutes value $("#min").html((minutes < 10 ? "0" : "") + minutes); }, 1000); setInterval(function() { // Create a newDate() object and extract the hours of the current time on the visitor's var hours = new Date().getHours(); // Add a leading zero to the hours value $("#hours").html((hours < 10 ? "0" : "") + hours); }, 1000); }); </script> <?php include "../Include/admin_page/footer_admin.php"; ?><file_sep>/sql/check_login.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <!-- Site favicon --> <link rel="apple-touch-icon" sizes="180x180" href="../vendors/images/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="../vendors/images/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../vendors/images/favicon-16x16.png"> <!-- Mobile Specific Metas --> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <!-- Google Font --> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet"> <!-- CSS --> <link rel="stylesheet" type="text/css" href="../vendors/styles/core.css"> <link rel="stylesheet" type="text/css" href="../vendors/styles/icon-font.min.css"> <link rel="stylesheet" type="text/css" href="../src/plugins/sweetalert2/sweetalert2.css"> <link rel="stylesheet" type="text/css" href="../vendors/styles/style.css"> </head> <body> <?php session_start(); if(isset($_POST['username'])){ //connection include("../sql/conn.php"); //รับค่า user & password $username = $_POST['username']; $password = MD5($_POST["password"]); //query $sql="SELECT * FROM user Where username ='".$username."' and password ='".$password."' "; $result = mysqli_query($conn,$sql); if(mysqli_num_rows($result)==1){ $row = mysqli_fetch_array($result); $_SESSION["id"] = $row["id"]; $_SESSION["username"] = $row["username"]; $_SESSION["user"] = $row["fname"]." ".$row["lname"]; $_SESSION["level"] = $row["level"]; if($_SESSION["level"]=="admin"){ //ถ้าเป็น admin ให้ไปหน้า admin_page.php echo '<script type="text/javascript"> swal("Login Success", "The username or password is correct.", "success"); </script>'; echo '<meta http-equiv="refresh" content="4; url=../Back End/dashboard.php" />'; } if ($_SESSION["level"]=="personnel"){ //ถ้าเป็น member ให้ไปหน้า user_page.php echo '<script type="text/javascript"> swal("Login Success", "The username or password is correct.", "success"); </script>'; echo '<meta http-equiv="refresh" content="4; url=../Back End/dashboard.php-" />'; } if ($_SESSION["level"]=="member"){ //ถ้าเป็น member ให้ไปหน้า user_page.php echo '<script type="text/javascript"> swal("Login Success", "The username or password is correct.", "success"); </script>'; echo '<meta http-equiv="refresh" content="4; url=../Front End/member_index.php" />'; } }else{ echo '<script type="text/javascript"> swal("Oops...", "username or password incorrect back to login again!!!", "error"); </script>'; echo '<meta http-equiv="refresh" content="4;url=../Login/login.php" />'; } }else{ echo '<script type="text/javascript"> swal("Oops...", "username or password incorrect back to login again!!!", "error"); </script>'; echo '<meta http-equiv="refresh" content="4;url=../Login/login.php" />'; //Header("Location: ../Login/login.php"); //user & password incorrect back to login again } //-----------------------------------------------remember me -------------------------------------------------------------- if(!empty($_POST["remember"])) { setcookie ("username",$_POST["username"],time()+ 3600); setcookie ("password",$_POST["password"],time()+ 3600); //echo "Cookies Set Successfuly"; } else { setcookie("username",""); setcookie("password",""); //echo "Cookies Not Set"; } //-----------------------------------------------remember me -------------------------------------------------------------- ?> <!-- js --> <script src="../vendors/scripts/core.js"></script> <script src="../vendors/scripts/script.min.js"></script> <script src="../vendors/scripts/process.js"></script> <script src="../vendors/scripts/layout-settings.js"></script> <!-- add sweet alert js & css in footer --> <script src="../src/plugins/sweetalert2/sweetalert2.all.js"></script> <script src="../src/plugins/sweetalert2/sweet-alert.init.js"></script> </body> </html><file_sep>/Back End/dashboard.php <?php include '../Include/admin_page/header_admin.php'; include '../Include/admin_page/menu_admin.php'; include '../sql/conn.php'; include '../sql/count_sql.php'; $sql = "SELECT * FROM user"; $result = mysqli_query($conn, $sql); ?> <div class="mobile-menu-overlay"></div> <div class="main-container"> <div class="xs-pd-20-10 pd-ltr-20"> <div class="title pb-20"> <h2 class="h3 mb-0 text-danger"><i class="icon-copy dw dw-analytics-21" data-color="#0500FF"> </i> Dashboard Overview</h2> </div> <!-- ----------------------------------------------dashboard ----------------------------------------------------------------> <div class="row pb-10"> <div class="col-xl-3 col-lg-3 col-md-6 mb-20"> <div class="card-box height-100-p widget-style3"> <div class="d-flex flex-wrap"> <div class="widget-data"> <div class="weight-700 font-24 text-dark"><?php echo $row['COUNT(id)'] ?></div> <div class="font-14 text-secondary weight-500">Customer</div> </div> <div class="widget-icon"> <div class="icon" data-color="#00eccf"><i class="icon-copy fa fa-user-circle"></i></div> </div> </div> </div> </div> <div class="col-xl-3 col-lg-3 col-md-6 mb-20"> <div class="card-box height-100-p widget-style3"> <div class="d-flex flex-wrap"> <div class="widget-data"> <div class="weight-700 font-24 text-dark">124,551</div> <div class="font-14 text-secondary weight-500">Personnel</div> </div> <div class="widget-icon"> <div class="icon" data-color="#F97807"><span class="icon-copy ion-android-contacts"></span></div> </div> </div> </div> </div> <div class="col-xl-3 col-lg-3 col-md-6 mb-20"> <div class="card-box height-100-p widget-style3"> <div class="d-flex flex-wrap"> <div class="widget-data"> <div class="weight-700 font-24 text-dark">50,000</div> <div class="font-14 text-secondary weight-500">Chef cooking</div> </div> <div class="widget-icon"> <div class="icon" data-color="#FFFFFF"><i class="icon-copy dw dw-chef" aria-hidden="true"></i></div> </div> </div> </div> </div> <div class="col-xl-3 col-lg-3 col-md-6 mb-20"> <div class="card-box height-100-p widget-style3"> <div class="d-flex flex-wrap"> <div class="widget-data"> <div class="weight-700 font-24 text-dark">400+</div> <div class="font-14 text-secondary weight-500">Food ingredients</div> </div> <div class="widget-icon"> <div class="icon" data-color="#261BFE"><i class="icon-copy dw dw-fish" aria-hidden="true"></i></div> </div> </div> </div> </div> </div> <div class="row pb-10"> <div class="col-xl-3 col-lg-3 col-md-6 mb-20"> <div class="card-box height-100-p widget-style3"> <div class="d-flex flex-wrap"> <div class="widget-data"> <div class="weight-700 font-24 text-dark">75</div> <div class="font-14 text-secondary weight-500">Food menu</div> </div> <div class="widget-icon"> <div class="icon" data-color="#F31212"><i class="icon-copy dw dw-pizza"></i></div> </div> </div> </div> </div> <div class="col-xl-3 col-lg-3 col-md-6 mb-20"> <div class="card-box height-100-p widget-style3"> <div class="d-flex flex-wrap"> <div class="widget-data"> <div class="weight-700 font-24 text-dark">124,551</div> <div class="font-14 text-secondary weight-500">Table</div> </div> <div class="widget-icon"> <div class="icon" data-color="#FFFE00"><span class="icon-copy dw dw-table"></span></div> </div> </div> </div> </div> <div class="col-xl-3 col-lg-3 col-md-6 mb-20"> <div class="card-box height-100-p widget-style3"> <div class="d-flex flex-wrap"> <div class="widget-data"> <div class="weight-700 font-24 text-dark">$50,000</div> <div class="font-14 text-secondary weight-500">Total sales</div> </div> <div class="widget-icon"> <div class="icon" data-color="#09cc06"><i class="icon-copy dw dw-money-2" aria-hidden="true"></i></div> </div> </div> </div> </div> </div> <!-- ----------------------------------------------dashboard ----------------------------------------------------------------> <div class="row pb-10"> <div class="col-md-8 mb-20"> <div class="card-box height-100-p pd-20"> <div class="d-flex flex-wrap justify-content-between align-items-center pb-0 pb-md-3"> <div class="h5 mb-md-0">Hospital Activities</div> </div> <div id="activities-chart"></div> </div> </div> <div class="col-md-4 mb-20"> <div class="card-box min-height-200px pd-20 mb-20" data-bgcolor="#455a64"> <div class="d-flex justify-content-between pb-20 text-white"> <div class="icon h1 text-white"> <div class="font-14 text-warning">Daily sales</div> <div class="font-50 weight-500">1865</div> </div> <div class="font-14 text-right"> <div><i class="icon-copy ion-arrow-up-c"></i> 2.69%</div> <div class="font-12">BTH/Day</div> </div> </div> <div class="d-flex justify-content-between align-items-end"> <div class="text-white"> <i class="dw dw-money-1" aria-hidden="true"></i> </div> <div class="max-width-150"> <div id="appointment-chart"></div> </div> </div> </div> <div class="card-box min-height-200px pd-20" data-bgcolor="#265ed7"> <div class="d-flex justify-content-between pb-20 text-white"> <div class="icon h1 text-white"> <i class="fa fa-stethoscope" aria-hidden="true"></i> </div> <div class="font-14 text-right"> <div><i class="icon-copy ion-arrow-down-c"></i> 3.69%</div> <div class="font-12">Since last month</div> </div> </div> <div class="d-flex justify-content-between align-items-end"> <div class="text-white"> <div class="font-14">Surgery</div> <div class="font-24 weight-500">250</div> </div> <div class="max-width-150"> <div id="surgery-chart"></div> </div> </div> </div> </div> </div> <div class="card-box pb-10"> <div class="h5 pd-20 mb-0">Customer List</div> <table class="data-table table nowrap"> <thead> <tr> <th class="table-plus">Name</th> <th>Gender</th> <th>Weight</th> <th>Assigned Doctor</th> <th>Admit Date</th> <th>Disease</th> <th class="datatable-nosort">Actions</th> </tr> </thead> <tbody> <?php if (mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_assoc($result)) { ?> <tr> <td class="table-plus"> <div class="name-avatar d-flex align-items-center"> <div class="avatar mr-2 flex-shrink-0"> <img src="../src/images/user.png" class="border-radius-100 shadow" width="40" height="40" alt=""> </div> <div class="txt"> <div class="weight-600"><?php echo $row['level'] ?></div> </div> </div> </td> <td><?php echo $row['username'] ?></td> <td><?php echo $row['fname'] ?></td> <td><?php echo $row['lname'] ?></td> <td><?php echo $row['gender'] ?></td> <td><?php echo $row['tel'] ?></td> <td> <div class="table-actions"> <a href="#" data-color="#265ed7"><i class="icon-copy dw dw-edit2"></i></a> <a href="#" data-color="#e95959"><i class="icon-copy dw dw-delete-3"></i></a> </div> </td> </tr> <?php } } else { echo "0 results"; } ?> </tbody> </table> </div> <div class="title pb-20 pt-20"> </div> <?php include '../Include/admin_page/footer_admin.php'; ?><file_sep>/Back End/add_customer.php <?php include "../Include/admin_page/header_admin.php"; include "../Include/admin_page/menu_admin.php"; ?> <div class="mobile-menu-overlay"></div> <div class="main-container"> <div class="pd-ltr-20 xs-pd-20-10"> <div class="min-height-200px"> <!-- Default Basic Forms Start --> <div class="pd-20 card-box mb-30"> <div class="clearfix"> <div class="pull-left"> <h2 class="text-dark h2 ">Forms Add Customer</h2> <p class="mb-30"></p> </div> </div> <!-- Forms Start --> <form action="" method="post"> <div class="form-group row"> <label class="col-sm-12 col-md-3 col-form-label">Name</label> <div class="col-md-6 col-sm-12"> <input class="form-control" type="text" name="fname" id="fname" placeholder="Your Name example 'Johnny'"> <div class="text-danger">65644</div> </div> </div> <div class="form-group row"> <label class="col-sm-12 col-md-3 col-form-label">Surname</label> <div class="col-md-6 col-sm-12"> <input class="form-control" type="text" name="lname" id="lname" placeholder="Your Name example 'Brown'"> </div> </div> <div class="form-group row"> <label class="col-sm-12 col-md-3 col-form-label">Email</label> <div class="col-md-6 col-sm-12"> <input class="form-control" type="email" name="email" id="email" placeholder="<EMAIL>"> </div> </div> <div class="form-group row"> <label class="col-sm-12 col-md-3 col-form-label">Gender</label> <div class="col-md-2 col-sm-6"> <select class="custom-select col-12"> <option selected="">Choose...</option> <option value="1">Male</option> <option value="2">Female</option> <option value="3">Not specified</option> </select> </div> </div> <div class="form-group row"> <label class="col-sm-12 col-md-3 col-form-label">Telephone</label> <div class="col-md-6 col-sm-12"> <input class="form-control" placeholder="1-(111)-111-1111" type="tel"> </div> </div> <div class="form-group row"> <label class="col-sm-12 col-md-3 col-form-label">Password</label> <div class="col-md-6 col-sm-12"> <input class="form-control" placeholder="<PASSWORD>" type="<PASSWORD>"> </div> </div> <div class="form-group row"> <label class="col-sm-12 col-md-3 col-form-label">Re-Password</label> <div class="col-md-6 col-sm-12"> <input class="form-control" placeholder="re-password" type="<PASSWORD>"> </div> </div> <div class="form-group row"> <label class="col-sm-12 col-md-3 col-form-label">Address</label> <div class="col-md-6 col-sm-12"> <textarea class="form-control" placeholder="Your address" type="text" name="" id="" cols="20" rows="10"></textarea> </div> </div> <div> <label class="col-sm-12 col-md-5 col-form-label"> </label> <button type="submit" class="btn btn-success btn-lg">Add User</button> <button type="reset" class="btn btn-danger btn-lg">Reset</button> </div> </form> <!-- Forms End --> </div> <?php include "../Include/admin_page/footer_admin.php"; ?> <file_sep>/sql/timeworking_in.php <?php include "../sql/conn.php"; $per_id = $_POST['per_id']; $working_date = $_POST['working_date']; $time_in = $_POST['time_in']; $time_out = $_POST['time_out']; $sql = "INSERT INTO working_time VALUE ('$per_id','$working_date','$time_in','$time_out'')"; if (mysqli_query($conn, $sql)) { echo '<script type="text/javascript"> swal("Record Time Success", "The username or password is correct.", "success"); </script>'; echo '<meta http-equiv="refresh" content="3; url=../Back End/time_working.php" />'; } else { echo '<script type="text/javascript"> swal("Error", "Failed to save Time !!!!!!!", "error"); </script>'; echo '<meta http-equiv="refresh" content="3;url=../Back End/time_working.php" />'; } mysqli_close($conn); <file_sep>/sql/time_logout.php <?php /* เราสามารถกำหนดเวลาให้ ตัวแปร SESSION หมดอายุได้ ด้วย ฟังก์ชัน ini_set(’session.gc_maxlifetime’, 1800); 1800 คือจำนวนวินาทีของตัวแปร SESSION ว่าต้องการ ให้ตัวแปร SESSION นั้นอยู่ได้นานแค่ไหน หาก ฟังก์ชันข้างต้นไม่สามารถทำงานได้ เราสามารถ สร้างฟังก์ชันไว้ใช้งานเองแบบง่ายๆ ได้ ดังนี้ */ function setSessionTime($_timeSecond){ if(!isset($_SESSION['ses_time_life'])){ $_SESSION['ses_time_life']=time(); } if(isset($_SESSION['ses_time_life']) && time()-$_SESSION['ses_time_life']>$_timeSecond){ if(count($_SESSION)>0){ foreach($_SESSION as $key=>$value){ unset($$key); unset($_SESSION[$key]); } } } } // การใช้งาน setSessionTime(10); // 10 คือจำนวนวินาทีที่ต้องการให้ตัวแปร SESSION หมดอายุ // สามารถกำหนดเป็น 30*60 // หมายถึงกำหนดให้ตัวแปร SESSION หมดอายุภายใน 30 นาที // เช่น setSessionTime(30*60); // ฟังก์ชันนี้สามารถนำไปใช้ในการกำหนดเวลาว่าให้ user ต้องทำการล็อกอิน // ใหม่ทุกๆ กี่นาทีหรือกี่วินาที หรือกี่ชั่วโมงก็ได้ ?><file_sep>/sql/check_session.php <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <?php session_start();?> <?php if (!$_SESSION["id"]){ //check session echo '<script type="text/javascript"> swal("Warning !!", "Please Login before you can use it.", "warning"); </script>'; echo '<meta http-equiv="refresh" content="4; url=../Login/login.php" />'; //Header("Location: ../Login/login.php"); //ไม่พบผู้ใช้กระโดดกลับไปหน้า login form }else{?> <?php }?><file_sep>/Login/login.php <?php include "../Include/login_page/header_login.html"; ?> <body class="login-page"> <div class="login-header box-shadow"> <div class="container-fluid d-flex justify-content-between align-items-center"> <div class="brand-logo "> <a href="../Login/login.php"> <img src="../vendors/images/tamsung-logo.png" alt=""> </a> </div> <div class="login-menu"> <ul> <li> <i class="dw dw-add-user"> </i><a class="text-success " href="../Login/register.php">REGISTER</a></li> </ul> </div> </div> </div> <div class="login-wrap d-flex align-items-center flex-wrap justify-content-center"> <div class="container"> <div class="row align-items-center"> <div class="col-md-8 col-lg-12"> <div class="login-box bg-white box-shadow border-radius-10"> <div class="login-title "> <h2 class=" text-center text-success">Login To DeskApp</h2> </div> <form action="../sql/check_login.php" method="post" name="myformlogin" onclick="return validateform()"> <div id="username" class="text-danger"></div> <div id="password" class="text-danger"></div> <div class="input-group custom"> <input type="text" class="form-control form-control-lg " placeholder="Username" name="username" value="<?php if(isset($_COOKIE["username"])) { echo $_COOKIE["username"]; } ?>"> <div class="input-group-append custom"> <span class="input-group-text"><i class="icon-copy dw dw-user1"></i></span> </div> </div> <div class="input-group custom"> <input type="password" class="form-control form-control-lg" placeholder="*********" name="password" value="<?php if(isset($_COOKIE["password"])) { echo $_COOKIE["password"]; } ?>"> <div class="input-group-append custom"> <span class="input-group-text"><i class="dw dw-padlock1"></i></span> </div> </div> <div class="row pb-30"> <div class="col-6"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck1" name="remember"> <label class="custom-control-label" for="customCheck1">Remember</label> </div> </div> <div class="col-6"> <div class="forgot-password"><a href="../Error file/404.html">Forgot Password</a></div> </div> </div> <div class="row"> <div class="col-sm-12"> <div class="input-group mb-0"> <button class="btn btn-success btn-lg btn-block" type="submit" >LOG IN</button> </div> <div class="font-16 weight-600 pt-10 pb-10 text-center" data-color="#707373">OR</div> <div class="input-group mb-0"> <a class="btn btn-outline-success btn-lg btn-block" href="register.php">Register To Create Account</a> </div> </div> </div> </form> </div> </div> <!-- form --> </div> </div> </div> <script> function validateForm() { var username = document.forms["myformlogin"]["username"].value; var pasword = document.forms["myformlogin"]["password"].value; if (username == "") { document.getElementById('username').innerHTML = "<b> Please Your Enter username "; document.forms["myformlogin"]["username"].value = ""; document.forms["myformlogin"]["username"].focus(); return false; } else { document.getElementById('username').innerHTML = ""; } if (password == "") { document.getElementById('password').innerHTML = "<b> Please Your Enter password "; document.forms["myformlogin"]["password"].value = ""; document.forms["myformlogin"]["password"].focus(); return false; } else { document.getElementById('password').innerHTML = ""; } } </script> <?php include "../Include/login_page/footer_login.html"; ?> <file_sep>/Back End/chef.php <?php include '../Include/admin_page/header_admin.php'; include '../Include/admin_page/menu_admin.php'; ?> <div class="main-container"> <div class="pd-ltr-20 xs-pd-20-10"> <div class="min-height-200px"> <!-- Simple Datatable start --> <div class="card-box mb-30"> <div class="pd-20 "> <a href="../Back End/add_customer.php"><button type="button" class="btn btn-danger btn-lg "><i class="icon-copy dw dw-add"></i> Large button</button></a> </div> <div></div> <div class="pb-20"> <table class="data-table table stripe hover nowrap"> <thead> <tr> <th class="table-plus datatable-nosort">Name</th> <th>Age</th> <th>Office</th> <th>Address</th> <th>Start Date</th> <th class="datatable-nosort">Action</th> </tr> </thead> <tbody> <tr> <td class="table-plus"><NAME></td> <td>25</td> <td>Sagittarius</td> <td>2829 Trainer Avenue Peoria, IL 61602 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Gemini</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>20</td> <td>Gemini</td> <td>2829 Trainer Avenue Peoria, IL 61602 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Sagittarius</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>25</td> <td>Gemini</td> <td>2829 Trainer Avenue Peoria, IL 61602 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>20</td> <td>Sagittarius</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>18</td> <td>Gemini</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Sagittarius</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Sagittarius</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Gemini</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Gemini</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> <tr> <td class="table-plus"><NAME></td> <td>30</td> <td>Gemini</td> <td>1280 Prospect Valley Road Long Beach, CA 90802 </td> <td>29-03-2018</td> <td> <div class="dropdown"> <a class="btn btn-link font-24 p-0 line-height-1 no-arrow dropdown-toggle" href="#" role="button" data-toggle="dropdown"> <i class="dw dw-more"></i> </a> <div class="dropdown-menu dropdown-menu-right dropdown-menu-icon-list"> <a class="dropdown-item" href="#"><i class="dw dw-eye"></i> View</a> <a class="dropdown-item" href="#"><i class="dw dw-edit2"></i> Edit</a> <a class="dropdown-item" href="#"><i class="dw dw-delete-3"></i> Delete</a> </div> </div> </td> </tr> </tbody> </table> </div> </div> <!-- Simple Datatable End --> </div> <?php include '../Include/admin_page/footer_admin.php'; ?> <file_sep>/sql/logout.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <!-- Site favicon --> <link rel="apple-touch-icon" sizes="180x180" href="../vendors/images/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="../vendors/images/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../vendors/images/favicon-16x16.png"> <!-- Mobile Specific Metas --> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <!-- Google Font --> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet"> <!-- CSS --> <link rel="stylesheet" type="text/css" href="../vendors/styles/core.css"> <link rel="stylesheet" type="text/css" href="../vendors/styles/icon-font.min.css"> <link rel="stylesheet" type="text/css" href="../src/plugins/sweetalert2/sweetalert2.css"> <link rel="stylesheet" type="text/css" href="../vendors/styles/style.css"> </head> <body> <?php session_start(); session_destroy(); echo '<script type="text/javascript"> swal(" Logout Successfully", "Successfully logged out.", "success"); </script>'; echo '<meta http-equiv="refresh" content="4; url=../Login/login.php" />'; //header("Location: ../Login/login.php"); ?> <!-- js --> <script src="../vendors/scripts/core.js"></script> <script src="../vendors/scripts/script.min.js"></script> <script src="../vendors/scripts/process.js"></script> <script src="../vendors/scripts/layout-settings.js"></script> <!-- add sweet alert js & css in footer --> <script src="../src/plugins/sweetalert2/sweetalert2.all.js"></script> <script src="../src/plugins/sweetalert2/sweet-alert.init.js"></script> </body> </html>
8554eed5b8cd353d10f30e66f646b9c11338f676
[ "PHP" ]
15
PHP
JAKKARIN2544/project65
001b466e972e6a7a4901c778fb98796747892eaf
1d378178f6d29ccfd89da6407f8242d6cbdbe769
refs/heads/master
<file_sep><div align="center"> # Dokumentacja projektu: Forum Informatyczne </div> ## Wykonali: - <NAME> - <NAME> - <NAME> - <NAME> <div align="center"> # Opis Przedmiotem projektu jest forum informatyczne. Powstało ono dla pogłębiania wiedzy o tematyce informatycznej. Forum informatyczne skierowane jest do graczy, diagnostyków, programistów, maniaków sprzętowych, a także osób które miewają problemy z programowaniem w różnych językach. </div> ## 1. Typy użytkowników 1. Administrator: Posiada takie sama prawa jak moderator. 2. Moderator: Posiada prawa do: tworzenia działów/tematów/postów/komentarzy, banowania i odbanowywania użytkowników. 3. Zalogowany użytkownik: Posiada prawa do: tworzenia postów. 4. Gość: Posiada prawa do: Przeglądania forum. ## 2. System rang System rang będzie klasyfikował użytkowników na podstawie ich udzielania się na forum. Zdobycie rangi, będzie zależne od zdobycia łapek polubień. Im większa ilość łapek polubień tym wyższa ranga. Zakładamy, że wyższy stopień rangi użytkownika będzie go określał jako bardziej pomocnego na forum. Dodawanie łapek jest w tym projekcie ograniczone. Użytkownik danej przeglądarki ma możliwość dodania tylko jednej oceny. Jest to zasługa użycia biblioteki Fingerprint, która wykorzystuje ustawienia przeglądarki oraz mechanizm hashowania. Po wykonaniu Fingerprinta dostajemy hash przeglądarki, który jest zapisywany do bazy do późniejszych porównań. ## 3. Zamykanie postów • Administrator/Moderator posiadają prawa do zamykania postów. • Użytkownik, który stworzył post ma prawo do zamknięcia własnych postów. ## 4. Działy dostępne na forum: 1. Hardware 1. „Moje maszyny” 1. Software 1. Języki programowania 1. Frameworki ## 5. Zarządzanie profilem - Administrator posiada opcję zarządzania listą moderatów w której może nadawać prawa zwykłemu użytkownikowi do roli moderatora jak i odbierać. - Administrator posiada opcję zarządzania listą użytkowników, dzięki której może banować i odbanowywać. - Administrator posiada opcję tworzenia tematów i przypisywanie do wybranej zakładki. ## 6. System tworzenia kont - Na forum został zaimplementowany system rejestracji i logowania. ## 7. Technologie wykorzystane w projekcie - Forum zostało stworzone w środowisku PHPStorm. Mechanizmem kieruje język PHP wraz z Frameworkiem Laravel. Baza danych została wygenerowana w MySQL. ### W projekcie wykorzystano wzorzec MVC Model-View-Controller (pol. Model-Widok-Kontroler) – to wzorzec architektoniczny służący do organizowania struktury aplikacji posiadających graficzne interfejsy użytkownika. Wzorzec zakłada podział aplikacji na trzy główne części: - Model – jest pewną reprezentacją problemu bądź logiki aplikacji. - Widok – opisuje, jak wyświetlić pewną część modelu w ramach interfejsu użytkownika. Może składać się z podwidoków odpowiedzialnych za mniejsze części interfejsu. - Kontroler – przyjmuje dane wejściowe od użytkownika i reaguje na jego poczynania, zarządzając aktualizacje modelu oraz odświeżenie widoków. Struktura katalogów w Laravel przewiduje miejsca, gdzie umieszcza się pliki w zależności od tego czy są to kontrolery, widoki czy modele. #### Kontrolery Kontrolery przechowywane są w kalalogu Controllers znajdującym się w katalogu Http w katalogu app. Są swoistymi łącznikami pomiędzy modelem a widokiem. Odpowiadają za przetwarzanie danych wejściowych i przekazywaniem ich do modelu. Następnie tak przetworzone dane są odbierane i wyświetlone użytkownikowi w widoku w którym wysyłał żądanie albo zostaje przekierowany na inną stronę. #### Modele Znajdują się w katalogu app. Stanowią mózg aplikacji. To w nich są zdefiniowane obiekty. Zakładając, że piszemy bloga to w modelu zdefiniujemy klasy opisujące Posty, Tagi, Kategorie, Użytkowników itp. ale to nie wszytko. Żeby taki blog mógł prawidłowo funkcjonować trzeba te klasy i ich obiekty powiązać ze sobą. Powiązania są realizowane przy użyciu kilku rodzajów relacji. #### Widoki Pliki widoków umieszczone są w katalogu views znajdującym się w katalogu resources. W Laravel widoki umieszczane są w szablonach Blade. Są to podstawowe pliki HTML, które ładowane są podczas pracy kontrolera. Jest to element z punktu widzenia Back end’owych programistów mało doceniany, ale to właśnie tu użytkownik styka się ze stroną. Dane pobrane z bazy danych, obliczone w modelu poprzez kontroler wysłane do widoku. <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/model-view-controller-mvc.png"> <img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/model-view-controller-mvc.png" alt="MVC" > </a> #### FingerPrint Fingerprint ma unikalne podejście do zapobiegania oszustwom w naszej witrynie. Biblioteka generuje unikalny identyfikator przeglądarki bez użycia plików cookie ani żadnych informacji, które może łatwo zmodyfikować złośliwy użytkownik. Przechowując ten identyfikator w bazie danych, zapobiegamy oszustwom, jeśli ktoś próbuje użyć tego samego urządzenia (komputera, tabletu lub telefonu) w celu dwukrotnej rejestracji, wielokrotnego przesłania głosu polubień lub wykonania dowolnego innego podejrzanego działania . Biblioteka automatycznie wykrywa funkcje przeglądarki i selektywnie sprawdza dostępne parametry przeglądarki. # Prezentacja forum <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/glowna1.PNG"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/glowna1.PNG" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/glowna2.PNG"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/glowna2.PNG" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/glowna3.PNG"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/glowna3.PNG" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/glowna4.PNG"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/glowna4.PNG" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/glowna5.PNG"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/glowna5.PNG" alt="Obraz"></a> ## Główna strona forum komputerowego. Przedstawione działy Software, Hardware, Moje Maszyny, Języki programowania i Frameworki posiadają tematy. W tych tematach można umieszczać posty przez zalogowanego użytkownika. Post utworzony przez użytkownika w dziale Software. Informuje o tytule postu, opisem problemu, a także ilością odpowiedzi i data utworzenia. <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/post.jpg"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/post.jpg" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/post_z_komentarzami.PNG"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/post_z_komentarzami.png" alt="Obraz"></a> Wnętrze postu charakteryzuje się komentarzami wraz z informacją przez kogo został napisany post/komentarz. Informacje o użytkownikach widnieją obok treści komentarza. Są to: nazwa użytkownika, ranga, typ konta (Admin, Moderator, Zwykły Użytkownik) i ilość napisanych łącznie komentarzy na forum. Możliwość komentowania jest przydzielona tylko dla zalogowanych użytkowników. ## System rejestracji <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/rejestracja.PNG"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/rejestracja.png" alt="Obraz"></a> System ten umożliwia każdemu otrzymane dostępu do członkostwa w naszym forum. Wystarczy uzupełnić odpowiednimi danymi formularz, a po zatwierdzeniu danych przyciskiem „Rejestruj” strona przeniesie nowo utworzonego użytkownika na stronę główną. Nowo utworzony użytkownik ma możliwość wylogowania i ponownego zalogowania. <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/nowy_uzytkownik.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/nowy_uzytkownik.png" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/Logowanie.PNG"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/Logowanie.png" alt="Obraz"></a> Po zalogowaniu, pojawiła się opcja utworzenia postu po wybraniu dowolnego tematu znajdującego się na stronie forum. <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/Tworzenie_postu.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/Tworzenie_postu.png" alt="Obraz"></a> ## Stwórzmy post! <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/tworzenie_postu2.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/tworzenie_postu2.png" alt="Obraz"></a> Do stworzenia postu został utworzony formularz zgłoszeniowy. Podajemy nazwę tematu zgodną z wybranym działem oraz niezbędny jest szczegółowy opis. Gdy to już zostanie zrealizowane – kliknij Dodaj! Po stworzeniu postu, pojawił się komunikat o pomyślnie utworzonym poście, a tym samym nasz nowo utworzony post! <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/post_komunikat.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/post_komunikat.png" alt="Obraz"></a> ## Witaj w swoim poście! Można z komentować swój własny post jeśli otrzyma się odpowiedź zwrotną lub dodając coś od siebie klikając „Dodaj komentarz” <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/dodaj_komentarz.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/dodaj_komentarz.png" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/dodaj_komentarz2.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/dodaj_komentarz2.png" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/dodaj_komentarz3.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/dodaj_komentarz3.png" alt="Obraz"></a> ##### Możliwość polubień komentarzy. Wystarczy kliknąć łapkę w górę lub w dół. ## Przejdźmy do panelu użytkownika! <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/panel.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/panel.png" alt="Obraz"></a> W panelu można zmienić Avatar i login. Ponadto możemy dowiedzieć się o własnej randze i na jakim poziomie uprawnień jest nasze konto. ## Panel zarządzania przez administratora! <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/zarzadzanie.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/zarzadzanie.png" alt="Obraz"></a> Administrator posiada opcję zarządzania listą moderatów, w której może nadawać prawa zwykłemu użytkownikowi do roli moderatora jak i odbierać je. Znajduje się tam także opcja zarządzania listą użytkowników, dzięki której może banować i odbanowywać. Posiada również opcję tworzenia tematów i przypisywanie do wybranej zakładki. Opcja zarządzania listą moderatów, w której administrator może nadawać prawa zwykłemu użytkownikowi do roli moderatora oraz odbierać je. Opcja do zarządzania listą użytkowników, dzięki której administrator może banować i odbanowywać użytkowników i moderatorów. <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/lista_moderatorow.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/lista_moderatorow.png" alt="Obraz"></a> Opcję do tworzenia tematów i przypisywanie do wybranej zakładki. <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/tworzenie_tematu.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/tworzenie_tematu.png" alt="Obraz"></a> Opcja do zarządzania listą użytkowników, dzięki której administrator może banować i odbanowywać użytkowników i moderatorów. <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/lista_userow.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/lista_userow.png" alt="Obraz"></a> Administrator i moderator mogą banować użytkowników bezpośrednio z poziomu komentowania postów. <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/ban.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/ban.png" alt="Obraz"></a> Zbanowany użytkownik nie posiada dostępu do treści strony po zalogowaniu. Odblokowanie konta może wykonać administrator. <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/ban2.png"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/ban2.png" alt="Obraz"></a> Funkcja zrobiona, aby nie wpisywać różnych dziwnych rzeczy w pasku adresu. Poniżej przykład: <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/pasekadresu.PNG"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/pasekadresu.PNG" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/nieZnalezionoStrony.PNG"><img src="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/screeny%20dokumentacja/nieZnalezionoStrony.PNG" alt="Obraz"></a> ## Zainstalowanie Aplikacji 1. Instalacja pakietu XAMPP. 2. Uruchomienie aplikacji w PhpStorm: - Sklonowanie aplikacji z GitHuba - Instalacja Composera komendą w terminalu: ***Composer install*** - Następnie wpisujemy komendę do wygenerowania klucza: ***php artisan key:generate*** - Po tych komendach wpisujemy komendę do uruchomenia serwera i uruchomienia strony: ***php artisan serve*** (klikamy w link do localhosta lub wpisujemy w przeglądarkę http://127.0.0.1:8000) 3. Import bazy do phpMyAdmin: - utworzenie bazy danych o nazwie „baza2” - import bazy z pliku o nazwie „baza2.sql” # Szkic wyglądu strony w programie Axure (całościowy plik znajduję się w folderze ***projekt***) <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/home.png"><img src="../master/zdj/home.png" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/strona_z_postami_dzialu.png"><img src="../master/zdj/strona_z_postami_dzialu.png" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/pojedynczy_post_z_komentarzami.png"><img src="../master/zdj/pojedynczy_post_z_komentarzami.png" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/zarzadzanie.png"><img src="../master/zdj/zarzadzanie.png" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/rejestracja.png"><img src="../master/zdj/rejestracja.png" alt="Obraz"></a> <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/logowanie.png"><img src="../master/zdj/logowanie.png" alt="Obraz"></a> # Projekt bazy oraz diagram UML. ### Projekt bazy: <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/baza%20erd.PNG"><img src="../master/zdj/baza%20erd.PNG" alt="Obraz"></a> ### Diagram przypadków użycia: <a href="https://github.com/kamile890/Forum_Informatyczne/blob/master/zdj/uml.png"><img src="../master/zdj/uml.png" alt="Obraz"></a> ## License The Laravel framework is open-source software licensed under the [MIT license](https://opensource.org/licenses/MIT). <file_sep><?php namespace App\Http\Controllers; use App\Comment; use App\Like; use App\Post; use App\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class CommentController extends Controller { public function __construct() { $this->middleware('banned'); $this->middleware('rank'); } public function tworzenie_komentarza(Request $request){ // $opis = $request->validate(['opis'=> 'required|regex:/^[][a-zA-Z0-9]+$/u']); $opis = $request->validate(['opis'=> 'required']); $postID = $request->input('postID'); Comment::create([ 'content' => $opis['opis'], 'post_id' => $postID, 'user_id' => Auth::user()->id, 'rating' => 0, ]); $komunikat = "Komentarz został dodany pomyślnie."; return back()->with(compact('komunikat')); } public static function go_to_comments($id){ $posts = Post::where('id',$id)->first(); $comments = Comment::where('post_id', $id)->latest()->paginate(5); $user = User::where('id', $posts->user_id)->first(); $users = User::all(); $likes = Like::all(); $liked = false; return view('pages.odpowiedzi')->with(compact('posts','id', 'comments', 'users', 'user', 'likes', 'liked')); } public static function count_number_of_comments($user_id){ $number = DB::table('comments')->where('user_id', $user_id)->count(); return $number; } public static function getAvatar($user_avatar_id){ $avatar = DB::table('avatars')->where('id', $user_avatar_id)->first(); return $avatar->avatar; } public static function hand_up(Request $request){ $id = $request->input('id'); $fingerprint = $request->input('fingerprint'); $fingerprintExists = false; $likes = Like::all(); foreach($likes as $like){ if($like['comment_id'] == $id && $like['fingerprint'] == $fingerprint){ $fingerprintExists = true; } } if($fingerprintExists){ return "Już oceniano"; }else { $comment = Comment::where('id', $id)->first(); $user_id = Auth::user()->id; Like::create([ 'user_id' => $user_id, 'comment_id' => $id, 'fingerprint' => $fingerprint, ]); $rating = $comment->rating; $return = $rating + 1; Comment::where('id', $id)->update(['rating' => $return]); // updateowanie rangi $id = $comment->user_id; $rating = Comment::where('user_id', $id)->sum('rating'); if ($rating <= 2) { User::where('id', $id)->update(['rank_name' => 'Nowicjusz']); } else if ($rating > 2 && $rating <= 10) { User::where('id', $id)->update(['rank_name' => 'Zadziorny żółtodziób']); } else if ($rating > 10 && $rating <= 15) { User::where('id', $id)->update(['rank_name' => 'Znawca komputerów']); } else if ($rating > 15 && $rating <= 20) { User::where('id', $id)->update(['rank_name' => 'Weteran']); } else if ($rating > 20 && $rating <= 25) { User::where('id', $id)->update(['rank_name' => 'Nerd']); } else if ($rating > 25 && $rating <= 30) { User::where('id', $id)->update(['rank_name' => 'Władca bajtów']); } else if ($rating > 30) { User::where('id', $id)->update(['rank_name' => 'Piwniczak']); } return $return; } } public static function hand_down(Request $request){ $id = $request->input('id'); $comment = Comment::where('id', $id)->first(); $fingerprint = $request->input('fingerprint'); $user_id = Auth::user()->id; $fingerprintExists = false; $likes = Like::all(); foreach($likes as $like){ if($like['comment_id'] == $id && $like['fingerprint'] == $fingerprint){ $fingerprintExists = true; } } if($fingerprintExists){ return "Już oceniano"; }else { Like::create([ 'user_id' => $user_id, 'comment_id' => $id, 'fingerprint' => $fingerprint, ]); $rating = $comment->rating; $return = $rating - 1; Comment::where('id', $id)->update(['rating' => $return]); $id = $comment->user_id; $rating = Comment::where('user_id', $id)->sum('rating'); if ($rating <= 2) { User::where('id', $id)->update(['rank_name' => 'Nowicjusz']); } else if ($rating > 2 && $rating <= 10) { User::where('id', $id)->update(['rank_name' => 'Zadziorny żółtodziób']); } else if ($rating > 10 && $rating <= 15) { User::where('id', $id)->update(['rank_name' => 'Znawca komputerów']); } else if ($rating > 15 && $rating <= 20) { User::where('id', $id)->update(['rank_name' => 'Weteran']); } else if ($rating > 20 && $rating <= 25) { User::where('id', $id)->update(['rank_name' => 'Nerd']); } else if ($rating > 25 && $rating <= 30) { User::where('id', $id)->update(['rank_name' => 'Władca bajtów']); } else if ($rating > 30) { User::where('id', $id)->update(['rank_name' => 'Piwniczak']); } return $return; } } }
0b43e7ed747c40b9039a63ff8e693d9275a8ffb2
[ "Markdown", "PHP" ]
2
Markdown
DemoBoss/Forum_Informatyczne
81dca9069b44b8ff8863e9234e01750d35b471e7
cd5208eedb4a2ff8df80f3b1df18fc72e4cdc40e
refs/heads/master
<repo_name>mgambrell/LibFabline<file_sep>/README.md THIS IS A WORK IN PROGRESS Goal: create a specification for commandline tool arguments which solves deficiencies I've identified in all existing approaches; this will then be implemented in standard libraries for use in all my tools. I don't like data-driven stuff. It's always too hard to learn and implement. The easiest in both respects is to treat the command line as a short script and process tokens in order. Note that some very complex programs like ffmpeg have taken this approach. I also find that it's handy in many cases to set up a project where tools are run on config files. Why not make the command line syntax and config file syntax equivalent? Now, I know what you're thinking. I want hierarchical data in my config files; I want to use YAML or XML or even a script file or some ad-hoc language. I've done all those things. But then I realized--this was not a proper separation of concerns. If you want a complex config file, write a script to generate it. In other words, `python myscript_makes_a_cfg.py | mytool.exe -` Therefore, we also will take pains to ingest config files on stdin; to that end this library manages the program's execution environment completely for you: it processes the commandline into commands, reads config files as needed, and incorporates stdin as an additional command stream. Here's the specifications (WIP) `mytool.exe - mycommand arg - mycommand arg arg` is the normal use. if that looks familiar, it should. for familiarity, this style is accepted as well: `mytool.exe -mycommand arg -mycommand arg arg` In other words, - is used as a command delimiter. `mytool.exe - mycommand arg - mycommand arg arg -` will read remaining commands from stdin. You've basically said: "here's a command, and....?" `mytool.exe -` is needed when you just want to read commands from stdin. That is because `mytool.exe` will be commonly used by people wondering what to do, and we don't want it to get stuck reading stdin `mytool.exe file` having received something besides a command, knows to interpret that as a file name full of commands; thus we have convenient syntax for this very common case. `mytool.exe - commands file` will read the commands from the given command file. We need this, because we might want: `mytool.exe - mycommand arg - commands file` which would be a common pattern of setting up some parameters before running a commands file The special command `commands` is unlikely to be used by any tool; it already IS a list of commands. You wouldnt have a command named `commands`, it's redundant. An alternative would be to use a new symbol, likely @, but I favor `commands`. Now, in principle, command files can then use `-` as a line-comment. I know that's confusing, but `-` is already reserved for special meaning anyway, and that meaning isn't needed inside the command file. Luckily, if `-` is a comment then so too is `--`, which is more familiar. So, let's use -- as the line-comment. I believe it can be used to end lines without any problem, besides typical parsing context difficulties (i.e. `mycommand "quoted--argument--with--these" --now a real comment` but that's solvable.) Furthermore lines are pre-trimmed, post-trimmed, and empty lines are ignored. It isn't fair that you can use ${Variables} or %variables% on the commandline, but not in a commands file. Therefore, I should support one of those--probably the bash style one. OK, you're asking, why not let it be as programmable as bash? Because no. Now the only remaining problem is a tool which is designed to receive input on stdin: `mydatasource | mystdinreader.exe - mycommand arg - commands file` -- no problem `mystdinreader.exe - mycommand arg - commands file < mydatasource` -- no problem But what if we want to issue commands and input both via stdin? Since the command name `commands` is already reserved, let's end the stream by writing `commands end`. This should be followed by a newline (I do have a rationale for that). As a result of this, the tool can stop processing commands after `commands end` and begin processing the remainder as stdin data. Newlines are defined to be determined by the 1st of CR, LF, or CRLF encountered; LFCR is assumed not to exist, but as long as it's not preceded by CR (that is, CRLFCR ...lf) then it could be caught as an erroneously garbled file. If the stream is only one line, then the newline style can't be known; in that case, it's `command end` and it is interpreted as ending the stream immediately after the `d`. In other words, `command end` before any other lines ends at the `d`, and `command end` after any other lines ends after that line. Now after having read all of the above, why not have `command end` always terminate after the `d`? Because who's going to remember this, that's why. I don't want to have my name cursed every time (admittedly uncommonly) someone joins commands to stdin data and put an extra newline at the end of the commands. Note: `command end` in a commands file may be useful; you might send it through stdin. For orthogonality, it works the same way as a stdin stream. We will opt to enforce the same rules as above for streams. However, since command files may be used in a more elementary "response file" facility, the `command end` is not required (it only would be if it was stdin'd and concatenated with more stdin data) `mytool.exe help` would introduce something I'm wary of, a kind of ur-command. It isn't necessary, either, since `mytool.exe` can detect an empty stdin and print help information. Moreover, it's impossible to reliably distinguish between this and a specified command file. We'd have to have some kind of `mytool.exe @ file_with_same_name_as_ur_command` disambiguator. So, I'm writing this here in case we need it later. Yes, due to the way this is set up, command arguments beginning with dashes (i.e. negative numbers) need to be quoted. You can't win them all. This would be possible if we defined commands ahead of time or returned them to the tool incrementally for processing, but I'm trying to keep this simple... right? I might allow for some more custom formatting here to improve that. For instance, we would have `mytool.exe -xofs=-10` be equivalent to `mytool.exe -xofs "-10"`. In thinking about this, we should use to our advantage the C-identifier (see below) rule; it's possible that there are a lot of symbols at our disposal. But I want to wait and see how big a deal this is. Since the intention is for a library to handle these specifications, there are some additional specifications I do not need to, but do insist on providing: 1. Commands will always be returned as lower-cased strings, regardless of how they're entered by the user. The lower-casing 2. Commands are valid C identifiers, with the exception that the length is unlimited. Other ideas for the future: 1. Commands may be permitted to be a valid C expression consisting of dots and subscripts containing integer, string, or float literals or identifiers (in other words, a rudimentary js-like object path expression). This is intended mostly for simple array syntaxes like `mytool.exe - sources[0] file.png - sources[1] overlay.png` but I don't see why it couldn't be expanded. The library might or might not assist with parsing those. 2. An extra library layer for data-driven specifications, the way everyone else likes to do it Definite future work: 1. C and C++ versions of this library<file_sep>/LibFabline.cs using System; using System.IO; using System.Linq; using System.Xml; using System.Xml.Serialization; using System.Text; using System.Collections.Generic; namespace LibFabline { public class FablineEnvironment { /// <summary> /// Prepares the Fabline environment from the given commandline /// Will terminate the process with standard error messages if the user's input is wrong /// </summary> public FablineEnvironment(string[] args, System.IO.Stream stdin) { if (args == null) throw new ArgumentNullException("args", "args must be provided, even if it's an empty array"); if (stdin == null) throw new ArgumentNullException("stdin", "stdin must be provided"); ParseArguments(args); } void ParseArguments(string[] args) { bool haveDash = false; foreach (var _a in args) { var a = _a; bool isDash = a == "-"; bool isTreatedAsDash = isDash; bool startsDash = a.StartsWith("-"); //if we got something that isn't a dash, but starts with a dash, treat it as if it was separate if (startsDash && !isDash) { a = a.Substring(1); isTreatedAsDash = true; } //any time we get a dash, we just register it and then move along (unless we already had a dash) if (isDash || isTreatedAsDash) { if (haveDash) InvalidCLISyntax("succession of dashes"); haveDash = true; if(isDash) continue; } string lower = a.ToLowerInvariant(); if (haveDash) { if (IsValidCommandToken(lower)) { haveDash = false; EmitCommand(lower); continue; } else Bail("invalid command name"); } //we don't have a dash; so, token is assumed to be an argument if (currCommand == null) { //well, if we're not in a command, this is interpreted as a filename (there can be multiple) ParseFilename(a); } else { EmitArgument(a); } } //if we ended with a dash, then we're supposed to read from stdin commandsFromStdin = haveDash; } class FileParser { enum CRLFStyle { Unset, CR,LF,CRLF } public string FullName; StreamReader Reader; CRLFStyle CrlfStyle; string ReadLine() { StringBuilder line = new StringBuilder(); if (Reader.Peek() == -1) return null; for (;;) { int c = Reader.Read(); if(c==-1) break; if(CrlfStyle == CRLFStyle.CR) { if (c == '\r') break; } if(CrlfStyle == CRLFStyle.LF) { if (c == '\n') break; } if (CrlfStyle == CRLFStyle.CRLF) { if (c == '\r' && Reader.Peek() == '\n') { Reader.Read(); break; } } if (CrlfStyle == CRLFStyle.Unset) { if (c == '\r') { if (Reader.Peek() == '\n') { CrlfStyle = CRLFStyle.CRLF; Reader.Read(); break; } if (Reader.Peek() == '\r') { CrlfStyle = CRLFStyle.CR; break; } } else if (c == '\n') { CrlfStyle = CRLFStyle.LF; break; } } line.Append((char)c); } return line.ToString(); } public FileParser(string filename) { FullName = Path.GetFullPath(filename); try { //read each line from the input file //to stay sane ive split the line reading from the line parsing using (Reader = new StreamReader(FullName)) { for (;;) { var line = ReadLine(); if (line == null) break; line = line.Trim(); if (line == "") continue; //tokenize the line; this is not simple, and surely not complete //we have a choice of parsing similar to the command line, or similar to a programming language //umm let's be inspired by whatever bash would do List<StringBuilder> tokens = new List<StringBuilder>(); StringBuilder sbToken = null; bool hasDash = false; bool hasBackslash = false; bool inQuoted = false; foreach (var c in line) { bool isQuot = c == '\"'; bool isDash = c == '-'; bool isBackslash = c == '\\'; bool isWhitespace = (c == ' ' || c == '\t'); if (hasBackslash) { if (sbToken == null) sbToken = new StringBuilder(); sbToken.Append(c); hasBackslash = false; continue; } if (inQuoted) { if (isBackslash) { hasBackslash = true; continue; } if (isQuot) { inQuoted = false; continue; } } if (isQuot) { inQuoted = true; continue; } else if (isDash) { if (hasDash) break; hasDash = true; continue; } if (isWhitespace && !inQuoted) { if (sbToken != null) { sbToken = null; } } else { if (sbToken == null) { sbToken = new StringBuilder(); tokens.Add(sbToken); } if(hasDash) sbToken.Append('-'); hasDash = false; sbToken.Append(c); } hasDash = false; } if (hasBackslash) InvalidFileSyntax(filename, "Line terminates with incomplete escape character"); if (inQuoted) InvalidFileSyntax(filename, "Line terminates with incomplete quoted string"); var doneTokens = tokens.Select(t => t.ToString()).ToList(); if (doneTokens.Count == 0) continue; if (!IsValidCommandToken(doneTokens[0])) InvalidFileSyntax(filename, "invalid command name"); doneTokens[0] = doneTokens[0].ToLowerInvariant(); EmitCommand(doneTokens[0]); for (int i = 1; i < tokens.Count; i++) EmitArgument(doneTokens[i]); } //LINE LOOP } //FILE READER } //TRY catch { Bail("Error reading specified file: " + filename); } Reader = null; } FablineCommand currCommand; public List<FablineCommand> Commands = new List<FablineCommand>(); void EmitCommand(string command) { currCommand = new FablineCommand() { Name = command }; Commands.Add(currCommand); } void EmitArgument(string argument) { currCommand.Args.Add(argument); } } //class FileParser void ParseFilename(string filename) { var parser = new FileParser(filename); FablineCommand fileCommand = new FablineCommand(); fileCommand.Name = "<file>"; fileCommand.Args.Add(parser.FullName); Commands.Add(fileCommand); Commands.AddRange(parser.Commands); } /// <summary> /// Empty is set if the commandline was totally empty. /// </summary> public bool Empty { get; private set; } FablineCommand currCommand; public List<FablineCommand> Commands = new List<FablineCommand>(); void EmitCommand(string command) { currCommand = new FablineCommand() { Name = command }; Commands.Add(currCommand); } void EmitArgument(string argument) { currCommand.Args.Add(argument); } bool commandsFromStdin; static System.Text.RegularExpressions.Regex rxIdentifier = new System.Text.RegularExpressions.Regex("[_a-zA-Z][_a-zA-Z0-9]", System.Text.RegularExpressions.RegexOptions.Compiled); static bool IsValidCommandToken(string value) { return rxIdentifier.IsMatch(value); } static void InvalidCLISyntax(string message) { Bail("Invalid CLI syntax: " + message); } static void InvalidFileSyntax(string filename, string message) { Bail("Invalid syntax in file " + filename + ": " + message); } static void Bail(string message) { Console.Error.WriteLine(message); Environment.Exit(1); } } /// <summary> /// One of the commands provided by the user /// </summary> public class FablineCommand { /// <summary> /// The name of the command /// </summary> public string Name; /// <summary> /// The arguments that were provided to the command /// </summary> public List<string> Args = new List<string>(); } }
7c63769f91a78e5614a6915c1652c68a3691fb56
[ "Markdown", "C#" ]
2
Markdown
mgambrell/LibFabline
c674b3df1bab3022fa148309c6f921a5b9fed7e0
5810dea82449f0d7c42513ec682b5d07f37159cf
refs/heads/master
<file_sep>#include <stdio.h> #include "ezJSON/ezJSON.h" int main(int argc, char *argv[]) { char jsonStr[1024]; char* string[3] = {"one", "two", "three"}; float number[3] = {1, 2, 3}; ezJSON(jsonStr) { // 使用索引 ARR("array1", 3) { STR(NULL, string[_IDX]); }} // 不使用索引 ARR("array2", -1) { NUM(NULL, number[0]); NUM(NULL, number[1]); NUM(NULL, number[2]); }} ARR("array3", 3) {OBJ(NULL) { STR("string", string[_IDX]); NUM("number", number[_IDX]); }}}} ARR("array4", -1) { ARR(NULL, 3) { STR(NULL, string[_IDX]); }} ARR(NULL, 3) { NUM(NULL, number[_IDX]); }} }} }} printf("%s\n", jsonStr); return 0; } <file_sep>#include <stdio.h> #include "ezJSON/ezJSON.h" typedef struct DATASTRUCT { char strings[3][16]; float numbers[3]; struct { char string[16]; float number; }objects[3]; struct { char string[3][16]; float number[3]; }arrays; }Data; int main(int argc, char *argv[]) { char jsonStr[1024]; Data data; int err; FILE *pFile = fopen("parse_array.json", "r"); fseek(pFile, 0L, SEEK_END); long lenFile = ftell(pFile); fseek(pFile, 0L, SEEK_SET); jsonStr[fread(jsonStr, 1, lenFile, pFile)] = '\0'; fclose(pFile); _ezJSON(NULL, jsonStr) { _ARR("strings") {_VAL(NULL, data.strings[_IDX]); }} _ARR("numbers") { _VAL(NULL, data.numbers[_IDX]); }} _ARR("objects") {_OBJ(NULL) { _VAL("string", data.objects[_IDX].string); _VAL("number", data.objects[_IDX].number); }}}} _ARR("arrays") { _ARR(NULL) {_VAL(NULL, data.arrays.string[_IDX]); }} _ARR(NULL) {_VAL(NULL, data.arrays.number[_IDX]); }} }} }_END_} return 0; } <file_sep>/* MIT License Copyright (c) 2020 zhoutianhao Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "ezJSON.h" void _ezJsonCreate(char *content) { *(content++) = '{'; *content = '\0'; } void _ezJsonCreateEnd(char *content) { content += strlen(content) - 1; *(content++) = '}'; *content = '\0'; } void _ezJsonPostObject(char *content, char *key) { content += strlen(content); if (NULL != key) { int idx; *(content++) = '\"'; int sizeKey = strlen(key); for (idx = 0; idx < sizeKey; idx++) *(content++) = *(key + idx); *(content++) = '\"'; *(content++) = ':'; } *(content++) = '{'; *content = '\0'; } void _ezJsonPostObjectEnd(char *content) { content += strlen(content) - 1; if (',' != *content) content++; *(content++) = '}'; *(content++) = ','; *content = '\0'; } void _ezJsonPostArray(char *content, char *key) { int idx; content += strlen(content); if (NULL != key) { *(content++) = '\"'; int sizeKey = strlen(key); for (idx = 0; idx < sizeKey; idx++) *(content++) = *(key + idx); *(content++) = '\"'; *(content++) = ':'; } *(content++) = '['; *content = '\0'; } void _ezJsonPostArrayEnd(char *content) { content += strlen(content) - 1; if (',' != *content) content++; *(content++) = ']'; *(content++) = ','; *content = '\0'; } void _ezJsonPostString(char *content, char *key, char *value) { int idx; content += strlen(content); if (NULL != key) { *(content++) = '\"'; int sizeKey = strlen(key); for (idx = 0; idx < sizeKey; idx++) *(content++) = *(key + idx); *(content++) = '\"'; *(content++) = ':'; } *(content++) = '\"'; int sizeValue = strlen(value); for (idx = 0; idx < sizeValue; idx++) { if (32 > *(value + idx) || '\\' == *(value + idx) || '\"' == *(value + idx)) { *(content++) = '\\'; switch (*(value + idx)) { case '\\': *(content++) = '\\'; break; case '\"': *(content++) = '\"'; break; case '\b': *(content++) = 'b'; break; case '\f': *(content++) = 'f'; break; case '\n': *(content++) = 'n'; break; case '\r': *(content++) = 'r'; break; case '\t': *(content++) = 't'; break; default: *(content++) = '?'; } } else { *(content++) = *(value + idx); } } *(content++) = '\"'; *(content++) = ','; *content = '\0'; } void _ezJsonPostNumber(char *content, char *key, double value) { char _value[16]; int idx; sprintf(_value, "%lf", value); int sizeValue = strlen(_value); for (idx = sizeValue - 1; idx >= 0; idx--) { if ('.' == *(_value + idx)) { for (idx = sizeValue - 1; idx >= 0; idx--) { if ('0' == *(_value + idx)) *(_value + idx) = '\0'; else { if ('.' == *(_value + idx)) *(_value + idx) = '\0'; break; } } break; } } content += strlen(content); if (NULL != key) { *(content++) = '\"'; int sizeKey = strlen(key); for (idx = 0; idx < sizeKey; idx++) *(content++) = *(key + idx); *(content++) = '\"'; *(content++) = ':'; } sizeValue = strlen(_value); for (idx = 0; idx < sizeValue; idx++) *(content++) = *(_value + idx); *(content++) = ','; *content = '\0'; } void _ezJsonPostBool(char *content, char *key, int value) { content += strlen(content); if (NULL != key) { int idx; *(content++) = '\"'; int sizeKey = strlen(key); for (idx = 0; idx < sizeKey; idx++) { *(content++) = *(key + idx); } *(content++) = '\"'; *(content++) = ':'; } if (0 == value) { *(content++) = 'f'; *(content++) = 'a'; *(content++) = 'l'; *(content++) = 's'; } else { *(content++) = 't'; *(content++) = 'r'; *(content++) = 'u'; } *(content++) = 'e'; *(content++) = ','; *content = '\0'; } void _ezJsonPostNull(char *content, char *key) { int idx; content += strlen(content); *(content++) = '\"'; int sizeKey = strlen(key); for (idx = 0; idx < sizeKey; idx++) { *(content++) = *(key + idx); } *(content++) = '\"'; *(content++) = ':'; *(content++) = 'n'; *(content++) = 'u'; *(content++) = 'l'; *(content++) = 'l'; *(content++) = ','; *content = '\0'; } void _ezJsonClear(char *content) { int _doubleQuotes = 1; int idx = 0; char *point = content; while (*point) { switch (*point) { case ' ': case '\t': case '\r': case '\n': { if (0 > _doubleQuotes) content[idx++] = *point; } break; case '\"': { int _existSlash = 1; char *_point = point - 1; while (content <= _point && '\\' == *_point) { _existSlash = -_existSlash; _point--; } if (0 < _existSlash) _doubleQuotes = -_doubleQuotes; content[idx++] = *point; } break; default: content[idx++] = *point; break; } point++; } content[idx] = '\0'; } int _ezJsonErr(int err) { return err; } static char *__ezJsonGetValueStart(char *content, int *err) { *err = 0; char *endPtr = content + strlen(content); for (; '\0' != *content && content < endPtr; content++) { switch (*content) { case ' ': case '\b': case '\f': case '\n': case '\r': case '\t': case ',': break; case '\"': case '{': case '[': case 't': case 'f': case 'n': case '-': case ']': { return content; } break; default: { if (0x30 > *content || 0x39 < *content) *err = ezJSON_ERR_FORMAT; return content; } break; } } return content; } static char *__ezJsonGetTargetStart(char *content, int *err, char *key) { *err = 0; int _curlyBraces = -1; int _doubleQuotes = 1; char *_object; char *_point; int sizeKey = strlen(key); char *endPtr = content + strlen(content); FIND: _object = strstr(content, key); if (NULL == _object) { *err = ezJSON_ERR_NOTEXIST; return content; } _point = content; for (; _point < _object + sizeKey && '\0' != *_point && endPtr > _point; _point++) { switch (*_point) { case '{': case '[': { if (0 < _doubleQuotes) _curlyBraces++; } break; case ']': case '}': { if (0 < _doubleQuotes) _curlyBraces--; } break; case '\"': { int _existSlash = 1; char *__point = _point - 1; while (content <= __point && '\\' == *__point) { _existSlash = -_existSlash; __point--; } if (0 < _existSlash) _doubleQuotes = -_doubleQuotes; } break; } } content = _object + sizeKey; if ('\"' == *(_object - 1) && '\"' == *content) { for (content++; '\0' != *content && content < endPtr; content++) { switch (*content) { case ' ': break; default: { if (':' == *content && 0 == _curlyBraces) goto NEXT; content = _object + sizeKey; goto FIND; } break; } } NEXT: content = __ezJsonGetValueStart(content + 1, err); if (0 > *err) return content; } else goto FIND; return content; } static char *__ezJsonGetTargetStop(char *content, int *err, int *type) { *err = 0; char *revalue = NULL; char *_point = content; char *endPtr = content + strlen(content); switch (*_point) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case '-': { *type = ezJSON_NUMBER; for (; '\0' != *_point && endPtr > _point; _point++) { if ('.' != *_point && ('0' > *_point || '9' < *_point)) { revalue = _point; return revalue; } } *err = ezJSON_ERR_FORMAT; return revalue; } break; case 't': case 'f': { *type = ezJSON_BOOL; if (*_point == 't' && *(_point + 1) == 'r' && *(_point + 2) == 'u' && *(_point + 3) == 'e') revalue = _point + 4; else if (*_point == 'f' && *(_point + 1) == 'a' && *(_point + 2) == 'l' && *(_point + 3) == 's' && *(_point + 4) == 'e') revalue = _point + 5; else *err = ezJSON_ERR_FORMAT; return revalue; } break; case 'n': { *type = ezJSON_NULL; if (*_point == 'n' && *(_point + 1) == 'u' && *(_point + 2) == 'l' && *(_point + 3) == 'l') revalue = _point + 4; else *err = ezJSON_ERR_FORMAT; return revalue; } break; case '{': { *type = ezJSON_OBJECT; int _existBraces = 1; int _doubleQuotes = 1; for (_point++; '\0' != *_point && endPtr > _point; _point++) { switch (*_point) { case '{': { if (0 < _doubleQuotes) _existBraces++; } break; case '}': { if (0 < _doubleQuotes) _existBraces--; } break; case '\"': { int _existSlash = 1; char *__point = _point - 1; while (content <= __point && '\\' == *__point) { _existSlash = -_existSlash; __point--; } if (0 < _existSlash) _doubleQuotes = -_doubleQuotes; } break; } if (1 > _existBraces) { revalue = _point + 1; return revalue; } } *err = ezJSON_ERR_FORMAT; return revalue; } break; case '[': { *type = ezJSON_ARRAY; int _existBraces = 1; int _doubleQuotes = 1; for (_point++; '\0' != *_point && endPtr > _point; _point++) { switch (*_point) { case '[': { if (0 < _doubleQuotes) _existBraces++; } break; case ']': { if (0 < _doubleQuotes) _existBraces--; } break; case '\"': { int _existSlash = 1; char *__point = _point - 1; while (content <= __point && '\\' == *__point) { _existSlash = -_existSlash; __point--; } if (0 < _existSlash) _doubleQuotes = -_doubleQuotes; } break; } if (1 > _existBraces) { revalue = _point + 1; return revalue; } } *err = ezJSON_ERR_FORMAT; return revalue; } break; case '\"': { *type = ezJSON_STRING; for (_point++; '\0' != *_point; _point++) { if ('\"' == *_point) { int _existSlash = 1; char *__point = _point - 1; while (content <= __point && '\\' == *__point) { _existSlash = -_existSlash; __point--; } if (0 < _existSlash) { revalue = _point + 1; return revalue; } } } *err = ezJSON_ERR_FORMAT; return revalue; } break; default: *err = ezJSON_ERR_SYMBOL; return revalue; } return revalue; } int _ezJsonGetType(char *content, int *err, char *key) { *err = 0; int revalue = 0; char *begin = content; if (NULL != key) { begin = __ezJsonGetTargetStart(content, err, key); if (0 > *err) { revalue = *err; return revalue; } } else revalue = ezJSON_ERR_NONE; __ezJsonGetTargetStop(begin, err, &revalue); if (0 > *err) revalue = *err; return revalue; } char *_ezJsonGetObject(char *content, int *err, char *key) { *err = 0; char *revalue = content; char *begin = content; if (NULL != key) { begin = __ezJsonGetTargetStart(content, err, key); if (0 > *err) return revalue; revalue = begin; } else { begin = __ezJsonGetValueStart(begin, err); if (0 > *err) return revalue; int type; char *end = __ezJsonGetTargetStop(begin, err, &type); if (0 > *err) return revalue; revalue = end + 1; } return revalue; } char *_ezJsonGetArray(char **content, int *err, int *size, char *key) { *err = 0; char *revalue = *content; char *begin = *content; char *endPtr = *content + strlen(*content); if (NULL != key) begin = __ezJsonGetTargetStart(*content, err, key); else begin = __ezJsonGetValueStart(*content, err); int type; __ezJsonGetTargetStop(begin, err, &type); if (0 > *err) return revalue; if (ezJSON_ARRAY != type) { *err = ezJSON_ERR_FORMAT; return revalue; } int _existCnt = 0; int _existComma = 0; int _doubleQuotes = 1; int _curlyBraces = 0; char *_point = begin; for (; '\0' != *_point && endPtr > _point && (']' != *(_point - 1) || 0 != _curlyBraces); _point++) { switch (*_point) { case ',': { if (0 < _doubleQuotes && 1 == _curlyBraces) _existComma++; } break; case '{': case '[': { if (0 < _doubleQuotes) _curlyBraces++; } break; case ']': case '}': { if (0 < _doubleQuotes) _curlyBraces--; } break; case '\"': { int _existSlash = 1; char *__point = _point - 1; while (*content <= __point && '\\' == *__point) { _existSlash = -_existSlash; __point--; } if (0 < _existSlash) _doubleQuotes = -_doubleQuotes; } break; case ' ': case '\t': case '\r': case '\n': break; default: _existCnt = 1; } } *size = _existComma + 1; if (0 == _existComma && 0 == _existCnt) *size = 0; if (NULL == key) revalue = __ezJsonGetValueStart(_point, err); *content = begin + 1; return revalue; } char *_ezJsonGetValue(char *content, int *err, char *key, void *value) { *err = 0; char *revalue = content; char *begin = content; if (NULL != key) { begin = __ezJsonGetTargetStart(content, err, key); if (0 > *err) return revalue; } begin = __ezJsonGetValueStart(begin, err); if (0 > *err) return revalue; int type; char *end = __ezJsonGetTargetStop(begin, err, &type); if (0 > *err) return revalue; if (NULL == key) { revalue = __ezJsonGetValueStart(end, err); if (0 > *err) return revalue; } switch (type) { case ezJSON_NULL: { } break; case ezJSON_BOOL: { if ('t' == *begin) *((int *)value) = 1; else *((int *)value) = 0; } break; case ezJSON_NUMBER: { char _value[16]; sprintf(_value, "%.*s", (int)(end - begin), begin); *((float *)value) = atof(_value); } break; case ezJSON_STRING: { char *_value = (char *)value; char *_point = begin + 1; int idx; for (idx = 0; idx < end - begin - 2; idx++) { if ('\\' == _point[idx]) { switch (_point[++idx]) { case '\\': case '\"': case '/': *(_value++) = _point[idx]; break; case 'b': *(_value++) = '\b'; break; case 'f': *(_value++) = '\f'; break; case 'n': *(_value++) = '\n'; break; case 'r': *(_value++) = '\r'; break; case 't': *(_value++) = '\t'; break; default: *err = ezJSON_ERR_FORMAT; return revalue; } } else *(_value++) = _point[idx]; } *_value = '\0'; } break; } return revalue; } <file_sep>/* MIT License Copyright (c) 2020 zhoutianhao Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _EZJSON_H_ #define _EZJSON_H_ #ifdef __cplusplus extern "C" { #endif #define ezJSON_NULL 1 #define ezJSON_OBJECT 2 #define ezJSON_ARRAY 3 #define ezJSON_STRING 4 #define ezJSON_NUMBER 5 #define ezJSON_BOOL 6 #define ezJSON_ERR_NONE 0 #define ezJSON_ERR_SYMBOL -1 #define ezJSON_ERR_NOTEXIST -2 #define ezJSON_ERR_FORMAT -3 void _ezJsonCreate(char *content) ; void _ezJsonCreateEnd(char *content) ; void _ezJsonPostObject(char *content, char *key) ; void _ezJsonPostObjectEnd(char *content) ; void _ezJsonPostArray(char *content, char *key) ; void _ezJsonPostArrayEnd(char *content) ; void _ezJsonPostString(char *content, char *key, char *value) ; void _ezJsonPostNumber(char *content, char *key, double value) ; void _ezJsonPostBool(char *_ezJSONContent, char *_ezJSONKey, int _ezJSONValue) ; void _ezJsonPostNull(char *content, char *key) ; void _ezJsonClear(char *content) ; int _ezJsonErr(int err) ; int _ezJsonGetType(char *content, int *err, char *key) ; char *_ezJsonGetObject(char *content, int *err, char *key) ; char *_ezJsonGetArray(char **content, int *err, int *size, char *key) ; char *_ezJsonGetValue(char *content, int *err, char *key, void *value) ; #define ezJSON(_CONTENT) {\ char *_ezJSON_CONTENT = _CONTENT;\ _ezJsonCreate(_ezJSON_CONTENT);\ int ezJSON_IDX;\ for (ezJSON_IDX = 0; ezJSON_IDX++ < 1; _ezJsonCreateEnd(_ezJSON_CONTENT)) #define OBJ(_ezJSON_KEY) {\ _ezJsonPostObject(_ezJSON_CONTENT, _ezJSON_KEY);\ int ezJSON_IDX;\ for (ezJSON_IDX = 0; ezJSON_IDX++ < 1; _ezJsonPostObjectEnd(_ezJSON_CONTENT)) #define ARR(_ezJSON_KEY, _ezJSON_ARRAY_SIZE) {\ _ezJsonPostArray(_ezJSON_CONTENT, _ezJSON_KEY);\ int ezJSON_IDX;\ int _IDX;\ int ezJSON_SIZE = _ezJSON_ARRAY_SIZE;\ if (0 > _ezJSON_ARRAY_SIZE)\ ezJSON_SIZE = 1;\ for (ezJSON_IDX = 0; ezJSON_IDX++ < 1; _ezJsonPostArrayEnd(_ezJSON_CONTENT))\ for (_IDX = 0; _IDX < ezJSON_SIZE; _IDX ++) #define NUM(_ezJSON_KEY, _ezJSON_VALUE)\ _ezJsonPostNumber(_ezJSON_CONTENT, _ezJSON_KEY, _ezJSON_VALUE); #define STR(_ezJSON_KEY, _ezJSON_VALUE)\ _ezJsonPostString(_ezJSON_CONTENT, _ezJSON_KEY, _ezJSON_VALUE); #define BOL(_ezJSON_KEY, _ezJSON_VALUE)\ _ezJsonPostBool(_ezJSON_CONTENT, _ezJSON_KEY, _ezJSON_VALUE); #define NUL(_ezJSON_KEY)\ _ezJsonPostNull(_ezJSON_CONTENT, _ezJSON_KEY); #define _ezJSON(_ERR, _CONTENT) {\ if (NULL == _CONTENT)\ goto _ezJSON_END;\ char *_ezJSON_CONTENT = _CONTENT;\ int _ezJSON_ERR = ezJSON_ERR_NONE;\ int *_ezJSON_ERR_POINT = &_ezJSON_ERR;\ int _ezJSON_ERR_LOCK = 0;\ if (NULL != _ERR){\ _ezJSON_ERR_POINT = _ERR;\ _ezJSON_ERR_LOCK = 1;\ }\ int ezJSON_IDX;\ for (ezJSON_IDX = 0; ezJSON_IDX++ < 1; *_ezJSON_ERR_POINT = _ezJSON_ERR) #define _END_\ _ezJSON_END:\ _ezJSON_ERR = _ezJSON_ERR; #define _OBJ(_ezJSON_KEY) _ezJsonErr(_ezJSON_ERR); {\ if (0 > _ezJSON_ERR && 1 == _ezJSON_ERR_LOCK)\ goto _ezJSON_END;\ char **__ezJSON_CONTENT = &_ezJSON_CONTENT;\ char *_ezJSON_CONTENT = *__ezJSON_CONTENT;\ char *_ezJSON_POINT = _ezJsonGetObject(_ezJSON_CONTENT, &_ezJSON_ERR, _ezJSON_KEY);\ if (NULL == _ezJSON_KEY)\ *__ezJSON_CONTENT = _ezJSON_POINT;\ else\ _ezJSON_CONTENT = _ezJSON_POINT; #define _ARR(_ezJSON_KEY) _ezJsonErr(_ezJSON_ERR); {\ if (0 > _ezJSON_ERR && 1 == _ezJSON_ERR_LOCK)\ goto _ezJSON_END;\ char **__ezJSON_CONTENT = &_ezJSON_CONTENT;\ char *_ezJSON_CONTENT = *__ezJSON_CONTENT;\ int zJSON_ARRAY_SIZE = 0;\ char *_ezJSON_POINT = _ezJsonGetArray(&_ezJSON_CONTENT, &_ezJSON_ERR, &zJSON_ARRAY_SIZE, _ezJSON_KEY);\ if (NULL == _ezJSON_KEY)\ *__ezJSON_CONTENT = _ezJSON_POINT;\ int _IDX;\ for(_IDX = 0; _IDX < zJSON_ARRAY_SIZE; _IDX ++) #define _VAL(_ezJSON_KEY, _ezJSON_VALUE) _ezJsonErr(_ezJSON_ERR);\ if (0 > _ezJSON_ERR && 1 == _ezJSON_ERR_LOCK)\ goto _ezJSON_END;\ if (NULL == _ezJSON_KEY)\ _ezJSON_CONTENT = _ezJsonGetValue(_ezJSON_CONTENT, &_ezJSON_ERR, _ezJSON_KEY, &_ezJSON_VALUE);\ else\ _ezJsonGetValue(_ezJSON_CONTENT, &_ezJSON_ERR, _ezJSON_KEY, (void *)(&_ezJSON_VALUE)); #define _TYPE(_ezJSON_KEY)\ _ezJsonGetType(_ezJSON_CONTENT, &_ezJSON_ERR, _ezJSON_KEY) #define _CLR(_CONTENT)\ _ezJsonClear(_CONTENT); #ifdef __cplusplus } #endif #endif <file_sep> # ezJSON <font color=#999AAA >C语言下的人性化、高性能、轻量级JSON库 ## 目录 * [License](#License) * [使用](#使用) * [特性](#特性) * [编译](#编译) * [参数](#参数) * [示例](#构建和解析) * [基础结构](#基础结构) * [object对象](#object对象) * [array数组](#array数组) * [校验](#校验) * [API](#API) * [构建相关](#构建相关) * [解析相关](#解析相关) * [性能测试](#性能测试) * [测试内容](#测试内容) * [测试代码](#测试代码) * [结果](#结果) ## License MIT License > Copyright (c) 2020 zhoutianhao > > Permission is hereby granted, free of charge, to any person obtaining a copy > of this software and associated documentation files (the "Software"), to deal > in the Software without restriction, including without limitation the rights > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell > copies of the Software, and to permit persons to whom the Software is > furnished to do so, subject to the following conditions: > > The above copyright notice and this permission notice shall be included in all > copies or substantial portions of the Software. > > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE > SOFTWARE. ## 使用 ### 特性 <font color=#999AAA >ezJSON 命名自单词 easy 的谐音,目标是实现以精简的代码实现对复杂数据的处理,包含了一个C文件和一个头文件,对于小容量 MCU 芯片具有良好的支持。其具备以下特性: 人性化,相同于Json协议的结构设计,代码简洁,可读性强; 高性能,超快的构建速度,支持查询式解析; 轻量级,接口的实现基于指针操作,执行不申请占用额外内存。 ### 编译 <font color=#999AAA >由于整个库只有一个 C 文件和一个头文件,因此您只需将包含副本 __zJSON.c__ 和 __zJSON.h__ 的文件夹复制到项目源,并添加以下内容: ``` #include "ezJSON/ezJSON.h" ``` ### 参数 <font color=#999AAA >ezJSON 支持以下几种数据类型: | 类型 | 宏定义 | 变量类型 | | :---- | :---- | :---- | | 对象 | _ezJSON_OBJECT | - | | 数组 | _ezJSON_ARRAY| - | | 字符串 | _ezJSON_STRING | char[] | | 数字 | _ezJSON_NUMBER | float | | 布尔 | _ezJSON_BOOL | int | | 空 | _ezJSON_NULL | NULL | ### 示例 #### 基本结构 <font color=#999AAA >构建数据请使用 `ezJSON()` 和 `双括号` 结尾,以下是一个标准的构建结构: ``` ezJSON(jsonStr) { STR("string", "this is a string"); NUM("number", 23.64); BOL("bool", 1); NUL("null"); }} ``` <font color=#999AAA >解析数据请使用 `_ezJSON()` 和 `}_END_}` 结尾,`errPtr` 为 _int_ 型变量的指针,以下是一个标准的解析结构: ``` _ezJSON(errPtr, jsonStr) { _VAL ("value", value); // 字符、数字、布尔动态获取 }_END_} ``` #### object对象 <font color=#999AAA >现有字符数组 `char string[1024];` 存储有Json字符串如下: ``` { "title": "object test", "object_1": { "string": "this is object_1 string", "number": 10.01, "bool": true, "object_2": { "string": "this is object_2 string", "number": 10.02, "bool": false } } } ``` <font color=#999AAA >用于存储数据的结构体如下: ``` typedef struct DATASTRUCT { char title[64]; struct { char string[64]; float number; int bool; struct { char string[64]; float number; int bool; }object2; }object1; } Data; ``` ##### 构建代码(示例): ``` ezJSON(jsonStr) { STR("title", "object test"); OBJ("object_1") { STR("string", "this is object_1 string"); NUM("number", 10.01); BOL("bool", 1); OBJ("object_2") { STR("string", "this is object_2 string"); NUM("number", 10.02); BOL("bool", 0); }} }} }} ``` ##### 解析代码(示例): ``` _ezJSON(NULL, jsonStr) { _VAL("title", data.title); _OBJ("object_1") { _VAL("string", data.object1.string); _VAL("number", data.object1.number); _VAL("bool", data.object1.bool); _OBJ("object_1") { _VAL("string", data.object1.object2.string); _VAL("number", data.object1.object2.number); _VAL("bool", data.object1.object2.bool); }} }} }_END_} ``` #### array数组 <font color=#999AAA >现有字符数组 `char string[1024];` 存储有Json字符串如下: ``` { "strings": ["one", "two", "three"], "numbers": [1, 2, 3], "objects": [ { "string": "one", "number": 1 }, { "string": "two", "number": 2 }, { "string": "three", "number": 3 } ], "arrays": [ ["one", "two", "three"], [1, 2, 3] ] } ``` <font color=#999AAA >用于存储数据的结构体如下: ``` typedef struct DATASTRUCT { char strings[3][16]; char numbers[3][16]; struct { char string[16]; float number; }objects[3]; struct { char string[16]; float number[3]; }arrays; }Data; ``` ##### 构建代码(示例): <font color=#999AAA >_预设值 `size`,大于 __0__ 表示预设元素个数,使用 `_IDX` 标记元素索引,等于 __-1__ 表示不预设个数;键名 `key`,当键值作为数组元素时填 __NULL__;_ ``` char* string[3] = {"one", "two", "three"}; float number[3] = {1, 2, 3}; ``` ``` ezJSON(jsonStr) { // 使用索引 ARR("strings", 3) { STR(NULL, string[_IDX]); }} // 不使用索引 ARR("numbers", -1) { NUM(NULL, number[0]); NUM(NULL, number[1]); NUM(NULL, number[2]); }} ARR("objects", 3) {OBJ(NULL) { STR("string", string[_IDX]); NUM("number", number[_IDX]); }}}} ARR("arrays", -1) { ARR(NULL, 3) { STR(NULL, string[_IDX]); }} ARR(NULL, 3) { NUM(NULL, number[_IDX]); }} }} }} ``` ##### 解析代码(示例): ``` _ezJSON(NULL, jsonStr) { _ARR("strings") {_VAL(NULL, data.strings[_IDX]); }} _ARR("numbers") { _VAL(NULL, data.numbers[_IDX]); }} _ARR("objects") {_OBJ(NULL) { _VAL("string", data.objects[_IDX].string); _VAL("number", data.objects[_IDX].number); }}}} _ARR("arrays") { _ARR(NULL) {_VAL(NULL, data.arrays.string[_IDX]); }} _ARR(NULL) {_VAL(NULL, data.arrays.number[_IDX]); }} }} }_END_} ``` ### 校验 #### 异常检测 <font color=#999AAA >__`常规检测`__ 由于ezJSON采用的是查询式解析,校验操作不会在入口函数 `_ezJSON(errPtr, jsonStr)` 的开头进行,而是在执行解析函数时同步执行数据的校验,并返回响应的错误码,码值 __小于0__ 表示数据异常。ezJSON 支持的异常类型有: | 宏定义 | 对应值 | 含义 | | :----: | :----: | :----: | | _ezJSON_ERR_NONE| 0 | 无 | | _ezJSON_ERR_SYMBOL | -1 | 非法字符 | | _ezJSON_ERR_NOTEXIST | -2 | 键不存在 | | _ezJSON_ERR_FORMAT | -3 | 格式错误 | 以下是常规异常检测的示例代码: ``` _ezJSON(NULL, jsonStr) // 参数`errPtr` 为 NULL { if (0 > _VAL("title", title)) { printf("parse title error\n"); } int errObj = _OBJ("object") { if (0 > errObj) { printf("parse object error\n"); } }} }_END/_} ``` <font color=#999AAA >__`全局检测`__ 启用该检测方式时,当解析函数检测到异常,则自动结束解析项目,并将错误码赋值到 `errPtr` 指向的整数型变量。以下是全局检测的示例代码: ``` int err; _ezJSON(&err, jsonStr) // 参数`errPtr` 不为 NULL { _VAL("title", title); printf("title: %s\n", title); _OBJ("object") { _VAL("string", string); printf("string: %s\n", string); }} }_END/_} if (0 > err) printf("error code %d !\n", err); ``` #### 类型检测 <font color=#999AAA >在执行解析动作前,可使用 `_TYPE()` 预先获取键值的类型。以下是类型检测的代码示例: ``` _ezJSON(NULL, jsonStr) { switch(_TYPE("value")) { case ezJSON_NULL: printf("this is a null\n"); break; case ezJSON_OBJECT: printf("this is a object\n"); break; case ezJSON_ARRAY: printf("this is a array\n"); break; case ezJSON_STRING: printf("this is a string\n"); break; case ezJSON_NUMBER: printf("this is a number\n"); break; case ezJSON_BOOL: printf("this is a bool\n"); break; case ezJSON_ERR_NOTEXIST: printf("key not exist !\n"); break; default: printf("parse err !\n"); } }_END/_} ``` ## API ### 构建相关 <font color=#999AAA >创建一个构建工程;内存指针 `string`; > ezJSON( char* string ) { > > }} <font color=#999AAA >创建对象类型;键 `key`,为 __null__ 表示添加到数组; > void OBJ( char* key ) { > > }} <font color=#999AAA >创建数组类型;键 `key`,为 __null__ 表示添加到数组;元素个数 `size`,大于 __0__ 表示预设大小,__-1__ 表示不预设; > void ARR( char* key , int size ) { > > }} <font color=#999AAA >创建数字类型;键 `key`,为 __null__ 表示添加到数组;键值 `value`,__float__ 类型; > void NUM( char* key , float value ) ; <font color=#999AAA >创建字符类型;键 `key`,为 __null__ 表示添加到数组;键值 `value`,__char *__类型; > void STR( char* key , char* value ) ; <font color=#999AAA >创建布尔类型;键 `key`,为 __null__ 表示添加到数组;键值 `value`,__int__ 类型; > void BOL(char *key, int value) ; <font color=#999AAA >创建空类型;键 `key`,不能为 __null__; > void NUL( char *key ) ; ### 解析相关 <font color=#999AAA >创建解析目标;全局错误码 `err`,为 __null__ 表示启用全局异常检测;目标指针 `string`; > void _ezJSON( int* errPtr , char* string ) { > > }_END\_} <font color=#999AAA >解析对象类型;键 `key`,为 __null__ 表示上级为数组,返回值为错误码; > int _OBJ( char* key ) { > > }} <font color=#999AAA >解析数组类型;键 `key`,为 __null__ 表示上级为数组;返回值为错误码; > int _ARR( char* key ) { > > }} <font color=#999AAA >获取键值;键 `key`,为 __null__ 表示上级为数组;键值 `value`,动态获取数字、字符、布尔值;返回值 __小于0__ 时表示错误码,否则表示键值的类型; > int _VAL( char* key , float \char *\int value ) ; <font color=#999AAA >获取键值类型;返回值大于 __0__ 表示 __类型码__,否则表示 __错误码__;键 `key`,为 __null__ 表示上级为数组; > int _TYPE( char* key ) ; ## 性能测试 <font color=#999AAA >测试平台使用的是阿里云单核CPU、2G内存的服务器,搭载有64位Ubuntu18.04系统。对目标字符串进行一百万次循环的构建、全部解析和局部解析,分别使用两种库进行5次计时测试。 ### 测试内容 > 目标字符串: ``` { "school": "Guangdong University Of Petrochemical Technology", "location": "Maoming", "ranking": 505, "area": 2020.643, "student": { "name": "zhoutianhao", "age": 23, "grades": [ 97, 62, 84 ], "office": true, "exp": [ { "address": "Guangdong", "date": 1906 }, { "address": "Chengdu", "date": 1910 } ] } } ``` > 目标结构体: ``` typedef struct INFOSTRUCT { char school[64]; char location[16]; float ranking; float area; struct { char name[16]; float age; float grades[3]; int office; struct { char address[16]; float date; }exp[2]; }student; }Info; ``` ### 测试代码 > 使用ezJSON构建: ``` ezJSON(string) { STR("school", info.school); STR("location", info.location); NUM("ranking", info.ranking); NUM("area", info.area); OBJ("student") { STR("name", info.student.name); NUM("age", info.student.age); ARR("grades", 3) { NUM(NULL, info.student.grades[_IDX]); }} BOL("office", info.student.office); ARR("exp", 2) {OBJ(NULL) { STR("address", info.student.exp[_IDX].address); NUM("date", info.student.exp[_IDX].date); }}}} }} }} ``` > 使用ezJSON解析全部: ``` _ezJSON(NULL, string) { _VAL("school", info.school); _VAL("location", info.location); _VAL("ranking", info.ranking); _VAL("area", info.area); _OBJ("student") { _VAL("name", info.student.name); _VAL("age", info.student.age); _ARR("grades") { _VAL(NULL, info.student.grades[_IDX]); }} _VAL("office", info.student.office); _ARR("exp") {_OBJ(NULL) { _VAL("address", info.student.exp[_IDX].address); _VAL("date", info.student.exp[_IDX].date); }}}} }} }_END/_} ``` > 使用ezJSON解析局部: ``` _ezJSON(NULL, string) { _OBJ("student") {_ARR("exp") {_OBJ(NULL) { _VAL("address", info.student.exp[_IDX].address); _VAL("date", info.student.exp[_IDX].date); }}}} }} }_END/_} ``` ### 结果 <font color=#999AAA >五场测试执行一百万次循环用时(单位:ms): | 内容 \ 场| 1 | 2 | 3 | 4 | 5 | | :----: | :----: | :----: | :----: | :----: | :----: | | 构建全部 | 5385 | 5291 | 5388 |5430 | 5327 | | 解析全部 | 10709 |10663 | 10807 |10740 | 10536 | | 解析部分 | 5107 |5028 | 5040 |5172 | 5125 | <file_sep>#include <stdio.h> #include "ezJSON/ezJSON.h" int main(int argc, char *argv[]) { char jsonStr[1024]; ezJSON(jsonStr) { OBJ("object_1") { STR("string", "this is object_1 string"); NUM("number", 23.62); BOL("bool", 1); OBJ("object_2") { STR("string", "this is object_2 string"); NUM("number", 23.62); BOL("bool", 1); }} }} }} printf("%s\n", jsonStr); return 0; } <file_sep>#include <stdio.h> #include "ezJSON/ezJSON.h" typedef struct DATASTRUCT { char title[64]; struct { char string[64]; float number; int bool; struct { char string[64]; float number; int bool; }object_2; }object_1; } Data; int main(int argc, char *argv[]) { char jsonStr[1024]; Data data; FILE *pFile = fopen("parse_object.json", "r"); fseek(pFile, 0L, SEEK_END); long lenFile = ftell(pFile); fseek(pFile, 0L, SEEK_SET); jsonStr[fread(jsonStr, 1, lenFile, pFile)] = '\0'; fclose(pFile); _ezJSON(NULL, jsonStr) { _VAL("title", data.title); _OBJ("object_1") { _VAL("string", data.object_1.string); _VAL("number", data.object_1.number); _VAL("bool", data.object_1.bool); _OBJ("object_2") { _VAL("string", data.object_1.object_2.string); _VAL("number", data.object_1.object_2.number); _VAL("bool", data.object_1.object_2.bool); }} }} }_END_} return 0; }
df38a9d2c52153101252d9d57bbfdd2a5000b347
[ "Markdown", "C" ]
7
C
ajunlonglive/ezJSON
e5127280d4b26eed921532647c00cd2be7f2a274
ab4378aec5ba2ce10005f2d6a26f4c5d5fa47a50
refs/heads/master
<file_sep>#!/bin/sh # # thp manages transparent huge pages availability on a system # # chkconfig: 345 99 99 # description: manages the start and stop of transparent huge page support # ### BEGIN INIT INFO # Provides: # Required-Start: # Required-Stop: # Should-Start: # Should-Stop: # Default-Start: # Default-Stop: # Short-Description: # Description: ### END INIT INFO # Source function library. . /etc/rc.d/init.d/functions prog="thp" [ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog lockfile=/var/lock/subsys/$prog start() { if [[ -n $THP ]] ; then if [ -f /sys/kernel/mm/transparent_hugepage/enabled ] ; then echo "$THP" > /sys/kernel/mm/transparent_hugepage/enabled fi fi if [[ -n $THP_DEFRAG ]] ; then if [ -f /sys/kernel/mm/transparent_hugepage/defrag ] ; then echo "$THP_DEFRAG" > /sys/kernel/mm/transparent_hugepage/defrag fi fi echo -n $"Configuring $prog: " rh_status return 0 } restart() { stop start } reload() { restart } force_reload() { restart } rh_status() { # run checks to determine if the service is running or use generic status if [ -f /sys/kernel/mm/transparent_hugepage/enabled ] ; then grep -q '\[always\]' /sys/kernel/mm/transparent_hugepage/enabled retval_thp=$? fi if [ -f /sys/kernel/mm/transparent_hugepage/defrag ] ; then grep -q '\[always\]' /sys/kernel/mm/transparent_hugepage/defrag retval_thp_defrag=$? fi if [[ $retval_thp -eq 1 && $retval_thp_defrag -eq 1 ]] ; then echo "THP disabled, THP Defrag disabled" return 3 elif [[ $retval_thp -eq 1 ]] ; then echo "THP disabled, THP Defrag enabled" return 3 elif [[ $retval_thp_defrag -eq 1 ]] ; then echo "THP enabled, THP Defrag disabled" return 3 else echo "THP and THP Defrag enabled" return 0 fi } rh_status_q() { rh_status >/dev/null 2>&1 } case "$1" in start) $1 ;; stop) rh_status_q || exit 7 ;; restart) $1 ;; reload) rh_status_q || exit 7 $1 ;; force-reload) force_reload ;; status) rh_status ;; condrestart|try-restart) rh_status_q || exit 0 restart ;; *) echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}" exit 2 esac exit $? <file_sep># puppet-module-thp === Puppet module to manage Transparent Huge Pages on RHEL6/CentOS6 and higher === # Compatibility --------------- This module is built for use with Puppet v3 on the following platforms and supports Ruby versions 1.8.7, 1.9.3, and 2.0.0. * EL 6 === # Parameters ------------ All numbers should be type cast as strings. Each per service option can be accessed as parameters and follow the naming scheme of `<service>_<option>` with the dashed changed to underscores. So enable-cache for the passwd service is available as `passwd_enable_cache`. The default values follow that of the man page, unless otherwise noted. ## Resource parameters --- config_path ----------- Path to sysconfig thp - *Default*: '/etc/sysconfig/thp' config_owner ------------ Owner of sysconfig thp. - *Default*: 'root' config_group ------------ Group of sysconfig thp. - *Default*: 'root' config_mode ----------- Mode of sysconfig thp. Must be in four digit octal notation. - *Default*: '0644' service_name ------------ String or array for name of service(s). - *Default*: 'thp' service_ensure -------------- String for value of ensure attribute of thp service. Valid values are 'present', 'running', 'absent', or 'stopped'. *Note*: This does not actually run a service - *Default*: 'stopped' service_enable -------------- Value of enable attribute of thp service. This determines if the service will start at boot or not. Allows for boolean, 'true', or 'false'. - *Default*: true service_init_path ----------------- Value of the default init.d path - *Default*: '/etc/init.d' service_init_owner ------------------ Owner of sysconfig thp. - *Default*: 'root' service_init_group ------------------ Group of sysconfig thp. - *Default*: 'root' service_init_mode ----------------- Mode of sysconfig thp. Must be in four digit octal notation. - *Default*: '0755' thp_status ---------- Kernel configuration option to enable or disable Transparent Huge Pages by setting a value in /sys/kernel/mm/transparent_hugepage/enabled. Valid values are 'always,' 'never,' or 'madvise.' - *Default*: 'always' thp_defrag_status ---------- Kernel configuration option to enable or disable Transparent Huge Pages Defragmentation by setting a value in /sys/kernel/mm/transparent_hugepage/defrag. Valid values are 'always,' 'never,' or 'madvise.' - *Default*: 'always' ## Usage with Hiera Because this is a parameterized class, you can use hiera to override the defaults. This is primarily to allow for modifying thp_status and thp_defrag_status from defaults. To do this, include the thp module somewhere in your manifests and then set the following options in your hiera YAML configuration. thp::thp_status: 'always' thp::thp_defrag_status: 'never'
b865dbafa0e7991d4e9297c915aa8e3183d8294c
[ "Markdown", "Shell" ]
2
Shell
hcoyote/puppet-thp
8aed8fc64cec920a6154c90c200220392e8bdc87
a1fda189cbaaf067191f85b18b9dddc1a8dfdac1
refs/heads/master
<file_sep># github-restoration-notifier github が復旧するまで監視する君 ## Description github が復旧したかどうか確認できる。 復活すると terminal-notifier を使って、通知が飛ぶよ ※ mac のみだよ ## Usage 1. git clone git@github.com:Surume/github-restoration-notifier.git 1. `sh ./start.sh` で起動して正常稼働している場合は通知が飛ぶよ - github が落ちているかどうか確認するときに便利だね! 2. watch コマンドを噛ませれば監視も出来るね便利だね ```sh watch -n30 sh ./start.sh ``` 3. さあみんなで `sh start.sh` !! <file_sep>#!bin/zsh if ! type terminal-notifier > /dev/null 2>&1; then brew install terminal-notifier fi hugahuga=$(curl -s -L https://github.com/ | egrep "No server is currently available to service your request.|Sorry, we're down for maintenance" | wc -l | xargs echo) if [ $hugahuga = "0" ]; then terminal-notifier -message 'github 復旧したってよ!!' else echo "damepo@$(date '+%Y/%m/%d %T')" fi
9b82101211d06f85e7570dcfca0de77da8edce41
[ "Markdown", "Shell" ]
2
Markdown
Surume/github-restoration-notifier
0e695730f06a085321c6d9e20f572b32a0af41c1
ea4b71e8924bded8b3c293e76e71d59a32a0085f
refs/heads/master
<file_sep>var numClicks = 0; var pointIncrement = 1; function generatePoints() { /*if (numClicks==25) { document.getElementById("pic").style.visibility="visible"; }*/ if (numClicks==24) { document.getElementById("firstUpgrade").style.visibility="visible"; } numClicks = numClicks + pointIncrement; document.getElementById("p1").innerHTML = numClicks; } function firstUpgrade() { pointIncrement = 2; numClicks = 0; }
6dd6d26f2476379912455c36522b0afb10705084
[ "JavaScript" ]
1
JavaScript
HandleThatError/Practice
cc91954da801c726e2467db7598d36884775a4cc
f98832f15e9c4d2176132e20f922c4acdf88b75b
refs/heads/master
<file_sep>import initialState from './initialState'; import { ScoreTypes, UserTypes } from '../actions/actionTypes'; export default function app(state = initialState, action) { let newState; switch (action.type) { case ScoreTypes.FETCH_SCORES: return action; case ScoreTypes.RECEIVE_SCORES: newState = Object.assign({}, state, { scores: { foosball: action.scores.filter(score => score.game_type === 'foosball'), pingpong: action.scores.filter(score => score.game_type === 'pingpong'), } }); return newState; case ScoreTypes.ADD_SCORE: return action; case ScoreTypes.FETCH_SCORES_BY_PLAYERS: return action; case ScoreTypes.RECEIVE_SCORES_BY_PLAYERS: newState = Object.assign({}, state, { scores_by_players: action.scores_by_players }); return newState; case ScoreTypes.SET_GAME_TYPE: newState = Object.assign({}, state, { game_type: action.game_type }) return newState; case UserTypes.FETCH_USERS: return action; case UserTypes.RECEIVE_USERS: newState = Object.assign({}, state, { users: action.users }); return newState; case UserTypes.ADD_USER: return action; default: return state; } }<file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchUsers } from '../../actions/userActions'; import { fetchScores, addScore, setGameType } from '../../actions/scoreActions'; export class Stats extends Component { constructor(props) { super(props); this.state = { game_type: '', } } componentDidMount() { const { fetchUsers, fetchScores } = this.props; fetchUsers(); fetchScores(); this._changeDisplayOption(); } getPlayerGames = (player) => { const game_type = this.refs.game_type && this.refs.game_type.value; return this.props[game_type] && this.props[game_type].length && this.props[game_type].filter((game) => { return game.p1_name === player || game.p2_name === player; }); } calculateWinPercentage = (player) => { let winPercent = 0; let playerGames = this.getPlayerGames(player); let totalWins = this.calculateTotalWins(player); if (playerGames && playerGames.length === 0) { winPercent = 0; } else { if (playerGames && playerGames.length) { winPercent = ((totalWins / playerGames.length) * 100); } } return winPercent.toFixed(1); } calculateLoseBy = (player) => { let loseBy = 0; let playerGames = this.getPlayerGames(player); playerGames && playerGames.forEach((game) => { if (game.p1_name === player && (game.p1_score < game.p2_score)) { loseBy += game.p1_score; } else if (game.p2_name === player && (game.p2_score < game.p1_score)) { loseBy += game.p2_score; } }); let playerWins = this.calculateTotalWins(player); if (playerGames && playerGames.length === 0){ return 0; } if (loseBy === 0) { return "N/A"; } loseBy = (loseBy / (playerGames.length - playerWins)).toFixed(2); return loseBy; } calculateTotalPointsFor = (player) => { let pointsFor = 0; let playerGames = this.getPlayerGames(player); playerGames && playerGames.forEach((game) => { if (game.p1_name === player) { pointsFor += game.p1_score; } else if (game.p2_name === player) { pointsFor += game.p2_score; } return pointsFor; }); return pointsFor; } calculateTotalPointsAgainst = (player) => { let pointsAgainst = 0; let playerGames = this.getPlayerGames(player); playerGames && playerGames.forEach((game) => { if (game.p1_name !== player) { pointsAgainst += game.p1_score; } else if (game.p2_name !== player) { pointsAgainst += game.p2_score; } return pointsAgainst; }); return pointsAgainst; } calculateTotalWins = (player) => { const game_type = this.refs.game_type && this.refs.game_type.value; let totalWins = 0; if (this.props[game_type]) { let playerScores = this.props[game_type] && this.props[game_type].filter((score) => { return ((score.p1_name === player && score.p1_score > score.p2_score) || (score.p2_name === player && score.p2_score > score.p1_score)) }); totalWins = playerScores.length; } return totalWins; } calculateStats = () => { let stats = []; this.props.users && this.props.users.forEach((player) => { player.name = `${player.first_name} ${player.last_name}`; stats.push({ name: player.name, totalWins: this.calculateTotalWins(player.name), winPercentage: this.calculateWinPercentage(player.name), loseBy: this.calculateLoseBy(player.name), pointsFor: this.calculateTotalPointsFor(player.name), pointsAgainst: this.calculateTotalPointsAgainst(player.name), games: this.getPlayerGames(player.name), }); }); return stats; } renderStats = () => { const stats = this.calculateStats(); if (stats && stats.length) { return stats.map((stat) => { if (stat.games && stat.games.length > 0) { return ( <tr key={ stat.name + stat.winPercentage }> <td>{ stat.name }</td> <td>{ stat.winPercentage }%</td> <td>{ stat.totalWins }</td> <td>{ stat.games.length }</td> <td>{ stat.pointsFor }</td> <td>{ stat.pointsAgainst }</td> <td>{ stat.loseBy > 0 ? stat.loseBy : 'N/A' }</td> </tr> ) } return null; }); } } _changeDisplayOption = () => { this.setState({ game_type: this.refs.game_type.value }); this.renderStats(); } render() { return ( <div> <form onChange={this._changeDisplayOption}> <div className="form-group"> <div className="col-lg-6 col-lg-offset-3 col-sm-6 col-sm-offset-3 pad-top"> <select className="form-control text-center" id="select" name="game_type" ref="game_type" defaultValue="pingpong"> <option value="pingpong" className="text-center">Ping Pong</option> <option value="foosball" className="text-center">Foosball</option> </select> </div> </div> </form> <table className="table table-striped table-hover text-center"> <thead> <tr> <th className="text-center">Player Name</th> <th className="text-center">Win Percentage</th> <th className="text-center">Total Wins</th> <th className="text-center">Total Games</th> <th className="text-center">Points For</th> <th className="text-center">Points Against</th> <th className="text-center">Average Points / Loss</th> </tr> </thead> <tbody> { this.renderStats() } </tbody> </table> </div>); } } const mapStateToProps = (state) => { const users = state.app.users; const foosball = state.app.scores && state.app.scores.foosball; const pingpong = state.app.scores && state.app.scores.pingpong; return { users, foosball, pingpong, } } const mapDispatchToProps = (dispatch) => { return bindActionCreators({ fetchUsers, fetchScores, addScore, setGameType }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(Stats);<file_sep>// User action types export const UserTypes = { FETCH_USERS: 'FETCH_USERS', RECEIVE_USERS: 'RECEIVE_USERS', ADD_USER: 'ADD_USER' } // Score action types export const ScoreTypes = { FETCH_SCORES: 'FETCH_SCORES', RECEIVE_SCORES: 'RECEIVE_SCORES', ADD_SCORE: 'ADD_SCORE', RECEIVE_SCORES_BY_PLAYERS: 'RECEIVE_SCORES_BY_PLAYERS', FETCH_SCORES_BY_PLAYERS: 'FETCH_SCORES_BY_PLAYERS', SET_GAME_TYPE: 'SET_GAME_TYPE', }<file_sep>import React, { Component } from 'react'; class ScoreList extends Component { componentDidMount() { const { scoreActions } = this.props; const { fetchScores } = scoreActions; fetchScores(); } _renderScores() { if (this.props.scores && this.props.scores.length) { let game_number = 0; return this.props.scores.map((score) => { return ( <tr key={ score.p1_name + score.id }> <td>{ ++game_number }</td> <td>{ score.p1_name }</td> <td>{ score.p1_score }</td> <td>{ score.p2_score }</td> <td>{ score.p2_name }</td> <td>{ this.formatGameType(score.game_type) }</td> </tr> ) }); } else { return ( <tr> <td></td> <td>No Scores Available</td> <td>No Scores Available</td> <td></td> </tr> ) } } formatGameType = (game_type) => { if (game_type === 'pingpong') { return 'Ping Pong'; } else if (game_type === 'foosball') { return 'Foosball'; } else { return 'Not Specified'; } } render() { return ( <div className="ScoreList container"> <header className="ScoreList-header"> <h1 className="ScoreList-title text-center">All Scores</h1> </header> <table className="table table-striped table-hover text-center"> <thead> <tr> <th className="text-center">Game</th> <th className="text-center">Player 1 Name</th> <th className="text-center">Player 1 Score</th> <th className="text-center">Player 2 Score</th> <th className="text-center">Player 2 Name</th> <th className="text-center">Game Type</th> </tr> </thead> <tbody> { this._renderScores() } </tbody> </table> </div> ); } } export default ScoreList; <file_sep>import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import React, { Component } from 'react'; import * as userActions from '../../actions/userActions'; require('../../index.css'); class AddPlayers extends Component { componentDidMount() { const { userActions } = this.props; userActions.fetchUsers(); } _renderPlayers = () => { if (this.props.users && this.props.users.length) { return this.props.users.map((player) => { return ( <tr key={ player.first_name + player.id }> <td>{ player.first_name }</td> <td>{ player.last_name }</td> <td>{ player.is_admin ? "Yes" : "No" }</td> </tr> ) }); } } _handleSubmit = (event) => { event.preventDefault(); let newPlayer = { first_name: this.refs.first_name.value, last_name: this.refs.last_name.value, is_admin: this.refs.is_admin.checked, } return this.props.userActions.addUser(newPlayer) .then((response) => { document.getElementById("player_form").reset(); }); } render() { return ( <div className="AddPlayers container"> <header className="AddPlayers-header"> <h1 className="AddPlayers-title text-center">Current Players</h1> </header> <table className="table table-striped table-hover text-center"> <thead> <tr> <th className="text-center">First Name</th> <th className="text-center">Last Name</th> <th className="text-center">Admin?</th> </tr> </thead> <tbody> { this._renderPlayers() } </tbody> </table> <div className="container"> <h3 className="text-center">Add Players</h3> <hr /> <form className="form-horizontal" id="player_form" onSubmit={ this._handleSubmit } name="player"> <fieldset> <div className="form-group text-center"> <div className="col-lg-3 col-sm-3 col-lg-offset-3 col-sm-offset-3"> <input className="form-control text-center" type="text" placeholder="<NAME>" name="first_name" ref="first_name" autoComplete="off"/> </div> <div className="col-lg-3 col-sm-3"> <input className="form-control text-center" type="text" placeholder="<NAME>" name="last_name" ref="last_name" autoComplete="off"/> </div> </div> <div className="col-lg-2 col-sm-2 col-lg-offset-5 col-sm-offset-5"><label htmlFor="is_admin"><input className="aligned-checkbox" name="is_admin" type="checkbox" ref="is_admin"/>Is Admin</label></div> <div className="form-group text-center"> <div className="col-lg-4 col-lg-offset-4 col-sm-4 col-sm-offset-4"> <button type="reset" className="btn btn-default">Cancel</button> <button type="submit" className="btn btn-primary">Submit</button> </div> </div> </fieldset> </form> </div> </div> ); } } const mapStateToProps = (state) => { return { users: state.app.users }; } const mapDispatchToProps = (dispatch) => { return { userActions: bindActionCreators(userActions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(AddPlayers); <file_sep>import { ScoreTypes } from './actionTypes'; function baseUrl() { return process.env.REACT_APP_PROXY_URL + process.env.REACT_APP_BASE_URL; } export function setGameType(game_type) { return { type: ScoreTypes.SET_GAME_TYPE, game_type }; } export function getScoresByPlayers(players) { return dispatch => { dispatch({ type: ScoreTypes.FETCH_SCORES_BY_PLAYERS }); return fetch(baseUrl() + '/scores', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(players) }) .then((response) => { return response.json(); }) .then(json => dispatch(receiveScoresByPlayer(json))); } } export function receiveScoresByPlayer(json) { return { type: ScoreTypes.RECEIVE_SCORES_BY_PLAYERS, scores_by_players: json.scores }; } export function addScore(scoreToAdd) { return dispatch => { return fetch(baseUrl() + '/scores/add', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(scoreToAdd) }) .then((response) => { return response.json(); }) .then(json => dispatch(fetchScores(scoreToAdd.game_type))); } } export function receiveScores(json) { return { type: ScoreTypes.RECEIVE_SCORES, scores: json.scores }; } export function fetchScores(game_type) { return dispatch => { dispatch({ type: ScoreTypes.FETCH_SCORES }); let url = ''; if (game_type !== undefined) { url = `${baseUrl()}/scores/${game_type}`; } else { url = `${baseUrl()}/scores`; } return fetch(url, { method: 'GET', headers: { 'Accept': 'application/json' } }) .then((response) => { return response.json(); }) .then(json => dispatch(receiveScores(json))); }; } <file_sep>import React, { Component } from 'react'; import Statistics from './statistics'; import { formatGameType } from '../../../utils/formatGameType'; class Matchups extends Component { constructor(props) { super(props); this.state = { game_type: '', } } _renderUsers = () => { if (this.props.users && this.props.users.length) { return this.props.users.map((user) => { return ( <option value={ user.id } key={ user.first_name + user.id }>{ user.first_name } { user.last_name }</option> ) }); } } _getPlayerGames = () => { const { game_type } = this.refs; const { users } = this.props; // player 1 const p1_id = this.refs.p1_id && this.refs.p1_id.value; const p1 = users && users.filter((user) => user.id === +p1_id)[0]; const p1_name = p1 && `${p1.first_name} ${p1.last_name}`; // player 2 const p2_id = this.refs.p2_id && this.refs.p2_id.value; const p2 = users && users.filter((user) => user.id === +p2_id)[0]; const p2_name = p2 && `${p2.first_name} ${p2.last_name}`; if (p1 && p1_name && p2 && p2_name) { if (game_type && this.props[game_type.value] && this.props[game_type.value].length) { return this.props[game_type.value] .filter((game) => { return (game.p1_name === p1_name && game.p2_name === p2_name) || (game.p2_name === p1_name && game.p1_name === p2_name); }); } } } _renderScores = () => { const games = this._getPlayerGames(); if (games && games.length) { return games.map((score) => { return ( <tr key={ score.p1_name + score.id }> <td>{ score.p1_name }</td> <td>{ score.p1_score }</td> <td>{ score.p2_score }</td> <td>{ score.p2_name }</td> <td>{ formatGameType(score.game_type) }</td> </tr> ) }); } return ( <tr> <td></td> <td>No Scores Available</td> <td>No Scores Available</td> <td></td> <td></td> </tr> ) } _getScores = (event) => { event.preventDefault() this.setState({ game_type: this.refs.game_type.value, }); this._renderScores(); } render() { const games = this._getPlayerGames(); return ( <div className="container"> <h3>Matchup Stats</h3> <hr /> <form className="form-horizontal" onSubmit={ this._getScores }> <fieldset> <div className="form-group"> <div className="col-lg-3 col-sm-3 col-lg-offset-3 col-sm-offset-3"> <select className="form-control text-center" id="select" required name="p1_id" ref="p1_id"> <option value="0"> -- Select a Player -- </option> { this._renderUsers() } </select> </div> <div className="col-lg-3 col-sm-3"> <select className="form-control text-center" id="select" required name="p2_id" ref="p2_id"> <option value="0"> -- Select a Player -- </option> { this._renderUsers() } </select> </div> </div> <div className="form-group"> <div className="col-lg-4 col-lg-offset-4 col-sm-4 col-sm-offset-4 pad-top"> <select className="form-control text-center" id="select" name="game_type" ref="game_type" defaultValue="pingpong"> <option value="foosball" className="text-center">Foosball</option> <option value="pingpong" className="text-center">Ping Pong</option> </select> </div> </div> <div className="form-group"> <div className="col-lg-4 col-lg-offset-4 col-sm-4 col-sm-offset-4"> <button type="reset" className="btn btn-default" onClick={ this._resetScores }>Cancel</button> <button type="submit" className="btn btn-primary">Submit</button> </div> </div> </fieldset> </form> <hr /> { games && games.length ? <Statistics scores={ games } playerOne={ games[0].p1_name || "" } playerTwo={ games[0].p2_name || "" } /> : <div>No Statistics Available</div> } <hr /> <table className="table table-striped table-hover text-center"> <thead> <tr> <th className="text-center">Player 1 Name</th> <th className="text-center">Player 1 Score</th> <th className="text-center">Player 2 Score</th> <th className="text-center">Player 2 Name</th> <th className="text-center">Game Type</th> </tr> </thead> <tbody> { this._renderScores() } </tbody> </table> </div> ); } } export default Matchups; <file_sep>export function formatGameType(game_type) { if (game_type === 'pingpong') { return 'Ping Pong'; } else if (game_type === 'foosball') { return 'Foosball'; } else { return 'Not Specified'; } } <file_sep>import React, { Component } from 'react'; class AddScore extends Component { componentWillMount() { this.props.fetchUsers(); } _renderUsers = () => { if (this.props.users && this.props.users.length) { return this.props.users.map((user) => { return ( <option value={ user.id } key={ user.first_name + user.id }>{ user.first_name } { user.last_name }</option> ) }); } } _handleScoreSubmit = (event) => { event.preventDefault(); let newScore = { p1_id: this.refs.p1_id.value, p2_id: this.refs.p2_id.value, p1_score: this.refs.p1_score.value, p2_score: this.refs.p2_score.value, game_type: this.refs.game_type.value, } if (!newScore.win_by_amount && (newScore.p1_score && newScore.p2_score)) { let p1_score = newScore.p1_score; let p2_score = newScore.p2_score; let win_by_amount; if (p1_score > p2_score) { win_by_amount = p1_score - p2_score; newScore = { ...newScore, win_by_amount, } } else { win_by_amount = p2_score - p1_score; newScore = { ...newScore, win_by_amount, } } } return this.props.addScore(newScore) .then(() => { document.getElementById("score_form").reset(); }); } render() { return ( <div className="container"> <h3>Add Scores</h3> <hr /> <form id="score_form" onSubmit={ this._handleScoreSubmit }> <fieldset> <div className="form-group"> <div className="col-lg-4 col-sm-4"> <select className="form-control text-center" id="select" name="p1_id" ref="p1_id"> <option value="0" className="text-center"> -- Select Player 1 -- </option> { this._renderUsers() } </select> </div> <div className="col-lg-2 col-sm-2"> <input type="number" pattern="[0-9]*" className="form-control text-center" name="p1_score" placeholder="Player 1 Score" ref="p1_score" autoComplete="off"/> </div> <div className="col-lg-2 col-sm-2"> <input type="number" pattern="[0-9]*" className="form-control text-center" name="p2_score" placeholder="Player 2 Score" ref="p2_score" autoComplete="off"/> </div> <div className="col-lg-4 col-sm-4"> <select className="form-control text-center" id="select" name="p2_id" ref="p2_id"> <option value="0" className="text-center"> -- Select Player 2 -- </option> { this._renderUsers() } </select> </div> <div className="form-group"> <div className="col-lg-4 col-lg-offset-4 col-sm-4 col-sm-offset-4 pad-top"> <select className="form-control text-center" id="select" name="game_type" ref="game_type" defaultValue="pingpong"> <option value="foosball" className="text-center">Foosball</option> <option value="pingpong" className="text-center">Ping Pong</option> </select> </div> </div> </div> <div className="form-group"> <div className="col-lg-4 col-lg-offset-4 col-sm-4 col-sm-offset-4"> <button type="reset" className="btn btn-default">Cancel</button> <button type="submit" className="btn btn-primary">Submit</button> </div> </div> </fieldset> </form> </div> ); } } export default AddScore; <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom' import { Provider } from 'react-redux'; import './index.css'; import App from './App'; import ScoreListContainer from './containers/scoreListContainer'; import FoosballScoreList from './containers/FoosballScoreList'; import PingPongScoreList from './containers/PingPongScoreList'; // import AddPlayerContainer from './containers/addPlayerContainer'; // import StatsContainer from './containers/statsContainer'; import Stats from './components/stats/stats'; import AddPlayers from './components/add_players/add_players'; import registerServiceWorker from './registerServiceWorker'; import configureStore from './store/configureStore'; const store = configureStore(); const PrimaryLayout = () => { return ( <nav className="navbar navbar-inverse"> <div className="container-fluid"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-2"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <Link to="/" className="navbar-brand">Foosball</Link> </div> <div className="collapse navbar-collapse" id="bs-example-navbar-collapse-2"> <ul className="nav navbar-nav"> <li><Link to="/scores/all">All Scores</Link></li> <li><Link to="/scores/pingpong">Ping Pong</Link></li> <li><Link to="/scores/foosball">Foosball</Link></li> <li><Link to="/players/add">Add Players</Link></li> <li><Link to="/stats">Stats</Link></li> </ul> <ul className="nav navbar-nav navbar-right"> </ul> </div> </div> </nav> ) } ReactDOM.render( <Provider store={ store }> <Router> <div> <PrimaryLayout></PrimaryLayout> <Route exact path="/" component={App}/> <Route path="/scores/all" component={ScoreListContainer}/> <Route path="/scores/foosball" component={FoosballScoreList}/> <Route path="/scores/pingpong" component={PingPongScoreList}/> <Route path="/players/add" component={AddPlayers}/> <Route path="/stats" component={Stats}/> </div> </Router> </Provider>, document.getElementById('root')); registerServiceWorker();<file_sep>Front end of the Foosball app, now expanded to handle ping pong also. <file_sep>import React, { Component } from 'react'; class Statistics extends Component { calculateStats = () => { let { scores, playerOne, playerTwo } = this.props; let p1_total_points = 0, p1_win_percent, p1_total_wins, p1_lose_by = 0, p1_scores, p2_total_points = 0, p2_win_percent, p2_total_wins, p2_lose_by = 0, p2_scores; // Get p1_win games p1_scores = scores.filter((score) => { return (score.p1_name === playerOne && score.p1_score > score.p2_score) || (score.p2_name === playerOne && score.p2_score > score.p1_score); }); // calculate p1 win percentage p1_win_percent = (p1_scores.length / scores.length * 100).toFixed(2); // calculate p1 total wins p1_total_wins = p1_scores.length; // get p2_win games p2_scores = scores.filter((score) => { return (score.p1_name === playerTwo && score.p1_score > score.p2_score) || (score.p2_name === playerTwo && score.p2_score > score.p1_score); }); // calculate p2 win percentage p2_win_percent = (p2_scores.length / scores.length * 100).toFixed(2); // calculate p2 total wins p2_total_wins = p2_scores.length; // get total points for both players scores.forEach((score) => { if (score.p1_name === playerOne) p1_total_points += score.p1_score; if (score.p2_name === playerOne) p1_total_points += score.p2_score; if (score.p1_name === playerTwo) p2_total_points += score.p1_score; if (score.p2_name === playerTwo) p2_total_points += score.p2_score; }); // get p1_lose_by amounts p2_scores.forEach((score) => { if (score.p1_name === playerOne) p1_lose_by += score.p1_score; if (score.p2_name === playerOne) p1_lose_by += score.p2_score; }); p1_lose_by = (p1_lose_by / p2_scores.length).toFixed(2); p1_scores.forEach((score) => { if (score.p1_name === playerTwo) p2_lose_by += score.p1_score; if (score.p2_name === playerTwo) p2_lose_by += score.p2_score; }); p2_lose_by = (p2_lose_by / p1_scores.length).toFixed(2); return ( <table className="table table-striped text-center"> <thead> <tr> <th className="text-center">Player</th> <th className="text-center">Win Percentage</th> <th className="text-center">Total Wins</th> <th className="text-center">Total Points</th> <th className="text-center">Average Points / Loss</th> </tr> </thead> <tbody> <tr> <td>{ playerOne }</td> <td>{ p1_win_percent }%</td> <td>{ p1_total_wins }</td> <td>{ p1_total_points }</td> <td>{ p1_lose_by > 0 ? p1_lose_by : 'N/A' }</td> </tr> <tr> <td>{ playerTwo }</td> <td>{ p2_win_percent }%</td> <td>{ p2_total_wins }</td> <td>{ p2_total_points }</td> <td>{ p2_lose_by > 0 ? p2_lose_by : 'N/A' }</td> </tr> </tbody> </table> ) } render() { return (<div> { this.calculateStats() } </div>); } } export default Statistics;<file_sep>import { UserTypes } from './actionTypes'; function baseUrl() { return process.env.REACT_APP_PROXY_URL + process.env.REACT_APP_BASE_URL; } export function addUser(userToAdd) { return dispatch => { return fetch(baseUrl() + '/users', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(userToAdd) }) .then((response) => { return response.json(); }) .then(json => dispatch(fetchUsers())); } } export function receiveUsers(json) { return { type: UserTypes.RECEIVE_USERS, users: json.users }; } export function fetchUsers() { return dispatch => { return fetch(baseUrl() + '/users', { method: 'GET', headers: { 'Accept': 'application/json' } }) .then((response) => { return response.json(); }) .then(json => dispatch(receiveUsers(json))); }; } <file_sep>export default { scores: [], users: [] }
e3d36f7d00ea32e12a46deed9e3b2642b9162924
[ "JavaScript", "Markdown" ]
14
JavaScript
michaeldiguiseppi/dishgames.club
7b21bf9b9e6ead71c7d170135ed9ca2d877bd8a4
0853429be61514f4c43402881857a662640c1a8d
refs/heads/master
<file_sep>package lgavilanes.com.intentexplicito; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import org.w3c.dom.Text; /** * Created by DellLuis on 23/06/2015. */ public class SecondaryActivity extends Activity { @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_secondary); Bundle bundle = getIntent().getExtras(); String textoRecibido = bundle.getString(MainActivity.CLAVE_EXTRA_PASAR, "1texto por si la clave no tiene valor"); String textoRecibido2 = bundle.getString(MainActivity.CLAVE_EXTRA_PASAR2, "2texto por si la clave no tiene valor"); String resultrecibifo = bundle.getString(MainActivity.Clave_3,"4"); TextView tvDatoRecibido = (TextView) findViewById(R.id.tv_act2); tvDatoRecibido.setText(textoRecibido); TextView tvDatoRecibido2 = (TextView) findViewById(R.id.tv2_act2); tvDatoRecibido2.setText(textoRecibido2); } }
67b48f9ff27daf8942c5f3c6e09c7e361bf5e8ef
[ "Java" ]
1
Java
luis9717/IntentExplicito
67a4084f7237e7fbee0d7304042973c0e486b8a8
e53f0daa3d4497335b1340a10a48a46beb911f91
refs/heads/master
<file_sep># reactlearn react 基础知识复习 <file_sep>import React from 'react'; class List extends React.Component{ constructor(props){ super(props); this.state = { theme:true } } render(){ console.log(this.props); const { list } = this.props; const balckBtn = <button className="btn-black">black</button> const whiteBtn = <button className="btn-white">whiteBtn</button> // if (this.stat.theme === 'black'){ // return balckBtn // }else { // return whiteBtn // } return ( <div> { //列表渲染 list.map((item,index)=>{ return (<div key={item.id}>{index}{item.id}{item.name}</div>) }) } </div> ) } componentDidMount(){ console.log("ComponentDidMount") } componentDidUpdate(prevProps){ console.log("componentDidUpdate") } componentWillUnmount(){ console.log("componentWillUnmount") } } export default List; //函数组件 function list(props) { const { list } = this.props return <ul> { list.map((item,index)=>{ return <li key={item.id}>{item.title}</li> })} </ul> }<file_sep>import React from 'react' import { BrowserRouter as Router,Switch,Route } from 'react-router-dom' import App from './App'; import TodoListDEmo from './text5' function RouterComponent() { return( <Router> <Switch> <Route exact path="/"> <App/> </Route> <Route path="/TodoListDEmo/:id"> <TodoListDEmo/> </Route> </Switch> </Router> ) } export default RouterComponent;<file_sep>import React from 'react'; import PropTypes from "prop-types" import { Link,useParams } from 'react-router-dom' class List extends React.Component { constructor(props) { super(props) } render() { const { list } = this.props; //获取 url 参数,如 '/TodoListDEmo/100' return ( <ul> {list.map((item, index) => { return <li key={item.id}>{item.title}</li> })} </ul> ) } } List.propTypes = { list: PropTypes.arrayOf(PropTypes.object).isRequired } class Input extends React.Component { constructor(props) { super(props) this.state = { value: "" } } render() { return ( <div> <input value={this.state.value} onChange={this.inputOnchage}></input> <button onClick={this.submitTitle}>提交</button> </div> ) } inputOnchage = (e) => { this.setState({ value: e.target.value }) console.log(e.target.value) // this.props.submitTitle(e.target.value); } submitTitle = (e) => { this.props.submitTitle(this.state.value); } } class Footer extends React.Component { constructor(props) { super(props) } render() { return <p>{this.props.text}</p> } componentWillUpdate(){ console.log('footer did update') } shouldComponentUpdate(nextProps, nextState){ if(nextProps.text !== this.props.text){ return true } return false } //React 默认: 父组件更新,子组件则无条件更新 //性能优化对于 react 更为重要! //SCU 一定要用吗? 需要的时候才用 } class TodoListDEmo extends React.Component { constructor(props) { super(props); this.state = { text: '底部文字', list: [ { id: "id-1", title: "标题1" }, { id: "id-2", title: "标题2" }, { id: "id-3", title: "标题3" } ] } } render() { //受控组件 console.log(this.props); return ( <div> <Input submitTitle={this.onSumbitTitle} /> <List list={this.state.list}></List> <Footer text={this.state.text}/> </div> ) } componentDidMount() { } onSumbitTitle = (title) => { this.setState({ list: [...this.state.list, { id: `id-${Date.now()}`, title }], }) } } export default TodoListDEmo;<file_sep>import {ADD_TODO} from '../actionType' let initialState = { todos: [ { id: 1, completed:false }, { id: 2, completed:false }, { id: 3, completed:false } ] } //同步action export function addTodo(id) { return { type: ADD_TODO, id } } //异步action export const addTodoAsync = text =>{ return (dispatch) =>{ //异步获取数据 setTimeout(() => { dispatch(addTodo(3)) },1000) } } export const listReducer = (state = initialState,action) => { switch (action.type) { case ADD_TODO: let todos=state.todos; todos = [ ...todos,{ id: action.id, completed: false }] return { ...state,todos } default: return state } } <file_sep>import React from 'react'; import "./text_6.css" import ReactDom from "react-dom"; class ProtalsDemo extends React.Component { constructor(props) { super(props) } render() { return ( // <div className="modal"> // {this.props.children} // </div> //使用Portal 渲染到body上 //fixed 元素要放在body 上 ,有更好的浏览器兼容性。 ReactDom.createPortal( <div className="modal"> {this.props.children} </div>,document.body ) ) } } export default ProtalsDemo;<file_sep>import React from 'react'; import PropTypes from "prop-types" const RenderPropDemo = (props) => ( <div style={{ height: '500px'}}> <p>{props.a}</p> <Mouse render={ ({x,y}) => <h1>the mouse positon is ( {x}, {y} )</h1> }></Mouse> </div> ) class Mouse extends React.Component { constructor(props) { super(props) this.state = { x:0, y:0 } } handleMouseMove = (event) => { this.setState({ x:event.clientX, y:event.clientY }) } render(){ return ( <div style={{ height: '500px'}} onMouseMove={this.handleMouseMove}> {this.props.render(this.state)} </div> ) } } Mouse.propTypes = { render: PropTypes.func.isRequired } export default RenderPropDemo;<file_sep>import React from "react" const ThemeContext = React.createContext('light'); class ThemeDemo extends React.Component { constructor(props) { super(props) this.state = { theme: 'light' } } render() { return <ThemeContext.Provider value={this.state.theme}> <Toolbar></Toolbar> <button onClick={this.changeTheme}>change Theme </button> </ThemeContext.Provider> } changeTheme = () => { this.setState({ theme: this.state.theme === 'light' ? 'dark' : 'light' }) } } function Toolbar(props) { return ( <div> <ThemeButton></ThemeButton> <ThemeLink></ThemeLink> </div> ) } class ThemeButton extends React.Component { render() { const theme = this.context return <div> <p>button theme is {theme}</p> </div> } } ThemeButton.contextType = ThemeContext //指定 contextType 读取当前 context function ThemeLink(props) { return <ThemeContext.Consumer> {value => <p> link theme is {value} </p>} </ThemeContext.Consumer> } export default ThemeDemo<file_sep>import React from 'react'; class FromDemo extends React.Component { constructor(props) { super(props); this.state = { name: 'zhangsan', info:'个人信息', city:'beijing', flag:true, gender:'male' } this.nameInputRef = React.createRef() // } render() { //受控组件 return ( <div> <p>{this.state.name}</p> <label htmlFor="inputName">姓名:</label> <input id="inputName" value={this.state.name} onChange={this.onInputChange}></input> {/* select -使用 value */} <select value={this.state.city} onChange={this.onSelectChange}> <option value="bejing">北京</option> <option value="shanghai">上海</option> <option value="shenzhen">深圳</option> </select> <p>{this.state.city}</p> {/* 非受控组件 */} <input defaultValue={this.state.name} ref={this.nameInputRef}></input> <span>state.name:{this.state.name}</span> <br/> <button onClick={this.alertName}>alertName</button> </div> ) } onInputChange = (e) => { this.setState({ name: e.target.value }) } onSelectChange = (e) => { this.setState({ city: e.target.value }) } alertName = () => { const elem = this.nameInputRef.current alert(elem.value) } } export default FromDemo;
34286c6133cb38fe8cb5987d0a09ce3b036ac34e
[ "Markdown", "JavaScript" ]
9
Markdown
museL/reactlearn
5ab9a43d787b50c807101f44beecb0c13a9f6f38
013cc5e76c1c11adb8cf5dadd6292e1dba1dbe2c
refs/heads/master
<repo_name>mikedanylov/opening-hours-api<file_sep>/models.py SECONDS_PER_HOUR = 3600 SECONDS_PER_DAY = 86400 class DayOfWeek: DAY_OPTIONS = ('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday',) def __init__(self, day_of_week_name: str): assert day_of_week_name in self.DAY_OPTIONS self.name = day_of_week_name self.index = self.DAY_OPTIONS.index(day_of_week_name) def __str__(self): return self.name.title() class OpenHoursEvent: EVENT_TYPE_CLOSE = 'close' EVENT_TYPE_OPEN = 'open' EVENT_TYPE_OPTIONS = (EVENT_TYPE_CLOSE, EVENT_TYPE_OPEN,) def __init__(self, day_of_week_name: str, event_type: str, event_time: int): self.day_of_week = DayOfWeek(day_of_week_name) assert event_type in self.EVENT_TYPE_OPTIONS self.event_type = event_type assert 0 <= event_time < SECONDS_PER_DAY self.event_time = event_time def __str__(self): hours = self.event_time // SECONDS_PER_HOUR return (f'{hours} AM' if hours < 12 else f'{hours if hours % 12 == 0 else hours % 12} PM') <file_sep>/utils_tests.py import unittest from models import OpenHoursEvent from utils import (flatten_opening_hours_data, sort_events_by_day_and_time, push_back_first_closing_event, ) class TestFlattenOpeningHoursData(unittest.TestCase): def test_no_data_input(self): self.assertEqual(flatten_opening_hours_data(None), []) def test_single_opening_event(self): data = {'tuesday': [{'type': 'close', 'value': 36000}]} self.assertRaises(ValueError, flatten_opening_hours_data, data) def test_correct_output_type(self): data = { 'tuesday': [ {'type': 'open', 'value': 36000}, {'type': 'close', 'value': 64800} ], 'thursday': [ {'type': 'open', 'value': 46000}, {'type': 'close', 'value': 54800} ] } events = flatten_opening_hours_data(data) self.assertEqual(len(events), 4) self.assertEqual(events[0].event_type, OpenHoursEvent.EVENT_TYPE_OPEN) self.assertEqual(events[0].event_time, 36000) self.assertEqual(events[0].day_of_week.name, 'tuesday') self.assertEqual(events[0].day_of_week.index, 1) self.assertEqual(events[2].event_type, OpenHoursEvent.EVENT_TYPE_OPEN) self.assertEqual(events[2].event_time, 46000) self.assertEqual(events[2].day_of_week.name, 'thursday') self.assertEqual(events[2].day_of_week.index, 3) class TestSortEventsByDayAndTime(unittest.TestCase): def test_no_data_input(self): self.assertEqual(sort_events_by_day_and_time(None), []) def test_sorted_by_day(self): items = [ {'day': 'friday', 'type': 'open', 'value': 36000}, {'day': 'friday', 'type': 'close', 'value': 64800}, {'day': 'tuesday', 'type': 'open', 'value': 36000}, {'day': 'tuesday', 'type': 'close', 'value': 64800}, {'day': 'monday', 'type': 'open', 'value': 36000}, {'day': 'monday', 'type': 'close', 'value': 64800}, ] events = [OpenHoursEvent(item['day'], item['type'], item['value']) for item in items] sorted_events = sort_events_by_day_and_time(events) self.assertEqual(sorted_events[0].day_of_week.name, 'monday') self.assertEqual(sorted_events[2].day_of_week.name, 'tuesday') self.assertEqual(sorted_events[4].day_of_week.name, 'friday') def test_sorted_by_time(self): items = [ {'day': 'friday', 'type': 'open', 'value': 36000}, {'day': 'friday', 'type': 'close', 'value': 76000}, {'day': 'friday', 'type': 'open', 'value': 56000}, {'day': 'friday', 'type': 'close', 'value': 46000} ] events = [OpenHoursEvent(item['day'], item['type'], item['value']) for item in items] sorted_events = sort_events_by_day_and_time(events) self.assertEqual(sorted_events[0].event_time, 36000) self.assertEqual(sorted_events[1].event_time, 46000) self.assertEqual(sorted_events[2].event_time, 56000) self.assertEqual(sorted_events[3].event_time, 76000) class TestPushBackFirstClosingEvent(unittest.TestCase): def test_no_data_input(self): self.assertEqual(push_back_first_closing_event(None), []) def test_first_event_type_close(self): items = [ {'day': 'sunday', 'type': 'close', 'value': 3600}, {'day': 'tuesday', 'type': 'open', 'value': 36000}, {'day': 'tuesday', 'type': 'close', 'value': 64800}, {'day': 'saturday', 'type': 'open', 'value': 44800}, ] events = [OpenHoursEvent(item['day'], item['type'], item['value']) for item in items] events_normalized = push_back_first_closing_event(events) self.assertEqual(events_normalized[0].day_of_week.name, 'tuesday') self.assertEqual(events_normalized[-1].day_of_week.name, 'sunday') def test_first_event_not_type_close(self): items = [ {'day': 'tuesday', 'type': 'open', 'value': 36000}, {'day': 'tuesday', 'type': 'close', 'value': 64800}, {'day': 'saturday', 'type': 'open', 'value': 36000}, {'day': 'saturday', 'type': 'close', 'value': 64800}, ] events = [OpenHoursEvent(item['day'], item['type'], item['value']) for item in items] events_normalized = push_back_first_closing_event(events) self.assertEqual(events_normalized[0].day_of_week.name, 'tuesday') self.assertEqual(events_normalized[-1].day_of_week.name, 'saturday') <file_sep>/utils.py from typing import List from models import OpenHoursEvent def flatten_opening_hours_data(data: dict) -> List[OpenHoursEvent]: """Flatten nested opening hours data and sort by day of week and time """ if not data: return [] week_opening_hours_events = [] for day_of_week in data.keys(): week_opening_hours_events += [ OpenHoursEvent(day_of_week, event['type'], event['value']) for event in data[day_of_week] ] if len(week_opening_hours_events) % 2 != 0: raise ValueError('Number of events should be even') return week_opening_hours_events def sort_events_by_day_and_time(events: List[OpenHoursEvent]) -> List[OpenHoursEvent]: """Sort opening event by day of week and time in ascending order """ if not events: return [] return sorted(events, key=lambda event: (event.day_of_week.index, event.event_time)) def push_back_first_closing_event(events: List[OpenHoursEvent]) -> List[OpenHoursEvent]: """Check if the first opening hours event during the week is closing event, pop it from the beginning and push to the end of events list """ if not events: return [] if (len(events) > 1 and events[0].event_type == OpenHoursEvent.EVENT_TYPE_CLOSE): return events[1:] + [events[0]] return events <file_sep>/handler_tests.py import json import unittest from handler import get_opening_hours class TestLambdaHandler(unittest.TestCase): def test_serialization_error_response(self): data = { 'thursday': [ {'type': 'reopen', 'value': 36000}, {'type': 'close', 'value': 64800} ], 'friday': [ {'type': 'open', 'value': 136000} ], 'saturday': [ {'type': 'close', 'value': 3600} ] } response = get_opening_hours(data, None) res_json = json.loads(response['body']) self.assertEqual(response['statusCode'], 400) self.assertEqual(res_json['error']['thursday']['0']['type'][0], 'Invalid opening hours event type') self.assertEqual(res_json['error']['friday']['0']['value'][0], 'Invalid opening hours event time') def test_data_flattening_error_response(self): data = { 'thursday': [ {'type': 'open', 'value': 36000}, {'type': 'close', 'value': 64800} ], 'friday': [ {'type': 'open', 'value': 36000} ] } response = get_opening_hours(data, None) res_json = json.loads(response['body']) self.assertEqual(response['statusCode'], 400) self.assertEqual(res_json['error'], 'Number of events should be even') def test_successful_response(self): data = { 'monday': [], 'tuesday': [ {'type': 'open', 'value': 36000}, {'type': 'close', 'value': 64800} ], 'wednesday': [], 'thursday': [ {'type': 'open', 'value': 36000}, {'type': 'close', 'value': 64800} ], 'friday': [ {'type': 'open', 'value': 36000} ], 'saturday': [ {'type': 'close', 'value': 3600}, {'type': 'open', 'value': 36000} ], 'sunday': [ {'type': 'close', 'value': 3600}, {'type': 'open', 'value': 43200}, {'type': 'close', 'value': 75600} ] } response = get_opening_hours(data, None) res_json = json.loads(response['body']) self.assertEqual(response['statusCode'], 200) self.assertTrue('Monday: Closed\n' in res_json['opening_hours']) self.assertTrue('Tuesday: 10 AM - 6 PM\n' in res_json['opening_hours']) self.assertTrue('Wednesday: Closed\n' in res_json['opening_hours']) self.assertTrue('Thursday: 10 AM - 6 PM\n' in res_json['opening_hours']) self.assertTrue('Friday: 10 AM - 1 AM\n' in res_json['opening_hours']) self.assertTrue('Saturday: 10 AM - 1 AM\n' in res_json['opening_hours']) self.assertTrue('Sunday: 12 PM - 9 PM\n' in res_json['opening_hours']) def test_complex_payload(self): data = { 'monday': [ {'type': 'open', 'value': 32400}, {'type': 'close', 'value': 39600}, {'type': 'open', 'value': 46800}, {'type': 'close', 'value': 61200} ], 'friday': [ {'type': 'open', 'value': 64800} ], 'saturday': [ {'type': 'close', 'value': 3600}, {'type': 'open', 'value': 32400}, {'type': 'close', 'value': 39600}, {'type': 'open', 'value': 57600}, {'type': 'close', 'value': 82800} ] } response = get_opening_hours(data, None) res_json = json.loads(response['body']) self.assertEqual(response['statusCode'], 200) self.assertTrue('Monday: 9 AM - 11 AM, 1 PM - 5 PM\n' in res_json[ 'opening_hours']) self.assertTrue('Friday: 6 PM - 1 AM\n' in res_json['opening_hours']) self.assertTrue( 'Saturday: 9 AM - 11 AM, 4 PM - 11 PM\n' in res_json['opening_hours']) <file_sep>/serializers.py from marshmallow import fields, Schema, ValidationError from models import SECONDS_PER_DAY, OpenHoursEvent def validate_type(type: str): if type not in OpenHoursEvent.EVENT_TYPE_OPTIONS: raise ValidationError('Invalid opening hours event type') def validate_time(time: int): if not (0 <= time < SECONDS_PER_DAY): raise ValidationError('Invalid opening hours event time') class OpenHoursEventSerializer(Schema): type = fields.String(required=True, validate=validate_type) value = fields.Integer(required=True, validate=validate_time) class OpenHoursSerializer(Schema): monday = fields.Nested(OpenHoursEventSerializer, many=True, required=False) tuesday = fields.Nested(OpenHoursEventSerializer, many=True, required=False) wednesday = fields.Nested(OpenHoursEventSerializer, many=True, required=False) thursday = fields.Nested(OpenHoursEventSerializer, many=True, required=False) friday = fields.Nested(OpenHoursEventSerializer, many=True, required=False) saturday = fields.Nested(OpenHoursEventSerializer, many=True, required=False) sunday = fields.Nested(OpenHoursEventSerializer, many=True, required=False) <file_sep>/serializers_tests.py import unittest from marshmallow import ValidationError from serializers import OpenHoursSerializer class TestSerializers(unittest.TestCase): def test_type_not_provided(self): data = { 'tuesday': [ {'type': 'open', 'value': 36000}, {'value': 64800} ] } serializer = OpenHoursSerializer(strict=True) self.assertRaises(ValidationError, serializer.load, data) def test_type_not_string(self): data = { 'tuesday': [ {'type': 'open', 'value': 36000}, {'type': 123, 'value': 64800} ] } serializer = OpenHoursSerializer(strict=True) self.assertRaises(ValidationError, serializer.load, data) def test_value_not_provided(self): data = { 'tuesday': [ {'type': 'open'}, {'type': 'close', 'value': 64800} ] } serializer = OpenHoursSerializer(strict=True) self.assertRaises(ValidationError, serializer.load, data) def test_value_not_integer(self): data = { 'tuesday': [ {'type': 'open', 'value': '!'}, {'type': 'close', 'value': 64800} ] } serializer = OpenHoursSerializer(strict=True) self.assertRaises(ValidationError, serializer.load, data) def test_invalid_type(self): data = { 'tuesday': [ {'type': 'reopen', 'value': 36000}, {'type': 'close', 'value': 64800} ] } serializer = OpenHoursSerializer(strict=True) self.assertRaises(ValidationError, serializer.load, data) def test_invalid_value(self): data = { 'tuesday': [ {'type': 'reopen', 'value': 36000}, {'type': 'close', 'value': 164800} ] } serializer = OpenHoursSerializer(strict=True) self.assertRaises(ValidationError, serializer.load, data) <file_sep>/handler.py import json import logging from marshmallow import ValidationError from models import OpenHoursEvent, DayOfWeek from serializers import OpenHoursSerializer from utils import (flatten_opening_hours_data, sort_events_by_day_and_time, push_back_first_closing_event, ) logger = logging.getLogger() logger.setLevel(logging.INFO) def get_opening_hours(event, context): logger.info(f'event payload: {event}') request_payload = event if 'body' in event: request_payload = json.loads(event['body']) try: serialized_data = OpenHoursSerializer(strict=True).load(request_payload).data except ValidationError as e: return make_response({'error': e.messages}, 400) try: flattened_events = flatten_opening_hours_data(serialized_data) except ValueError as e: return make_response({'error': str(e)}, 400) sorted_events = sort_events_by_day_and_time(flattened_events) normalized_events = push_back_first_closing_event(sorted_events) opening_events = [event for event in normalized_events if event.event_type == OpenHoursEvent.EVENT_TYPE_OPEN] closing_events = [event for event in normalized_events if event.event_type == OpenHoursEvent.EVENT_TYPE_CLOSE] if len(opening_events) != len(closing_events): return make_response( {'error': 'Number of opening and closing events should be equal'}, 400) day_groups = {} for day in DayOfWeek.DAY_OPTIONS: day_groups[day] = [] for open_event, close_event in zip(opening_events, closing_events): day_groups[open_event.day_of_week.name].append((open_event, close_event,)) output = '' for day in day_groups.keys(): output += f'{day.title()}: ' if len(day_groups[day]) == 0: output += 'Closed\n' else: time_intervals = [f'{open_event} - {close_event}' for open_event, close_event in day_groups[day]] output += ', '.join(time_intervals) output += '\n' return make_response({'opening_hours': output}, 200) def make_response(response_body, status_code=200): response_headers = {'content-type': 'application/json'} return { 'statusCode': status_code, 'headers': response_headers, 'body': json.dumps(response_body) } <file_sep>/README.md # opening-hours-api Single end-point to convert json payload of opening hours to a more human readable format. Function is deployed to AWS Lambda and can be invoked with a http client. Here is a `curl` example: ```bash [mikedanylov@t470p opening-hours-api]$ curl -v -X POST \ > 'https://fen95154l0.execute-api.us-east-1.amazonaws.com/dev/opening-hours' \ > -H 'content-type: application/json' \ > -d '{ > "monday": [], > "tuesday": [ > {"type": "open", "value": 36000 }, > {"type": "close", "value": 64800} > ], > "wednesday": [], > "thursday": [ > {"type": "open", "value": 36000}, > {"type": "close", "value": 64800} > ], > "friday": [ > {"type": "open", "value": 36000} > ], > "saturday": [ > {"type": "close", "value": 3600}, > {"type": "open", "value": 36000} > ], > "sunday": [ > {"type": "close", "value": 3600}, > {"type": "open", "value": 43200}, > {"type": "close", "value": 75600} > ] > }' ``` The example above will produce the following response: ```bash {"opening_hours": "Monday: Closed\nTuesday: 10 AM - 6 PM\nWednesday: Closed\nThursday: 10 AM - 6 PM\nFriday: 10 AM - 1 AM\nSaturday: 10 AM - 1 AM\nSunday: 12 PM - 9 PM\n"} ``` Regarding the data structure(DT) of the payload, I think it depends on the context and there is probably a larger context which should be considered beyond this single end-point. However, if we concentrate on this particular problem at hand, first incremental change that could help is to make the data structure more flat. For example, instead of providing a dictionary with days of the week as keys we could transform the payload to contain an array of items which represent single open/close events in time and add the day of the week name to new event DT. Let's modify the initial payload structure accordingly: ```python payload = [ {"day_of_week": 1, "day_of_week_name": "tuesday", "type": "open", "value": 36000 }, {"day_of_week": 1, "day_of_week_name": "tuesday", "type": "close", "value": 64800}, {"day_of_week": 3, "day_of_week_name": "thursday", "type": "open", "value": 36000}, {"day_of_week": 3, "day_of_week_name": "thursday", "type": "close", "value": 64800}, {"day_of_week": 4, "day_of_week_name": "friday", "type": "open", "value": 36000}, {"day_of_week": 5, "day_of_week_name": "saturday", "type": "close", "value": 3600}, {"day_of_week": 5, "day_of_week_name": "saturday", "type": "open", "value": 36000}, {"day_of_week": 6, "day_of_week_name": "sunday", "type": "close", "value": 3600}, {"day_of_week": 6, "day_of_week_name": "sunday", "type": "open", "value": 43200}, {"day_of_week": 6, "day_of_week_name": "sunday", "type": "close", "value": 75600} ] ``` From the example above `day_of_week` is the day position in the week which can allow to extend the service later if the `day_of_week` value should change based on locale. As for new field `day_of_week_name` it could be used as a key for localization of days of the week. Thus, using this DT it is possible by examining single object to derive what happened and when. Also, it is easier to do further transformations with filter, map, reduce etc. The second update is related more to the domain of the problem. Do we really need to store each open/close event separately or maybe the only thing that matters is when the event occurred and for how long it continued? There is one small complication in the current implementation when `open` event happens on one day and `close` on the following day. To solve this problem required some sorting and checking that each `open` event has corresponding `close` event. What if we structure data as intervals in time instead? Let's try to modify the `payload` again. ```python payload = [ { "day_of_week": 1, "day_of_week_name": "tuesday", "start_time": 36000, "duration": 28800 }, { "day_of_week": 3, "day_of_week_name": "thursday", "start_time": 36000, "duration": 28800 }, { "day_of_week": 4, "day_of_week_name": "friday", "start_time": 36000, "duration": 46800 }, { "day_of_week": 5, "day_of_week_name": "saturday", "start_time": 36000, "duration": 46800 }, { "day_of_week": 6, "day_of_week_name": "sunday", "start_time": 43200, "duration": 32400 } ] ``` Thus, this DT could be easier to work with and transform because it has all the properties of the original payload meaning that we can still easily find start/close time for any opening hours interval. Also, `type` was removed since each interval already represents the start of opening hours. In addition, structuring data this way could be less error prone because it requires less transformations to achieve more human readable result.
7d7798ea7524b5199b4f212752364d0f02e7b43e
[ "Markdown", "Python" ]
8
Python
mikedanylov/opening-hours-api
b4167c577ae8aa7a278e120bea9e5cd361b377d7
8b4ee1c3243b81225c6636fdf64da11608c12e96
refs/heads/main
<repo_name>thedarkzeno/spotify-mobile<file_sep>/src/Store/index.js import { createStore } from "redux"; const INITIAL_STATE = { results: {}, refresh: false, token: "", filters: {}, applyFilters: {}, query: "", }; function reducer(state = INITIAL_STATE, action) { if (action.type === "Set_Results") { return { ...state, results: action.value }; } if (action.type === "Set_Refresh") { return { ...state, refresh: action.value }; } if (action.type === "Set_Token") { return { ...state, token: action.value }; } if (action.type === "Set_Filters") { return { ...state, filters: action.value }; } if (action.type === "Set_ApplyFilters") { return { ...state, applyFilters: action.value }; } if (action.type === "Set_Query") { return { ...state, query: action.value }; } return state; } const store = createStore(reducer); export default store;<file_sep>/src/Screens/Home/index.js import React from "react"; import { StyleSheet, ImageBackground, View, Dimensions } from "react-native"; import background from "../../Assets/wallpaper.png"; import Search from "../../Components/Search"; import Results from "../../Components/Results"; const d = Dimensions.get("screen"); const Home = ({ navigation }) => { return ( <View style={styles.container}> <ImageBackground source={background} style={styles.backgroundImage}> <Search navigation={navigation} /> <Results /> {/* <Button title="logout" onPress={()=>navigation.navigate("Logout")}/> */} </ImageBackground> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", }, backgroundImage: { flex: 1, width: d.width, height: d.height, alignItems: "center", justifyContent: "center", }, }); export default Home; <file_sep>/src/Screens/Logout.js import React, { useEffect } from "react"; import { useDispatch } from "react-redux"; import { SetToken } from "../Store/actions"; const Logout = ({ navigation }) => { const dispatch = useDispatch(); useEffect(() => { dispatch(SetToken("")); navigation.navigate("Home"); }, []); return <></>; }; export default Logout; <file_sep>/src/Services/auth.js import AsyncStorage from "@react-native-async-storage/async-storage"; const TOKEN_KEY = "SPOTIFY"; export const getToken = async () => await AsyncStorage.getItem(TOKEN_KEY + "_Token"); export const isAuthenticated = async () => { try { const token = await getToken(); if (!token) { return false; } else { return true; } } catch (error) { console.log("error isAuthenticated"); return false; } }; export const login = async (token) => { await AsyncStorage.setItem(TOKEN_KEY + "_Token", token); }; export const logout = async () => { await AsyncStorage.removeItem(TOKEN_KEY + "_Token"); }; <file_sep>/src/Components/Results/index.js import React, { useState, useEffect } from "react"; import { useSelector } from "react-redux"; import { ScrollView, View, Text, StyleSheet, Image, TouchableOpacity, } from "react-native"; const Results = () => { const ReduxState = useSelector((state) => state); const [tracks, setTracks] = useState([]); useEffect(() => { if (ReduxState.results.playlists) { setTracks(ReduxState.results.playlists.items); } }, [ReduxState]); if (tracks.length > 0) { return ( <ScrollView style={styles.container}> <View style={{ padding: 10, paddingTop: 30 }}> <Text style={styles.title}>{ReduxState.results.message}</Text> {ReduxState.results.playlists && tracks.map((item, index) => ReduxState.query === "" ? ( <View style={styles.card} key={`${item.name} - ${index}`}> <Image source={{ uri: item.images[0].url }} style={styles.image} /> <Text style={styles.text}>{`${item.name}`}</Text> </View> ) : ( item.name .toLowerCase() .includes(ReduxState.query.toLowerCase()) && ( <View style={styles.card} key={`${item.name} - ${index}`}> <Image source={{ uri: item.images[0].url }} style={styles.image} /> <Text style={styles.text}>{`${item.name}`}</Text> </View> ) ) )} </View> </ScrollView> ); } return null; }; const styles = StyleSheet.create({ container: { position: "absolute", top: 100, width: "50%", minWidth: 300, height: "70%", backgroundColor: "#fff", }, title: { justifyContent: "center", alignItems: "center", textAlign: "center", fontWeight: "bold", fontSize: 24, margin: "auto", marginBottom: 20, }, image: { width: 128, height: 128, }, card: { flex: 1, flexDirection: "row", marginBottom: 2, justifyContent: "center", alignItems: "center", }, text: { flex: 1, flexWrap: "wrap", marginLeft: 10, }, }); export default Results; <file_sep>/README.md # SPOTIFY MOBILE <p align="center"> <a href="https://github.com/thedarkzeno"> <img src="https://img.shields.io/badge/Author-thedarkzeno-brightgreen" alt="Author" /> </a> <img src="http://img.shields.io/static/v1?label=License&message=MIT&color=green"/> </p> > Search by playlists with a simple interface <p align="center"><img src="./screenshots/1.jpeg"/></p> <p align="center"><img src="./screenshots/2.jpeg"/></p> <p align="center"><img src="./screenshots/3.jpeg"/></p> ## Summary - [Overview ](#eyes-overview) - [Pre requisites](#warning-pre-requisites) - [How to run](#construction_worker-how-to-run) - [Dependencies](#books-dependecies) - [License](#license) ## :eyes: Overview <p align="justify"> With Spotify-MOBILE you can search for spotify playlists. </p> ## :warning: Pre requisites - [Node](https://nodejs.org/en/download/) ## :construction_worker: How to run: First, you need a valid client id of the [spotify](https://www.spotify.com/), you can create one [here](https://developer.spotify.com/dashboard/applications). Clone the project from github: ```shell git clone https://github.com/thedarkzeno/spotify-mobile cd spotify-mobile ``` Change de CLIENT ID inside the file `config.js` ```shell yarn # or npm i ``` Start the application: ```shell expo start ``` ## :books: Dependencies - [React Natine](https://reactnative.dev/docs/getting-started) - [Expo](https://docs.expo.io/) - [React Navigation](https://reactnavigation.org/docs/getting-started) - [Redux](https://redux.js.org/) - [Axios](https://github.com/axios/axios) ## License The [MIT License]() (MIT) --- <p align="center"> Made with :heart: by <a href="https://www.linkedin.com/in/adalberto-junior-62618a176/">Adalberto</a> </p> <file_sep>/src/Routes.js import React, { useState, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { StatusBar } from "react-native"; import { NavigationContainer } from "@react-navigation/native"; import { createStackNavigator } from "@react-navigation/stack"; import { isAuthenticated } from "./Services/auth"; import Login from "./Screens/Login"; import Home from "./Screens/Home"; import Config from "./Screens/Config"; import Logout from "./Screens/Logout"; const Stack = createStackNavigator(); function Routes() { const ReduxState = useSelector((state) => state); const Dispatch = useDispatch(); const [auth, setAuth] = useState(false); useEffect(() => { isAuthenticated().then((res) => { if (ReduxState.refresh === true) { Dispatch(SetRefresh(false)); } }); }, [ReduxState.refresh, Dispatch]); if (ReduxState.token !== "") { return ( <NavigationContainer> <Stack.Navigator screenOptions={{ headerShown: false, }} > <Stack.Screen name="Home" component={Home} /> <Stack.Screen name="Config" component={Config} /> <Stack.Screen name="Logout" component={Logout} /> </Stack.Navigator> <StatusBar /> </NavigationContainer> ); } return ( <NavigationContainer> <Stack.Navigator screenOptions={{ headerShown: false, }} > <Stack.Screen name="Home" component={Login} /> </Stack.Navigator> <StatusBar /> </NavigationContainer> ); } export default Routes;
fdced29816bfd586ed7b7fbe39b860adbeaf6a4b
[ "JavaScript", "Markdown" ]
7
JavaScript
thedarkzeno/spotify-mobile
9032c3e87269e272b47e8440bf94d7ac3bd521a5
4c144befbd1344004169e4464cba06c332ff43ed
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Http; // for session using Microsoft.AspNetCore.Identity; // for password hashing using BankAccounts.Models; namespace BankAccounts.Controllers { public class HomeController : Controller { private BAContext dbContext; public HomeController(BAContext context) { dbContext = context; } // ROUTE: METHOD: VIEW: // ----------------------------------------------------------------------------------- // GET("") Index() Index.cshtml // POST("/register") Create(User user) ------ (Index.cshtml to display errors) // POST("/login") Login(LoginUser user) ------ (Index.cshtml to display errors) // GET("/logout") Logout() ------ // GET("/success") Success() Success.cshtml [HttpGet("")] public IActionResult Index() { //List<User> AllUsers = dbContext.Users.ToList(); return View(); } [HttpPost("/register")] public IActionResult Create(User user) { if (ModelState.IsValid) { // If a User exists with provided email if (dbContext.Users.Any(u => u.Email == user.Email)) { // Manually add a ModelState error to the Email field ModelState.AddModelError("Email", "Email already in use!"); return View("Index"); } // hash password PasswordHasher<User> Hasher = new PasswordHasher<User>(); user.Password = Hasher.HashPassword(user, user.Password); // create user dbContext.Add(user); dbContext.SaveChanges(); // sign user into session var NewUser = dbContext.Users.FirstOrDefault(u => u.Email == user.Email); int UserId = NewUser.UserId; HttpContext.Session.SetInt32("UserId", UserId); // go to success return RedirectToAction("Account"); } // display errors else { return View("Index"); } } [HttpPost("/login")] public IActionResult Login(LoginUser user) { if (ModelState.IsValid) { var userInDb = dbContext.Users.FirstOrDefault(u => u.Email == user.LoginEmail); if (userInDb == null) { // Add an error to ModelState and return to View! ModelState.AddModelError("LoginEmail", "Invalid Email/Password"); return View("Index"); } // Initialize hasher object var hasher = new PasswordHasher<LoginUser>(); // verify provided password against hash stored in db var result = hasher.VerifyHashedPassword(user, userInDb.Password, user.LoginPassword); if (result == 0) { // handle failure (this should be similar to how "existing email" is handled) ModelState.AddModelError("LoginPassword", "Password is invalid."); return View("Index"); } // sign user into session int UserId = userInDb.UserId; HttpContext.Session.SetInt32("UserId", UserId); return RedirectToAction("Account"); } // display errors else { return View("Index"); } } [HttpGet("/logout")] public IActionResult Logout() { HttpContext.Session.Clear(); return RedirectToAction("Index"); } [HttpGet("success")] public IActionResult Success() { int? userId = HttpContext.Session.GetInt32("UserId"); if (userId == null) { return RedirectToAction("Index"); } return View(); } [HttpGet("/account")] public IActionResult Account() { ViewBag.ErrorMessage = ""; int? userId = HttpContext.Session.GetInt32("UserId"); if (userId == null) { return RedirectToAction("Index"); } int uId = userId ?? default(int); User user = dbContext.Users .Include(u => u.CreatedTransactions) .FirstOrDefault(u => u.UserId == uId); return View("Account", user); } [HttpPost("/account")] public IActionResult UpdateAccount() { int? userId = HttpContext.Session.GetInt32("UserId"); int uId = userId ?? default(int); User user = dbContext.Users .Include(u => u.CreatedTransactions) .FirstOrDefault(u => u.UserId == uId); if (Request.Form["Amount"] == "") { ViewBag.ErrorMessage = "Invalid submission. Please enter a valid amount."; return View("Account", user); } decimal amount = Convert.ToDecimal(Request.Form["Amount"]); if (user.Balance + amount < 0) { ViewBag.ErrorMessage = "Insufficient funds for this transaction."; return View("Account", user); } Transaction transaction = new Transaction() { Amount = amount, UserId = user.UserId }; ViewBag.ErrorMessage = ""; dbContext.Add(transaction); dbContext.SaveChanges(); user.Balance += amount; user.UpdatedAt = DateTime.Now; dbContext.SaveChanges(); return RedirectToAction("Account"); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
fbd2c5c07c85a2a80ae64b9f164cd052039bb093
[ "C#" ]
1
C#
John-W-Stevens/ASP.NET-BankAccounts
7c02e4e6849bb2c8472dfbe48203fb976ccd6fbf
e2388b77ba9129a1c33861f04a28e1b9ceb9f824
refs/heads/main
<file_sep>import React, { useEffect, useState } from "react"; import fakeData from "../../assets/fakeData"; import { getDatabaseCart, processOrder, removeFromDatabaseCart, } from "../../assets/utilities/databaseManager"; import Cart from "../cart/Cart"; import ReviewItem from "../reviewItems/ReviewItem"; import orderConfirmed from "../../assets/images/giphy.gif"; const Review = () => { const [cart, setCart] = useState([]); const [orderPlaced, setOrderPlaced] = useState(false); // Syncing cart state with database useEffect(() => { // Getting cart items from local storage const cartItems = getDatabaseCart(); const cartItemKeys = Object.keys(cartItems); // Add new "quantity" property to product object const cartProducts = cartItemKeys.map((key) => { const product = fakeData.find((items) => items.key === key); product.quantity = cartItems[key]; return product; }); setCart(cartProducts); }, []); // Removing Cart Items from the local storage and updating Cart const removeCartItem = (key) => { const newCartItems = cart.filter((cartItem) => cartItem.key !== key); setCart(newCartItems); removeFromDatabaseCart(key); }; // Cleaning Data base after order placement const placeOrder = () => { setCart([]); setOrderPlaced(true); processOrder(); }; return ( <div className="container"> <section className="product-container"> {cart.map((items) => ( <ReviewItem key={items.key} product={items} removeCartItem={removeCartItem} ></ReviewItem> ))} {orderPlaced && ( <img src={orderConfirmed} alt="Order is confirmed"></img> )} </section> <aside className="cart-container"> <Cart cart={cart}> <button className="button" onClick={placeOrder}> Place Order </button> </Cart> </aside> </div> ); }; export default Review; <file_sep>import React from "react"; const ReviewItem = (props) => { const { name, quantity, key, price } = props.product; const reviewItemsStyle = { margin: "1rem", }; return ( <div style={reviewItemsStyle}> <h1>{name}</h1> <p>Quantity: {quantity}</p> <p>Single Item Price: {price}</p> <p> Total Item Price: {quantity} X ${price} = {quantity * price} </p> <button className="button" onClick={() => props.removeCartItem(key)}> Remove Items </button> </div> ); }; export default ReviewItem; <file_sep>import React, { useEffect, useState } from "react"; import fakeData from "../../assets/fakeData"; import "./Shop.css"; import Product from "../product/Product"; import Cart from "../cart/Cart"; import { addToDatabaseCart, getDatabaseCart, } from "../../assets/utilities/databaseManager"; import { NavLink } from "react-router-dom"; const Shop = () => { const productArr = fakeData.slice(0, 10); const [product, setProduct] = useState(productArr); const [cart, setCart] = useState([]); // Syncing cart sate with database useEffect(() => { // Getting data from the database const cartItems = getDatabaseCart(); const cartItemsKey = Object.keys(cartItems); // Adding quantity property to product item const cartProducts = cartItemsKey.map((key) => { const product = fakeData.find((items) => items.key === key); product.quantity = cartItems[key]; return product; }); setCart(cartProducts); }, []); const addToCart = (product) => { let productCount = 1; let newCart; // Checking if the product added in the cart already exists const productAlreadyExist = cart.find((item) => item.key === product.key); // Increasing product quantity with each when the product already found if (productAlreadyExist) { productCount = productAlreadyExist.quantity + 1; productAlreadyExist.quantity = productCount; const otherProduct = cart.filter( (items) => items.key !== productAlreadyExist.key ); newCart = [...otherProduct, productAlreadyExist]; } else { product.quantity = 1; newCart = [...cart, product]; } // Updating the cart and saving it to database setCart(newCart); addToDatabaseCart(product.key, productCount); }; return ( <main className="container"> <section className="product-container"> {product.map((item) => ( <Product key={item.key} items={item} showAddToCartBtn={true} addToCart={addToCart} ></Product> ))} </section> <aside className="cart-container"> <Cart cart={cart}> <NavLink to="/order-review"> <button className="button">Review Order</button> </NavLink> </Cart> </aside> </main> ); }; export default Shop; <file_sep>import React from "react"; import "./Header.css"; import logo from "../../assets/images/logo.png"; const Header = () => { return ( <header> <div className="logo_container"> <img src={logo} alt="ema john ecommerce logo"></img> </div> <div> <nav className="nav_container"> <a href="/shop">Shop</a> <a href="/order-review">Order Review</a> <a href="/inventory">Manage Inventory</a> </nav> </div> </header> ); }; export default Header; <file_sep>import React from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faCartPlus } from "@fortawesome/free-solid-svg-icons"; import "./Product.css"; import { Link } from "react-router-dom"; const Product = (props) => { const { img, name, seller, price, stock, key } = props.items; return ( <div className="products"> <div className="product-image"> <img src={img} alt="Product Images"></img> </div> <div className="product-details"> <h1> <Link to={"/product/" + key}>{name}</Link> </h1> <p> <small>by: {seller}</small> </p> <p> Price: <strong>${price}</strong> </p> <p> <small> Only <strong>{stock}</strong> piece available. Order soon. </small> </p> {props.showAddToCartBtn === true && ( <button className="button" onClick={() => props.addToCart(props.items)} > <FontAwesomeIcon icon={faCartPlus} /> <b> Add to Cart</b> </button> )} </div> </div> ); }; export default Product;
0383fe375fb2e930b1a8f51f55335d933dbf7cf6
[ "JavaScript" ]
5
JavaScript
promisingd1/simple-reactbased-ecommerce-app
dce5fc80865774d98ad186f866fdcdb6366a274c
ea3d68d3d120247bf8e94cd86d600a8d0b2d6881
refs/heads/master
<file_sep>package com.sdnawang.edaixi_copy.util; import android.content.Context; import android.graphics.Point; import android.os.Build; import android.view.WindowManager; /** * Created by android on 2016/2/16. */ public class ScreenUtil { /** * 返回屏幕宽度 * * @param context * @return */ public static int getScreenWidth(Context context) { WindowManager wm = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); Point point = new Point(); int width=0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { wm.getDefaultDisplay().getSize(point); width = point.x; }else{ width =wm.getDefaultDisplay().getWidth(); } return width; } /** * 返回屏幕高度 * @param context * @return */ public static int getScreenHeight(Context context) { WindowManager wm = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); Point point = new Point(); int height = 0; if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.HONEYCOMB_MR2){ wm.getDefaultDisplay().getSize(point); height = point.y; }else { height = wm.getDefaultDisplay().getHeight(); } return height; } } <file_sep>package com.sdnawang.systemuidemo; import android.os.Build; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.design.widget.TabLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class CoordinatorLayoutActivity extends AppCompatActivity { /** * I believe that the CoordinatorLayout works only with RecyclerView and NestedScrollView. * Try wrapping your ListView in a NestedScrollView or convert it to a RecyclerView with a LinearLayoutManager */ private ListView listView; private TabLayout tabLayout; private Toolbar toolbar; private FloatingActionButton floatingActionButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_coordinator_layout); listView = (ListView) findViewById(R.id.listview); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { listView.setNestedScrollingEnabled(true); } listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getData())); tabLayout = (TabLayout) findViewById(R.id.tablayout); tabLayout.addTab(tabLayout.newTab().setText("Title1")); tabLayout.addTab(tabLayout.newTab().setText("Title2")); tabLayout.addTab(tabLayout.newTab().setText("Title3")); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); final ActionBar ab = getSupportActionBar(); ab.setHomeAsUpIndicator(R.mipmap.ic_launcher); /* ab.setHomeAsUpIndicator(R.drawable.ic_menu);*/ ab.setDisplayHomeAsUpEnabled(true); floatingActionButton = (FloatingActionButton) findViewById(R.id.fab); floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e("--->OUT","floatingactionbutton click"); Snackbar.make(v,"Snackbar", Snackbar.LENGTH_SHORT).setAction("Action",null).show(); } }); } private List<String> getData(){ List<String> data = new ArrayList<>(); for(int i=0; i< 25; i++){ data.add("position" + i); } return data; } } <file_sep>package com.sdnawang.edaixi_copy.activity; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.OnApplyWindowInsetsListener; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPager; import android.support.v4.view.WindowInsetsCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.RadioButton; import android.widget.RadioGroup; import com.sdnawang.edaixi_copy.R; import com.sdnawang.edaixi_copy.fragment.MyFragment; import com.sdnawang.edaixi_copy.fragment.OrderFragment; import com.sdnawang.edaixi_copy.fragment.WashFragment; public class MainActivity extends AppCompatActivity { private static final int PAGER_NUM = 3; private RadioGroup radioGroup; private RadioButton wash_rb; private RadioButton order_rb; private RadioButton my_rb; private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); radioGroup = (RadioGroup) findViewById(R.id.bottom_menu_rg); wash_rb = (RadioButton) findViewById(R.id.wash_rb); order_rb = (RadioButton) findViewById(R.id.order_rb); my_rb = (RadioButton) findViewById(R.id.my_rb); viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setAdapter(new mFragmentPageAdapter(getSupportFragmentManager())); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { ((RadioButton) radioGroup.getChildAt(position)).setChecked(true); if (position == 1) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark)); } } else if (position == 2) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(getResources().getColor(android.R.color.transparent)); } } } @Override public void onPageScrollStateChanged(int state) { } }); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.wash_rb: viewPager.setCurrentItem(0); break; case R.id.order_rb: viewPager.setCurrentItem(1); break; case R.id.my_rb: viewPager.setCurrentItem(2); break; } } }); /** * 用于解决ViewPager 和 CoordinatorLayout之间存在的fitSystemWindows属性无效bug。 */ ViewCompat.setOnApplyWindowInsetsListener(viewPager, new OnApplyWindowInsetsListener() { @Override public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) { insets = ViewCompat.onApplyWindowInsets(v, insets); if (insets.isConsumed()) { return insets; } boolean consumed = false; for (int i = 0, count = viewPager.getChildCount(); i < count; i++) { ViewCompat.dispatchApplyWindowInsets(viewPager.getChildAt(i), insets); if (insets.isConsumed()) { consumed = true; } } return consumed ? insets.consumeSystemWindowInsets() : insets; } }); } class mFragmentPageAdapter extends FragmentPagerAdapter { public mFragmentPageAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0: return WashFragment.newInstance("", ""); case 1: return OrderFragment.newInstance("", ""); case 2: return MyFragment.newInstance("", ""); } return null; } @Override public int getCount() { return PAGER_NUM; } } } <file_sep>package com.sdnawang.edaixi_copy.activity; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.sdnawang.edaixi_copy.R; import com.sdnawang.edaixi_copy.util.NetConnectivityReceiver; import com.umeng.socialize.UMShareAPI; public abstract class BaseActivity extends AppCompatActivity implements NetConnectivityReceiver.OnNetConnectivityStateListener{ private NetConnectivityReceiver netReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_base); IntentFilter filter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); netReceiver = new NetConnectivityReceiver(); this.registerReceiver(netReceiver, filter); netReceiver.setOnNetStateListener(this); } /** * 友盟需要添加 * UMShareAPI.get( this ).onActivityResult( requestCode, resultCode, data); * @param requestCode * @param resultCode * @param data */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //UMShareAPI.get( this ).onActivityResult( requestCode, resultCode, data); } @Override protected void onDestroy() { this.unregisterReceiver(netReceiver); super.onDestroy(); } } <file_sep>package com.sdnawang.systemuidemo; import android.os.Build; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v4.widget.NestedScrollView; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.Menu; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class CollapsingToolbarLayoutActivity extends AppCompatActivity { private ListView listView; private Toolbar toolbar; private CollapsingToolbarLayout collapsingToolbarLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_collapsing_toolbar_layout); listView = (ListView) findViewById(R.id.listview); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { listView.setNestedScrollingEnabled(true); } listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getData())); toolbar = (Toolbar)findViewById(R.id.toolbar); toolbar.setSubtitle("subtitle"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar); collapsingToolbarLayout.setTitle(""); //collapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER); final Button button1 = (Button)findViewById(R.id.button1); if (button1 != null) { button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(CollapsingToolbarLayoutActivity.this, "Button1", Toast.LENGTH_SHORT).show(); } }); } } private List<String> getData(){ List<String> data = new ArrayList<>(); for(int i=0; i< 25; i++){ data.add("position" + i); } return data; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } } <file_sep>package com.sdnawang.edaixi_copy.fragment; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.sdnawang.edaixi_copy.R; public class OrderFragment extends Fragment { private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private String mParam1; private String mParam2; private static final int PAGE_NUM = 2; private View parent; private ViewPager viewPager; private TabLayout tabLayout; private Toolbar toolbar; public OrderFragment() { } public static OrderFragment newInstance(String param1, String param2) { OrderFragment fragment = new OrderFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { parent = inflater.inflate(R.layout.fragment_order, container, false); viewPager = (ViewPager) parent.findViewById(R.id.order_vp); tabLayout = (TabLayout) parent.findViewById(R.id.order_tl); tabLayout.setTabMode(TabLayout.MODE_FIXED); viewPager.setAdapter(new OrderPagerAdapter(getActivity().getSupportFragmentManager())); tabLayout.setupWithViewPager(viewPager); toolbar = (Toolbar) parent.findViewById(R.id.toolbar); /* toolbar.setTitle("订单列表");*/ return parent; } private class OrderPagerAdapter extends FragmentPagerAdapter{ public OrderPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position){ case 0: return CompleteOrderFragment.newInstance("",""); case 1: return UndoneOrderFragment.newInstance("",""); } return null; } @Override public int getCount() { return PAGE_NUM; } @Override public CharSequence getPageTitle(int position) { switch (position){ case 0: return "未完成"; case 1: return "已完成"; } return null; } } } <file_sep>package com.sdnawang.systemuidemo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends Activity { //4.1向上 private int systemUIMode = 1;//0:清除 1:SYSTEM_UI_FLAG_LOW_PROFILE 2:SYSTEM_UI_FLAG_FULLSCREEN private ListView mainListView; private ArrayList<String> mainList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = (ListView) findViewById(R.id.main_listview); listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getData())); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position){ case 0: Intent intent = new Intent(MainActivity.this, NavigationViewActivity.class); startActivity(intent); break; case 1: Intent intent1 = new Intent(MainActivity.this, TextInputLayoutActivity.class); startActivity(intent1); break; case 2: Intent intent2 = new Intent(MainActivity.this, FloatingActionActivity.class); startActivity(intent2); break; case 3: Intent intent3 = new Intent(MainActivity.this, TabLayoutActivity.class); startActivity(intent3); break; case 4: Intent intent4 = new Intent(MainActivity.this, CoordinatorLayoutActivity.class); startActivity(intent4); break; case 5: Intent intent5 = new Intent(MainActivity.this, CollapsingToolbarLayoutActivity.class); startActivity(intent5); break; default: Toast.makeText(MainActivity.this, "POSITION"+ position ,Toast.LENGTH_SHORT).show(); } } }); final View decorView = this.getWindow().getDecorView(); final FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab); floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Calling setSystemUiVisibility() with a value of 0 clears all flags. switch (systemUIMode) { case 0: break; case 1: decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); Toast.makeText(MainActivity.this,"SYSTEM_UI_FLAG_LOW_PROFILE",Toast.LENGTH_SHORT).show(); systemUIMode++; break; case 2: decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); Toast.makeText(MainActivity.this,"SYSTEM_UI_FLAG_HIDE_NAVIGATION",Toast.LENGTH_SHORT).show(); systemUIMode++; break; case 3://同时隐藏状态栏和导航栏 int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN; Toast.makeText(MainActivity.this,"SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_FULLSCREEN",Toast.LENGTH_SHORT).show(); decorView.setSystemUiVisibility(uiOptions); systemUIMode++; break; case 4: decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE); Toast.makeText(MainActivity.this,"View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE",Toast.LENGTH_SHORT).show(); systemUIMode++; break; case 5: decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); Toast.makeText(MainActivity.this,"View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY",Toast.LENGTH_SHORT).show(); systemUIMode++; break; default: decorView.setSystemUiVisibility(0); systemUIMode = 1; } } }); decorView.setOnSystemUiVisibilityChangeListener (new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int visibility) { // Note that system bars will only be "visible" if none of the // LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set. if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) { // TODO: The system bars are visible. Make any desired // adjustments to your UI, such as showing the action bar or // other navigational controls. } else { // TODO: The system bars are NOT visible. Make any desired // adjustments to your UI, such as hiding the action bar or // other navigational controls. } } }); } private List<String> getData(){ mainList = new ArrayList<>(); mainList.add("Navigation View"); mainList.add("TextInputLayout"); mainList.add("FloatActionButton"); mainList.add("TabLayout"); mainList.add("CoordinatorLayout"); mainList.add("CollapsingToolbarLayout"); for(int i = 0; i<20 ; i++){ mainList.add("item" + i); } return mainList; } } <file_sep>package com.sdnawang.edaixi_copy; import android.app.Application; import com.sdnawang.edaixi_copy.baidu.BaiduLocService; import com.sdnawang.edaixi_copy.util.UMengUtil; /** * Created by android on 2016/4/9. */ public class MApplication extends Application { public BaiduLocService baiduLocService; @Override public void onCreate() { super.onCreate(); // initBaiduLocService(); // UMengUtil.initUMengConfig();//配置各个平台信息 } /** * 初始化百度定位服务 */ private void initBaiduLocService(){ baiduLocService = new BaiduLocService(getApplicationContext()); } }
4f13b0adef5e5dde6d2ff894aa568142710a4a56
[ "Java" ]
8
Java
BigggFish/UIdemo
a4b5a7399f1e257d045cb99354184100487fc894
7221b8209ae39353580818126dedbfb0f180d81d
refs/heads/master
<file_sep>using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.CSharp; using Microsoft.Win32; using System.Xml.Linq; using System.Xml.Xsl; using System.Reflection; using WizardLibrary; namespace WizardCreator { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private XslCompiledTransform transform; public MainWindow() { InitializeComponent(); } private void OnOpenXml(object sender, RoutedEventArgs e) { var d = new OpenFileDialog(); d.Filter = "*XML Files|*.xml"; if (d.ShowDialog().GetValueOrDefault()) { try { var transform = new XslCompiledTransform(); transform.Load(@"D:\Projects\WizardCreator\WizardCreator\StateMachine.xslt"); var doc = XDocument.Load(d.OpenFile()); Flatten(doc.Root); var output = new MemoryStream(); transform.Transform(doc.CreateReader(), null, output); output.Position = 0; var reader = new StreamReader(output); SourceBlock.Text = reader.ReadToEnd(); reader.Dispose(); CompileMenuItem.IsEnabled = true; } catch (Exception exception) { MessageBox.Show(exception.Message); } } } void Flatten(XElement element) { var states = element.Elements("state").ToList(); if (states.Count == 0) return; foreach (var e in element.Elements()) { if (e.Name == "state") continue; foreach (var state in states) { var existingElement = state.Elements(e.Name).FirstOrDefault(x => x.Attribute("name") != null && e.Attribute("name") != null && x.Attribute("name").Value == e.Attribute("name").Value); if (existingElement == null) { state.Add(e); } else { var attributes = e.Attributes(); foreach (var attr in attributes) { if (existingElement.Attribute(attr.Name) == null) { existingElement.Add(attr); } } } } } if (element.Parent != null) { foreach (var state in states) { state.Remove(); element.Parent.Add(state); } element.Remove(); } foreach (var state in states) { Flatten(state); } } private void OnCompile(object sender, RoutedEventArgs e) { var dialog = new SaveFileDialog(); dialog.Filter = "Assembly File|*.dll"; if (!dialog.ShowDialog().GetValueOrDefault()) return; var code = SourceBlock.Text; var codeProvider = new CSharpCodeProvider(); var options = new CompilerParameters(); options.ReferencedAssemblies.Add("System.Core.dll"); options.ReferencedAssemblies.Add("WizardLibrary.dll"); options.OutputAssembly = dialog.FileName; options.GenerateExecutable = false; var compilerResults = codeProvider.CompileAssemblyFromSource(options, code); foreach (CompilerError error in compilerResults.Errors) { var icon = error.IsWarning ? MessageBoxImage.Warning : MessageBoxImage.Error; MessageBox.Show(error.ErrorText, "Error", MessageBoxButton.OK, icon); } } private void OnLoadAssembly(object sender, RoutedEventArgs e) { var d = new OpenFileDialog(); d.Filter = "*Assembly Files|*.dll"; if (!d.ShowDialog().GetValueOrDefault()) return; var asm = Assembly.LoadFile(d.FileName); // Find the initial state var types = asm.GetExportedTypes(); var first = types.FirstOrDefault(x => x.GetCustomAttributes(typeof (InitialStateAttribute), true).Length > 0); if (first == null) { MessageBox.Show("No initial state found."); return; } var wizard = new Wizard(new ReflectedState(Activator.CreateInstance(first))); wizard.Show(); wizard.Activate(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using WizardLibrary; using System.Windows; using System.IO; namespace WizardCreator { public class ReflectedState { public string Name; public List<MethodInfo> Events { get; private set; } public PropertyInfo[] Properties { get; private set; } public object Object { get; private set; } public ReflectedState(object obj) { Object = obj; Events = new List<MethodInfo>(); var type = obj.GetType(); Name = type.Name; var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance); foreach (var method in methods) { if (method.GetCustomAttributes(typeof(EventAttribute), true).Length > 0 && method.GetParameters().Length == 0) { Events.Add(method); } } Properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WizardLibrary { [AttributeUsage(AttributeTargets.Class)] public class InitialStateAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class EventAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] public class StatePropertyAttribute : Attribute { public bool IsVisible { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using WizardLibrary; namespace WizardCreator { /// <summary> /// Interaction logic for Wizard.xaml /// </summary> public partial class Wizard : Window { private ReflectedState currentState; public Wizard(ReflectedState firstState) { InitializeComponent(); currentState = firstState; CreateInterface(); } void CreateInterface() { PropertyGrid.Children.Clear(); PropertyGrid.RowDefinitions.Clear(); EventsPanel.Children.Clear(); foreach (var property in currentState.Properties) { var attrs = property.GetCustomAttributes(typeof (StatePropertyAttribute), true); if (attrs.Length == 0 || !((StatePropertyAttribute)attrs.First()).IsVisible) continue; Control input = null; var currentValue = property.GetValue(currentState.Object, null); if (property.PropertyType == typeof(string)) { var textBox = new TextBox(); if (currentValue != null) textBox.Text = (string) currentValue; PropertyInfo property1 = property; textBox.TextChanged += (sender, e) => property1.SetValue(currentState.Object, textBox.Text, null); input = textBox; } else if (property.PropertyType == typeof(bool)) { var checkBox = new CheckBox(); if (currentValue != null) checkBox.IsChecked = (bool) currentValue; PropertyInfo property1 = property; checkBox.Checked += (sender, e) => property1.SetValue(currentState.Object, true, null); checkBox.Unchecked += (sender, e) => property1.SetValue(currentState.Object, false, null); input = checkBox; } if (input != null) { PropertyGrid.RowDefinitions.Add(new RowDefinition() {Height = new GridLength(20)}); var text = new TextBlock(); text.SetValue(Grid.ColumnProperty, 0); text.SetValue(Grid.RowProperty, PropertyGrid.RowDefinitions.Count - 1); text.Text = property.Name; text.VerticalAlignment = VerticalAlignment.Center; PropertyGrid.Children.Add(text); input.SetValue(Grid.ColumnProperty, 1); input.SetValue(Grid.RowProperty, PropertyGrid.RowDefinitions.Count - 1); PropertyGrid.Children.Add(input); } } foreach (var evt in currentState.Events) { var button = new Button(); button.Margin = new Thickness(4, 5, 4, 5); button.Content = evt.Name; button.Click += OnButtonClick; EventsPanel.Children.Add(button); } } private void OnButtonClick(object sender, RoutedEventArgs e) { var button = (Button) sender; var evt = currentState.Events.First(x => x.Name == button.Content.ToString()); if (evt.ReturnType != typeof(void)) { ReflectedState newState = null; try { newState = new ReflectedState(evt.Invoke(currentState.Object, new object[0])); } catch (TargetInvocationException exception) { if (!(exception.InnerException is GuardException)) throw exception.InnerException; MessageBox.Show(exception.InnerException.Message, "Guard Exception", MessageBoxButton.OK, MessageBoxImage.Error); return; } // Copy over any properties both states have in common foreach (var property in newState.Properties) { var oldProp = currentState.Properties.FirstOrDefault(x => x.Name == property.Name && x.PropertyType == property.PropertyType); if (oldProp != null) { property.SetValue(newState.Object, oldProp.GetValue(currentState.Object, null), null); } } currentState = newState; CreateInterface(); } } } } <file_sep> using System; using System.IO; namespace NoNamespace { } e="Configuration"> <event name="Cancel" state="Cancelled" /> </state> <state name="Cancelled" /> <state name="Finished" /> <state name="Introduction"> <event name="Next" state="Components" /> <event name="Cancel" state="Cancelled" /> </state> <state name="Components"> <property type="System.Boolean" name="Binary Files" /> <property type="System.Boolean" name="Source Code" /> <property type="System.Boolean" name="HAL 2012" /> <property type="System.Boolean" name="Documentation" /> <event name="Back" state="Introduction" /> <event name="Next" state="Finished" /> <event name="Cancel" state="Cancelled" /> </state> </statemachine>
3a95f80402871c55899d21108ded5239ef8439e2
[ "C#" ]
5
C#
eschalks/WizardCreator
c2007e4d5ff04cc3aef90e516df409c3a1c81755
db5ca8afa632180c2c21f8238dfa3489b02ce3a7
refs/heads/master
<file_sep> public class shiftPractice { public static void main(String[] args) { int size = 26; char[] alphabet = new char[size]; alphabet[0] = 'A'; alphabet[1] = 'B'; alphabet[2] = 'C'; alphabet[3] = 'D'; alphabet[4] = 'E'; alphabet[5] = 'F'; alphabet[6] = 'G'; alphabet[7] = 'H'; alphabet[8] = 'I'; alphabet[9] = 'J'; alphabet[10] = 'K'; alphabet[11] = 'L'; alphabet[12] = 'M'; alphabet[13] = 'N'; alphabet[14] = 'O'; alphabet[15] = 'P'; alphabet[16] = 'Q'; alphabet[17] = 'R'; alphabet[18] = 'S'; alphabet[19] = 'T'; alphabet[20] = 'U'; alphabet[21] = 'V'; alphabet[22] = 'W'; alphabet[23] = 'X'; alphabet[24] = 'Y'; alphabet[25] = 'Z'; String input = "FIZZ BUZZ"; int shift = 1; // If shift = 1, // char = 'Z', shiftChar = 'A' // char = 'Z', shiftChar = 'A' // If shift = 2, // char = 'Z', shiftChar = 'B' // char = 'Y', shiftChar = 'A' // If shift = 24, // char = 'A', shiftChar = 'B' // char = 'Y', shiftChar = 'A' // If we mod the (charIndex + shift) % 26 } } <file_sep> public class Array01 { public static void main(String[] args) { int topScore1 = 110; int topScore2 = 100; int topScore3 = 99; float topScore4 = 88.5f; int topScore5 = 88; int topScore6 = 87; int topScore7 = 86; int topScore8 = 85; int topScore9 = 84; int topScore10 = 83; int topScore11 = 82; int topScore12 = 81; int topScore13 = 80; // this is how you declare an array of type int int [] myIntArray; // here we create 100 elements in memory for myIntArray myIntArray = new int[100]; // arrays are indexed in a zero-based fashion . . . we start counting at 0 myIntArray[0] = 110; // this is the first element in the array myIntArray[1] = 100; myIntArray[2] = 99; myIntArray[3] = 89; myIntArray[4] = 88; myIntArray[5] = 87; myIntArray[6] = 86; for(int i = 100; i > 0; i--) { myIntArray[i] = i; } // declare a string array, float array, and a double array String [] myStringArray; float [] myFloatArr; double [] myDoubleArr; } } <file_sep>#Fri Jun 02 09:18:17 PDT 2017 org.eclipse.core.runtime=2 org.eclipse.platform=4.6.2.v20161124-1400 <file_sep> public class Array03 { public static void main(String[] args) // args is short for? A: Agruments { } }
3699cf7e36f0f9fcfd2ceee3b81b23bc22aa2ded
[ "Java", "INI" ]
4
Java
91073005/workspace
dfd124787d3c57cf37c91e46db77b5ff464cb48f
491dde54b83f43a805f21837ef8d4d79306f7e61
refs/heads/master
<repo_name>fireslime/gravitational_waves<file_sep>/game/android/keys/key.properties ../../../../../dot-keys/gravitational-waves/key.properties<file_sep>/art/logo/fonts.md https://www.dafont.com/pt/quantum-4.font <file_sep>/scripts/sync.sh #!/bin/bash -e cp ./art/tileset/tileset.png ./game/assets/images/ cp ./art/tileset/tileset.json ./game/assets/images/ cp ./art/char/char.png ./game/assets/images/ cp ./art/char/char.json ./game/assets/images/ cp ./art/crystal/crystal.png ./game/assets/images/ cp ./art/container-tileset.png ./game/assets/images/ cp ./art/tutorial/hand.png ./game/assets/images/ cp ./art/animated-props/spacebattle/spacebattle.png ./game/assets/images/ cp ./art/firing-ship/firing-ship.png ./game/assets/images/ cp ./art/jetpack/jetpack.png ./game/assets/images/jetpack.png cp ./art/pulser/pulser.png ./game/assets/images/pulser.png cp ./art/crystal/crystal_container.png ./game/assets/images/crystal_container.png cp ./art/poofs/poofs.png ./game/assets/images/poofs.png cp ./art/poofs/poofs.json ./game/assets/images/poofs.json <file_sep>/game/scripts/update-assets.sh #!/bin/bash cp ../../art/char/char.png ../assets/images/char.png cp ../../art/char/char.json ../assets/images/char.json <file_sep>/README.md # gravitational_waves [![Powered by Flame](https://img.shields.io/badge/Powered%20by-%F0%9F%94%A5-orange.svg?style=for-the-badge)](https://flame-engine.org) This is a simple homage to Gravity Square, an old inifinity runner discountinued by Kongregate. Color palette: https://lospec.com/palette-list/fzt-ethereal-16 ## Credits Music Dark Moon, by <NAME> > Contains music ©2019 <NAME> (<EMAIL>) > Licensed under Creative Commons Attribution 4.0 International Sound Effects by ... <file_sep>/game/scripts/build.sh #!/bin/bash flutter packages pub run build_runner build --delete-conflicting-outputs flutter build appbundle # builds 64-bit compatible artifact echo 'Built at build/app/outputs/bundle/release/app.aab' <file_sep>/game/README.md # gravitational_waves ## Priorities ``` 0: Background stars 1: Planets, Space Battle 2: Wall (glass panes) 3: Background (green pipes) 4: Coins, Powerups 5: Player 6: HUD 7: Tutorial ```<file_sep>/game/CHANGELOG.md # 0.3.1 - Fix ads # 0.3.0 - Final polishing # 0.1.1 - Fixing minor layout bugs - Fixing FireScore integration not working # 0.1.0 - First official release on Google Play Store. <file_sep>/art/poofs/gen_spritesheet.sh #!/bin/bash SPRITES=( "./renders/poofs.png" "./renders/airflowing.png" "./renders/glass_breaking.png" ) LAST_Y=0 # First arg is the sprite # Second is the comma or blank function json_entry { W=`convert $1 -format "%w" info:` H=`convert $1 -format "%h" info:` SIZE="\"x\": 0, \"y\": $LAST_Y, \"w\": $W, \"h\": $H" IMAGE_NAME=`basename $1 .png` LAST_Y="$(($LAST_Y + $H))" } rm -f ./poofs.png cp "${SPRITES[0]}" ./poofs.png json_entry "${SPRITES[0]}" "," for SPRITE in ${SPRITES[@]:1}; do COMMA=$([ "$SPRITE" == "${SPRITES[${#SPRITES[@]}-1]}" ] && echo "" || echo ",") json_entry $SPRITE $COMMA convert ./poofs.png $SPRITE -append -transparent white ./poofs.png done convert ./poofs.png -transparent white ./poofs.png <file_sep>/game/scripts/web.sh #!/bin/bash -xe flutter run --release -d chrome --dart-define=FLUTTER_WEB_USE_SKIA=true
217e27f36aff5ef63a449102149bd03634541cb7
[ "Markdown", "Shell", "INI" ]
10
INI
fireslime/gravitational_waves
a3c94d217a28590288743a934938636acca80ea4
9f32cb5a8f300fa306217cdb5b3713731bab8fb2